#include <Arduino.h>
#include <U8g2lib.h>
#include <qrcode.h>
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* 默认引脚reset=*/ U8X8_PIN_NONE);
unsigned long getCurrentTimestampMillis() { //函数定义,函数名为getCurrentTimestampMillis,调用Arduino内置函数mills(),用于获取当前时间戳的毫秒数
return millis();}
// 定时更新的时间间隔(毫秒)
const unsigned long UPDATE_INTERVAL = 30000; //定义了一个长量UPDATA_INTERVAL。
unsigned long lastUpdateTime = 0; //跟踪上次更新时间
void setup() {
// 初始化OLED显示屏
u8g2.begin();
// 初始时更新一次二维码
updateQRCode("hello");
}
void updateQRCode(const char* text) { //绘制到oled屏幕上,接收一个字符串参数text,该字符串将被编码到二维码中
// 创建二维码
QRCode qrcode;
uint8_t qrcodeData[qrcode_getBufferSize(5)]; // 根据二维码大小获取缓冲区大小
qrcode_initText(&qrcode, qrcodeData, 5, ECC_HIGH, text);
// 开始绘制
u8g2.clearBuffer(); // 清除屏幕内容
u8g2.firstPage();
do {
// 二维码在oled屏幕上的起始位置
uint8_t x0 = (128 - qrcode.size * 2) / 2;
uint8_t y0 = (64 - qrcode.size ) ;
// 绘制二维码
for (uint8_t y = 0; y < qrcode.size; y++) {
for (uint8_t x = 0; x < qrcode.size; x++) {
// 检查点是黑色还是白色
if (qrcode_getModule(&qrcode, x, y)) {
u8g2.setColorIndex(1); // 白色
} else {
u8g2.setColorIndex(0); // 黑色
}
u8g2.drawPixel(x0 + x, y0 + y);
}
}
} while (u8g2.nextPage());
// 发送缓冲区到OLED屏幕
u8g2.sendBuffer();
}
void loop() {
unsigned long currentTime = millis(); //获取从Arduino启动以来经过的毫秒数,并将其存储在currentTime变量中
// 检查是否需要更新二维码
if (currentTime - lastUpdateTime >= UPDATE_INTERVAL) { //检查自从上次更新二维码以来经过时间是否超过了UPDATE_INTERVAL
char text[32];
unsigned long seconds = currentTime / 1000; //将毫秒数转化为秒数
unsigned int minutes = seconds / 60; //计算分钟数
seconds %=60; //获取剩余的秒数(不满一分钟的部分)
sprintf(text, "%02u:%02u",minutes,seconds); //将分钟和秒格式化为一个字符串,并存储在text数组中
// 更新二维码文本
updateQRCode(text);
// 重置最后更新时间
lastUpdateTime = currentTime;
}
}
esp8266创建二维码
最新推荐文章于 2024-09-09 22:50:15 发布