Good Day,
I've been working to interface the A02YYUW sensor with an ESP32. Thus far, I have not been successful. Im using the SoftwareSerial library to interact with the sensor as it is connected to HW pins 12 and 14. I do not have physical access to the ESP32, so I cannot change these pins to HW UART pins. Likewise, I am using the WebSerial library to get readouts from the ESP32/Ultrasonic.
[Codebox]
// Import required libraries
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>
#include <WebSerial.h>
#include <SoftwareSerial.h>
// Replace with your network credentials
const char* ssid = "placeholder";
const char* password = "placeholder";
#define MYPORT_TX 12
#define MYPORT_RX 14
bool relayState = 0;
const int relayPin = 32;//17;
//SoftwareSerial myPort (MYPORT_RX, MYPORT_TX);
unsigned char data[4]={};
float distance;
EspSoftwareSerial::UART myPort;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<style>
html {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
h1 {
font-size: 1.8rem;
color: white;
}
h2{
font-size: 1.5rem;
font-weight: bold;
color: #143642;
}
.topnav {
overflow: hidden;
background-color: #143642;
}
body {
margin: 0;
}
.content {
padding: 30px;
max-width: 600px;
margin: 0 auto;
}
.card {
background-color: #F8F7F9;;
box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
padding-top:10px;
padding-bottom:20px;
}
.button {
padding: 15px 50px;
font-size: 24px;
text-align: center;
outline: none;
color: #fff;
background-color: #0f8b8d;
border: none;
border-radius: 5px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
/*.button:hover {background-color: #0f8b8d}*/
.button:active {
background-color: #0f8b8d;
box-shadow: 2 2px #CDCDCD;
transform: translateY(2px);
}
.state {
font-size: 1.5rem;
color:#8c8c8c;
font-weight: bold;
}
</style>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
</head>
<body>
<div class="topnav">
<h1>ESP WebSocket Server</h1>
</div>
<div class="content">
<div class="card">
<h2>Output - GPIO 2</h2>
<p class="state">state: <span id="state">%STATE%</span></p>
<p><button id="button" class="button">Toggle</button></p>
</div>
</div>
<script>
var gateway = `ws://${window.location.hostname}/ws`;
var websocket;
window.addEventListener('load', onLoad);
function initWebSocket() {
console.log('Trying to open a WebSocket connection...');
websocket = new WebSocket(gateway);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage; // <-- add this line
}
function onOpen(event) {
console.log('Connection opened');
}
function onClose(event) {
console.log('Connection closed');
setTimeout(initWebSocket, 2000);
}
function onMessage(event) {
var state;
if (event.data == "1"){
state = "ON";
}
else{
state = "OFF";
}
document.getElementById('state').innerHTML = state;
}
function onLoad(event) {
initWebSocket();
initButton();
}
function initButton() {
document.getElementById('button').addEventListener('click', toggle);
}
function toggle(){
websocket.send('toggle');
}
</script>
</body>
</html>)rawliteral";
void notifyClients() {
ws.textAll(String(relayState));
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, "toggle") == 0) {
relayState = !relayState;
notifyClients();
}
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}
void initWebSocket() {
ws.onEvent(onEvent);
server.addHandler(&ws);
}
String processor(const String& var){
Serial.println(var);
if(var == "STATE"){
if (relayState){
return "ON";
}
else{
return "OFF";
}
}
return String();
}
void recvMsg(uint8_t *data, size_t len){
WebSerial.println("Received Data...");
String d = "";
for(int i=0; i < len; i++){
d += char(data);
}
WebSerial.println(d);
if (d == "ON"){
digitalWrite(relayPin, HIGH);
}
if (d=="OFF"){
digitalWrite(relayPin, LOW);
}
}
void setup()
{
Serial.begin(115200); // Standard hardware serial port
// Connect to Wi-Fi network with SSID and password
Serial.print("Setting AP (Access Point)…");
// Remove the password parameter, if you want the AP (Access Point) to be open
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
server.begin();
initWebSocket();
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Start ElegantOTA
AsyncElegantOTA.begin(&server);
// Start server
server.begin();
// WebSerial is accessible at "<IP Address>/webserial" in browser
WebSerial.begin(&server);
WebSerial.msgCallback(recvMsg);
server.begin();
myPort.begin(9600, EspSoftwareSerial::SWSERIAL_8N1, MYPORT_RX, MYPORT_TX, false);
if (!myPort) { // If the object did not initialize, then its configuration is invalid
WebSerial.println("Invalid EspSoftwareSerial pin configuration, check config");
while (1) { // Don't continue with invalid configuration
delay (1000);
}
}
}
void loop() {
do{
for(int i=0;i<4;i++)
{
data=myPort.read();
}
}while(myPort.read()==0xff);
WebSerial.print("Data 0 =");
WebSerial.println(data[0]);
delay(500);
WebSerial.print("Data 1 =");
WebSerial.println(data[1]);
delay(500);
WebSerial.print("Data 2 =");
WebSerial.println(data[2]);
delay(500);
WebSerial.print("Data 3 =");
WebSerial.println(data[3]);
delay(500);
if(data[0]==0xff)
{
int sum;
sum=(data[0]+data[1]+data[2])&0x00FF;
if(sum==data[3])
{
distance=(data[1]<<8)+data[2];
if(distance>30){
WebSerial.print("distance=");
WebSerial.print(distance/10);
WebSerial.println("cm");
}
else
{
WebSerial.println("Below the lower limit");
}
}else WebSerial.println("ERROR");
}
ws.cleanupClients();
myPort.flush();
delay(500);
}[/Codebox]
A02YYUW UART communication with ESP32 not Working properly.
-
- Posts: 826
- Joined: Mon Jul 22, 2019 3:20 pm
Re: A02YYUW UART communication with ESP32 not Working properly.
Hardware serial can be redirected to any of the gpio pins, 12 and 14 will work just fine, although it will be better to have TX on 12 (https://github.com/espressif/esp-idf/tr ... out-gpio12).
https://github.com/espressif/arduino-es ... ial.h#L109
https://github.com/espressif/arduino-es ... ial.h#L109
Who is online
Users browsing this forum: No registered users and 74 guests