使用Platformio平台的libopencm3开发框架来开发STM32G0,下面介绍SPI接口的基本使用。
1 SPI配置
以下为设置SPI1,引脚映射为PA567,使用软件控制CS-PA4;
1/* Enable SPI1 Periph and gpio clocks */
2 rcc_periph_clock_enable(RCC_SPI1);
3 rcc_periph_clock_enable(RCC_GPIOA);
4
5/* Configure GPIOs:
6 *
7 * SCK=PA5
8 * MOSI=PA7
9 * MISO=PA6
10 *
11 * for SD card
12 * SDCS PA4
13 */
14
15//MOSI & SCK & MISO
16gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE,GPIO5|GPIO7|GPIO6);
17gpio_set_af(GPIOA,GPIO_AF0,GPIO5|GPIO7|GPIO6);
18gpio_set_output_options(GPIOA, GPIO_OTYPE_PP,GPIO_OSPEED_LOW,GPIO5|GPIO7|GPIO6);
19
20//SDCS
21gpio_mode_setup(GPIOA,GPIO_MODE_OUTPUT,GPIO_PUPD_NONE,GPIO4);
22gpio_set(GPIOA,GPIO4);
23
24/* Reset SPI, SPI_CR1 register cleared, SPI is disabled */
25spi_reset(SPI1);
26
27/* Set up SPI in Master mode with:
28 * Clock baud rate
29 * Clock polarity
30 * Clock phase
31 * Frame format MSB
32 */
33spi_init_master(SPI1, SPI_CR1_BAUDRATE_FPCLK_DIV_128,
34 SPI_CR1_CPOL_CLK_TO_0_WHEN_IDLE,
35 SPI_CR1_CPHA_CLK_TRANSITION_1,
36 SPI_CR1_MSBFIRST);
37
38 spi_set_data_size(SPI1,SPI_CR2_DS_8BIT);
39 spi_set_full_duplex_mode(SPI1);
40
41/*
42 * Set NSS management to software.
43 *
44 * Note:
45 * Setting nss high is very important, even if we are controlling
46 * the GPIO
47 * ourselves this bit needs to be at least set to 1, otherwise the spi
48 * peripheral will not send any data out.
49 */
50spi_enable_software_slave_management(SPI1);
51spi_set_nss_high(SPI1);
52
53/* Enable SPI1 periph. */
54spi_enable(SPI1);
设置流程:打开外设时钟-> 设置SPI引脚 -> CS引脚 -> 配置SPI模式包括SPI速度、CPOLCPHA -> SPI传输数据位数 -> NSS配置 -> SPI使能;
2 SPI读写
写入后读取
1uint16_t spi_xfer(uint32_t spi, uint16_t data)
发送
1void spi_send(uint32_t spi, uint16_t data)
2
接收
1uint16_t spi_read(uint32_t spi)
对于8bit的发送和接收在STM32G0上,libopencm3库需要使用如下接口:
1spi_send8();
2spi_read8();
3 说明
默认配置的SPI时钟是连续的,波形如下:
在某些时候需要在帧之间有些空隙,可以设置CR2寄存器的NSSP位或者直接在发送前进行延时:
1SPI_CR2(SPI1) |= SPI_CR2_NSSP; //NSSP
波形如下:
相关文章