74HC595四位数码管显示stm32f103库代码共阳
时间: 2023-09-29 22:07:14 浏览: 120
STM32+2片74HC595驱动四位共阳极数码管
5星 · 资源好评率100%
以下是使用74HC595驱动共阳式4位数码管的STM32F103库代码:
```c
#include "stm32f10x.h"
//定义74HC595的引脚连接
#define HC595_PORT GPIOA
#define HC595_DS_PIN GPIO_Pin_0 // data pin
#define HC595_SHCP_PIN GPIO_Pin_1 // shift clock pin
#define HC595_STCP_PIN GPIO_Pin_2 // store clock pin
//定义数码管显示字符数组
const uint8_t num[10][8] = {
{1,1,1,1,1,1,0,0}, // 0
{0,1,1,0,0,0,0,0}, // 1
{1,1,0,1,1,0,1,0}, // 2
{1,1,1,1,0,0,1,0}, // 3
{0,1,1,0,0,1,1,0}, // 4
{1,0,1,1,0,1,1,0}, // 5
{1,0,1,1,1,1,1,0}, // 6
{1,1,1,0,0,0,0,0}, // 7
{1,1,1,1,1,1,1,0}, // 8
{1,1,1,1,0,1,1,0} // 9
};
//发送数据到74HC595
void HC595_SendData(uint8_t data) {
uint8_t i;
for (i = 0; i < 8; i++) {
if (data & 0x80) {
GPIO_SetBits(HC595_PORT, HC595_DS_PIN);
} else {
GPIO_ResetBits(HC595_PORT, HC595_DS_PIN);
}
GPIO_SetBits(HC595_PORT, HC595_SHCP_PIN);
GPIO_ResetBits(HC595_PORT, HC595_SHCP_PIN);
data <<= 1;
}
}
//锁存数据到74HC595
void HC595_LatchData(void) {
GPIO_SetBits(HC595_PORT, HC595_STCP_PIN);
GPIO_ResetBits(HC595_PORT, HC595_STCP_PIN);
}
//在数码管上显示一个数字
void DisplayNum(uint8_t num, uint8_t bit) {
uint8_t i;
for (i = 0; i < 8; i++) {
if (num[bit][i]) {
GPIO_SetBits(HC595_PORT, 1 << i);
} else {
GPIO_ResetBits(HC595_PORT, 1 << i);
}
}
HC595_LatchData();
}
int main(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = HC595_DS_PIN | HC595_SHCP_PIN | HC595_STCP_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(HC595_PORT, &GPIO_InitStructure);
while (1) {
//显示数字0-9
uint8_t i;
for (i = 0; i < 10; i++) {
DisplayNum(num, i);
delay_ms(1000);
}
}
}
```
请注意,此代码仅作为参考。您需要根据实际硬件连接和需求进行相应的修改和调整。
阅读全文