#include <Arduino.h>
//used 220 ohm resistors to limit current for LEDs
const int ledPins[] = {11, 12, 13}; //define the GPIO pins connected to LEDs
//division of the total size of LEDs array of size of a single element in the array
const int numLeds = sizeof(ledPins) / sizeof(ledPins[0]);
const int buttonPins[] = {5, 6, 7}; //define the GPIO pins connected to push-buttons
const int numButtons = sizeof(buttonPins) / sizeof(buttonPins[0]);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //serial communication
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW); //set LEDs to OFF
}
for (int i = 0; i < numButtons; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); //internal pull-up resistors, pins are input
}
}
void loop() {
// put your main code here, to run repeatedly:
//reads the state of push-buttons
for (int i = 0; i < numButtons; i++) {
int buttonState = digitalRead(buttonPins[i]);
Serial.print("Button ");
Serial.print(i);
Serial.print(": ");
Serial.println(buttonState);
delay(500);//500 ms delay for button state so we can see the button readings
}
while (Serial.available() > 0) {
char command = Serial.read();
if (command == '0' || command == '1' || command == '2') {
int ledIndex = command - '0'; //converts command to integer ('0' to 0)
//toggle LED state, negates current LED state and turn it to high or low
digitalWrite(ledPins[ledIndex], !digitalRead(ledPins[ledIndex]));
} else if (command == 'A') {
//set all LEDs simultaneously
int newState = Serial.parseInt(); //read integer value from serial intput (1 to integer)
for (int i = 0; i < numLeds; i++) {
//sets state of LED associated with the pin number retrieved and turns on/off LED
digitalWrite(ledPins[i], newState);
}
} else if (command == 'G') {
//get all push-button states simultaneously
for (int i = 0; i < numButtons; i++) {
//reads the button state and GPIO pin for button and stores either high or low in button state
int buttonState = digitalRead(buttonPins[i]);
Serial.print("Button ");
Serial.print(i);
Serial.print(": ");
Serial.println(buttonState);
}
}
}
}