Created
October 24, 2014 23:11
-
-
Save glisha/9219935f04e088e37e50 to your computer and use it in GitHub Desktop.
arduino+esp8266+relay
This file contains hidden or 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
boolean wifiReady = 0; | |
boolean wifiConnected = 0; | |
void setup() { | |
pinMode(10,OUTPUT); | |
pinMode(13,OUTPUT); | |
digitalWrite(10,LOW); | |
digitalWrite(13,LOW); | |
Serial.begin(115200); | |
Serial.setTimeout(2000); | |
while (!wifiReady) { | |
wifiReset(); | |
delay(1000); | |
} | |
while (!wifiConnected) { | |
digitalWrite(13,LOW); | |
wifiConnect(); | |
delay(1000); | |
} | |
setupTCPservice(); | |
delay(1000); | |
} | |
void loop() { | |
if(wifiConnected){ | |
char recvBuf[128]; | |
//bzero(recvBuf,128); | |
for( int i = 0; i < sizeof(recvBuf); ++i ) | |
recvBuf[i] = (char)0; | |
Serial.flush(); | |
Serial.readBytesUntil('\n',recvBuf,128); | |
switch (recvBuf[0]){ | |
case 'r': | |
case 'l': | |
case 'u': | |
case 'O': | |
// probably initial ready,link,unlink,OK | |
break; | |
case '+': | |
// probably +IPD, which is what we want | |
decodeIPD(recvBuf); | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
void wifiReset(){ | |
Serial.setTimeout(5000); | |
Serial.print("AT+RST\r\n"); // Reset the ESP8266 | |
delay(1000); | |
if(Serial.find("ready")){ | |
wifiReady = 1; | |
}else{ | |
wifiReady = 0; | |
} | |
} | |
void wifiConnect(){ | |
Serial.print("AT+CWMODE=3\r\n"); | |
Serial.find("OK"); | |
delay(1000); | |
Serial.print("AT+CWJAP=\"KIKA\",\"sz123456\"\r\n"); | |
delay(1000); | |
if(Serial.find("OK")){ | |
wifiConnected = 1; | |
digitalWrite(13,HIGH); | |
} else { | |
wifiConnected = 0; | |
digitalWrite(13,LOW); | |
} | |
} | |
void setupTCPservice(){ | |
Serial.print("AT+CIPMUX=1\r\n"); | |
delay(1000); | |
Serial.print("AT+CIPSERVER=1,8023\r\n"); | |
delay(1000); | |
} | |
void decodeIPD(char *recvBuf){ | |
int ch,len; | |
unsigned char cmd[128]; | |
//bzero(cmd,128); | |
for( int i = 0; i < sizeof(cmd); ++i ) | |
cmd[i] = (char)0; | |
sscanf(&recvBuf[5],"%d,%d:%s", &ch ,&len, cmd); | |
if(len > 128) | |
len=128; | |
cmd[len] = 0; | |
switch (cmd[0]){ | |
case 'P': | |
digitalWrite(10,HIGH); | |
break; | |
case 'G': | |
digitalWrite(10,LOW); | |
break; | |
default: | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment