3455| 2
|
用ATmega 328 板和TM1638数显板和简单代码制作的小电子钟 |
小孩参加学校的机器人制作竞赛,剩下了一块Mini 的 ATmega 328 板和TM1638数显板,为了不白白浪费扔垃圾桶,我就拿来自学一下Arduino,好像还有点意思。今天编了一个电子钟小程序,也算是动起来了。找到这里分享一下。 因为学校只提供安装教程,没有讲解这些板子是怎么连接编程的,连板子的参数资料都没有提供,所以资料都是自己上网找的,花了点时间。为了简化程序,我在网上找到了TM1638的一个库文件,所以实际代码只需要几行。也没有安装时钟模块,所以钟走的不太准,而且一拔电得重设时间。所以也把按钮做成了可随时调节时钟。 具体代码如下:(程序文件和TM1638库文件见附件)[mw_shl_code=applescript,true] #include <InvertedTM1638.h> #include <TM1638.h> #include <TM1638QYF.h> #include <TM1640.h> #include <TM16XX.h> #include <TM16XXFonts.h> //TM1638模块引脚定义 int DIO = 9; int CLK = 12; int STB = 13; //这里定义了那三个脚 TM1638 disp(DIO,CLK, STB); //data,clk,stb uint16_t j = 0; unsigned long TimeNow; void setup () { TimeNow = Time2second(9174100);//initialization time day|hour|min|sec } void loop() { unsigned long i; ++TimeNow; i=disp.getButtons();//time setting disp.setLEDs(i); switch (i) { case 1: //Reduce day case 4: //Reduce hour case 16: //Reduce minute case 64: //Reduce second TimeNow=second2Time(TimeNow); i= pow(10,(7-getBaseLog(2,i*2))); TimeNow=TimeNow + i; TimeNow = Time2second(TimeNow); break; case 2: //Add day case 8: //Plus hour case 32: //Plus minute case 128: //Plus second TimeNow=second2Time(TimeNow); i= pow(10,(7-getBaseLog(2,i))); TimeNow=TimeNow - i; TimeNow = Time2second(TimeNow); break; default: // statements break; } disp.setDisplayToDecNumber(second2Time(TimeNow), 0,false); delay(1000); } unsigned long second2Time(unsigned long DATA) //convert second count to a time showing { unsigned long second; unsigned long minute; unsigned long hour; unsigned long day; unsigned long result; second = DATA % 60; DATA = ceil(DATA/60); minute = DATA % 60; DATA = ceil(DATA/60); hour = DATA % 24; DATA = ceil(DATA/24); day = DATA % 30; result = day * 1000000 + hour * 10000 + minute *100 + second; return result; } unsigned long Time2second(unsigned long DATA) //convert a time showing num to second num { unsigned long second; unsigned long minute; unsigned long hour; unsigned long day; unsigned long result; second = DATA % 100 % 60; DATA = ceil(DATA/100); minute = DATA % 100 % 60; DATA = ceil(DATA/100); hour = DATA % 100 % 24; DATA = ceil(DATA/100); day = DATA % 100 % 30 ; result = day * 86400 + hour * 3600 + minute * 60 + second; return result; } int getBaseLog(int x, int y) //logx y): { return log(y) / log(x); } [/mw_shl_code] |
912 Bytes, 下载次数: 1153
1.16 MB, 下载次数: 1102
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed