So, I'm trying to make the DHT11 sensor work without any library on a Raspberry Pi 2 using C. I'm using this tutorial to manipulate the GPIO pins registers so i can set them as input,output, HIGH and LOW. I am also using the wiringPi library to be sure that the timers are correct when sending initialization signals to the DHT11 sensor.
Here is the code that i am trying to make work:
#include <wiringPi.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "RPI.h"
#define MAXTIMINGS 85
int dht11_dat[5] = {0, 0, 0, 0, 0};
int read_GPIO(int number)
{
if(GPIO_READ(number))
return 1;
else
return 0;
}
void read_dht11_dat()
{
uint8_t laststate = 1;
uint8_t counter = 0;
uint8_t j = 0, i;
float f; /* fahrenheit */
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
if(map_peripheral(&gpio) == -1)
{
printf("Failed to map the physical GPIO register!");
}
INP_GPIO(4);//befot output, must set as INPUT
OUT_GPIO(4);//set outout
/* pull pin down for 18 milliseconds */
GPIO_CLR = 1 << 4;
delay( 18 );
/* then pull it up for 40 microseconds */
GPIO_SET = 1 << 4; // digitalWrite(7, HIGH );
delayMicroseconds( 40 );
/* prepare to read the pin */
INP_GPIO(4);//pinMode( 7, INPUT );
/* detect change and read data */
for ( i = 0; i < MAXTIMINGS; i++ )
{
counter = 0;
while ( read_GPIO(4) == laststate )
{
counter++;
delayMicroseconds( 1 );
if ( counter == 255 )
{
break;
}
}
laststate = read_GPIO(4);/*digitalRead( 7 );*/
if ( counter == 255 )
break;
/* ignore first 3 transitions */
if ( (i >= 4) && (i % 2 == 0) )
{
/* shove each bit into the storage bytes */
dht11_dat[j / 8] <<= 1;
if ( counter > 16 )
dht11_dat[j / 8] |= 1;
j++;
}
}
/*
* check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
* print it out if data is good
*/
if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
{
f = dht11_dat[2] * 9. / 5. + 32;
printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
}
else {
printf( "Data not good, skip\n" );
}
//unmap_peripheral(&gpio); should this be here, im confused is this restarting the state of the gpio pin
}
int main()
{
printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );
if ( wiringPiSetup() == -1 )
exit( 1 );
while ( 1 )
{
read_dht11_dat();
delay( 1000 ); /* wait 1sec to refresh */
}
return 0;
}
So my question is why is this not working? When I test the GPIO manipulations with a simple blinking LED program everything is working OK. I assume that the problem is in the INP_GPIO, OUT_GPIO, when they are called more than once the addresses of the registers are not set appropriate. Is there a way i can somehow "restart" the gpio pins original state at the beginning of the function? I guess this will fix my problem?
Correct me if i'm wrong!