Hi there again.
Few months ago I have posted a question on a problem reading data from RS232 barcode scanner to Arduino. It was solved and thanks to everyone who helped me.
But now I’m doing some experiment with a USB Barcode Scanner. The code is taken from example at https://www.circuitsathome.com/mcu/connecting-barcode-scanner-arduino-usb-host-shield/
And I modified it a bit and it my barcode scanner output the barcode number in LCD and serial monitor(though serial monitor has a square character at the end of the code. an end marker perhaps?).
Here’s my code
#include <hid.h> //Add to Oleg Mazurov code to Bar Code Scanner
#include <hiduniversal.h> //Add to Oleg Mazurov code to Bar Code Scanner
#include <usbhub.h>
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#define DISPLAY_WIDTH 16
//initialize the LCD library with the numbers of the interface pins//
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
USB Usb;
USBHub Hub(&Usb); //I enable this line
HIDUniversal Hid(&Usb); //Add this line so that the barcode scanner will be recognized, I use "Hid" below
HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard(&Usb);
class KbdRptParser : public KeyboardReportParser
{
void PrintKey(uint8_t mod, uint8_t key); // Add this line to print character in ASCII
protected:
virtual void OnKeyDown (uint8_t mod, uint8_t key);
virtual void OnKeyPressed(uint8_t key);
};
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
uint8_t c = OemToAscii(mod, key);
if (c)
OnKeyPressed(c);
}
/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0; //watchdog
static uint8_t current_cursor = 0; //tracks current cursor position
if( millis() > next_time ) {
lcd.clear();
current_cursor = 0;
delay( 5 ); //LCD-specific
lcd.setCursor( 0,0 );
}//if( millis() > next_time ...
next_time = millis() + 200; //reset watchdog
if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) { //switch to second line if cursor outside the screen
lcd.setCursor( 0,1 );
}
Serial.print( (char)key ); //Add char to print correct number in ASCII
lcd.print( (char)key );
if ((char)key == 882020554)
{
lcd.setCursor(0,1);
lcd.print("TEST PRODUCT 1");
}
};
KbdRptParser Prs;
void setup()
{
Serial.begin( 115200 );
Serial.println("Start");
if (Usb.Init() == -1) {
Serial.println("OSC did not start.");
}
delay( 200 );
Hid.SetReportParser(0, (HIDReportParser*)&Prs); //Here I change "Keyboard" for "Hid"
// set up the LCD's number of columns and rows:
lcd.begin(DISPLAY_WIDTH, 2);
lcd.clear();
lcd.noAutoscroll();
lcd.print("Ready");
delay( 200 );
}
void loop()
{
Usb.Task();
}
However, nothing besides the barcode number is printed on the LCD when I scan “882020554”.
Is my if-else wrong? Or do I need to implement it the same way as serial input(by using null terminated char array).
Thank you.