MECH 3032 Arduino - LED Finite State Machine Part 1: LED Finite State Machine, Random States Arduino Code
MECH 3032 Arduino - LED Finite State Machine Part 1: LED Finite State Machine, Random States Arduino Code
void setup() {
// put your setup code here, to run once:
// set up LED pins as output
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
//wait for 1 sec
delay(1000);
//pick random value between 0 and 3
current_state = random(0, 4);
//print on the serial monitor random varibale
Serial.println(current_state);
//check the state change variable and change its state due to input variable
switch(current_state)
{
//state S0 and switches OFF all LEDs
case S0:
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
break;
//state S1 and switches OFF 2 LEDs and switch ON 1 LED
case S1:
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, HIGH);
break;
//state S2 and switch ON 2 LEDs and switch OFF 1 LED
case S2:
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, HIGH);
break;
//state S3 and switches ON all LEDs
case S3:
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, HIGH);
break;
}
}
void setup() {
//Setting up Baud rate
Serial.begin(9600);
// put your setup code here, to run once:
//Setting up LED pins as output
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
}
void loop() {
//check if data is being sent through Serial
if (Serial.available() > 0)
{
//store its value in this variable
current_state = Serial.read();
//check if the value is different from previous value then print on Serial monitor
if (current_state != prev_state){
Serial.println("State is change. New state is:");
Serial.println(current_state);
}
//update previous stae vaalue
prev_state = current_state;