条码是人类的伟大发明之一,特别是对于零售业主来说。你可以看到现在从大到小的商店,都会放着一台收银机或者电脑,一个条码枪。用扫描的方式能够马上取得售卖的价格。有了条码枪,记忆力已经不是售货员必须的要求了。而在此之前,人么或者需要记住复杂的零售价格,或者用贴标的方式给每一样商品都打上“价签”,显而易见的是如果要进行调价,对于营业人员将是灾难,更简单一些的则是或者是像小抄一样在柜台边上准备一个小本子,忘记价格的时候只能偷看。此外,诸如火车站汽车站旁边的店铺则是店主根据相面结果来决定要价的。
从原理上来说是这样的:USB Barcode Scanner使用的是 USB Keyboard 的 HID协议,条码上面的每一个字符都会像按键一样从USB端口输入到 PC中。
首先使用 USB HOST Shield来解析USB Barcode Scanner的HID协议,和解析USB 键盘协议一样,我们够获得每次输入的键盘的按键信息,每一次输入的字符会被拼接到字符串中,直到收到结束的符号。这个字符串就是完整的条码信息。之后,我们将这个信息显示在 1602 LCD上,同时使用蓝牙键盘模块把这个字符传输到电脑上。
实验用到的设备如下:
USB条码枪 x1
USB Host Shield x1
蓝牙 HID键盘模块 x1
扩展面包板 x1 (可选)
完整的代码:
#include "LiquidCrystal_I2C.h"
#include <hidboot.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
char KeyPress[]= {0x0C,0x00,0xA1,0x01,0x00,0x00,0x1E,0x00,0x00,0x00,0x00,0x00};
char KeyRelease[]={0x0C,0x00,0xA1,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
String Barcode;
class KbdRptParser : public KeyboardReportParser
{
protected:
void OnKeyDown (uint8_t mod, uint8_t key);
};
void SendKeyByBT()
{
for (byte i=0;i<sizeof(KeyPress);i++)
{
Serial.write(KeyPress[i]);
}
for (byte i=0;i<sizeof(KeyRelease);i++)
{
Serial.write(KeyRelease[i]);
}
}
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
uint8_t c = OemToAscii(mod, key);
if (c)
{
KeyPress[6]=key;
SendKeyByBT();
//Serial.print("ASCII: ");
//Serial.println((char)c);
Barcode=Barcode+ (char) c;
if ((c==19) || (Barcode.length()> 40)) {
lcd.clear();
lcd.setCursor(0,0);
//这里是单独发送的,因为我测试发现 1.6.10 的IDE存在一个 bug
//lcd.print(Barcode) 会丢失字符
for (byte i=0;i<Barcode.length();i++)
{
lcd.print(Barcode[i]);
if (i==15) { lcd.setCursor(0,1);}
}
//Serial.println(Barcode);
Barcode="";
}
}
}
USB Usb;
HIDBoot<HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
uint32_t next_time;
KbdRptParser Prs;
void setup()
{
Serial.begin(9600);
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.backlight();
//mySerial.begin(9600);
//Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
next_time = millis() + 5000;
HidKeyboard.SetReportParser(0, (HIDReportParser*)&Prs);
}
void loop()
{
Usb.Task();
}
[align=left]

除了条形码之外,现在还有 RFID 之类的也能完成自动识别的工作,显而易见价格便宜是条形码最大的优点是。对于一般场合的应用,编码信息也足够用,因此在未来条形码还会有着巨大的生命力。
也许有一天,人们用条码来进行身份的识别和验证,就像下面这样:
完整代码下载
Barcodescaner
工作的视频
