整理桌子的时候翻到这份打印出来的文件,依稀记得是孩子学校的一个小任务,实现一个计时器,按下后开始计时,到时间了驱动电机举牌。当时正学习arduino,就尝试用arduino配合0.91寸OLED实现了一个粗糙的模型,增加了一个简单菜单,以供简单设置一下时间。
很长时间不用,其中原理与语句早已模糊不清,不舍得随手一扔,毕竟曾经也花了很多时间学习,干脆用白描ocr重新将打印的文件转回文字,整理了一下记录在了博客上,供将来有机会参考。因为中间转了几道,可能会因文字或符号确实的原因,无法直接运行。
#include<SPI.h> //串行外设接口库#include<Wire.h>#include<Adafruit_GFX.h>#include<Adafruit_SSD1306.h>#define SCREEN WIDTH 128 //定义OLED宽度#define SCREEN_HEIGHT 32 //定义OLED高度#define OLED_RESET 4 //定义复位键//Arduino UNO板接线:A4(SDA),A5(SCL)Adafruit_SSD1306 display (SCREEN_WIDTH, SCREEN_HEIGHT,&Wire, OLED_RESET);const int startPin=5;const int setPin=6;int startstate=1;int setState=1;int workState=0;int setTime=8;unsigned long countTime;void setup(){ Serial.begin(9600); //检测当前库是否正常运行 if(!display.begin(SSD1306_SWITCHCAPVCC,0x3C)){ //Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } //显示Adafruit的LOGO display.display(); delay(1000); display.clearDisplay(); //display.drawLine(X1, Y1, X2, Y2, SSD1306 WHITE); //display.drawRect(i, i, display.width()-2*i,display.height()-2*i, SSD1306_WHITE);}void loop(){ if(workState==0){ setState =digitalRead(setPin); startState=digitalRead(startPin); mainPage(); if(workState==0&&setState==0){ workState=1; delay(1000); } if(workState==0&&startState==0){ workState=2; delay(1000); } } if(workState==1){ setState = digitalRead(setPin); startState = digitalRead(startpin); testdrawstyles(setTime); if(workState==1&&startState==0){ setTime+=2; if(setTime>30){ setTime=8; } } if(workState==1&&setState==0){ workState=0; delay(1000); } } if(workState==2){ setState = digitalRead(setPin); startstate = digitalRead(startPin); countTime =millis()/1000; while(true) { if((millis()/1000-countTime)>10) { timeOver(); }else{ startCount(setTime,millis()/1000-countTime); } if(digitalRead(setPin)==0)break; } workState=0; delay(1000); }}void timeOver(){ display.clearDisplay(); display.setCursor(0,0); display.setTextSize(2); display.setTextColor(SSD1306_WHITE); display.print1n(F("OVER!")); display.display(); delay(200);void mainPage(){ display.clearDisplay(); display.setCursor(0,0); display.setTextSize(2); display.setTextColor(SSD1306_WHITE); display.print1n(F("WELCOME!")); display.print (F("TIME=")); display.print(setTime); display.display(); delay(200);}void testdrawstyles(int setTime){ display.clearDisplay(); display.setTextSize(2); displar.setTextColor (SSD1306 WHITE); display.setCursor(0,0); display.print1n(F("Set Times:")); display.print(setTime); display.printin(F(" Min") ); display.display(); delay(200);}void startCount (int set,double count){ display.clearDisplay(); display.setTextSize(2); display.setTextColor(SSD1306_WHITE); display.setCursor(0,0); display.printin(set); display.print1n(count); display.display(); delay(200);}