I am using two ultrasonic distance sensor (A02YYUW) to measure distance. the output of sensor is UART. I have found this code which measures the distance for one sensor (A02YYUW Waterproof Ultrasonic Sensor Wiki - DFRobot).
It uses <SoftwareSerial.h> library. But this library has limitations that " * If using multiple software serial ports, only one can receive data at a time). and I need to use two sensors.
I am using Arduino Mega which have multiple serial ports.
Please support.
Hello
You don´t need the SoftwareSerial.h libary by using an Arduino Mega.
You can e.g. read and write to the UART like Serial1.read(); etc.
Have a nice day and enjoy coding in C++.
The Mega2560 has 3 more hardware serial ports, Serial1, Serial2 and Serial3, Have a look at this pinout picture (bottom right, pins 14 ~ 19).
mega2.pdf (354.3 KB)
Could you please support me with the modified the code.
The original code is :
/*
*@File : DFRobot_Distance_A02.ino
*@Brief : This example use A02YYUW ultrasonic sensor to measure distance
* With initialization completed, We can get distance value
*@Copyright [DFRobot](https://www.dfrobot.com),2016
* GUN Lesser General Pulic License
*@version V1.0
*@data 2019-8-28
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(11,10); // RX, TX
unsigned char data[4]={};
float distance;
void setup()
{
Serial.begin(57600);
mySerial.begin(9600);
}
void loop()
{
do{
for(int i=0;i<4;i++)
{
data[i]=mySerial.read();
}
}while(mySerial.read()==0xff);
mySerial.flush();
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)
{
Serial.print("distance=");
Serial.print(distance/10);
Serial.println("cm");
}else
{
Serial.println("Below the lower limit");
}
}else Serial.println("ERROR");
}
delay(100);
}
as others have said, you can use hardware serials 1,2, or 3
you can keep the software serial mySerial
for your sensor1 then use Serial1
for sensor2
Or, more sensibly, use hardware serial for all the sensors.
There's a topic somewhere (possibly in the tutorial section) about robist handling of serial input.
It's well-worth a read.
I have an example sketch for the A02YYUW
A02YYUW Ultrasonic Sensor (Serial) (rothschopf.net)
The basic concept is based on "Serial Input Basics" Tutorial.
However - you can easily create two "Receiver Objects" and hand over different HW Serials when you create the object/instance.
First try to adopt the sketch for one HW Serial.
If this is working for you and you have problems to implement the second object/instance, post your code in code tags and come back to us.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.