wifi避障小車最終完整版(可實現手機端操作小車)

2020-10-12 14:00:36
#include <ESP8266WiFi.h>

#define Dong1 D6
#define Dong2 D7
#define Zhuan1 D4
#define Zhuan2 D5
#define Echo D2
#define Trig D8

char* ssid = "126587"; //WiFi熱點名稱
char* passwd = "12345678"; //WiFi熱點密碼
int port = 8888;
WiFiServer server(port);//設定伺服器埠號

long getTime()
{
  digitalWrite(Trig, HIGH); //*******************
  delayMicroseconds(10);    //傳送一個10微秒的脈衝
  digitalWrite(Trig, LOW); //************

  return pulseIn(Echo, HIGH); //波傳輸過程echo高電平,計算高電平時間就獲取波傳輸的時間,單位是微秒
}

void initWifiSta()
{
  WiFi.mode(WIFI_STA);//設定STA模式
  WiFi.begin(ssid, passwd); //連線網路
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println(WiFi.localIP());//通過串列埠列印wemos的ip地址
}

void initChaoShengBo()
{
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);

}

void initL9110s()
{
  pinMode(Dong1, OUTPUT);
  pinMode(Dong2, OUTPUT);
  pinMode(Zhuan1 , OUTPUT);
  pinMode(Zhuan2, OUTPUT);
}
void qian()
{
  digitalWrite(Dong1, HIGH);
  digitalWrite(Dong2, LOW);
}
void hou()
{
  digitalWrite(Dong1, LOW);
  digitalWrite(Dong2, HIGH);
}
void ting()
{
  digitalWrite(Dong1, LOW);
  digitalWrite(Dong2, LOW);
}

void zuo()
{
  digitalWrite(Zhuan1, HIGH);
  digitalWrite(Zhuan2, LOW);

} void you()
{
  digitalWrite(Zhuan1, LOW);
  digitalWrite(Zhuan2, HIGH);
}
void zheng()
{
  digitalWrite(Zhuan1, LOW);
  digitalWrite(Zhuan2, LOW);
}
void setup() {
  // put your setup code here, to run once:
  initL9110s();
  initChaoShengBo();
  Serial.begin(115200);
  initWifiSta();
  server.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  char cmd;
  long dis;
  int mark = 0;

  WiFiClient client = server.available();//伺服器初始化
  while (client.connected()) {    //等待使用者端接入
    while (client.available() > 0) {
      cmd = client.read();
      Serial.println(cmd);
      dis = getTime() / 58;
      if (dis < 10) {
        hou();
        delay(300);
        ting();
        mark = 1;
      } else {
        mark = 0;
      }
      if (mark == 0) {
        switch (cmd) {
          case'q':
            qian();
            break;
          case'h':
            hou();
            break;
          case'z':
            zuo();
            break;
          case'y':
            you();
            break;
          case's':
            ting();
            break;
          case'p':
            zheng();
            break;
        }
      }
    }
  }
}