Nuppiz

Temphum

Mar 1st, 2022 (edited)
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. //Temperature and Humidity Sensor
  2. #include "DHT.h"
  3. #include <Arduino.h>
  4. #include <U8x8lib.h>
  5. #define DHTPIN 3 // what pin we're connected to
  6. #define DHTTYPE DHT11 // DHT 11
  7. #define CELSIUS 0
  8. #define FAHRENHEIT 1
  9. #define BUTTON_INTERVAL 100
  10.  
  11. const int buttonPin = 2;
  12. int buttonState = 0;
  13. int tempUnit = CELSIUS;
  14.  
  15. DHT dht(DHTPIN, DHTTYPE);
  16. U8X8_SSD1306_128X64_ALT0_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
  17.  
  18. void setup(void) {
  19.    Serial.begin(9600);
  20.    Serial.println("DHTxx test!");
  21.    dht.begin();
  22.    u8x8.begin();
  23.    u8x8.setPowerSave(0);
  24.    u8x8.setFlipMode(1);
  25.    attachInterrupt(digitalPinToInterrupt(buttonPin), changeUnit, RISING);
  26. }
  27.  
  28. void print_temp(void) {
  29.    float temp = dht.readTemperature();
  30.    u8x8.setCursor(0, 33);
  31.    u8x8.print("Temp:");
  32.  
  33.    if (tempUnit == CELSIUS)
  34.    {
  35.      u8x8.print(temp);
  36.      u8x8.print("C");
  37.    }
  38.    else
  39.    {
  40.      u8x8.print(temp * 1.8 + 32);
  41.      u8x8.print("F");
  42.    }
  43. }
  44.  
  45. void changeUnit(void) {
  46.     static unsigned long last_press = 0;
  47.     static unsigned long timer;
  48.    
  49.     timer = millis();
  50.  
  51.     if (timer - last_press > BUTTON_INTERVAL)
  52.     {
  53.       if (tempUnit == CELSIUS)
  54.         tempUnit = FAHRENHEIT;
  55.       else
  56.         tempUnit = CELSIUS;
  57.  
  58.       last_press = millis();
  59.     }
  60. }
  61.  
  62. void loop(void) {
  63.      buttonState = digitalRead(buttonPin);
  64.      float humi;
  65.      humi = dht.readHumidity();
  66.      u8x8.setFont(u8x8_font_chroma48medium8_r);
  67.      print_temp();
  68.      u8x8.setCursor(0,50);
  69.      u8x8.print("Humidity:");
  70.      u8x8.print(humi);
  71.      u8x8.print("%");
  72.      u8x8.refreshDisplay();
  73.      delay(200);
  74. }
Add Comment
Please, Sign In to add comment