Last active
August 29, 2015 14:18
-
-
Save sapher/b954ec831e3e60606105 to your computer and use it in GitHub Desktop.
Example of using a DHT11 sensor with a PIC16F1704. We use Timer2 to handle the timing part.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************************/ | |
/* This example is running on a PIC16F1704 @ 4Mhz INTOSC */ | |
/* To use it you need to configure your OSC and other things. */ | |
/* The SIGNAL pin of the DHT11 is wired to the RA4 pin */ | |
/* We add a little margin for all timing (~) */ | |
/* Some information about the DHT11 : */ | |
/* http://akizukidenshi.com/download/ds/aosong/DHT11.pdf */ | |
/******************************************************************************/ | |
#include <xc.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
void readDHT11() { | |
// Declaration & Initialisation | |
int i, j = 0; | |
uint8_t data[5] = {0x00, 0x00, 0x00, 0x00, 0x00}; | |
// Hardware initialisation | |
ANSELAbits.ANSA4 = 0; | |
// 1/ Start condition (We ask him if he's there and for data in the same time) | |
TRISAbits.TRISA4 = 0; // RA4 as output | |
RA4 = 0; // RA4 put LOW | |
__delay_ms(20); // LOW for ~18uS | |
RA4 = 1; // RA4 put HIGH | |
__delay_us(30); // HIGH for ~20/~40uS | |
TRISAbits.TRISA4 = 1; // RA4 as input | |
// 2/ Acknowledge (Guess if he understand our demand) | |
TMR2 = 0; | |
TMR2ON = 1; | |
// Should be LOW for 80uS (if it took more than 100uS then the sensor is not reachable) | |
while(!PORTAbits.RA4) { | |
if(TMR2 > 100) { | |
printf("DHT11 timeout error\n"); | |
return; | |
} | |
} | |
TMR2 = 0; | |
// Should be HIGH for 80uS (if it took more than 100uS then the sensor is not reachable) | |
while(PORTAbits.RA4) { | |
if(TMR2 > 100) { | |
printf("DHT11 timeout error\n"); | |
return; | |
} | |
} | |
// 3/ Read data sent by the DHT11 (5bytes == 40bits == 5x8 bits) (He respond & When are listening) | |
for(i = 0; i < 5; i++) { | |
for(j = 0; j < 8; j++) { | |
while(!PORTAbits.RA4); // LOW 50uS | |
// Reset and restart timer2 | |
TMR2 = 0; | |
TMR2ON = 1; | |
while(PORTAbits.RA4); // HIGH 30-70uS | |
TMR2ON = 0; | |
// If it was high for more than 30uS then it's a 1, otherwise it's a 0 | |
if(TMR2 > 30) | |
data[i] |= 1<<(7-j); | |
} | |
} | |
// Print out the data | |
printf("%d %d %d %d %d\n", data[0], data[1], data[2], data[3], data[4]); | |
} | |
void main(void) | |
{ | |
// Configure Timer2 | |
T2CON = 0b0; // Prescaler 1:1 / Postcaler 1:1 / Turned Off | |
PR2 = 255; // Maximum Value (not used anyway) | |
// Read DHT11 every 0.5s | |
while(1) { | |
readDHT11(); | |
__delay_ms(500); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment