aboutsummaryrefslogtreecommitdiff
path: root/02-usart/src/core/gpio.c
blob: c46b1ff9da03c003c3eca4bcb1c32f6240ec8f71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "core/gpio.h"
#include "core/rcc.h"

/*
 * Sets the mode of a pin on a gpio por.
 */
void set_gpio_pin_mode(
    __IO gpio_port_t* gpio_port, gpio_pin_t pin, gpio_pin_mode_t mode)
{
  /* Each pin has a 2-bit mode provided at bits pin#*2 and pin#*2+1 */
  gpio_port->mode_r &= ~(0x03 << pin * 2);
  gpio_port->mode_r |= mode << pin * 2;
}

gpio_output_pin_t set_gpio_pin_output(
    __IO gpio_port_t* gpio_port, gpio_pin_t pin)
{
  set_gpio_pin_mode(gpio_port, pin, MODE_OUTPUT);

  return (gpio_output_pin_t){.gpio_port = gpio_port, .pin = pin};
}

void set_gpio_output_pin(gpio_output_pin_t pin, bool onoff)
{
  if (onoff) {
    pin.gpio_port->output_r |= 1 << pin.pin;
  } else {
    pin.gpio_port->output_r &= ~(1 << pin.pin);
  }
}

void set_gpio_alternate_function(
    __IO gpio_port_t* port, gpio_pin_t gpio_pin, alternate_function_t afn)
{
  __IO uint32_t* reg;
  if (gpio_pin < 8) {
    reg = &(port->af_rl);
  } else {
    reg = &(port->af_rh);
    gpio_pin -= 8;
  }

  uint32_t tmp = *reg & (~0x0f << gpio_pin * 4);
  *reg = tmp | (afn << gpio_pin * 4);
}

#define GPIO_PORTS_BASE_ADDR ((uint8_t*)0x48000000)
__IO gpio_port_t* enable_gpio(gpio_port_number_t gpio_port_number)
{
  RCC.ahb2en_r |= 1 << gpio_port_number; /* Enable the GPIO port. */
  return (__IO gpio_port_t*)(GPIO_PORTS_BASE_ADDR + (gpio_port_number * 0x400));
}