Arduino Serial Software Communication: 2 Ultrasonics

25 views Asked by At

I am trying to get my Arduino Nano to take in two values using serial software from two US shown at the bottom. I was only able to get one to work and I need help getting the other to work.

Using the example code provided by the company I was able to get one to work. This one ultrasonic was also able to communicate over i2c to another board. When I started to introduce another sensor it kept getting stuck in the setup where I was trying mySerial2.begin(112500). This would also stop the first US from being on the same baud rate. I then changed the baud rate and nothing happened.

#include <SoftwareSerial.h>
#include <Wire.h> 

unsigned char buffer_RTT[4] = {0};
uint8_t CS;
int Distance = 0;
int x=0; 

unsigned char buffer_RTT2[4] = {0};
uint8_t CS2; 
int Distance2 = 0;
int y=0; 

#define COM 0x55
#define COM2 0xAA

SoftwareSerial mySerial(5, 6); 
SoftwareSerial mySerial2(3, 4); 

void setup() {
  Serial.begin(115200);
  mySerial.begin(115200);
  mySerial2.begin(115200);
  Wire.begin();
}
void loop() {
  
  US1();
  US2();

  Wire.beginTransmission(9);
  Wire.write(x);  
  Wire.endTransmission();
}

void US1 (void){
  mySerial.write(COM);
  delay(100);
  if(mySerial.available() > 0){
    delay(4);
    if(mySerial.read() == 0xff){    
      buffer_RTT[0] = 0xff;
      for (int i=1; i<4; i++){
        buffer_RTT[i] = mySerial.read();   
      }
      CS = buffer_RTT[0] + buffer_RTT[1]+ buffer_RTT[2];  
      if(buffer_RTT[3] == CS) {
        Distance = (buffer_RTT[1] << 8) + buffer_RTT[2];
        Serial.print("Distance:");
        Serial.print(Distance);
        Serial.println("mm");
      }
      if (Distance < 50){
          x = 1; 
        }
        if (Distance > 50){
          x = 0; 
        }
    }
  }
}

void US2 (void)
{
  delay(5000);
  mySerial2.write(COM2); //Writes to the serial COM value 85
  delay(100);
  if(mySerial2.available() > 0){ //Starts here and reads the 4 bytes from serial
    delay(4);
    if(mySerial2.read() == 0xff){    
      buffer_RTT2[0] = 0xff;
      for (int i=1; i<4; i++){
        buffer_RTT2[i] = mySerial2.read();   
      } // Finishes reading them here
      
      //Adds up the first three values in the array
      CS2 = buffer_RTT2[0] + buffer_RTT2[1]+ buffer_RTT2[2];  
      if(buffer_RTT2[3] == CS) {//If they are the same as the fourth value 
        Distance2 = (buffer_RTT2[1] << 8) + buffer_RTT2[2];//turn it onto a distance 
        Serial.print("Distance2:");
        Serial.print(Distance2);
        Serial.println("mm");
        if (Distance2 < 50){
          y = 1; 
        }
        if (Distance2 > 50){
          y = 0; 
        }

      }
    }
  }
  
}
0

There are 0 answers