作者:admin,发布日期:2020-03-31
阅读:6755;评论:0
写在开头
最近闲来无事,研究Arduino,突发奇想想要编写代码输出二维码到显示屏上。于是,通过查找资料和第三方库,实现了二维码的显示,效果还是可以的,使用微信的扫一扫一般对焦后都可以扫描,这篇文章就为大家分享一下二维码的生成和显示。
使用材料
ESP8266 NodeMCU * 1
SSD1306 OLED显示屏(i2c接口)(128*64) * 1
杜邦线 * 4
硬件接线
GND - GND
VCC - 任意3.3V
SCL (Clock线) - GPIO4
SDA (Data线) - GPIO5
所需Arduino库
https://github.com/olikraus/u8g2
https://github.com/ricmoo/qrcode/
效果预览

实现原理
使用QRCode库,生成二维码数组,然后通过u8g2库drawPixel画像素点显示到屏幕上面。
实现代码
#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
#include "qrcode.h"
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 4, /* data=*/ 5); // ESP32 Thing, HW I2C with pin remapping
void setup() {
// put your setup code here, to run once:\
// init u8g2
u8g2.begin();
// gen the QR code
QRCode qrcode;
uint8_t qrcodeData[qrcode_getBufferSize(3)];
qrcode_initText(&qrcode, qrcodeData, 3 , ECC_LOW, "https://blog.craftyun.cn/");
// start draw
u8g2.firstPage();
do {
// get the draw starting point,128 and 64 is screen size
uint8_t x0 = (128 - qrcode.size * 2) / 2;
uint8_t y0 = (64 - qrcode.size * 2) / 2;
// get QR code pixels in a loop
for (uint8_t y = 0; y < qrcode.size; y++) {
for (uint8_t x = 0; x < qrcode.size; x++) {
// Check this point is black or white
if (qrcode_getModule(&qrcode, x, y)) {
u8g2.setColorIndex(1);
} else {
u8g2.setColorIndex(0);
}
// Double the QR code pixels
u8g2.drawPixel(x0 + x * 2, y0 + y * 2);
u8g2.drawPixel(x0 + 1 + x * 2, y0 + y * 2);
u8g2.drawPixel(x0 + x * 2, y0 + 1 + y * 2);
u8g2.drawPixel(x0 + 1 + x * 2, y0 + 1 + y * 2);
}
}
} while ( u8g2.nextPage() );
}
void loop() {
// put your main code here, to run repeatedly:
}关于二维码的version和可以存储的内容大小
参考https://github.com/ricmoo/qrcode/#data-capacities
大体来说就是二维码的version和校验程度会影响其内部可以存储的内容大小
博主这边使用了Version3 ECC_LOW,这会生成29*29像素的二维码,不过这样显示出来的像素点会非常小,这里将其放大了一倍,相当于58*58,使其更加容易被扫描。