In the previous tutorial, we learned how to use Arduino to control an LED light. In this tutorial, we will build upon that by adding a button to control the LED light. For this, we need:
– A push button switch
– A 10K ohm resistor
– Some jumper wires
– A breadboard
If you want to use an external LED, you will also need the materials mentioned in the previous tutorial (Tutorial 2).
Now, connect these components to the breadboard as follows:
The working principle of this circuit is as follows:
When the switch is not closed, meaning it is not pressed, the 5V circuit is disconnected from Arduino’s pin 2, and pin 2 is connected to ground, so the input received by Arduino from pin 2 is LOW.
When the switch is closed, pin 2 connects to 5V, causing Arduino to receive a HIGH input. Through programming, we can control the LED light based on the input changes received by Arduino.
The code is as follows:
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
Breaking down the code line by line, its function is as follows:
Store the two interface values used by this code in constants
const int buttonPin = 2;
const int ledPin = 13;
Store the state of the switch in the buttonState variable
int buttonState = 0;
Set the LED interface as an output; set the switch interface as an input
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
Use the digitalRead function to check the switch state
buttonState = digitalRead(buttonPin);
If the switch is pressed, then…
if (buttonState == HIGH) {
Turn on the LED light
digitalWrite(ledPin, HIGH);
If it is in another state (the switch is not pressed)…
} else {
Turn off the LED light
digitalWrite(ledPin, LOW);
Friends who have studied electronic circuits should understand that when a physical switch is opened or closed, a phenomenon called switch bouncing occurs. Each time a switch changes state, this circuit experiences an unstable state for several milliseconds. As shown in the image below, this state manifests as the circuit repeatedly “bouncing” between the on and off states. When a circuit’s information is received by a digital system, as in our case with Arduino, this bouncing can easily be misinterpreted as the button being switched on and off rapidly, leading to erroneous program execution.
To avoid this situation, we can implement a debounce switch in the code. This debounce switch will check the switch state multiple times in quick succession to confirm whether the switch is truly in the on or off state.
This piece of code is as follows:
const int buttonPin = 2;
const int ledPin = 13;
int ledState = HIGH;
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() – lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState);
lastButtonState = reading;
}
Breaking down the code line by line, its function is as follows:
Set the initial state of the LED to on, and the switch state to not closed
int ledState = HIGH;
int buttonState;
int lastButtonState = LOW;
Initialize a debounce initial time
unsigned long lastDebounceTime = 0;
Set the interval for repeated checks to 50 milliseconds
unsigned long debounceDelay = 50;
Store the switch state in the reading variable
int reading = digitalRead(buttonPin);
If the currently read switch state does not match the last read state…
if (reading != lastButtonState) {
Save the current time as the debounce initial time
lastDebounceTime = millis();
If the current time minus the debounce initial time exceeds the detection interval…
if ((millis() – lastDebounceTime) > debounceDelay) {
And if the switch state has changed…
if (reading != buttonState) {
Save the newly detected switch state
buttonState = reading;
If the switch is pressed…
if (buttonState == HIGH) {
Change the LED state (from on to off / off to on)
ledState = !ledState;
Write this change to the LED light
digitalWrite(ledPin, ledState);
Save the read switch state for the next iteration of the loop to make judgments
lastButtonState = reading;
Thus, we can create a very simple light using Arduino. With this code, every time we press the switch, the LED will light up until we press it again, at which point the LED will turn off.
—————-END——————-
More Exciting Content
* Mass production in Q4 this year! Yushu releases H1 universal humanoid robot equipped with high-torque, high-explosive M107 joint motor
* Tesla’s “Optimus” can do everything from watering flowers to yoga, motion capture makes robots more human-like
* Awarded SNSF support, the second-generation crocodile bionic robot Krock has made new research progress
* Yushu has released new products again, 3.6 times faster than Boston Dynamics, with a speed of up to 6m/s, the fastest quadruped robot B2 is here
* Latest research from Science Robotics: Flexible spine enhances the mobility of mouse robots!
* What did major companies like Xiaomi, Midea, Estun, and Jingpin Special Equipment say? Review of the Fourth Annual Meeting of the Chinese Robotics Industry
* 18 awards and 3 major lists announced! The 2023 Leaderobot China Robotics Industry Awards Ceremony!
* What majors have a promising future in the field of robotics?
* Ark Infinite X5, the key node connecting AI and the real robot world
* The first domestic high-dynamic humanoid robot has been mass-produced and delivered! The era of domestic production is approaching
* Is there a robot that can autonomously build houses?
* Leading AGV company, with BYD as the largest customer, Jike shares rose 256.25% after listing on the Beijing Stock Exchange
* Breaking news! The Beihang team has made new progress in the perception and environmental interaction of soft continuum robots in Science Robotics
* Patent numbers have increased 25 times in 8 years, from catching up to leading, China’s humanoid robots have entered a “golden period” of development
* “53.45% compound annual growth rate?” Let’s hear the views of 18 foreign perspectives on China’s humanoid robot new policies
* China’s humanoid robots are sparking a prairie fire, looking forward to the year of full-scale production
* Blood and soul cast the army’s soul, scientific research for the country’s needs! Congratulations to Professor Tang Peifu of the PLA General Hospital for being elected as an academician of the Chinese Academy of Engineering!
* Contributing outstandingly in the high-end equipment field, congratulations to Professor Chen Xuedong of Huazhong University of Science and Technology for being elected as an academician of the Chinese Academy of Engineering!
* Congratulations to Professor Yu Haibin, a well-known expert in Chinese robotics, for being elected as an academician! Promoting industrial development with innovative scientific and technological achievements
* Robot remote control system: A multiplier of human power
Join the Community
Welcome to join the 【Robot Lecture Hall】 reader discussion group, to discuss topics related to the field of robotics together, sharing cutting-edge technology and industry dynamics.
Discussion groups on educational robots, medical robots, legged robots, industrial robots, service robots, special robots, drones, soft robots, etc. are currently recruiting. Follow the Robot Lecture Hall WeChat public account and send ” Group Chat ” to get the way to join!
Recruiting Authors
The Robot Lecture Hall is recruiting 【part-time content creators】. If you are interested in writing articles related to robotics 【technology】 or 【industry】, you can send your resume and original works to the email: [email protected]
We have no requirements for profession, location, etc. Friends are welcome to join us!
Feeling tired? Click “Like” to support us!