#include <SoftwareSerial.h>
int MAX485_Receiver_Output_PIN = 10;
int MAX485_Driver_Input_PIN = 11;
int MAX485_Driver_Output_Enable_PIN = 12;
int led_1_PIN = 5;
int led_2_PIN = 6;
unsigned long time = 0;
unsigned long oldtime = 0;
int state = 0;
int next_ID_button_PIN = 2;
#define NUMSTATES 3
int states[NUMSTATES] = {7, 8, 9};
byte IDs[NUMSTATES] = {1, 2, 3};
#define MESSAGELENGTH 3
SoftwareSerial software_serial (MAX485_Receiver_Output_PIN, MAX485_Driver_Input_PIN); // RX, TX
void setup()
{
software_serial.begin(9600); // begin software serial
pinMode(MAX485_Driver_Output_Enable_PIN, OUTPUT);
digitalWrite(MAX485_Driver_Output_Enable_PIN, LOW);
pinMode(led_1_PIN, OUTPUT);
pinMode(led_2_PIN, OUTPUT);
pinMode(next_ID_button_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(next_ID_button_PIN), next_ID, RISING);
set_LEDs();
}
void loop() // run over and over
{
byte start_of_message = 0xDB;
byte incoming_byte;
byte message[MESSAGELENGTH];
while (true)
{
if (software_serial.available())
{
incoming_byte = software_serial.read();
if (incoming_byte == start_of_message)
{
software_serial.readBytes(message, MESSAGELENGTH);
process_message(message);
}
}
}
}
void process_message(byte message[])
{
byte system_ID = IDs[state];
byte incoming_ID = message[0];
byte incoming_mode = message[1];
byte LED_brightness = message[2];
if (incoming_ID == system_ID)
{
byte pin;
if (incoming_mode == 0)
{
pin = led_1_PIN;
}
else if (incoming_mode == 1)
{
pin = led_2_PIN;
}
analogWrite(pin, LED_brightness);
}
}
void next_ID()
{
time = millis();
//soft debounce
if (time - oldtime > 200)
{
oldtime = time;
state++;
if (state >= (NUMSTATES))
{
state = 0;
}
}
set_LEDs();
}
void set_LEDs()
{
for (int index = 0; index < NUMSTATES; index++)
{
if (index == state)
{
digitalWrite(states[index], HIGH);
}
else
{
digitalWrite(states[index], LOW);
}
}
}