#include <TM1637.h>
#include "TM1637Display.h"
#include <Arduino.h>
#include "DHT.h"


#define CLK  2
#define DIO  3
TM1637Display display(CLK, DIO);


#define CDA  5
#define DHTTYPE DHT22
DHT dht(CDA, DHTTYPE);

#define LIT_C B00111001
#define LIT_F B01110001
#define LIT_H B01110110
#define DEGREE_SIGN B01100011

uint8_t LETTERS[] = {DEGREE_SIGN, LIT_C, LIT_F, LIT_H};


int round_to_int(float number)
{
  number > 0 ? number += 0.5 : number -= 0.5; 
  return number;
}


void show_temperature(char type)
{
  float input_temp = dht.readTemperature();
  
  if( type == 'F')
    input_temp = input_temp * 9/5 + 32;
  
  bool sign = input_temp < 0 ? true : false;
  
  int temp = round_to_int(input_temp);
  int abs_temp = abs(temp);
  
  if(abs_temp >= 10 && abs_temp <= 99)
    display.showNumberDec(temp, false, 2 + sign, 0 - sign);
  else if(abs_temp >= 0 && abs_temp <= 9)
    display.showNumberDec(temp, false, 1 + sign, 1 - sign);
  
  if(type == 'C')
    display.setSegments(&LETTERS[0], 2, 2);
  else
  {
    display.setSegments(&LETTERS[2], 1, 3);
    display.setSegments(&LETTERS[0], 1, 2);
  } 

  delay(2000);
  display.clear();
}


void show_humidity()
{
  int h = round_to_int(dht.readHumidity());

  if (h >= 10 && h <= 99)
    display.showNumberDec(h, false, 2, 0);
  else if (h >= 0 && h <= 9)
    display.showNumberDec(h, false, 1, 1);
  else 
    display.showNumberDec(h, false, 3, 0);

  display.setSegments(&LETTERS[3], 1, 3);
  delay(2000);
  display.clear();
}


void setup() {
  display.setBrightness(0xff);
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));
  dht.begin();
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  Serial.print(F("Temperature :"));
  Serial.print(t);
}

void loop() {
  show_temperature('C');
  show_humidity();
}
4-Digit Display