[kenrobot_code]/*CODE FROM:
https://github.com/beadone/webserver_esp-12
* 修改内容:用于maibu 手表控制小车
* date:2017-05-22
* by:沧海笑1122
*/
#include <ESP8266WiFi.h>
//wifi设置
const char* ssid = "your ssid";
const char* password = "yourpsw ";
//小车驱动设置
/*
int redPin = 15; //GPIO15
int greenPin = 12; //GPIO12
int bluePin = 13; //GPIO13
*/
int DEFAULT_SPEED = 200 ;//默认速度,max=255
int inA = D8;
int inB = D6;
int pwmA = D7;
int pwmB = D5;
//小车反馈字头
int carzt;//反馈到客户端的小车字头
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
//小车控制pin设置
pinMode(inA, OUTPUT);
pinMode(inB, OUTPUT);
pinMode(pwmA, OUTPUT);
pinMode(pwmB, OUTPUT);
/*
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
*/
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
int carzt=0;
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
if (req.indexOf("/F") != -1) {
goForward();
carzt = 1; //小车前进
}
if (req.indexOf("/B") != -1) {
goBackward();
carzt = 2; //小车后退
}
if (req.indexOf("/S") != -1) {
stop();
carzt = 0; //小车停止
}
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println();
client.println("{");
// int sensorReading = analogRead(1);
client.print("\"car");
client.print("\": ");
client.print(carzt);
client.println("\n}");
// break;
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
void goForward()//小车前进
{
digitalWrite(inA,HIGH);
digitalWrite(inB,HIGH);
analogWrite(pwmA,DEFAULT_SPEED);
analogWrite(pwmB,DEFAULT_SPEED);
}
void goBackward()//小车后退
{
digitalWrite(inA,LOW);
digitalWrite(inB,LOW);
analogWrite(pwmA,DEFAULT_SPEED);
analogWrite(pwmB,DEFAULT_SPEED);
}
void stop()//小车停止
{
/*disable the enble pin, to stop the motor. */
digitalWrite(inA,LOW);
digitalWrite(inB,LOW);
analogWrite(pwmA,0);
analogWrite(pwmB,0);
}
[/kenrobot_code]