Hello,
I have been working on serial communication with Arduinos using RS485 and Arduino Mega 2560.
I am trying to perform an arithmetic operation between the master and the slave.
The master sends the two values to the slave with the operand and the slave gives the result on its serial monitor. But, when the slave shows the output, there is overflowing loop and also '-1' value. I am not sure how to overcome this. I have pasted the master and the slave code below. Please help me out with this.
Expected Input and output
Input = 10+20;1
slave 1 = 30
Master code:
//#include<Wire.h>
//int number = 0;
#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);
}
}
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[5] = {0};
char b[5] = {0};
char operation;
int i = 0;
boolean op2 = false;
digitalWrite (ENABLE_PIN, LOW);
while(rs485.available()){
char c = rs485.read();
delay(10);
//char c = Wire.read(); // receive byte as a character
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);
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;
}
//Serial.println(z);
char res[10] = {0};
itoa(z, res, 10);
z=-1;
Serial.println(res);
}
}