用SPI 写个例程 基于GD32F103ZET6
时间: 2023-07-04 10:28:04 浏览: 107
STM32F103ZET6 例程
3星 · 编辑精心推荐
好的,基于GD32F103ZET6的SPI读取TLE5012B温度寄存器的例程如下:
```c
#include "gd32f10x.h"
#define TLE5012B_CS_PIN GPIO_PIN_4
#define TLE5012B_CS_PORT GPIOB
#define SPI_DEV SPI1
void SPI_Configuration(void)
{
spi_parameter_struct spi_init_struct;
/* enable SPI1 clock */
rcu_periph_clock_enable(RCU_SPI1);
/* SPI1 configurate */
spi_i2s_deinit(SPI_DEV);
spi_init_struct.device_mode = SPI_MASTER;
spi_init_struct.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
spi_init_struct.frame_size = SPI_FRAMESIZE_8BIT;
spi_init_struct.nss = SPI_NSS_SOFT;
spi_init_struct.master_nss = SPI_MASTER_KEEPNSS;
spi_init_struct.prescale = SPI_PSC_16;
spi_init_struct.endian = SPI_ENDIAN_MSB;
spi_init(SPI_DEV, &spi_init_struct);
/* enable SPI1 */
spi_enable(SPI_DEV);
}
void GPIO_Configuration(void)
{
/* enable GPIOB clock */
rcu_periph_clock_enable(RCU_GPIOB);
/* configure GPIOB.4 as output push-pull */
gpio_init(TLE5012B_CS_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, TLE5012B_CS_PIN);
}
void TLE5012B_Read_Temperature(void)
{
uint8_t tx_buf[2], rx_buf[2];
uint16_t temperature;
/* configure TLE5012B chip select pin as low */
gpio_bit_reset(TLE5012B_CS_PORT, TLE5012B_CS_PIN);
/* send read temperature command to TLE5012B */
tx_buf[0] = 0x05 | 0x80;
tx_buf[1] = 0x00;
spi_i2s_data_transmit(SPI_DEV, tx_buf[0]);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_TBE) == RESET);
spi_i2s_data_transmit(SPI_DEV, tx_buf[1]);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_TBE) == RESET);
/* read temperature value from TLE5012B */
spi_i2s_data_transmit(SPI_DEV, 0x00);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_TBE) == RESET);
spi_i2s_data_transmit(SPI_DEV, 0x00);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_TBE) == RESET);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_RBNE) == RESET);
rx_buf[0] = spi_i2s_data_receive(SPI_DEV);
while(spi_i2s_flag_get(SPI_DEV, SPI_FLAG_RBNE) == RESET);
rx_buf[1] = spi_i2s_data_receive(SPI_DEV);
/* configure TLE5012B chip select pin as high */
gpio_bit_set(TLE5012B_CS_PORT, TLE5012B_CS_PIN);
/* calculate temperature value */
temperature = (rx_buf[0] << 8) | rx_buf[1];
temperature = temperature & 0x0FFF;
temperature = ((temperature * 165) / 4096) - 40;
/* print temperature value */
printf("TLE5012B temperature: %d\n", temperature);
}
int main(void)
{
/* configure SPI and GPIO */
SPI_Configuration();
GPIO_Configuration();
/* read temperature value from TLE5012B */
TLE5012B_Read_Temperature();
while(1);
}
```
在这个例程中,我们首先通过调用`SPI_Configuration()`函数配置了SPI接口,然后通过调用`GPIO_Configuration()`函数配置了TLE5012B的片选引脚。接着,我们调用`TLE5012B_Read_Temperature()`函数从TLE5012B中读取温度值。在这个函数中,我们先向TLE5012B发送了读取温度寄存器的命令,然后从TLE5012B中读取了温度值并计算出了真实的温度值。最后,我们通过调用`printf()`函数将温度值打印到终端上。
需要注意的是,这个例程中的SPI操作是基于GD32F103ZET6的标准库实现的,如果您使用的是其他的MCU或者不同的开发环境,可能需要进行一些修改。同时,为了使得这个例程能够正常工作,您还需要将`printf()`函数和串口相关的配置添加到代码中。
阅读全文