硬件探索——STM32F4控制74HC595数码管

使用STM32F407VET6,通过串行方式驱动74HC595控制的4位数码管

使用了PD0(DIO)、PD1(RCLK)、PD2(SCLK)三个GPIO,将其与数码管模块对应连接

程序中使用了延时函数,需要包含系统滴答定时器延时函数使用的头文件delay.h

头文件smg.h

#ifndef __74HC595_H__
#define __74HC595_H__
#include "sys.h"

#define DIGIT_NUM 4

/*  SMG时钟端口、引脚定义 */
#define SMG_PORT             GPIOD
#define SMG_PIN             (GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2)
#define SMG_PORT_RCC         RCC_AHB1Periph_GPIOD

#define SMG_DIO  PDout(0)
#define SMG_RCLK PDout(1)
#define SMG_SCLK PDout(2)

void SMG_Init(void);
void SMG_Display(int num);
void LED4_Display(void);

#endif

源文件smg.c

#include "smg.h"
#include "delay.h"

u8 SMG_Code[] =
{
    // 0	 1	  2	   3	4	 5	  6	   7	8	 9	  A	   b	C    d	  E    F    -
    0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90, 0x8C, 0xBF, 0xC6, 0xA1, 0x86, 0xFF, 0xbf
};//段码

void SMG_Init()
{
    GPIO_InitTypeDef GPIO_InitStructure;//定义结构体变量

    RCC_AHB1PeriphClockCmd(SMG_PORT_RCC, ENABLE);

    GPIO_InitStructure.GPIO_Pin = SMG_PIN;             //要设置的IO口
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;      //普通输出模式
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;     //推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //100MHz
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;       //上拉
    GPIO_Init(SMG_PORT, &GPIO_InitStructure); 	       /* 初始化GPIO */

    GPIO_ResetBits(SMG_PORT, SMG_PIN);  //将数码管端口拉高
}

void SMG_Output(u8 data)
{
    u8 i;
    for (i = 0; i < 8; i++)
    {
        if (data & 0x80)//按位与,先发送高位
        {
            SMG_DIO = 1;
        }
        else
        {
            SMG_DIO = 0;
        }
        data <<= 1;
        SMG_SCLK = 0;
        SMG_SCLK = 1; //产生一个上升沿
    }
}

void SMG_Display(int num)
{
    u8 digit[DIGIT_NUM], i, j;
    
    //将传入的数字转换为数组的元素
    for (i = 1; i <= DIGIT_NUM; i++)
    {
        digit[DIGIT_NUM - i] = num % 10;
        num /= 10;
    }
    
    for (j = i = 1; i <= DIGIT_NUM; i++, j *= 2)
    {
        SMG_Output(SMG_Code[digit[DIGIT_NUM - i]]); //发送显示数据
        SMG_Output(j);                              //发送显示位数
        SMG_RCLK = 0;
        SMG_RCLK = 1; //产生一个上升沿
        delay_ms(2);  //保持一定时间,否则数码管亮度较低
    }
}

使用实例如下:

int main()
{
    int Clock_MHz;
    float prev_roll;
    /*定义一个RCC_ClocksTypeDef类型的结构体*/
    RCC_ClocksTypeDef  RCC_Clock;
    /*调用RCC_GetClocksFreq获取系统时钟状态*/
    RCC_GetClocksFreq(&RCC_Clock);
    Clock_MHz = RCC_Clock.SYSCLK_Frequency / 1000 / 1000;

    uart1_init(460800);
    delay_init(Clock_MHz);

    SMG_Init();
    while (1)
    {
        SMG_Display(2021);
    }
}

 效果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值