I am using a A0221AU UART Ultrasonic Sensor and it is not responding as expected.
It gives a few readings at first and then sometimes does not respond.
I am using the DFRobot Example code. I already check and make the connection permanent but it still does not respond sometimes.
Please tell me is that a problem in the code or the sensor itself.
Thanks in advance.
Heres the code and the source link
#include<SoftwareSerial.h>
int pinRX1 = 11;
int pinTX1 = 10;
int pinRX2 = 13;
int pinTX2 = 12;
unsigned char data_buffer1[4] = {0};
unsigned char data_buffer2[4] = {0};
unsigned char data_buffer3[4] = {0};
unsigned char data_buffer4[4] = {0};
int distance1 = 0;
int distance2 = 0;
int distance3 = 0;
int distance4 = 0;
unsigned char CS1;
unsigned char CS2;
unsigned char CS3;
unsigned char CS4;
SoftwareSerial mySerial (pinRX1, pinTX1);
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
Serial3.begin(9600);
mySerial.begin(9600);
Serial.begin(9600);
}
void loop() {
if (mySerial.available()>0){ //sensor 1
delay(4);
if (mySerial.read() == 0xff){
data_buffer1[0] = 0xff;
for(int i = 1; i<4; i++){
data_buffer1[i] = mySerial.read();
}
CS1 = data_buffer1[0] + data_buffer1[1] + data_buffer1[2];
if (data_buffer1[3] == CS1){
distance1 = (data_buffer1[1] <<8) + data_buffer1[2];
delay(5);
Serial.print("distance 1: ");
Serial.print(distance1);
Serial.println(" mm ");
}
}
}
else if (Serial1.available()>0){ //sensor 2
delay(4);
if (Serial1.read() == 0xff){
data_buffer2[0] = 0xff;
for(int j = 1; j<4; j++){
data_buffer2[j] = Serial1.read();
}
CS2 = data_buffer2[0] + data_buffer2[1] + data_buffer2[2];
if (data_buffer2[3] == CS2){
distance2 = (data_buffer2[1] <<8) + data_buffer2[2];
delay(5);
Serial.print("distance 2: ");
Serial.print(distance2);
Serial.println(" mm ");
}
}
}
else if (Serial2.available()>0){ //sensor 3
delay(4);
if (Serial2.read() == 0xff){
data_buffer3[0] = 0xff;
for(int k = 1; k<4; k++){
data_buffer3[k] = Serial2.read();
}
CS3 = data_buffer3[0] + data_buffer3[1] + data_buffer3[2];
if (data_buffer3[3] == CS3){
distance3 = (data_buffer3[1] <<8) + data_buffer3[2];
delay(5);
Serial.print("distance 3: ");
Serial.print(distance3);
Serial.println(" mm ");
}
}
}
else if (Serial3.available()>0){ //sensor 4
delay(4);
if (Serial3.read() == 0xff){
data_buffer4[0] = 0xff;
for(int l = 1; l<4; l++){
data_buffer4[l] = Serial3.read();
}
CS4 = data_buffer4[0] + data_buffer4[1] + data_buffer4[2];
if (data_buffer4[3] == CS4){
distance4 = (data_buffer4[1] <<8) + data_buffer4[2];
delay(5);
Serial.print("distance 4: ");
Serial.print(distance4);
Serial.println(" mm");
Serial.println(" ");
}
}
}
}