使用stm32f103r6通过74hc595控制一位led数码管从0到9循环显示并且使用spi方式通讯 写出keil代码
时间: 2024-02-03 15:12:14 浏览: 86
以下是使用STM32F103R6和74HC595控制数码管并使用SPI通讯的Keil代码:
```c
#include "stm32f10x.h"
#define CS_PIN GPIO_Pin_4
#define CS_PORT GPIOA
#define MOSI_PIN GPIO_Pin_7
#define MOSI_PORT GPIOA
#define SCK_PIN GPIO_Pin_5
#define SCK_PORT GPIOA
void delay_ms(uint32_t ms)
{
uint32_t i;
for(i = 0; i < ms; i++)
{
uint32_t j;
for(j = 0; j < 7200; j++);
}
}
void spi_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
/* Enable SPI1 and GPIOA clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1 | RCC_APB2Periph_GPIOA, ENABLE);
/* Configure SPI MOSI, SCK and CS pins */
GPIO_InitStructure.GPIO_Pin = MOSI_PIN | SCK_PIN | CS_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure SPI1 */
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_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
/* Enable SPI1 */
SPI_Cmd(SPI1, ENABLE);
}
void spi_write(uint8_t data)
{
/* Enable CS */
GPIO_ResetBits(CS_PORT, CS_PIN);
/* Write data */
SPI_I2S_SendData(SPI1, data);
/* Wait for transmission to complete */
while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_BSY) == SET);
/* Disable CS */
GPIO_SetBits(CS_PORT, CS_PIN);
}
void shift_out(uint8_t data)
{
uint8_t i;
for(i = 0; i < 8; i++)
{
GPIO_ResetBits(SCK_PORT, SCK_PIN);
GPIO_WriteBit(MOSI_PORT, MOSI_PIN, (data & (1 << (7 - i))) ? Bit_SET : Bit_RESET);
GPIO_SetBits(SCK_PORT, SCK_PIN);
}
}
void digit_display(uint8_t digit)
{
static uint8_t digits[] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};
/* Set shift register to output mode */
spi_write(0x09);
/* Shift out digit pattern */
shift_out(digits[digit]);
/* Latch data to outputs */
spi_write(0x0C);
}
int main(void)
{
uint8_t i;
/* Initialize SPI and delay */
spi_init();
delay_ms(50);
while(1)
{
/* Loop from 0 to 9 */
for(i = 0; i < 10; i++)
{
digit_display(i);
delay_ms(1000);
}
}
}
```
该代码中,使用SPI1控制74HC595芯片,并使用GPIO控制74HC595的串行数据输入(MOSI)和时钟(SCK)线。在digit_display函数中,将要显示的数字转换为相应的数码管模式,并将其写入74HC595芯片。然后使用spi_write函数以SPI方式将数据写入74HC595芯片。
阅读全文