嵌入式设备中显示二维码在移动支付和其他领域都有广泛的应用,本文是一个嵌入式二维码实现方案,利用的是一个老外的开源二维码显示库,在控制台中模拟嵌入式中的lcd显示二维码(本文涉及的所有源码都可以去我的csdn下载资源中找到)。
开源库地址:https://fukuchi.org/works/qrencode/
使用方法:
1 下载代码后,提取如下文件(图1)即可:
注意:
- config.h是库里面没有的,我自己加的,用于配置这个开源库,内容见图2(这个内容是针对控制台这个window平台写的,移植的时候要按照对应的平台替换)
在所有的c文件开头第一行都请加一行:#define HAVE_CONFIG_H 1
- 这份代码多线程不安全,老外的库里面有个多线程的开关,请参照config.h的方法添加互斥锁之类的玩意儿。
图1 文件列表
#ifndef QR_CONFIG_H
#define QR_CONFIG_H
#define STATIC_IN_RELEASE static
#define malloc malloc
#define free free
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
#define MICRO_VERSION 0
#define VERSION "1.0.0"
#pragma warning(disable:4996)
#pragma warning(disable:4273)
#endif
图2 config.h内容
2 写个main函数和显示函数,调用库的接口看看效果,如下图代码:
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include ".\libqrencode\qrencode.h"
void printFrame(int width, unsigned char *frame)
{
int x, y;
for (y = 0; y<width; y++) {
for (x = 0; x<width; x++) {
printf("%02x ", *frame++);
}
printf("\n");
}
}
void printQRcode(QRcode *code)
{
printFrame(code->width, code->data);
}
using namespace std;
static void draw_QRcode(QRcode *qrcode, int ox, int oy, int margin, int size)
{
int x, y, width;
unsigned char *p;
HWND hwnd;
HDC hdc;
RECT rect;
HBRUSH black_brush = (HBRUSH)GetStockObject(BLACK_BRUSH);
HBRUSH white_brush = (HBRUSH)GetStockObject(WHITE_BRUSH);
BOOL ret;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT small_rect;
hwnd = GetConsoleWindow();
hdc = GetDC(hwnd);
small_rect.Left = 5;
small_rect.Right = 100;
small_rect.Top = 5;
small_rect.Bottom = 45;
ret = SetConsoleWindowInfo(hOut, TRUE, &small_rect);
if (!ret) printf("\r\nSetConsoleWindowInfo fail");
//CloseHandle(hOut);
system("color F0");
ox += margin * size;
oy += margin * size;
width = qrcode->width;
p = qrcode->data;
for (y = 0; y<width; y++) {
for (x = 0; x<width; x++) {
rect.left = ox + x * size;
rect.top = oy + y * size;
rect.right = rect.left+size;
rect.bottom = rect.top+size;
if (*p&0x01)
FillRect(hdc, &rect, black_brush);
else
FillRect(hdc, &rect, white_brush);
p++;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
QRcode *qrcode;
qrcode = QRcode_encodeString("一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十",
0, QR_ECLEVEL_H, QR_MODE_8, 1);
if (qrcode)
{
draw_QRcode(qrcode, 0, 0, 5, 6);
QRcode_free(qrcode);
}
else
{
printf("QRcode_encodeString error");
}
getchar();
return 0;
}
3 代码运行效果:
惊不惊喜,意不意外!!!