#include <Ethernet.h>
#include <SPI.h>
byte ip[] = { 192, 168, 0, 199 };
byte gateway[] = { 192, 168, 0, 1 };
byte subnet[] = { 255, 255, 255, 0 };
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server = EthernetServer(22000);
int
relayPins[] = {6, 7};
int
numRelays =
sizeof
(relayPins) /
sizeof
(
int
);
const
bool
useDhcp =
true
;
void
setup()
{
for
(
int
i = 0; i < numRelays; i++){
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], HIGH);
}
Serial.begin(9600);
Serial.println(
"Start"
);
Serial.print(
"Number of relays: "
);
Serial.println(numRelays);
if
(useDhcp) {
Ethernet.begin(mac);
}
else
{
Ethernet.begin(mac, ip, gateway, subnet);
}
server.begin();
Serial.println(Ethernet.localIP());
}
void
loop()
{
if
(useDhcp) {
Ethernet.maintain();
}
checkForClient();
}
int
state = 0;
int
relayNumber = 0;
int
action = 0;
void
Reset()
{
state = 0;
relayNumber = 0;
action = 0;
}
void
checkForClient()
{
EthernetClient client = server.available();
if
(client) {
int
timeout = 1000;
Serial.println(
"Connected"
);
while
(client.connected()) {
if
(client.available()) {
char
c = client.read();
switch
(state){
case
0:
if
(c ==
'R'
) state++;
break
;
case
1:
if
(c ==
'('
) state++;
else
Reset();
break
;
case
2:
case
3:
state++;
if
((c <=
'9'
) && (c >=
'0'
)){
relayNumber = relayNumber * 10 + (c -
'0'
);
}
else
{
Reset();
}
break
;
case
4:
if
((c ==
':'
) || (c ==
','
) || (c ==
'.'
) || (c ==
';'
)) state++;
else
Reset();
break
;
case
5:
case
6:
state++;
if
((c <=
'9'
) && (c >=
'0'
)){
action = action * 10 + (c -
'0'
);
}
else
{
Reset();
}
break
;
case
7:
if
(c ==
')'
) state++;
else
Reset();
break
;
case
8:
if
(c ==
'\r'
) state++;
else
Reset();
break
;
case
9:
if
(c ==
'\n'
) {
if
((relayNumber > numRelays) || (action > 1)){
client.print(
"ERROR\r\n"
);
}
else
{
setRelay(relayNumber, action);
client.print(
"OK\r\n"
);
}
client.flush();
delay(100);
}
Reset();
break
;
}
if
(state > 0){
timeout = 1000;
}
}
else
{
timeout--;
if
(timeout == 0){
Serial.println(
"Disconnecting - timeout"
);
client.stop();
return
;
}
else
{
delay(30);
}
}
}
Serial.println(
"Client disconnect"
);
}
}
void
setRelay(
int
relayNumber,
int
action)
{
if
(relayNumber == 0) {
for
(
int
i = 0; i < numRelays; i++){
digitalWrite(relayPins[i], (action)?LOW:HIGH);
}
return
;
}
digitalWrite(relayPins[relayNumber-1], (action)?LOW:HIGH);
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น