2 GPIO Programming
2 GPIO Programming
com
BIHE university
GPIO Programming
STM32
NRST NRST NRST
47 Reset Reset
35
VSS_3 Button Button
23
VSS_2
VSS_1
8
VSSA
PLLMUL 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Multiplication X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16
3.3V STM32F103
48 VDD_3 20pF
36 OSC_OUT
6
Vcc VDD_2
24 VDD_1
8MHz
9
VDDA 5
OSC_IN
10K
20pF
7
NRST
20pF
OSC32_OUT
4
47
VSS_3
Reset 35
Button VSS_2 32.768KHz
23
VSS_1 3
8 OSC32_IN
VSSA
20pF
• PORTA (PAn)
• PORTB (PBn)
• PORTC (PCn)
• PORTD
RAM Timers
PROGRAM
ROM
Program
Bus Bus
CPU
Interrupt Other
OSC I/O Port
Unit Peripherals
I/O
PINS
Output (MODE>00)
CNFx bits MODEx bits Direction Max speed
00 General purpose output push-pull 00 Input
01 General purpose output Open-drain 01 10 MHz
10 Alternate function output Push-pull 10 Output 2 MHz
11 Alternate function output Open-drain 11 50 MHz
Input (MODE=00)
CNFx bits Configuration Description
00 Analog mode Select this mode when you use a pin as an ADC
input.
01 Floating input In this mode, the pin is high-impedance.
10 Input with pull- The value of ODR chooses if the pull-up or pull-
up/pull-down down resistor is enabled. (1: pull-up, 0:pull-down)
11 reserved
GPIOx->ODR: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
GPIOx->IDR: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Px15 Px14 Px13 Px12 Px11 Px10 Px9 Px8 Px7 Px6 Px5 Px4 Px3 Px2 Px1 Px0
#include "stm32f10x.h“
void delay_ms(uint16_t t) {
volatile unsigned long l = 0;
for(uint16_t i = 0; i < t; i++)
for(l = 0; l < 6000; l++)
{ }
}
int main() {
RCC->APB2ENR |= 0xFC; //Enable the clocks for GPIO ports
while(1) {
GPIOA->ODR = 0x0000; //make all the pins of Port A low
delay_ms(1000); //wait 1000ms
GPIOA->ODR = 0xFFFF; //make all the pins of Port A high
delay_ms(1000); //wait 1000ms
}
}
#include <stm32f10x.h>
int main()
{
RCC->APB2ENR |= 0xFC; //Enable GPIO ports clocks
while(1)
{
GPIOC->ODR ^= (1<<13); //toggle PC13
delay_ms(1000);
}
}
• The following code gets the data present at the pins of port A and
sends it to port B indefinitely, after adding the value 5 to it:
#include <stm32f10x.h>
int main()
{
RCC->APB2ENR |= 0xFC; /* Enable GPIO ports clocks */
while(1)
{
GPIOA->ODR = GPIOB->IDR + 5;
/* read from port B and write to port A */
}
}
10K
while(1) {
if((GPIOB->IDR & (1<<10)) != 0) /* is PB10 high */
GPIOC->ODR |= (1 << 13); /* make PC13 high */
else
GPIOC->ODR &= ~(1 << 13); /* make PC13 low */
}
}
bit n of ODR
In CRH:CRL Pin n
0x4 = input bit n of IDR of port
(no pull-up/down)
0x8 = input with
pull-up/down
STM32F103
BIHE university
STM32F103
BIHE university
while(1) {
if((GPIOA->IDR&(1<<2)) == 0) /* is PA2 low? */
GPIOC->ODR ^= (1<<13); /* toggle PC13 */
else
GPIOC->ODR &= ~(1<<13);
delay_ms(500);
}
}
• Examples:
– GPIOB->BRR = 1<<5; //make PB5 low
– GPIOA->BRR = (1<<3)|(1<<5); /* make PA3 and
PA5 low */
• Examples:
– GPIOC->BSRR = (1<<5); //make PC5 high
– GPIOB->BSRR = (1<<5)|(1<<19); /*makes PB5
high and PB3 low */
IDR
BRR
BSRR
ODR