Last active
January 17, 2020 15:06
-
-
Save wactbprot/b30cbab438df98a79c7e6c0aa1f8c1a0 to your computer and use it in GitHub Desktop.
Check plant soil humidity via TCP
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
#include <Ethernet.h> | |
#define PORT 9009 | |
#define MAXTCPLENGTH 30 | |
#define MAXDRY 850 | |
#define MINDRY 450 | |
byte mac[] = {0x00, 0x50, 0x56, 0x1E, 0x38, 0x36}; | |
IPAddress ip(192, 168, 98, 135); | |
EthernetServer server(PORT); | |
String cmd, param; | |
const int analogInPin = A0; | |
void setup() { | |
Ethernet.begin(mac, ip); | |
server.begin(); | |
} | |
int cal_rel_wet(int x) { | |
int rel = 100 - (x - MINDRY)*100/(MAXDRY - MINDRY); | |
return rel; | |
} | |
int cal_rel_dry(int x) { | |
int rel = (x - MINDRY)*100/(MAXDRY - MINDRY); | |
return rel; | |
} | |
String ascii_graph(int rel) { | |
String out = "(dry)["; | |
for (int i = 1; i <= 100; i = i + 2) { | |
if (i > rel) { | |
out += " "; | |
}else{ | |
out += "|"; | |
} | |
} | |
out += "](wet)"; | |
return out; | |
} | |
String net_exec(String cmd, String param) { | |
String res = "unknown cmd\n"; | |
int val = analogRead(analogInPin); | |
if( cmd == "rel_wet") { | |
res = String(cal_rel_wet(val)) + "%"; | |
} | |
if( cmd == "rel_dry") { | |
res = String(cal_rel_dry(val)) + "%"; | |
} | |
if( cmd == "graph") { | |
res = ascii_graph(cal_rel_wet(val)); | |
} | |
return res; | |
} | |
void net_read(){ | |
EthernetClient client = server.available(); | |
if (client) { | |
int i = 0; | |
bool receive_cmd = true; | |
while (client.connected()) { | |
if (client.available()) { | |
char c = client.read(); | |
Serial.print(receive_cmd); | |
if (c == '\n' || i > MAXTCPLENGTH) { | |
client.println(net_exec(cmd, param)); | |
client.stop(); | |
cmd = ""; | |
param = ""; | |
break; | |
} | |
if(c == '='){ | |
receive_cmd = false; | |
} else { | |
if(receive_cmd) { | |
cmd += c; | |
} else { | |
param += c; | |
} | |
} | |
} // client available | |
i++; | |
} // while | |
}// client | |
} | |
void loop() { | |
net_read(); | |
delay(100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment