help me, use esp as a client
Posted: Fri Oct 21, 2016 7:41 pm
help me, What changed if you want to make esp-01 as client?
I have learned and no found reference.
I have learned and no found reference.
Code: Select all
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <Servo.h>
const char *ssid = "mywifi";
const char *pw = "qwerty123";
IPAddress ip(192, 168, 0, 1);
IPAddress netmask(255, 255, 255, 0);
const int port = 9876;
const int chCount = 4;
Servo servoCh[chCount];
int chPin[] = {0, 2, 14, 12};
int chVal[] = {1500, 1500, 1500, 1500};
int usMin = 700;
int usMax = 2300;
WiFiServer server(port);
WiFiClient client;
char cmd[100];
int cmdIndex;
unsigned long lastCmdTime = 60000;
unsigned long aliveSentTime = 0;
boolean cmdStartsWith(const char *st) {
for(int i=0; ; i++) {
if(st[i]==0) return true;
if(cmd[i]==0) return false;
if(cmd[i]!=st[i]) return false;;
}
return false;
}
void exeCmd() {
lastCmdTime = millis();
if( cmdStartsWith("ch") ) {
int ch = cmd[2] - '0';
if(ch>=0 && ch<=9 && cmd[3]==' ') {
chVal[ch] = (int)atof(cmd+4);
if(!servoCh[ch].attached()) {
servoCh[ch].attach(chPin[ch], usMin, usMax);
}
servoCh[ch].writeMicroseconds(chVal[ch]);
}
}
if( cmdStartsWith("ci") ) {
int ch = cmd[2] - '0';
if(ch>=0 && ch<=9 && cmd[3]==' ') {
chVal[ch] = -(int)atof(cmd+4);
if(!servoCh[ch].attached()) {
servoCh[ch].attach(chPin[ch], usMin, usMax);
}
servoCh[ch].writeMicroseconds(chVal[ch]);
}
}
if( cmdStartsWith("ca") ) {
int ch = cmd[2] - '0';
if(ch>=0 && ch<=9 && cmd[3]==' ') {
chVal[ch] = (usMax+usMin)/2 + (int)( atof(cmd+4)*51 );
if(!servoCh[ch].attached()) {
servoCh[ch].attach(chPin[ch], usMin, usMax);
}
servoCh[ch].writeMicroseconds(chVal[ch]);
}
}
if( cmdStartsWith("cb") ) {
int ch = cmd[2] - '0';
if(ch>=0 && ch<=9 && cmd[3]==' ') {
chVal[ch] = (usMax+usMin)/2 - (int)( atof(cmd+4)*51 );
if(!servoCh[ch].attached()) {
servoCh[ch].attach(chPin[ch], usMin, usMax);
}
servoCh[ch].writeMicroseconds(chVal[ch]);
}
}
}
void setup() {
delay(1000);
/*for(int i=0; i<chCount; i++) {
servoCh[i].attach(chPin[i], usMin, usMax);
chVal[i] = (usMin + usMax)/2;
servoCh[i].writeMicroseconds( chVal[i] );
}*/
cmdIndex = 0;
Serial.begin(115200);
WiFi.softAPConfig(ip, ip, netmask);
WiFi.softAP(ssid, pw);
server.begin();
Serial.println("ESP8266 RC receiver 1.1 powered by RoboRemo");
Serial.println((String)"SSID: " + ssid + " PASS: " + pw);
Serial.println((String)"RoboRemo app must connect to " + ip.toString() + ":" + port);
}
void loop() {
if(millis() - lastCmdTime > 500) {
for(int i=0; i<chCount; i++) {
servoCh[i].writeMicroseconds( (usMin + usMax)/2 );
servoCh[i].detach();
}
}
if(!client.connected()) {
client = server.available();
return;
}
if(client.available()) {
char c = (char)client.read();
if(c=='\n') {
cmd[cmdIndex] = 0;
exeCmd();
cmdIndex = 0;
} else {
cmd[cmdIndex] = c;
if(cmdIndex<99) cmdIndex++;
}
}
if(millis() - aliveSentTime > 500) {
client.write("alive 1\n");
aliveSentTime = millis();
}
}