Bluepill - Button with LED - how it works

 Here Bluepill board which uses STM32F103C8T6 chip is simulated with button and a LED in proteus. Proteus is an excellent software to test microcontroller or microcontroller boards like Bluepill, Arduino, Teensy, Raspberry Pi. The bluebill is a popular micrcontroller board. 

The circuit is simple and is shown below.

Bluepill button and led

The push button is connected to pin PB8 and is grounded on the other side. We will be using the internal pullup resistor of the bluepill so no need for external pullup resistor. The LED is connected to PC13 pin and grounded via the 100k resistor. When the button is pressed the LED turns on.

The code for this 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;
}

The code begins by defining two constant variables: buttonPin as PB8 and ledPin as PC13, which simply give names to the physical pins so they can be easily referenced later. In the setup function, which runs once at startup, the ledPin is configured as an output using pinMode so it can control the LED, while the buttonPin is set as an input with an internal pull-up resistor enabled, meaning the pin will naturally read high (3.3 volts) when the button is not pressed because it is internally connected to positive voltage. The loop function then runs continuously, repeatedly checking the button's state with digitalRead. Since the internal pull-up makes the pin high when the button is open, pressing the button connects PB8 directly to ground, pulling the voltage down to low. The if statement checks for this low condition; when true, it uses digitalWrite to set ledPin to low, which turns the LED on because the built-in LED on PC13 is active low (current flows when the pin is at 0 volts). If the button is not pressed and digitalRead returns high, the else clause sets ledPin to high, turning the LED off. This creates a simple direct relationship where the LED stays lit only while you hold the button down, with the microcontroller constantly reading the button state and updating the LED accordingly many times per second.

Watch the simulation video to learn how it works.




Related

Post a Comment

Previous Post Next Post