Skip to content
Newer
Older
100644 93 lines (71 sloc) 1.48 KB
7031195 @cdrttn Initial commit
authored Sep 8, 2012
1 static const int sensor = 8;
2 static int timing_pos = 0;
3 static int timings[64];
4
5 static int readBit(void)
6 {
7 int usec;
8
9 usec = pulseIn(sensor, HIGH);
10 timings[timing_pos++] = usec;
11
12 if (usec <= 40)
13 return 0;
14
15 return 1;
16 }
17
18 static uint8_t readByte(void)
19 {
20 int i;
21 uint8_t rv;
22
23 for (rv = 0, i = 0; i < 8; ++i) {
24 rv |= readBit() << (7 - i);
25 }
26
27 return rv;
28 }
29
30 static uint16_t readWord(void)
31 {
32 int i;
33 uint16_t rv;
34
35 for (rv = 0, i = 0; i < 16; ++i) {
36 rv |= readBit() << (15 - i);
37 }
38
39 return rv;
40 }
41
42 void setup()
43 {
44 Serial.begin(9600);
45 }
46
47 void loop()
48 {
49 uint16_t temp, humidity;
50 uint8_t chksum, chksum_test;
51 char buf[128];
52 int i;
53
54 timing_pos = 0;
55 pinMode(sensor, OUTPUT);
56 digitalWrite(sensor, HIGH);
57
58 delay(5000);
59
60 digitalWrite(sensor, LOW);
61 delay(18);
62 digitalWrite(sensor, HIGH);
63
64 pinMode(sensor, INPUT);
65
66 pulseIn(sensor, LOW);
67 while (digitalRead(sensor) == HIGH)
68 ;
69
70 humidity = readWord();
71 temp = readWord();
72 chksum = readByte();
73
74 chksum_test = (humidity & 0xff00) >> 8;
75 chksum_test += humidity & 0xff;
76 chksum_test += (temp & 0xff00) >> 8;
77 chksum_test += temp & 0xff;
78
79 sprintf(buf, "RH %d.%d, T %d.%d, CHKSUM %s",
80 humidity/10, humidity%10,
81 temp/10, abs(temp%10),
82 chksum == chksum_test? "Ok" : "Fail");
83 Serial.println(buf);
84 /*
85 Serial.println("Timings.\n");
86
87 for (i = 0; i < 16; ++i) {
88 sprintf(buf, "%d. %d", i, timings[i]);
89 Serial.println(buf);
90 }
91 */
92 }
Something went wrong with that request. Please try again.