|
用模塊廠(chǎng)家資料+豆包+自己修改生成的STC89C51單片機(jī)+TM1652 5位LED二鍵增減計(jì)數(shù)器,實(shí)際調(diào)試OK,獻(xiàn)給大家。
//51單片機(jī)+TM1652二按鍵增減計(jì)數(shù)5位LED顯示C代碼//
//普通顯示,無(wú)中斷,調(diào)試OK
#include "REG51.h"
unsigned char KEY_NUM = 0;
typedef unsigned char u8;
typedef unsigned int u16;
u16 count = 0; //按鍵計(jì)數(shù)值
sbit up = P3^6; //增加按鍵
sbit down = P3^7; //減少按鍵
sbit D_out = P0^0; //模擬UART數(shù)據(jù)輸出端,連接TM1652數(shù)據(jù)輸入端D_in
const u8 CODE[16] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71}; //共陰數(shù)碼管0~F字型碼
void Delay52us() //@11.0592MHz
{
unsigned char i;
i = 21;
while (--i);
}
void Delay5ms() //@11.0592MHz
{
unsigned char i, j;
i = 9;
j = 244;
do
{
while (--j);
} while (--i);
}
void Delay104us() //@11.0592MHz
{
unsigned char i;
i = 45;
while (--i);
}
void tm1652_send_data(u8 sdat) //向TM1652發(fā)送數(shù)據(jù)
{
unsigned char i = 0, sfalg = 0;
//起始位
D_out = 0;
Delay52us(); //保持52us
//發(fā)送8位數(shù)據(jù)
for (i = 0; i < 8; i++)
{
if (sdat & 0x01)
{
D_out = 1;
sfalg++;
}
else
{
D_out = 0;
}
Delay52us();
sdat >>= 1;
}
//校驗(yàn)位,按照發(fā)送數(shù)據(jù)中1的個(gè)數(shù)來(lái)判斷
if (sfalg % 2 == 0)
{
D_out = 1;
}
else
{
D_out = 0;
}
Delay52us();
//停止位
D_out = 1;
Delay104us();
}
void TM_Digtal_Display(u16 num)
{
tm1652_send_data(0x08);
// 確保能正確顯示五位數(shù)
tm1652_send_data(CODE[num / 10000]);
tm1652_send_data(CODE[num % 10000 / 1000]);
tm1652_send_data(CODE[num % 1000 / 100]);
tm1652_send_data(CODE[num % 100 / 10]);
tm1652_send_data(CODE[num % 10]);
Delay5ms();
tm1652_send_data(0x18); //向TM1652發(fā)送顯示控制命令
tm1652_send_data(0xFE); //設(shè)置位占空比為 15/16,設(shè)置段驅(qū)動(dòng)電流為 8/8,最大亮度。
}
// 延時(shí)函數(shù),用于按鍵消抖
void delay(unsigned int time)
{
unsigned int i, j;
for (i = 0; i < time; i++)
for (j = 0; j < 123; j++);
}
//主函數(shù)
void main()
{
u16 delaytick = 0;
// 開(kāi)機(jī)顯示00000
TM_Digtal_Display(0);
while (1)
{
// 檢測(cè)上按鍵是否按下
if (up == 0) {
delay(20); // 消抖
if (up == 0)
{
if (count < 99999) {
count++;
}
while (up == 0) {
delay(10); // 持續(xù)檢測(cè)按鍵釋放,避免重復(fù)觸發(fā)
}
delay(20); // 釋放后再次消抖
}
}
// 檢測(cè)下按鍵是否按下
if (down == 0) {
delay(20); // 消抖
if (down == 0) {
if (count > 0) {
count--;
}
while (down == 0)
{
delay(10); // 持續(xù)檢測(cè)按鍵釋放,避免重復(fù)觸發(fā)
}
delay(20); // 釋放后再次消抖
}
}
if (++delaytick == 50) // 提高顯示刷新頻率
{
delaytick = 0;
TM_Digtal_Display(count);
}
Delay5ms();
}
}
|
評(píng)分
-
查看全部評(píng)分
|