stm32f103c8t6驱动tm1638
时间: 2023-08-25 10:07:44 浏览: 112
STM32F103C8T6 TM1638芯片驱动文件
要驱动TM1638,您需要使用STM32F103C8T6的GPIO和SPI接口。首先,您需要将TM1638的CLK、STB和DIO引脚连接到STM32F103C8T6的GPIO引脚上,然后将TM1638的CS引脚连接到STM32F103C8T6的SPI CS引脚上。接下来,您需要编写STM32的代码来控制TM1638。
以下是一个简单的代码示例:
```c
#include "stm32f10x.h"
void TM1638_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_6 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
SPI_InitTypeDef SPI_InitStructure;
SPI_InitStructure.SPI_Direction = SPI_Direction_1Line_Tx;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Cmd(SPI1, ENABLE);
TM1638_SendCommand(0x8F);
TM1638_SendCommand(0x40);
TM1638_SendCommand(0xC0);
}
void TM1638_SendCommand(uint8_t command)
{
GPIO_ResetBits(GPIOA, GPIO_Pin_4);
SPI_I2S_SendData(SPI1, command);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) == SET);
GPIO_SetBits(GPIOA, GPIO_Pin_4);
}
void TM1638_SendData(uint8_t address, uint8_t data)
{
TM1638_SendCommand(0x44);
GPIO_ResetBits(GPIOA, GPIO_Pin_4);
SPI_I2S_SendData(SPI1, 0xC0 | address);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) == SET);
SPI_I2S_SendData(SPI1, data);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) == SET);
GPIO_SetBits(GPIOA, GPIO_Pin_4);
}
int main(void)
{
TM1638_Init();
while (1)
{
TM1638_SendData(0x00, 0x01);
delay_ms(1000);
TM1638_SendData(0x00, 0x00);
delay_ms(1000);
}
}
```
在这个代码中,TM1638_SendCommand()用于发送TM1638的命令,TM1638_SendData()用于发送TM1638的数据。在main()函数中,我们不停地向TM1638发送数据以使其灯光闪烁。
需要注意的是,本代码只是一个简单的示例,您可能需要根据您的具体情况进行修改。同时,您需要自行实现delay_ms()函数,用于延时。
阅读全文