Hello,
I am trying to make master ask the slave to perform an arithmetic operation using mega 2560 with rs485. The slaves gets the input, computes the operation and sends back the answer to the master . The 2 way communication is happening between the master and the slave but i see some other answer in the master apart from the actual answer.
Could any one please let me know what has to be rectified in the code. Please explain me and help me resolve this problem.
Input is given by the master-- 10+20;1
Expected output in the Master and Slave - 30
Master
#include "RS485_protocol.h"
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 2;
SoftwareSerial rs485 (10,11); // receive pin, transmit pin
char input[10];
int charsRead = 0;
int sl;
void setup()
{
Serial.begin(9600);
rs485.begin (28800);
pinMode (ENABLE_PIN, OUTPUT);
}
void loop()
{
Serial.flush();
if (Serial.available() == 0)
{
}
delay(200);
while (Serial.available() > 0)
{
charsRead = Serial.readBytesUntil('\n', input, sizeof(input)-1);
sl = input[charsRead - 1] - '0';
input[charsRead - 1] = '\0';
}
if(charsRead > 0){
digitalWrite (ENABLE_PIN, HIGH); // enable sending
rs485.write(input);
digitalWrite (ENABLE_PIN, LOW);
//Serial.println(input);
}
while(1<rs485.available()){
digitalWrite (ENABLE_PIN, LOW);
char c;
c = rs485.read();
delay(1000);
//digitalWrite (ENABLE_PIN, HIGH);
Serial.println(c);
digitalWrite (ENABLE_PIN, HIGH);
}
}
Slave:
#include "RS485_protocol.h"
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 2;
SoftwareSerial rs485 (10, 11); // receive pin, transmit pin
boolean replay = true;
int z = -1;
void setup()
{
Serial.begin(9600);
rs485.begin (28800);
pinMode (ENABLE_PIN, OUTPUT); // register event
}
void loop()
{
char a[10] = {0};
char b[10] = {0};
char operation;
int i = 0 ;
boolean op2 = false;
digitalWrite (ENABLE_PIN, LOW);
while(1<rs485.available()){
//while(rs485.available()){
char c = rs485.read();
delay(10);
//if(c == ';')
//break;
if(c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')')
{
i = 0;
op2 = true;
operation = c;
continue;
}
if(op2)
{b[i++] = c;
}
else
{a[i++] = c;
}
int x = atoi(a);
int y = atoi(b);
if(c == ';')
{
switch(operation)
{
case '+': z = x + y;
break;
case '-': z = x - y;
break;
case '*': z = x * y;
break;
case '/': z = x/y;
break;
case '(': z = max(x,y);
break;
case ')': z = min(x,y);
break;
}
}
char res[10] = {0};
itoa(z, res, 10);
//delay(100);
if (z!=-1){
//Serial.println(strlen(b));
Serial.println(res);
}
z=-1;
delay(1000);
digitalWrite (ENABLE_PIN, HIGH);
rs485.write(res);
digitalWrite (ENABLE_PIN, LOW);
}
}