本帖最后由 叶舞飞刃 于 2012-9-6 14:39 编辑
代码:
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
#define OPPREAD 0xa1
#define OPPWRITE 0xa0
sbit SCL = P3^4;
sbit SDA = P3^5;
sbit K5 = P1^4;//小时加1;
sbit K6 = P1^5;//分钟加1;
sbit K7 = P1^6;//秒加1;
sbit K8 = P1^7;//复位;
uchar code k[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//数码管显示数字;
uchar fen = 0;
uchar miao = 0;
uchar shi = 0;
uint num = 0;
void delay(uchar i) {
uchar j;
while(i--) {
for(j = 0; j < 115; j ++) {
;
}
}
}
void start() {//起始;
SDA = 1;
SCL = 1;
delay(5);
SDA = 0;
delay(5);
SCL = 0;
}
void stop() {//终止;
SDA = 0;
SCL = 1;
delay(5);
SDA = 1;
delay(5);
SCL = 0;
SDA = 0;
}
bit ask(){//应答;
bit ack_bit;
SDA = 1;
delay(5);
SCL = 1;
delay(5);
ack_bit = SDA;
SCL = 0;
return ack_bit;
}
uchar readdata() {//读;
uchar i, x;
for(i = 0; i < 8; i ++) {
SCL = 1;
x <<= 1;
x |=(uchar) SDA;
SCL = 0;
}
return x;
}
void writecurrent(uchar y) {//当前地址写;
uchar i;
for(i = 0; i < 8; i ++) {
SDA =(bit) (y&0x80);
delay(1);
SCL = 1;
delay(2);
SCL = 0;
y <<= 1;
}
}
void writeset(uchar addr, uchar dat) {//指定地址写;
start();
writecurrent(OPPWRITE);
ask();
writecurrent(addr);
ask();
writecurrent(dat);
ask();
stop();
delay(5);
}
uchar readcurrent() {//当前地址读;
uchar x;
start();
writecurrent(OPPREAD);
ask();
x = readdata();
stop();
return x;
}
uchar readset(uchar set) {//指定地址读;
start();
writecurrent(OPPWRITE);
ask();
writecurrent(set);
ask();
return readcurrent();
}
void displayshi(int h) {//数码管显示小时;
P2 = 0xfe;
P0 = k[h / 10];
delay(1);
P2 = 0xfd;
P0 = k[h % 10];
delay(1);
P2 = 0xff;
}
void displayfen(int f) {//数码管显示分钟;
P2 = 0xf7;
P0 = k[f / 10];
delay(1);
P2 = 0xef;
P0 = k[f % 10];
delay(1);
P2 = 0xff;
}
void displaymiao(int m) {//数码管显示秒;
P2 = 0xbf;
P0 = k[m / 10];
delay(1);
P2 = 0x7f;
P0 = k[m % 10];
delay(1);
P2 = 0xff;
}
void keyscan() {//键盘扫描;
if(K5 | K6 | K7 | K8 == 1){
TR0 = 0;
if(K5 == 0){
delay(15);
if(K5 == 0){
shi ++;
writeset(2, shi);
while(!K5);
}
}
if(K8 == 0){
delay(15);
if(K8 == 0){
shi = 0;
fen = 0;
miao = 0;
writeset(2, shi);
writeset(3, fen);
writeset(4, miao);
while(!K8);
}
}
if(K6 == 0){
delay(15);
if(K6 == 0){
fen ++;
writeset(3, fen);
while(!K6);
}
}
if(K7 == 0){
delay(15);
if(K7 == 0){
miao ++;
writeset(4, miao);
while(!K7);
}
}
}
}
void init() {
TMOD = 0x01;
EA = 1;
ET0 = 1;
TR0 = 1;
TH0 = (65536 - 45872) / 256;
TL0 = (65536 - 45872) % 256;
}
void main() {
init();
SDA = 1;
SCL = 1;
shi = readset(2);
fen = readset(3);
miao = readset(4);
while(1) {
keyscan();
TR0 = 1;
displaymiao(miao);
displayfen(fen);
displayshi(shi);
}
}
void t000() interrupt 1 {
TH0 = (65536 - 45872) / 256;
TL0 = (65536 - 45872) % 256;
num ++;
if(num == 20) {
miao ++;
writeset(4, miao);
num = 0;
if(miao == 60) {
fen ++;
writeset(3, fen);
miao = 0;
if(fen == 60) {
shi ++;
writeset(2, shi);
fen = 0;
if(shi == 24) {
shi = 0;
}
}
}
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>