Maple Lesson 03 - Button switch control LED
ContentsObjectiveThe first two experiments showed you how to use software to control the LED directly. If we add a button, to control the LED light, then realize the combination of hardware and software. Actually that two experiment use Microduino I/O port as the output to control the LED, if want to use the button, how to monitor the input signal of the button? Today we will take button as an example to show how to use the Microduino-CoreSTM32 as the input. EquipmentMicroduino-CoreSTM32 is an ARM development board using STM32F103CBT6 chip. It use special Upin7 interface, the size is similar with a coin and fully compatible other Microduino modules.
SchematicUse the pulldown resistor to connect the button, that is connect a resistor between I/O port and GND, then connect the button to VCC, so no press the button, the input value is 0, if press the button, input value is 1. Then we can use the input value to control the LED. Of course, we also can use the pull-up resistor. Debug
Click File -> Examples ->Digital ->Button: void setup() {
// Initialize the built-in LED pin as an output:
pinMode(BOARD_LED_PIN, OUTPUT);
// Initialize the built-in button (labeled BUT) as an input:
pinMode(BOARD_BUTTON_PIN, INPUT);
}
void loop() {
// Check if the button is pressed.
if (isButtonPressed()) {
// If so, turn the LED from on to off, or from off to on:
toggleLED();
}
} Program description: Firstly define LED pin as output and button as input.
If loosen the button, then return true, and run toggleLED() function to switch the value. If the pin is high, then change to low voltage, otherwise set to high voltage. Click the "Upload" to download the program to board.
Connect the module, copy the program to compile and then download the program. int buttonPin = 2; // Define button input pin
int ledPin = 13; //Define LED pin
int buttonState = 0; //Initialize the button value
void setup() {
pinMode(ledPin, OUTPUT); //Set the LED pin as output
pinMode(buttonPin, INPUT); //Set button pin as input
}
void loop(){
buttonState = digitalRead(buttonPin);//Read the value from the button Pin
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); //If the button input signal is high, the LED will light (LED connect method is that anode connects control pin, cathode connects GND)
}
else {
digitalWrite(ledPin, LOW); //LED goes out
}
} Grammar specification:
We will use another method, change “pinMode(buttonPin, INPUT);” to “pinMode(buttonPin, INPUT_PULLDOWN);”.
Video |