// tell the underlying compiler to use raw standard C
extern "C" {
// create a symbolic alias to point to the RCC_BASE register
// Reset and Clock Control block
#define RCC_BASE 0x40021000
// create a symbolic alias to point to the GPIOA_BASE register
// access to general purpose input/output pins and port A
#define GPIOA_BASE 0x50000000
// create a symbolic alias to point to the RCC_IOPENR register
// access to the input/output peripheral clock enable register
// bit 0 enables the clock for port A
#define RCC_IOPENR (*(volatile unsigned int *)(RCC_BASE + 0x34))
// create a symbolic alias to point to the GPIOA_MODER register
// basically pinMode
// bits 10 and 11 refer to PA5 (the onboard LED)
#define GPIOA_MODER (*(volatile unsigned int *)(GPIOA_BASE + 0x00))
// create a symbolic alias to point to the GPIOA_ODR register
// basically digitalWrite
// bit 5 refers to PA5 (the onboard LED)
#define GPIOA_ODR (*(volatile unsigned int *)(GPIOA_BASE + 0x14))
// create a symbolic alias to point to the GPIOA_PUPDR register
// enables the pull-up register for the pushbutton
#define GPIOA_PUPDR (*(volatile unsigned int *)(GPIOA_BASE + 0x0C))
// create a symbolic alias to point to the GPIOA_IDR register
// used to read the state of pins
#define GPIOA_IDR (*(volatile unsigned int *)(GPIOA_BASE + 0x10))
// entry point for the program
int main(void) {
// peripheral clock enable for port A (bit 0)
RCC_IOPENR |= (1 << 0);
// turn the pinMode for the LED to output
GPIOA_MODER &= ~(3 << (5 * 2));
GPIOA_MODER |= (1 << (5 * 2));
// turn the pinMode for the button to input
GPIOA_MODER &= ~(3 << (0 * 2));
// configure PA0 with an internal pull-up resistor
GPIOA_PUPDR &= ~(3 << (0 * 2));
GPIOA_PUPDR |= (1 << (0 * 2)); // 10 for pull-up resistor
// in a loop, read the button's pin (0)
while (1) {
// mask everything except bit 0 (which reads the state of the pin)
if ((GPIOA_IDR & (1 << 0)) == 0) {
// if 0, then it's connected to ground
// now turn the LED on
GPIOA_ODR |= (1 << 5);
} else {
GPIOA_ODR &= ~(1 << 5); // otherwise turn the LED off
}
}
}
}