Lesson 3: Digital Read Serial
Lesson 3: Digital Read Serial
Lesson: Digital Read Serial
Objective: At the end of this lesson, you will be able to read the state of a push button and display it on the serial monitor using an Arduino board.
Materials Required:
- Arduino board
- Push button
- 10k-ohm resistor
- Jumper wires
- USB cable
Circuit Connections:
- Connect one terminal of the push button to digital pin 2 on the Arduino board.
- Connect the other terminal of the push button to the ground (GND) pin on the Arduino board.
- Connect a 10k-ohm resistor from digital pin 2 to the 5V pin on the Arduino board.
Arduino Code:
void setup() {
Serial.begin(9600); // Initialize the serial communication
pinMode(2, INPUT_PULLUP); // Set digital pin 2 as input with internal pull-up resistor
}
void loop() {
int buttonState = digitalRead(2); // Read the state of the push button
Serial.println(buttonState); // Print the state on the serial monitor
delay(100); // Delay for 0.1 seconds
}
Experiment Steps:
- Set up the circuit connections as described above.
- Connect the Arduino board to your computer using a USB cable.
- Open the Arduino IDE software and create a new sketch.
- Copy and paste the provided code into the Arduino IDE.
- Click the "Upload" button to upload the code to the Arduino board.
- Open the Serial Monitor by clicking the magnifying glass icon in the Arduino IDE toolbar.
- Ensure the baud rate in the Serial Monitor is set to 9600.
- Press and release the push button while observing the state (0 for pressed, 1 for released) displayed on the serial monitor.
Note: The internal pull-up resistor ensures that the digital pin reads a HIGH state when the push button is not pressed.
Explanation:
The Arduino code above uses the Serial.begin()
function to initialize the serial communication with a baud rate of 9600. The pinMode()
function is used to set digital pin 2 as an input with the internal pull-up resistor enabled. The digitalRead()
function is then used to read the state of the push button connected to pin 2. The obtained button state is printed on the serial monitor using the Serial.println()
function. The delay()
function introduces a delay of 100 milliseconds between readings.
By pressing and releasing the push button, you can observe the state changes on the serial monitor. When the button is pressed, the state will be 0, and when the button is released, the state will be 1.
Challenge: Can you modify the code to add a delay that prevents multiple rapid state changes from being registered? For example, introduce a delay of 500 milliseconds after a state change before reading the button state again.
Comments
Post a Comment