Programming Blue Pill (STM32F103C8T6) to control a LED with a push button is simple using Arduino programming language with the STM32 Blue Pill microcontroller board. Here it is shown how to connect a push button to control a LED both of which are connected to the Blue Pill STM32 microcontroller board.
This is 2nd part of the Blue Pill tutorial, see the 1st part: Simulation of Bluepill (STM32F103C8T6) LED blinking circuit in Proteus.
Below is circuit diagram that shows a push button connected at PB8 pin and a LED connected to PC13 pin of the Blue Pill board.
The program code for controlling the LED using a push button both of which are connected to STM32 blue pill board is below.
const int buttonPin = PB8;
const int ledPin = PC13;
int lastButtonState = HIGH;
int ledState = HIGH;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(ledPin, ledState);
}
void loop() {
int currentButtonState = digitalRead(buttonPin);
// Check for button press (transition from HIGH to LOW)
if (lastButtonState == HIGH && currentButtonState == LOW) {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState);
delay(50); // Debounce delay
}
lastButtonState = currentButtonState;
}
This code configures pin
PB8 as an input with an internal pull-up resistor and pin PC13 as an output, continuously monitoring the button on PB8 to toggle the active-LOW onboard LED on pin PC13 every time a button press is detected. When the button is unpressed, PB8 reads HIGH, but pressing it connects the pin to ground, driving it LOW; the program detects this transition (a falling edge) by comparing lastButtonState with currentButtonState. Upon detecting a valid press, it flips ledState (HIGH to LOW or vice versa), updates the physical LED state via digitalWrite, and executes a delay(50) pause to debounce mechanical contact chatter before updating lastButtonState for the next loop iteration.