#include <wiringPi.h>
#include <stdio.h>
#include "dht21.h"

unsigned short data[5] = { 0, 0, 0, 0, 0 };

short readData(unsigned short pin)
{

	unsigned short val = 0x00;
	unsigned short signal_length = 0;
	unsigned short val_counter = 0;
	unsigned short loop_counter = 0;

	while (1) {
		while (digitalRead(pin) == HIGH) {
			signal_length++;
			if (signal_length >= 200) { return -1;}
			delayMicroseconds(1);
		}
		if (signal_length > 0) {
			loop_counter++;
			if (signal_length < 10) {val <<= 1;}
			else if (signal_length < 30) {val <<= 1;}
			else if (signal_length < 85) {val <<= 1; val |= 1;}
			else {return -1;}
			signal_length = 0;
			val_counter++;
		}
		if (loop_counter < 3) {val = 0x00; val_counter = 0;}
		if (val_counter >= 8) {
			data[(loop_counter / 8) - 1] = val;
			val = 0x00;
			val_counter = 0;
		}
	}
}
sensor dht21(unsigned short pin) {
	float humidity;
	float celsius;
	short checksum;
	sensor s;
	for (int i = 0; i < 10; i++) {
		pinMode(pin, OUTPUT);
		digitalWrite(pin, LOW);
		delay(20);
		pinMode(pin, INPUT);
		readData(pin);
		checksum = (data[0] + data[1] + data[2] + data[3]) & 0xFF;
		if (data[4] == checksum && checksum != 0x00) {
			humidity = ((data[0] * 256) + data[1]) / 10.0;
			celsius = ((data[2] * 256) + data[3]) / 10.0;
			if (data[2] == 0x80) { celsius *= -1;}
			s.temp = celsius;
			s.hum = humidity;
			for (int i = 0; i < 5; i++) {data[i] = 0;}
			return s;
		}
		for (int i = 0; i < 5; i++) { data[i] = 0; }
		delay(200);
	}
	s.temp = -1;
	s.temp = -1;
	return s;
}