Arduino reading digital scale
I am the proud owner of Stamps.com Model 510 5lb digital scale. It is a nice little scale which works very well (much better than Stamps.com service itself) while attached to my workstation. The scale doesn’t have a display making any kind of standalone use difficult. However, since the scale is a USB HID device reading data from it should be as easy as from a joystick and Arduino board should be adequate to provide a display function for it. To test this theory I made a simple setup consisting of Arduino UNO, USB Host shield and HD44780-compatible LCD display. I also wrote a small sketch which polls the scale and outputs the weight. The secondary objective of this project was to demonstrate LCD support in USB Host shield library.
For this project I used the following:
- An Arduino board. Standard size board, such as UNO, Duemilanove or Leonardo, will work
- USB Host Shield
- Toshiba HD44780-compatible LCD display, in 16×1 or 16×2 configuration. If you’re planning to use this sketch for something else, like data logging, the display is optional – all output from the scale is repeated to the serial port
- Stamps.com 5lb digital scale. Scales are standard HID devices with usage table 0x8d, therefore, scales from other brands may work as well with no or minimal modifications to the code
- USB Host library
The example code is also hosted at github, as well as in ‘examples’ section of the library under ‘HID’. It has been tested with Arduino IDE version 1.0.5.
In this project, the LCD is connected to the shield’s GPOUT pins, as documented in max_LCD.h header file. In addition to data lines, 5V and ground must also be connected to the shield’s 5V and GND terminals; the RW pin must be grounded – I do it on the LCD itself. In order to see the characters, the display must be biased – a 5K-10K pot with wiper on Vo and other two pins on 5V and ground will provide contrast adjustment.
Continue reading Adding a display to a digital scale using Arduino and USB Host shield
Bit reversal code
This is Part 3 of 3-part series of articles. Part 1 talks about ways of tweaking SPI code while Part 2 talks about hardware modifications.
After finishing hardware modifications for my three-SPI-device setup I started coding and hit a snag. Any device would happily work by its own, WiFi and SD were also happy together, however, adding NFC Shield to the mix would disable other two. If I moved NFC initialization to the beginnig, other two devices would work but NFC would not. At the same time, if a device was just present on a bus and not initialized, other two devices were not affected. It became clear that initialization itself was the source of error.
Seeedstudio NFC Shield uses NXP PN532 transmission module. This module supports several communication interfaces, namely SPI, I2C, and HSU. In SPI mode the data format is ‘LSB first’, i.e., transmission starts from bit 0. Such format is uncommon; all other SPI shields I’m aware of – Ethernet, WiFi, USB Host, etc., are using ‘MSB first’ format – the transmission starts with bit 7.
A quick look into NFC library source code revealed the following line in
This line sets the data format. In Atmega microcontrollers the default SPI data format is ‘MSB first’ – all other SPI devices don’t have to set it during initalization. Initial revision of PN532 code ( written by Adafruit ) was using software SPI and awkward bit order was dealt with in
read() functions. When Seeedstudio modified the code to work with hardware SPI, they just switched SPI to ‘LSB first’ format without much thinking, breaking compatibility with the rest of the world. Surely, when I commented out this line, NFC initialization stopped breaking WiFi. Predictably, NFC also stopped working.
Luckily for me, the SPI is pretty basic protocol and bit order setting in SPI controller doesn’t mean much. It really doesn’t matter how the bit order is set; if we need ‘MSB first’ for the majority of the devices we can initialize SPI in a normal way and then modify
read() functions for ‘LSB first’ device to serve it reversed bytes. This is exactly what I did. Below is modified version of Seeedstudio PN532 library (also presented on a title screenshot) – lines 6 and 16 perform bit reversing:
/************** low level SPI ********/
/*Function:Transmit a byte to PN532 through the SPI interface. */
inline void PN532::write(uint8_t _data)
/* bit reversing code copied vetbatim from http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious */
_data = ((_data * 0x0802LU & 0x22110LU) | (_data * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
/*Function:Receive a byte from PN532 through the SPI interface */
inline uint8_t PN532::read(void)
uint8_t data_ = pn532_SPI.transfer(0);
/* bit reversing code copied vetbatim from http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious */
data_ = ((data_ * 0x0802LU & 0x22110LU) | (data_ * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
After making these modifications, commenting out the ‘LSB first’ setting in the
PN532:begin() and also modifying WiFi code to stay away from pin 9 (see this article for discussion) all three devices are happily working together without conflicts. The library mod for PN532 can be left there permanently – the chip will never know that it is communicating with “misconfigured” SPI host. I’m hoping Seeedstudio will fix their code eventually; in the mean time, if you have SPI compatibility issues, simply make code modifications presented in this article.
Arduino connected to Nexus S
Since Kristian’s release of SPP service for USB Host 2.0 library
I got many e-mails with questions about Bluetooth serial communications in general and using the SPP class in particular. While establishing a Bluetooth connection is quite easy when using PCs/smartphones/tablets, the Arduino implementation is less user-friendly (for a good reason) and somewhat confusing. This article is intended to be a short tutorial of Arduino USB Bluetooth connectivity using an Android device as a peer – in my opinion, the simplest one to set up and communicate.
To follow this tutorial, you will need the following:
- An Arduino board ( I sell them too )
- full-size USB Host Shield 2.0
- USB Host Shield 2.0 library downloaded and installed in your Arduino library directory
- An SPP example sketch
- Bluetooth dongle – see below for detailed discussion
- Android device – a phone or tablet. The accuracy of this tutorial has been checked on Nexus S phone and Nexus 7 tablet, both running Jelly Bean 4.1.1 OS.
- A Bluetooth terminal emulator app for Android – I use Blueterm
The hardware setup is shown on the title photo (click on it to make it larger). It is a good idea to use external power supply at least in the beginning – some Bluetooth dongles are not happy when powered together with Arduino board/USB Host shield from USB cable. On a side note, it is always a good idea to use external power supply while experimenting with USB devices, especially when using current Arduino boards with their weak regulators. Also, Bluetooth code requires plenty of resources. The example used in this article compiles in ~24K and even though it would work on standard Arduino, any meaningful project will likely require a bigger board, like a Mega.
Continue reading Using USB Bluetooth dongle on Arduino to connect to Android phone
Compatible Bluetooth Dongles
[EDIT] Here is Kristian’s post with more detailed explanation of the example sketch.[/EDIT]
Kristian Lauszus from TKJ Electronics, a man behind PS3 and Xbox360 code in USB Host Shield 2.0 library did it again! I’m pleased to announce that the library now supports standard RFCOMM/SPP implementation, thanks to Kristian’s work.
RFCOMM is basic Bluetooth service and SPP is serial port emulator on top of this. The code allows interfacing standard USB Bluetooth dongles to Arduino boards using USB Host Shield v.2.0. Bluetooth dongles (the ones I’ve tested can be seen on a title picture ) are widely available, cost much less than specialized serial Bluetooth modules (I have a couple of powerful class 1 dongles bought on eBay for $1 shipped) and won’t occupy precious serial port on Arduino board. Even though most dongles are compatible with the code, there are also some that don’t work. The code has been tested for compatibility with all major OSes – Linux, MacOS and Windows 7, as well as Android devices. It will likely work with any RFCOMM client, however, more testing is necessary.
The example code is a simple SPP server. It needs to be started before attempting to connect to it from a PC/phone. Once started, the state of the server is printed on a terminal. After that, the device can be discovered/paired/connected to; it is then possible to send characters from one device to the other by means of a keyboard. In the coming days I will write a series of posts with details of connecting different Bluetooth devices to Arduino. In the mean time, enjoy the code! Please give it a try and let me know what you think.
Logitech joystick connected to Arduino
HID report parsing explained in the previous article works pretty well with properly aligned HID reports. The analog controls are placed on a byte or word boundary and buttons occupy dedicated fields. The majority of HID devices are designed this way, however, some other devices are not that simple to interface and today I’m going to show how to handle one of those.
A Logitech Extreme 3D Pro joystick is one nice HID device. It is good looking, well-built, and have a twist handle, which adds third axis to a stick making this model popular among FPV fliers since you can control pitch, roll and yaw with one hand. Also, X and Y axis are 10 bits which gives good precision. There is one problem with this joystick – its input report.
Logitech, in its infinite wisdom, decided to pack all the high and low resolution analog controls plus 12 buttons in 6 bytes of input report. The report looks like this – 10 bits of X, 10 bits of Y, and 4 bits of hat switch. After that, things become easier – one byte of Rz AKA “twist handle”, one byte of buttons, one byte of throttle (called “slider” in the report), and finally, one partially filled byte holding the rest of the buttons. Take a look at the screenshot below – two most important controls are not byte aligned, therefore, simple straightforward parsing of the report is not possible. Also,
USBHID_descr won’t show this report correctly.
To demonstrate how to deal with this report I wrote a simple Arduino sketch. It was made by modifying an example from the previous article. I also made it as simple as possible – as soon as any of the controls changes its value, new report is printed on the serial terminal. The sample output is shown below followed by code explanation.
Continue reading Using Logitech Extreme 3D Pro joystick with Arduino HID library
This article focuses on how to use the existing USB code library and HID report descriptor info to implement joystick functionality. Human readable HID report descriptor and report information can be easily obtained using
USBHID_desc.pde sketch – see previous article for details. This information will help you getting field details such as size and count info. Also, if you don’t have Arduino Mega or 2560 to run
USBHID_desc, report descriptor for your device can be obtained using one of many PC tools known as USB analyzers, or even the official usb.org device verification tool. This article is written by Alex Glushchenko – a developer behind second revision of USB Host Library as well as majority of device support code.
As you may already know report is a data structure used by HID device to return the information about the certain device parameters such as joystick coordinates or button events, or receive new settings such as switching on/off LEDs on keyboard.
Report descriptor is a data structure which describes report or reports, if there are few in number, field sequence, sizes and counts. Each report descriptor consists of several items. Each item describes some field property. I am not going too deep into details on items, explaining only the most important ones which are absolutely necessary in writing your own report parser.
The items usually describe type of field (input/output/feature), minimum, maximum field values, units, value meaning (usage) etc.
Continue reading Developing Arduino code for HID Joystick
A MOSFET controlling VBUS
Today I want to show a simple USB Host Shield 2.0 modification which allows controlling power to USB peripheral. I learned this technique from Camille’s comment to one of digital camera USB control articles. In short, the idea was to cut VBUS connection between USB host and peripheral, simulating disconnect state. P-channel MOSFET, inserted into VBUS, worked as a switch. I designed this capability into USB Host Shield 2.0 but never needed the functionality therefore this useful feature was left undocumented. Recently I started working with very interesting Nikon P&S camera which can be turned on and off with VBUS power so I finally made this modification. It is very simple.
Take a look at the title picture (click on it to make it larger). The modification uses existing VBUS power select pads of the shield. Out of the box, the one labeled 5V is shorted with solder bridge. First step is to remove this bridge with a solder wick so both pads are clean.
It can be seen that a MOSFET in SOT-23 package fits nicely on those pads (I’m using FDN306P). Drain and source pins are soldered to VBUS and 5V, respectively, and gate, which hangs in the air, is routed to an unused digital pin via an 1M resistor. When digital pin is low the MOSFET conducts. When digital pin goes high the MOSFET switches off disconnecting VBUS from the peripheral.
If you are going to drive high-power peripherals, like digital cameras or phones, it is a good idea to add some capacitance to 5V. I’m using 220uF low-ESR organic polymer tantalum cap in 1210 package which fits nicely on 0.1″ spaced 5V and GND pins of the shield; an ordinary leaded 100-200uF aluminum capacitor will work as well.
While playing with some cheap USB to RS-232 converters which use counterfeit PL2303 chips I found a bug in acm code which was sitting there from initial release. This bug was causing sluggish response from serial devices, as well as random
0x06 error codes. The bug is now fixed and corrected version of the library has been posted on GitHub a moment ago.
As a side effect to aforementioned bug fix some new functionality is now available. First,
PL2303 classes now have
isReady() method which can be used to check if certain device has been enumerated, initialized, and ready for service. This method is now used in all sample sketches, see, for example, pl2303_tinygps.pde, line 98.
Another addition is a block of code which performs proper PL2303 initialization. It is a mix of Linux pl2303.c code and Windows Prolific driver USB protocol traces. This block was added during troubleshooting; it turned out that it doesn’t make any difference on PL2303-based devices that I have – either genuine or counterfeit. However, it is tempting to be able to simulate “proper” manufacturer-recommended behaviour in the code so I decided to keep the initialization. It is turned off by default; if desired, it can be added during compilation by defining
PL2303_COMPAT (see cdcprolific.h, line 41 and cdcprolific.cpp, lines 159-179 ). The block adds ~500 bytes to the binary so don’t turn it on just in case.
Please check the new code with your devices and let me know if you can see any improvements or new issues.
Fresh update of USB Host Library 2.0 has just been posted to GitHub. The primary purpose of this release is to maintain compatibility with Arduino releases – the USB Host Library is now compiles in 1.0 as well as pre-1.0 versions of Arduino IDE. Enjoy!
Several important changes have been made to the code, some related to 1.0 compatibility and some not. The library examples were all tested and corrected, the information below is intended for developers using the library in their own projects:
- PL2302 driver. Arduino 1.0 defines PL symbol internally (thank you, Paul for finding this out!), therefore, I needed to change name of Prolific class driver. The new name is
PL2302; I updated library examples to compile correctly, if someone uses this class in their own development, the right way to define an instance of Prolific device is now
PL2303 Pl(&Usb, &AsyncOper);
- NAK handling. A bug preventing long polls of an endpoint has been fixed. Previously, if
bmNakPower member of
epInfo structure was left unitialized the transfer to this endpoint would stop after receiving a single NAK. With current version, the endpoint would be polled for up to 5 seconds. This is rarely desirable, so please initialize
USB_NAK_MAX_POWER. If a single poll is desired, as is often the case with interrupt endpoints, specify
USB_NAK_NOWAIT and if more than maximum number of NAKs (up to 5 seconds) is necessary, specify
- Code speed. An unnecessary delay of 20ms has been found (thank you, Alex for discovering this!) and removed from
USB::setAddress() member function. As a result, every USB transfer is now 20ms faster. While generally a good thing, it could inadvertently affect data exchanges with slow endpoints. If after upgrading to the current version you start seeing more NAKs, that’s probably why.
One nice thing about Arduino 1.0 is built-in PROGMEM support for strings. It is now possible to free about 300-400 bytes of RAM by redefining USBTRACE and USBTRACE2 macros used in debugging output (thank you, John, for the tip!). For example,
USBTRACE (Serial.print(F(s))) will move all USBTRACE strings to PROGMEM. The code size will increase so be careful with this feature if your code size is close to the limit for your Arduino board.
This is the end of announcement – download the code, play with it and if you have any issues please share your findings in the comments.
ND-100S GPS receiver connected to USB Host shield
After posting an article about interfacing USB GPS receiver to Arduino I started receiving e-mails from people asking about a decent inexpensive GPS receiver compatible with USB Host library. After some research and testing I finally found a device which I really like.
ND-100S from USGlobalsat is small, inexpensive (less than $30 shipped at DealExtreme) GPS receiver with excellent characteristics. Below are some bullet points:
- Lightweight – my scale shows 19g for the dongle without connector cover. It is possible to get weight close to 15g by removing the case, USB connector and hardwiring the module to USB Host shield.
- Sensitive – SiRF Star III high sensitivity GPS chip allows this module to lock in less than a minute from my basement (!). Outdoor performance is simply amazing while power consumption stays around 50ma.
- Easy to use – the module uses Prolific PL2303 USB to serial converter supported by USB Host library 2.0 and the sketch from the previous article works without any modifications. Also, the module has status LED showing when GPS position is fixed – comes in handy during field tests when serial console is not available. The dongle ships with semi-rigid USB cable which can be used as a raiser.
Overall, ND-100S is very small, sensitive and inexpensive GPS receiver. It can be used with USB Host shield using PL2303 USB to serial converter support in USB Host library rev.2.0. I have a couple of projects in mind which would use this receiver – will post as soon as I have more information about it.