Skip to content

Instantly share code, notes, and snippets.

@jdhenckel
Created July 23, 2023 21:05
Show Gist options
  • Save jdhenckel/263a6a63128cc93a84d1ac77f24173c6 to your computer and use it in GitHub Desktop.
Save jdhenckel/263a6a63128cc93a84d1ac77f24173c6 to your computer and use it in GitHub Desktop.
Sample code for reading POSTAGE scale with Arduino and USB Host Shield
#include <Arduino.h>
#include <usbhub.h>
#include <cdcprolific.h>
#include <SPI.h>
void print(String a, uint8_t b)
{
Serial.print(a);
Serial.print(' ');
Serial.println(b);
}
class PL2303_Oper : public CDCAsyncOper
{
public:
uint8_t OnInit(ACM *pacm);
};
uint8_t PL2303_Oper::OnInit(ACM *pacm)
{
LINE_CODING lc;
lc.dwDTERate = 2400;
lc.bDataBits = 8; // 8
lc.bParityType = 0; // N parity
lc.bCharFormat = 0; // 1 stop
uint8_t rcode = pacm->SetControlLineState(3);
if (rcode) print("SetControlLineState returned", rcode);
if (!rcode) rcode = pacm->SetLineCoding(&lc);
if (rcode) print("SetLineCoding returned", rcode);
return rcode;
}
USB Usb;
PL2303_Oper AsyncOper;
PL2303 Acm(&Usb, &AsyncOper);
void setup()
{
Serial.begin( 9600 );
delay(100);
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("Usb.Init failed: OSCOKIRQ failed to assert");
delay( 200 );
}
String data;
int ready = 0;
int i =0;
void loop()
{
Usb.Task();
Serial.print(i++); Serial.print("\r");
if (Acm.isReady())
{
Serial.println();
delay(50);
uint8_t buf[64];
uint16_t rcvd = 64;
uint8_t rcode = Acm.RcvData(&rcvd, buf);
Serial.println("rcvdata");
if (rcode && rcode != hrNAK)
print("Acm.RcvData failed:", rcode);
for(uint16_t i=0; i < rcvd; i++)
{
if (!ready && buf[i] == 2) { // 2 = start of data
ready = 1;
Serial.println();
Serial.println("Ready to weigh...");
}
else if (buf[i] == 135) // 135 = negative number
data = "-";
else if (buf[i] > 31 && buf[i] < 127)
data += (char) buf[i];
else if (ready && buf[i] == 13)
{
data += " ";
data += (char) buf[i];
Serial.print(data);
data = "";
}
}
delay(10);
}
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment