#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define button1 4 // Button B1 is connected to Arduino pin 9
#define button2 5 // Button B2 is connected to Arduino pin 8
Adafruit_SSD1306 display(128, 64, &Wire, -1);
void setup() {
Serial.begin(9600);
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
delay(1000);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
display.setTextColor(WHITE, BLACK);
}
char Calendar[] = " / /20 ";
byte i, date, month, year;
void Clock_display(){
// Convert BCD to decimal
date = 12;
month = 5;
year = 22;
// End conversion
Calendar[9] = year % 10 + 0x30;
Calendar[8] = year / 10 + '0';
Calendar[4] = month % 10 + 48;
Calendar[3] = month / 10 + '0';
Calendar[1] = date % 10 + 0x30;
Calendar[0] = date / 10 + 48;
draw_text(4, 18, Calendar, 2); //输出x,y ,函数,字号
}
void blink_parameter(){
byte j = 0;
while(j < 10 && digitalRead(button1) && digitalRead(button2)){
j++;
delay(25);
}
}
byte edit(byte x_pos, byte y_pos, byte parameter){
char text[3];
Serial.print(F("检查:"));
Serial.print(i);
Serial.print(F(" 输入:"));
Serial.println(parameter);
sprintf(text,"%02u", parameter);
while(!digitalRead(button1)); // Wait until button B1 released
while(true){
while(!digitalRead(button2)){ // If button B2 is pressed
parameter++;
if(i == 0 && parameter > 31) // If date > 31 ==> date = 1
parameter = 1;
if(i == 1 && parameter > 12) // If month > 12 ==> month = 1
parameter = 1;
if(i == 2 && parameter > 99) // If year > 99 ==> year = 0
parameter = 0;
sprintf(text,"%02u", parameter);
draw_text(x_pos, y_pos, text, 2);
Serial.print(F("X:"));
Serial.print(x_pos);
Serial.print(F(" Y:"));
Serial.print(y_pos);
Serial.print(F("数据:"));
Serial.println(text);
delay(200); // Wait 200ms
}
draw_text(x_pos, y_pos, " ", 2);
blink_parameter();
draw_text(x_pos, y_pos, text, 2);
blink_parameter();
if(!digitalRead(button1)){ // If button B1 is pressed
i++; // Increament 'i' for the next parameter
Serial.print(F("循环:"));
Serial.println(i);
return parameter; // Return parameter value and exit
}
}
}
void draw_text(byte x_pos, byte y_pos, char *text, byte text_size) {
display.setCursor(x_pos, y_pos);
display.setTextSize(text_size);
display.print(text);
display.display();
}
void loop() {
if(!digitalRead(button1)){ // If button B1 is pressed
i = 0;
while(!digitalRead(button1)); // Wait for button B1 release
date = edit(4, 18, date); // Edit date
month = edit(40, 18, month); // Edit month
year = edit(100, 18, year); // Edit year
delay(200); // Wait 200ms
}
Clock_display(); // Diaplay time & calendar
delay(50); // Wait 50ms
}
// End of code.