提供一個正整數的數碼管解決方案,供參考。- /*
- 本程序是在數碼管上顯示正整數的例程,顯示數字長度不超過8位(需要定義無符號長整型變量)
- */
- #include <reg52.h>
- #include <math.h>
- #include <stdlib.h>
- #include <stdio.h>
- typedef unsigned char uint8; //8位無符號型
- typedef unsigned char uchar; //8位無符號型
- typedef unsigned int uint16;
- typedef unsigned long uint32;
- #define DATA P0
- sbit KEY_S2 = P3^0; //S2獨立按鍵
- sbit KEY_S3 = P3^1; //S3獨立按鍵
- sbit seg_sel = P2^6;
- sbit bit_sel = P2^7;
- //共陰極數碼管0-9編碼
- uchar code seg_tab[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
- uchar code bit_tab[] = {0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};
- //將要被顯示的數字(只要不是大于8位的正整數均可)
- uint32 birthday = 508;
- //用于保存數字對應數碼管編碼的數組
- uchar num_code[8] = {0};
- void delay(uint16 num)
- {
- uint16 x,y;
- for(x=num; x>0; x--) for(y=110; y>0; y--){}
- }
- //拆分整數到num_code數組
- void int2code(uint32 inum)
- {
- uint8 i=0, n;
- uint32 tmp = inum;
- for(i=0; i<8; i++)
- {
-
- if(tmp>0)
- {
- n = tmp % 10;
- tmp = (tmp-n) / 10;
- num_code[7-i] = seg_tab[n];
- }else{
- num_code[i] = 0x00;
- }
- }
- }
- //8位數碼管顯示函數
- void display(void)
- {
- uint8 j = 0;
- for (j=0; j<8; j++)
- {
- //移位
- bit_sel = 1;
- DATA = bit_tab[j];
- bit_sel = 0;
- //顯數
- seg_sel = 1;
- DATA = num_code[j];
- delay(1);
-
- //消影(共陽極則為0xff,就是讓所有數碼管暫時不亮)
- DATA = 0x00;
- seg_sel = 0;
- }
- }
- void main(void)
- {
- while(1)
- {
- int2code(birthday);
-
- display();
-
- if (KEY_S2==0)
- {
- delay(10);
- if (KEY_S2==0){
- birthday++;
- }
- while(!KEY_S2);
- }
- }
- }
復制代碼
|