I setup MEGA 2560 as master and have 3 slaves. I get slave ID from MEGA serial monitor and send it to slaves via rs485 bus from softserial port. And waiting for the right slave to respond. It works fine if I don't have the timeout function in the while loop.
But when I try
ok=0;
while (mySerial.available()<=0){ // wait here to be sure to read and clear buffer
ok++;
if (ok>50000) break;
}
It will response to the last slaveID instead of the current Id I type in the serial monitor.
here is the complete code:
/*-----( Import needed libraries )-----*/
#include <SoftwareSerial.h>
/*-----( Constants and Pins )---------*/
int cx = 8; //DE/RE Controling pin of RS-485
int ledPin = 13;
/*-----( Declare objects )-------------*/
SoftwareSerial mySerial(10, 11); // RX, TX
/*-----( Declare Variables )-----------*/
unsigned int slave_id;
String incoming; //Declare a String variable to hold your name
unsigned int ok;
void setup() {
mySerial.begin(9600);//Using mySerial Port
Serial.begin(9600);
pinMode(cx, OUTPUT);
pinMode(ledPin, OUTPUT);//Led Connected
}
void loop() {
Serial.println("Please enter the slave ID "); //Prompt User for input
while (Serial.available()<=0) {}
slave_id=Serial.parseInt(); //Read user input into slave ID
digitalWrite(cx,HIGH);//DE/RE=HIGH Transmit Enabled M1
mySerial.print(slave_id);//Write outch and Fetch Data From slave
delay(3); //allows last 2 char send out
// before turn off control pin
digitalWrite(cx,LOW);//DE/RE=LOW Receive Enabled M1
Serial.println(slave_id);
getdata();
Serial.println(ok);
delay(2000);
digitalWrite(ledPin,HIGH);//Led ON
delay(2000);
} // end loop
void getdata() {
ok=0;
while (mySerial.available()<=0){ // wait here to be sure to read and clear buffer
//ok++;
//if (ok>50000) break;
}
if (ok<50000){
incoming=mySerial.readString(); //Read slave
Serial.println(incoming);
Serial.print('\n');
}else{
Serial.println("There is something wrong ");
Serial.print('\n');
}
}
here is the image that works fine:
here is the image that not work properly:
Hope if any one interested to help. thanks
Felix
Mega_Code4.ino (1.55 KB)