感谢EEPW推出的“换取逻辑分析仪”活动,让我分享更有动力!
本次继续分享之前做的Wi-Fi遥控小车。
主控还是老朋友ESP32 Firebeetle,采用锂电池供电。
电机驱动采用L298N,性价比不错:
安装在小车上,输入接单片机的IO信号,输出连接到两个电机上。
代码:
连接WIFI:
WiFi.begin("TP-LINK", "helloeepw"); // 启动网络连接 Serial.print("Connecting to "); // 串口监视器输出网络连接信息 Serial.print(ssid); Serial.println("Connect to TP LINK successfully"); // 告知用户NodeMCU正在尝试WiFi连接 WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP);
通信控制采用的是websocket:
server.begin(); Serial.println("Server started"); webSocket.onConnection([](WebSocket &ws) { const auto protocol = ws.getProtocol(); if (protocol) { Serial.print(F("Client protocol: ")); Serial.println(protocol); } ws.onMessage([](WebSocket &ws, const WebSocket::DataType dataType, const char *message, uint16_t length) { String cmd_str = String((char *)message); int command = cmd_str.toInt(); Serial.print("command: "); Serial.println(command); switch (dataType) { case WebSocket::DataType::TEXT: switch (command) { case CMD_STOP: Serial.println("Stop"); CAR_stop(); digitalWrite(LED_BUILTIN, LOW); break; case CMD_FORWARD: Serial.println("Move Forward"); CAR_moveForward(); digitalWrite(LED_BUILTIN, HIGH); break; case CMD_BACKWARD: Serial.println("Move Backward"); CAR_moveBackward(); digitalWrite(LED_BUILTIN, HIGH); break; case CMD_LEFT: Serial.println("Turn Left"); CAR_turnLeft(); digitalWrite(LED_BUILTIN, HIGH); break; case CMD_RIGHT: Serial.println("Turn Right"); CAR_turnRight(); digitalWrite(LED_BUILTIN, HIGH); break; default: Serial.println("Unknown command"); } break; case WebSocket::DataType::BINARY: Serial.println(F("Received binary data")); break; } }); ws.onClose([](WebSocket &, const WebSocket::CloseCode, const char *, uint16_t) { Serial.println(F("Disconnected")); }); Serial.print(F("New WebSocket Connnection from client: ")); Serial.println(ws.getRemoteIP()); }); webSocket.begin();
网页点击UP DOWN LEFT RIGHT后,调用相应的控制还是指挥小车做相应动作。
void CAR_moveForward() { digitalWrite(IN1_PIN, HIGH); digitalWrite(IN2_PIN, LOW); digitalWrite(IN3_PIN, HIGH); digitalWrite(IN4_PIN, LOW); } void CAR_moveBackward() { digitalWrite(IN1_PIN, LOW); digitalWrite(IN2_PIN, HIGH); digitalWrite(IN3_PIN, LOW); digitalWrite(IN4_PIN, HIGH); } void CAR_turnLeft() { digitalWrite(IN1_PIN, HIGH); digitalWrite(IN2_PIN, LOW); digitalWrite(IN3_PIN, LOW); digitalWrite(IN4_PIN, LOW); } void CAR_turnRight() { digitalWrite(IN1_PIN, LOW); digitalWrite(IN2_PIN, LOW); digitalWrite(IN3_PIN, HIGH); digitalWrite(IN4_PIN, LOW); } void CAR_stop() { digitalWrite(IN1_PIN, LOW); digitalWrite(IN2_PIN, LOW); digitalWrite(IN3_PIN, LOW); digitalWrite(IN4_PIN, LOW); }
实物测试:
打开WiFi,连接到ESP32 Firebeetle
打开浏览器,输入网址:192.168.4.1
切换Wi-Fi信号到本地路由器,联网下载“上” “下” “左” “右” 等图片
button_up {
background: url('https://esp32io.com/images/tutorial/up_inactive.png') no-repeat;
background-size: contain;
left: 200px;
top: 0px;
transform: translateX(-50%);
}
切换Wi-Fi到ESP32
回到浏览器,点击connect,连接到开发板
控制小车