-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathdht_i2c_nano_backpack.ino
110 lines (86 loc) · 1.81 KB
/
dht_i2c_nano_backpack.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <Wire.h>
#include "DHT.h"
#define DEBUG_MODE 0
// Address Pins
#define AD0 11
#define AD1 12
// I2C Defaults
#define I2C_DEFAULT_ADDRESS 0x0A
#define I2C_BUFFER_SIZE 4
//
// 0 H LSB
// 1 H MSB
// 2 T LSB
// 3 T MSB
//
byte buffer[I2C_BUFFER_SIZE];
int addressPins[] = { AD0, AD1 };
int address = I2C_DEFAULT_ADDRESS;
int dhtPin = -1;
int dhtType = -1;
void resetState() {
digitalWrite(dhtPin, LOW);
pinMode(dhtPin, INPUT);
}
void setup() {
int offset = 0;
for (int i = 0; i < 2; i++) {
pinMode(addressPins[i], INPUT);
if (digitalRead(addressPins[i])) {
offset |= 1 << i;
}
}
address += offset;
#if DEBUG_MODE
Serial.begin(9600);
#endif
resetState();
Wire.begin(address);
Wire.onRequest(onRequest);
Wire.onReceive(onReceive);
}
void loop() {
if (dhtPin != -1 && dhtType != -1) {
DHT dht(dhtPin, dhtType);
dht.begin();
int h = (int)((float)dht.readHumidity() * 100);
int c = (int)((float)dht.readTemperature() * 100);
buffer[0] = h >> 8;
buffer[1] = h & 0xFF;
buffer[2] = c >> 8;
buffer[3] = c & 0xFF;
#if DEBUG_MODE
Serial.print("h: ");
Serial.println(h);
Serial.print("c: ");
Serial.println(c);
#endif
delay(250);
#if DEBUG_MODE
Serial.print("free ram: ");
Serial.println(freeRam());
#endif
}
}
#if DEBUG_MODE
int freeRam() {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#endif
void onRequest() {
Wire.write(buffer, I2C_BUFFER_SIZE);
}
void onReceive(int howMany) {
// Order: [ pin, type ]
// Default: [ 2, 11 ]
dhtPin = (byte)Wire.read();
dhtType = (byte)Wire.read();
#if DEBUG_MODE
Serial.print("dhtPin: ");
Serial.println(dhtPin);
Serial.print("dhtType: ");
Serial.println(dhtType);
#endif
}