Here is the Arduino code you can use for your assignment based on the specified requirements:
// Definitions
const int LED11 = 11; // Pin for LED output
const int SW12 = 12; // Pin for pushbutton input
int sw_in; // Variable to store the state of the switch
void setup() {
// Configure LED11 as OUTPUT
pinMode(LED11, OUTPUT);
// Configure SW12 as INPUT with internal pull-up resistor
pinMode(SW12, INPUT_PULLUP);
// Initialize serial communication
Serial.begin(9600);
}
void loop() {
// Read the pushbutton switch
sw_in = digitalRead(SW12);
// If the value read is 0 (button pressed), turn on the LED
if (sw_in == LOW) {
digitalWrite(LED11, HIGH);
}
// If the value read is 1 (button released), turn off the LED
else {
digitalWrite(LED11, LOW);
}
// Print the values of the pushbutton switch and the LED state to the serial console
Serial.print("Switch State: ");
Serial.print(sw_in);
Serial.print(" | LED State: ");
Serial.println(digitalRead(LED11));
// Small delay to avoid flooding the serial output
delay(100);
}
Explanation:
-
Definitions:
LED11
is defined for pin 11 and configured as OUTPUT.SW12
is defined for pin 12 and configured as INPUT with an internal pull-up resistor.sw_in
is an integer variable to hold the state of the switch.
-
Setup Function:
pinMode()
is used to set the mode of the LED and the switch.- Serial communication is initialized for debugging.
-
Loop Function:
- Reads the state of the pushbutton switch.
- If the switch is pressed (LOW), the LED is turned on (HIGH).
- If the switch is not pressed (HIGH), the LED is turned off (LOW).
- Outputs the current state of the switch and the LED to the serial console.
- A delay of 100 milliseconds is added to prevent excessive serial output.
Make sure to upload this code to your Arduino and check the serial monitor to see the output states as specified.