Skip to content

Commit 8d8c133

Browse files
committed
Trying out various sensors
1 parent 9886dee commit 8d8c133

File tree

1 file changed

+128
-0
lines changed

1 file changed

+128
-0
lines changed

sensors.ino

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
#include <dht.h>
2+
3+
#define GREEN_PIN 2
4+
#define BLUE_PIN 3
5+
#define FAN_PIN 4
6+
#define DHT_PIN 5
7+
8+
const int WATER_PIN = 0;
9+
const int PHOTO_PIN = 1;
10+
const byte numChars = 32;
11+
char receivedChars[numChars]; // an array to store the received data
12+
dht DHT;
13+
14+
boolean newData = false;
15+
16+
void setup() {
17+
18+
// Initialise serial communication
19+
Serial.begin(9600);
20+
21+
// Initialise the output pins
22+
pinMode(GREEN_PIN, OUTPUT);
23+
pinMode(BLUE_PIN, OUTPUT);
24+
pinMode(FAN_PIN, OUTPUT);
25+
26+
// Initialise the input pin
27+
pinMode(DHT_PIN, INPUT);
28+
}
29+
30+
void loop() {
31+
32+
recvWithEndMarker();
33+
handleDevice();
34+
}
35+
36+
void handleDevice() {
37+
38+
if (newData == true) {
39+
40+
int command = receivedChars[0];
41+
42+
if (command == 104){
43+
44+
Serial.print("ARDUINO");
45+
46+
} else if (command == 108 || command == 102){
47+
48+
String stringDevice = (String) receivedChars[1];
49+
int device = stringDevice.toInt();
50+
51+
bool state = false;
52+
if (receivedChars[2] == '1') {
53+
54+
state = true;
55+
}
56+
57+
switch (device) {
58+
59+
case 2:
60+
digitalWrite(2, state);
61+
break;
62+
case 3:
63+
digitalWrite(3, state);
64+
break;
65+
case 4:
66+
digitalWrite(4, state);
67+
break;
68+
default:
69+
digitalWrite(2, state);
70+
digitalWrite(3, state);
71+
digitalWrite(4, state);
72+
}
73+
74+
Serial.print("OK");
75+
76+
} else if (command == 116){
77+
78+
int tries = 5;
79+
int chk = DHT.read11(DHT_PIN);
80+
while (chk != 0 && tries > 0){
81+
DHT.read(DHT_PIN);
82+
tries--;
83+
}
84+
85+
Serial.print((int) DHT.temperature);
86+
87+
} else if (command == 112){
88+
89+
int photoLevel = analogRead(PHOTO_PIN);
90+
Serial.print(photoLevel);
91+
92+
} else if (command == 119){
93+
94+
int waterLevel = analogRead(WATER_PIN);
95+
Serial.print(waterLevel);
96+
}
97+
98+
newData = false;
99+
}
100+
}
101+
102+
void recvWithEndMarker() {
103+
104+
static byte ndx = 0;
105+
char endMarker = '\n';
106+
char rc;
107+
108+
while (Serial.available() > 0 && newData == false) {
109+
110+
rc = Serial.read();
111+
112+
if (rc != endMarker) {
113+
114+
receivedChars[ndx] = rc;
115+
ndx++;
116+
117+
if (ndx >= numChars) {
118+
ndx = numChars - 1;
119+
}
120+
121+
} else {
122+
123+
receivedChars[ndx] = '\0'; // terminate the string
124+
ndx = 0;
125+
newData = true;
126+
}
127+
}
128+
}

0 commit comments

Comments
 (0)