Created
November 8, 2010 08:47
-
-
Save cornet/667488 to your computer and use it in GitHub Desktop.
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 the SoftwareSerial library so you can use its functions. | |
// We're using the software serial library as the Arduino only has one | |
// hardware serial port, and it's a shame to waste it on a 9600bps device. | |
#include <NewSoftSerial.h> | |
#include <Ethernet.h> | |
// Define the pins used for the software serial port. Note that we won't | |
// actually be transmitting anything over the transmit pin. | |
#define rxPin 3 | |
#define txPin 4 | |
// Set up the serial port | |
NewSoftSerial softSerial (rxPin, txPin); | |
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; | |
byte ip[] = { 10, 0, 0, 2 }; | |
byte gateway[] = { 10, 0, 0, 2 }; | |
byte subnet[] = { 255, 255, 255, 0 }; | |
Server server(23); | |
int pos = 0; | |
char startPattern[] = "<ch1><watts>"; | |
char endPattern[] = "<"; | |
int state = 0; | |
char power[6] = ""; | |
int j; | |
#define BUFSIZE 256 | |
char buffer[BUFSIZE]; | |
int bufpos = 0; | |
void setup() { | |
// Define pin modes for tx and rx pins: | |
pinMode(rxPin, INPUT); | |
pinMode(txPin, OUTPUT); | |
// Set the data rate for the SoftwareSerial port | |
softSerial.begin(9600); | |
// initialize the ethernet device | |
Ethernet.begin(mac, ip, gateway, subnet); | |
// start listening for clients | |
server.begin(); | |
// Set the data rate for the hardware serial port | |
Serial.begin(115200); | |
} | |
void loop() { | |
Client client = server.available(); | |
if (softSerial.available()) { | |
readLine(); | |
for (int i = 0; i < BUFSIZE; i++) { | |
Serial.print(buffer[i], BYTE); | |
if (state == 0) { | |
if (buffer[i] == startPattern[pos]) { | |
pos++; | |
if (startPattern[pos] == 0) { | |
// finished matching start pattern | |
state = 1; | |
power[0] = '\0'; | |
j = 0; | |
} | |
} else { | |
pos = 0; | |
} | |
} else if (state == 1) { | |
if (buffer[i] == endPattern[0]) { | |
// Finished reading power | |
client.write(power); | |
client.write("\n"); | |
state = 2; | |
power[0] = '\0'; | |
j = 0; | |
} else { | |
// Read another digit | |
power[j] = buffer[i]; | |
j++; | |
} | |
} | |
} | |
state = 0; | |
Serial.print("\n"); | |
} | |
} | |
void readLine(void) { | |
char c; | |
bufpos = 0; | |
buffer[0] = '\0'; | |
while (bufpos < BUFSIZE) { | |
if (softSerial.available()) { | |
c = softSerial.read(); | |
buffer[bufpos] = c; | |
bufpos++; | |
} | |
} | |
softSerial.flush(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment