Hello All,
I'm working on a small project in which I want to use a Raspberry Pi to control multiple slave Arduinos. I am using half-duplex RS485 for serial communications, I thought about using Modbus to facilitate multi-drop topology but it was a little complex for what I needed. I decided to try and work up a simple Interrupt based communications protocol instead.
Essentially, I want the Arduinos to monitor the serial line, if new data arrives I want them to read it, parse it and then take any necessary action.
The problem I seem to be having is that my interrupt only runs once, after the first iteration (which works fine) I get no response. I have tried resetting the interrupt flag but am something of a newbie.
Any advice would be appreciated. Code attached.
//Libraries
#include <SoftwareSerial.h>
//Constants & Pin Numbers
#define interrupt_Pin 2
#define LED_Pin 8
#define RS485_Toggle_Pin 9
#define RS485_Rx_Pin 10
#define RS485_Tx_Pin 11
#define RS485TX HIGH
#define RS485RX LOW
const byte bufferSize = 32;
char Buffer[bufferSize];
boolean newCommand = false;
//Software Serial Setup
SoftwareSerial RS485(RS485_Rx_Pin,RS485_Tx_Pin);
//Setup
void setup()
{
//Pin Modes
pinMode(LED_BUILTIN,OUTPUT);
pinMode(interrupt_Pin,INPUT_PULLUP);
pinMode(LED_Pin,OUTPUT);
pinMode(RS485_Toggle_Pin,OUTPUT);
//Intialise Pins
digitalWrite(LED_BUILTIN,LOW);
digitalWrite(LED_Pin,LOW);
digitalWrite(RS485_Toggle_Pin,RS485RX);
//Hardware Serial - Serial Monitor Debugging
Serial.begin(9600);
Serial.println("Arduino Interrupt Based Communications - Slave");
//Software Serial - RS485 Bus
RS485.begin(9600);
//Attach Interrupt
attachInterrupt(digitalPinToInterrupt(interrupt_Pin),getCommand,FALLING);
}
void loop()
{
if (newCommand == true)
{
Serial.println("Recieved from Pi: ");
Serial.println(Buffer);
digitalWrite(RS485_Toggle_Pin,RS485TX); //Enable RS485 Transmission
RS485.println((char*)Buffer); //Send Response
RS485.flush();
digitalWrite(RS485_Toggle_Pin,RS485RX);
newCommand = false;
}
}
void getCommand()
{
static boolean Receiving = false;
static byte index = 0;
char STX = 0x02;
char ETX = 0x04;
char currentByte;
if (RS485.available() > 0)
{
while (RS485.available() > 0 && newCommand == false)
{
currentByte = RS485.read();
if (Receiving == true)
{
if (currentByte != ETX)
{
Buffer[index] = currentByte;
index++;
if (index >= bufferSize)
{
index = bufferSize-1;
}
}
else
{
Buffer[index] = '\0';
Receiving = false;
index = 0;
newCommand = true;
}
}
else if (currentByte == STX)
{
Receiving = true;
}
}
}
}