USB GPIO Modules

32 Channel USB GPIO Module With Analog Inputs

2731 views February 6, 2016 admin 0

Introduction

32usbgpiomodule_1_1__20600.1437702073.1280.1280

Numato Lab’s 32 Channel USB GPIO Module is a versatile product for controlling electrical and electronic devices remotely from a PC over USB link. Ease of use and wider operating system compatibility are the primary goals behind this product’s design. Built in USB to serial conversion allows the module to be used without any USB specific knowledge. This simplicity allows use of off-the-shelf Terminal Emulation programs such as Hyper Terminal and PUTTY for controlling the module with a simple set of human readable commands. For power users, this module can be controlled by writing programs in various programming languages.

Features:

  • 32 TTL (3.3V) compatible GPIOs
  • 7 analog inputs with 10-bit resolution (multiplexed with digital IOs)
  • USB interface with CDC support. As easy as using a serial port, no USB knowledge required
  • All IOs available on easy to access screw terminals
  • Can be powered from USB or external power supply
  • Can be controlled by using standard serial console applications or custom applications

Some of the possible uses of this module includes:

  • Home Automation
  • Lighting Control
  • Garden Equipment Control
  • Industrial Automation
  • Test Fixtures
  • DIY and Hobby

This product is compatible with the following operating systems:

  • Windows XP and later versions (Windows 7, 8/8.1, 10 and future versions)
  • Windows 7 Embedded and later
  • Linux
  • Mac OS X
  • Android
  • Or any other operating system that supports USB CDC devices.

And these are some of the languages that can be used for programming:

  • C/C++
  • Visual Basic (VB6, VB2008, VB2010 express and other editions)
  • Visual Basic for Applications (Microsoft Office VBA)
  • Perl
  • Python
  • JAVA
  • Android
  • Javascript (Node.js)
  • And many more…

A complete list of sample code is available here.

This module has  32 on board General purpose I/Os multiplexed with 7 Analog Inputs, each connected to individual screw terminals.  The analog inputs (multiplexed with GPIOs) can be accessed over USB interface for extended functionality. When connected to PC, the module will appear as a serial port in Windows Device Manager (or a serial tty device in Linux and Mac).

How to Use 32 Channel USB GPIO Module

Using this product is very easy,  thanks to the human readable and easy to use command set and the USB CDC interface that  allows the device to be used with most readily available serial terminal software such as Tera Term or HyperTerminal.  This document has more information about using this device with the following Serial terminal software. But in no way limited to this software though.

  • Windows
    • HyperTerminal
    • Tera Term
  • Linux
    • GNU Screen
    • PuTTY
  • Mac OS X
    • Screen Command
    • CoolTerm
    • goSerial

Using this product involves the following simple steps.

  1. Connect the device to a USB port on the host system
  2. Install driver (Only needed for Windows. Driver available for download on the product page.)
  3. Open the COM port corresponding to the device using a Serial Terminal software
  4. Enter commands (Very similar to entering commands at DOS prompt or Bash prompt)
  5. Optionally write a script or application to automate your task (More info on custom programming/scripting is available in this document. Also we have a large set of sample code to help you with)

All aspects of the above steps are covered in the following sections including step by step demonstration.

Components/Tools Required

Along with the module, you may need the items in the list below for easy and fast installation.
1. USB A to Mini B cable.
2. Small screw driver.

USB Interface

The on board full speed USB controller helps a PC/Linux/computer to communicate and control this module seamlessly. Use a USB A to Mini B cable to connect with a PC. Please visit http://www.numato.com to buy cables and accessories for this product. By default, the logic section of the module is powered from USB so make sure not to overcrowd unpowered USB hubs (the picture on the right shows USB Mini connector).

DC Power Supply

This module uses +5V power supply to function properly. By default the board is configured to use +5V supply from USB. So an external +5V power is not required unless USB port is unable to supply enough current. In most cases USB ports are capable of providing enough current for the module. If for any reason, an external 5V power supply needs to be used for the logic section of the module, the Jumper K1 should be configured properly before connecting the power supply. Please refer to the marking on the board for more details. Make sure to connect the power supply in correct polarity. Connect the positive terminal of the power supply to the +5V terminal on the module.

Using a product similar to Numato’s DC Barrel Jack Adapter is recommended if the power supply has a Barrel Jack connector (See the image on right).

Connecting power supply incorrectly can cause damage to the module and/or other devices.

GPIO/Analog Inputs

The module has 32 General Purpose IO pins that can be used for various custom applications. Some of these pins can be used as Analog to Digital Converter inputs as well. All IO pins support 3.3V TTL signals and the ADC input range is 0 to +3.3V. The ADC can acquire analog signal at the resolution of 10 bits per sample. It is recommended to use a series resistor with the GPIO/ADC pins when interfacing with other circuits. In output mode, GPIOs can source up to 25mA (IO source/sink capacity varies depending on IO. Please refer to the Technical Specifications at the end of this document for more details).  Please see the ). So no additional circuitry is needed to drive regular LEDs. A 470 Ohms series resistor is recommended for current limiting when connecting LED to a GPIO.

In contrast to GPIOs, Analog inputs can read voltages at any level between 0 to 3.3V volts. It is recommended to use a series resistor to protect the input from stray voltages and spikes. The internal Analog to Digital converter supports 10 bits resolution which is adequate for most applications. The table below summarizes the GPIO and Analog to Digital Converter input positions on the screw terminals.
The table below summarizes the GPIO and Analog to Digital Converter input positions on the screw terminals in Version 10

GPIOADC
IO0NA
IO1ADC1
IO2ADC2
IO3ADC3
IO4ADC4
IO5ADC5
IO6ADC6
IO7ADC7
GNDGND
IO8NA
IO9NA
IO10NA
IO11NA
IO12NA
IO13NA
IO14NA
IO15NA
GNDGND
IO16NA
IO17NA
IO18NA
IO19NA
IO20NA
IO21NA
IO22NA
IO23NA
GNDGND
IO24NA
IO25NA
IO26NA
IO27NA
IO28NA
IO29NA
IO30NA
IO31NA
GNDGND

Driver Installation

Installing Numato Lab CDC Driver - Windows Desktop and Server Editions

The driver package for Numato Lab’s products can be downloaded from the product page at ttp://numato.com. To install the driver, unzip the contents of the downloaded driver package to a folder. Attach USB cable to the PC and when asked by Windows device installation wizard, point to the folder where driver files are present. When driver installation is complete, the module should appear in Windows Device Manager as a serial port. The picture below shows a 32 Channel USB GPIO Module visible in Windows Device Manager. For other devices, the name will be different but how the device is displayed and used is exactly same.

32 Channel GPIO Module Listed in Windows Device Manager

Note down the name of the serial port (COM1, COM2 etc..). This information is required to control the module from the PC.

You may notice that the driver package does not come with a .sys or .exe file as most driver packages do and is expected to be that way. The driver binary necessary in this case is shipped with all copies of windows Desktop/Server editions and gets installed automatically while Windows is installed for the first time. The .inf and .cat files present in the driver package downloaded from http://numato.com merely associate this pre-existing driver with the attached Numato Lab device.

The following video demonstrates how to install the driver on Windows 10.

Installing on Windows Embedded Editions

Windows Embedded editions do not install the infrastructure necessary for USB CDC by default in favor of a smaller footprint. This will cause the driver install to fail unless the necessary files are manually installed prior to installing the driver. Please follow the steps below to install the prerequisites and driver correctly. These steps are tested on Windows 7 Embedded Edition.

  1. Locate winemb-inf-mdmcpq.cab on Win 7 Embedded DVD/ISO image
  2. Copy winemb-inf-mdmcpq.cab to a folder Ex: C:Temp
  3. Run command DISM.exe /online /Add-Package /PackagePath:C:Temp
  4. Wait for Windows to restart (Restart machine manually if DISM does not restart the machine automatically)
  5. After reboot is complete, plug the device to a USB port and install driver normally (Driver is available for download at the product page)

Installing on Linux

To use any device that uses USB CDC protocol with Linux, USB CDC driver needs to be compiled in to the kernel. Fortunately, most Linux distributions (Ubuntu, Redhat, Debian etc..) has this driver pre-installed. The chances of you requiring to rebuild the kernel to include the USB CDC driver is very slim. When connected to a Linux machine, this product should appear as a serial port under /dev directory. Usually the name of the device will be ttyACMx or similar. The name may be different depending on the Linux distribution you have. The image below shows the result of ls /dev command on a Linux Mint system with a USB GPIO/Relay device attached.

Device Listing on Linux

In this particular case, the device shows up as ttyACM0 (highlighted on orange color) but it could be ttyACM1 or ttyACM2  etc… depending on the specific system and other connected devices. Once the device is visible under /dev directory, it can be treated just like any other serial device. Commands can be sent to the device using any mechanism that is valid for regular serial ports such as screen command or Serial Terminal Emulation applications. If there are more than one devices connected to the same host computer, each device will be displayed as separate serial devices with unique names. These separate serial devices can be used to control individual devices attached.

Installing on Mac OSX

Mac OSX is usually shipped with USB CDC driver pre-installed. When connected to a Mac computer, this product should appear as a serial port under /dev directory. Usually the name of the device will be tty.usbserialportx or similar. The name may be different depending on the Mac OSX version you have. The image below shows the result of ls /dev/*usb* command on a Mac OSX Yosemite system with a USB GPIO/Relay device attached.Listing USB GPIO Devices on Mac OSX

In this particular case, the device shows up as tty.usbmodem141141 (highlighted on orange color) but it could be any name starting tty.usbmodem  or even a completely different name depending on the exact version of operating system and other connected devices. Once the device is visible under /dev directory, it can be treated just like any other serial device. Commands can be sent to the device using any mechanism that is valid for regular serial ports such as screen command or Serial Terminal Emulation applications. If there are more than one devices connected to the same host computer, each device will be displayed as separate serial devices with unique names. These separate serial devices can be used to control individual devices attached.

Installing CDC Devices On Android

Most Android versions has built in driver that supports external USB Devices. Due to the presence of built-in driver any external USB device including Numato Lab’s USB GPIO/Relay products connected to Android based gadget will be enumerated by Android OS. Such enumerated devices can be listed/viewed by using apps such as USB Device Info. The image below shows info about a Numato Lab USB device printed by USB Device Info app.

Numato Lab USB Device Listed In Android

Devices detected by Android can be controlled by using any off the shelf Serial Terminal App such as USB Serial Terminal Lite.

Sending Commands

One of the most powerful features of this module is the simple easy to use command set it supports. This command set hides the complex USB protocol and gives a very simple interface to access the features of the module. The following sections give details of the command set and how to use the command set.

The Commands Set

This product supports a very simple command set that is designed to be less cryptic and easy to use manually (using serial terminal emulation programs) or through a program written in many supported languages.

List of currently supported commands.

No.CommandParametersExampleDescription
1vernoneverReturns firmware version.
2idget/set xxxxxxxxid get, id set 12345678Reads/Writes ID of the module
3gpioset/clear/read, gpio
readall/writeall/
iomask/iodir, gpio notify on/off/get, poweron
gpio set 0, gpio clear 0, gpio read 0, gpio readall,
gpio writeall ffffffff, gpio iomask ffff0000, gpio iodir 0000ffff
gpio notify on,
gpio notify off,
gpio notify get,
gpio poweron 00000000 ffffffff
Control General Purpose Input/Output
4adcreadadc read 1Read Analog to Digital Converter input
5infononeinfoReturns GPIO Power-On Direction & Status

NOTE!

gpio poweron, info feature are available from firmware version A0M10.01 onwards.

The table below has more detailed information about available commands.

No.CommandExampleDescription
1ververReturns current firmware version.
2idid get
Id get reads the module ID.
id set xxxxxxxxId set will assign a new ID to the module. “x” stands for alphanumeric characters including symbols. The new ID must be exactly 8 characters in length.
3gpiogpio set xSets the GPIO output status to high. Here “x” is the number of the GPIO. This command accepts GPIO number from 0 - 9, A-V total 32 values. Please see examples below.

gpio set 0 – Sets GPIO 0 to high state.
gpio set A – Sets GPO 10 to high state.
gpio clear xSets the GPIO output status to low. Here “x” is the number of the GPIO. This command accepts GPIO number from 0 - 9, A-V total 32 values. Please see examples below.

gpio clear 0 – Sets GPIO 0 to low state.
gpio clear A – Sets GPIO 10 to low state.
gpio read xReads the digital input status present at the input mentioned. Here “x” stands for the number of GPIO. This command accepts GPIO number from 0 - 9, A-V total 32 values. The response will be either “on” or “off” depending on the current digital state of the GPIO. Please see examples below.

gpio read 0 – Reads GPIO 0 status.
gpio read A – Reads GPIO 10 status.
gpio
iomask xxxxxxxx
Set mask for selectively update multiple GPIOs with writeall command. A hexadecimal value(xxxxxxxx) must be specified with desired bit positions set to 0 or 1 with no “0x” prepended (eg 0002ffff). A 0 in a bit position mask the corresponding GPIO and any update to that GPIO is ignored during writeall command. A 1 in a bit position will unmask that particular GPIO and any updates using writeall command will be applied to that GPIO. This mask does not affect the operation of set and clear commands.

gpio iomask ffffffff – Unmask all GPIOs.
gpio iomask 00000000 – mask all GPIOs.
Refer Understanding readall/writeall commands for GPIO Modules to know more.
gpio iodir xxxxxxxxSets the direction of all GPIO in a single operation. A hexadecimal value(xxxxxxxx) must be specified with desired bit positions set to 0 or 1 with no “0x” prepended (eg 0002ffff, 00450123, 00ff00ff). A 0 in a bit position configures that GPIO as output and 1 configures as input. Before using gpio readall/writeall commands, the direction of GPIO must be set using “gpio iodir xxxxxxxx" command. GPIO direction set by using iodir command will be modified with subsequent set/clear/read commands
(only affects the GPIO accessed using these commands).
gpio iodir 00000000 – Sets all GPIO to output.
Refer Understanding readall/writeall commands for GPIO Modules to know more.
gpio readallReads the status of all GPIO in a single operation. The return value will a hexadecimal number with binary value 1 at bit positions for GPIO in ON state and 0 for GPIO in OFF state. Eg: a return value 00000000 (binary 0000 0000 0000 0000 0000 0000 0000 0000) means all GPIO are OFF. A value FFFFFFFF (binary 1111 1111 1111 1111 1111 1111 1111 1111) means all GPIO are ON.

gpio readall – Reads all GPIO status.
Refer Understanding readall/writeall commands for GPIO Modules to know more.
gpio
writeall xxxxxxxx
Control all GPIO in a single operation. A hexadecimal value (xxxxxxxx) must be specified with desired bit positions set to 0 or 1. A value 0 at a bit position will turn off the corresponding GPIO. A value 1 at a bit position will turn on the corresponding GPIO.

gpio writeall ffffffff – Sets all GPIO's to high state.
Refer Understanding readall/writeall commands for GPIO Modules to know more.
gpio notify onThis command enables the gpio input change notification. When the gpio Notify feature is enabled, changes to the input pins will be detected and a notification is sent to the host.

To turn on the Notify feature, send the command in the format below.
"gpio notify on"

The GPIO change notification is sent to the host is in the below format.


Current value - 32 bits in hexadecimal format that represents the current input states of all GPIOs.
Previous value - 32 bits in hexadecimal format that represents the previous input states of all GPIOs.
IODIR - Current IODIR value on the device


For example, a GPIO change notification "FFFFFFFE FFFFFFFF FFFFFFFF" means the following.

1.Current IODIR value is FFFFFFFF which means all GPIOs are set to input mode.
2. Input values present on the GPIOs is FFFFFFFF. This means input logic applied to all IOs were logic 1s
2. Current input values present at GPIOs is FFFFFFFE. All IOs stayed the same except for IO0 which changed from logic 1 to 0. This change triggered the device to send this notification.
gpio notify offThis command disables the gpio input change notification feature.
gpio notify getThis command returns whether Notify feature is enabled or disabled.
gpio poweron xxxxxxxx
(feature available from firmware version A0M10.01 onwards)
This command is to control Power-On GPIO Direction and status in a single operation.
gpio poweron ffff0000 000011c5 – Sets GPIOs IO direction and status respectively at each bit position according to the bits of the specified hexadecimal value.
IO direction: 0 – To set the GPIO as output mode & 1 – To set the GPIO as input mode.
IO status: 0 - To clear the GPIO & 1 - To set the GPIO.
‘ffff0000 000011c5’- (1111 1111 1111 1111 0000 0000 0000 0000) (0000 0000 0000 0000 0001 0001 1100 0101):
GPIOs 0-15 are set to output mode & GPIOs 16-31 are set as input mode.
GPIO 0,2,6,7,8 & 12 are set to High
GPIO 1,3,4,5,9-11,13-14 & 15 are set to Low.
5infoinfo
(feature available from firmware version A0M10.01 onwards)
Returns GPIO Power-On Direction & Status

NOTE!

  1. For the commands like gpio read/set/clear, the gpio numbers greater than 9, should be given in upper case(A – V).
    Egs :- gpio set A, gpio clear H
  2. For the commands like gpio writeall/iomask/iodir, the value should be in lower case hexadecimal value(0000 – ffff).
    Egs :- gpio writeall f9ce, gpio iodir a2d5, gpio iomask 4ba8
  3. For the commands like gpio readall/notify on, the output will be showed in upper case hexadecimal value(0000 – FFFF).

Refer Understanding readall/writeall commands for GPIO Modules to know more.

Using the Serial Terminal Emulator Software (Windows)

HyperTerminal

Using this module with Hyper Terminal is very easy. Please follow the steps below.

  • Connect the module to the computer, install driver and note down the name of the new serial port that appears in the device manager.
  • Open Hyper Terminal and select the serial port corresponding to the GPIO module. Click OK.

HyperTerminal USBGPIO Select COM Port

  • A new window will pop up where the serial port settings can be changed. In this window, leave all settings to defaults except Flow Control which needs to be set to “None” and click OK.

HyperTerminal USBGPIO COMPortSettings

  • If everything goes well, you should be presented with a blank screen. Press ENTER key and the command prompt should appear. Commands listed in the table above can be entered here now.

HyperTerminal USBGPIO Command Prompt

For example, here is the response for “ver” command.

HyperTerminal USBGPIO Version Command

TeraTerm

Using the GPIO module with Teraterm is just as easy. Please follow the steps below.

Teraterm is an open source software. A free copy can be downloaded from http://en.sourceforge.jp/projects/ttssh2/releases/
  • Run Teraterm application and select the port corresponding to the GPIO module in the “New connection” dialog and click OK.

Teraterm USBGPIO Select COMPort

  • Press ENTER key on the main window and a command prompt should appear as in the image below.

Teraterm USBGPIO Command Prompt

  • Enter the command at the command prompt. Example “ver” command and response is in the image below.

Teraterm USBGPIO Version Command

Using Serial Terminal Software on Linux

GNU Screen

GNU Screen is a full-screen Window Manager that works with Serial Terminals as well. This makes GNU Screen a very handy tool to communicate with Numato Lab’s USB GPIO/Relay modules and other products. Please visit this document for details on how to install GNU Screen on your Linux machine. Run the command screen /dev/ttyACM0 as shown in the image below. Please don’t forget to replace the device name with device name retrieved from your system. Use sudo or set appropriate permissions for the device where necessary.

Screen Command On Linux

When the screen command is executed, you will be presented with an empty screen. Press ENTER key to see the command prompt. At the command prompt enter any command supported by the device. All commands must be completed by ENTER key press. Please see the list of available commands in the product documentation. The image below shows a few sample commands executed through the screen program and corresponding results.

Screen Command Examples On Linux

PuTTY

PuTTY is a free SSH/TELNET client that works with Serial Terminals as well. This makes PuTTY a very handy tool to communicate with Numato Lab’s USB GPIO/Relay modules and other products. Please visit this document for details on how to install PuTTY on your Linux machine. Start PuTTY by running the command putty at the terminal or double clicking the PuTTY icon. Use sudo or set appropriate permissions for the device where necessary. You will see a screen similar to the below image when PuTTY is started.

 Putty With Numato Lab GPIO On LInux Settings  Putty With Numato Lab GPIO On LInux Settings

Leave settings as shown in the images above. Please don’t forget to replace the device name with device name retrieved from your system.  Click Open button to start PuTTY session. PuTTY will start with an empty screen. Press ENTER key to show the command prompt. At the command prompt enter any command supported by the device. All commands must be completed by ENTER key press. Please see the list of available commands in the product documentation. The image below shows a few sample commands executed through PuTTY and corresponding results.

Putty With Numato Lab GPIO On LInux Command Examples

Using Serial Terminal Software on Mac OS X

The Screen Command

Mac OSX provides a built in command/program called screen that can be used to communicate with any serial device attached to a Mac device. The screen program is a light weight Terminal Emulator that is very easy to use. Run the command screen /dev/tty.usbmodem141141 as shown in the image below. Please don’t forget to replace the device name with device name retrieved from your system.

Screen Command On Mac OSX

When the screen command is executed, you will be presented with an empty screen. Press ENTER key to see the command prompt. At the command prompt enter any command supported by the device. All commands must be completed by ENTER key press. Please see the list of available commands in the product documentation. The image below shows a few sample commands executed through the screen program and corresponding results.

Scren Command Examples On Mac OSX

CoolTerm

CoolTerm is a free Serial Port Terminal application available for Mac OSX . Download and install CoolTerm on your Mac and run.

CoolTerm is a free software and can be downloaded from http://freeware.the-meiers.org/

Select the appropriate serial port corresponding to your attached device. In the image below /dev/tty.usbmodem141141  is selected. Please don’t forget to select the correct port name corresponds to your device and leave all other settings as in the image below. Once all correct settings are selected, click the OK button to open the port.CoolTerm Port Settings

If the port opened successfully, you will be presented with an empty screen. Press ENTER key to see the command prompt. At the command prompt enter any command supported by the device. All commands must be completed by ENTER key press. Please see the list of available commands in the product documentation. The image below shows a few sample commands executed using the CoolTerm and corresponding results.CoolTerm Command Examples

goSerial

goSerial is a free Serial Port Terminal application available for Mac OSX . Download and install goSerial on your Mac and run.

goSerial is a free software and can be downloaded from http://www.furrysoft.de/?page=goserial

Select the appropriate serial port corresponding to your attached device. In the image below /dev/tty.usbmodem141141  is selected. Please don’t forget to select the correct port name corresponds to your device and leave all other settings as in the image below. Once all correct settings are selected, click the OK button to open the port.GoSerial Port Settings

If the port opened successfully, you will be presented with an empty screen. Press ENTER key to see the command prompt. At the command prompt enter any command supported by the device. All commands must be completed by ENTER key press. Please see the list of available commands in the product documentation. The image below shows a few sample commands executed using the goSerial and corresponding results.

GoSerial Command Examples

Using Serial Terminal Software on Android

USB Serial Terminal

Device detected by Android can be controlled by sending commands using USB Serial Terminal Lite. Once connected to the device, enter commands to the command window and press the send button to execute. The commands and the results will be printed in the log window.

 

Using Custom Program and Script

This GPIO module can be controlled using custom programs written in many languages. Almost any language can be used as long as it supports some sort of serial communication method. Some of the supported languages include

  • C/C++
  • Visual Basic
  • Visual Basic for Applications (Microsoft Office VBA)
  • Perl
  • Python
  • JAVA
  • And a lot more…

The APIs need to be used may be different depending on the target operating system even when the same language is used. For example when using C/C++ on Windows, Win32 Serial Communication APIs along with File IO APIs (CreateFile, ReadFile, WriteFile, etc…) needs to be used (see Microsoft Developer Page on serial communications). But when C/C++ is used on Linux operating system “termios”, APIs can be used for serial communication. Please refer to your compiler/language documentation for more details about serial port communication.

Specific details of programming may vary depending on the language and operating system of choice. But the fundamental steps for writing a program to control the GPIO module can be more or less the same. Here is the list of steps that you may need to follow while writing your own program.

  1. Open the serial port for communication.
  2. Set port parameters. Most of the parameters can be left to defaults except Flow Control, which needs to be set to “none”.
  3. To send a command to the module, use an API equivalent to write/writefile and pass the buffer/string containing the command. It is important to append Carriage Return (ASCII 13) to emulate the ENTER key.
  4. If return data is expected (Eg: “ver” command), try to read the characters from the serial port input buffer. APIs equivalent to Read/ReadFile can be used to read data from the module. Please note that the return data will include the command itself (since the module echoes everything back), the result, carriage return and the “>” symbol.

Please visit the product page for available sample programs.

C/C++ on Windows

Visual C++

Microsoft Visual C++ is a C++ compiler/IDE from Microsoft. Express editions of Visual C++ are free to download and use for commercial and non-commercial purposes.  Visual C++ Express is perfectly suitable for writing full fledged applications for Windows and certainly can be used for writing custom applications for Numato Lab’s GPIO/Relay modules. This section talks about C implementation but using the device with C++ is very similar except that you may use object oriented programming techniques where necessary, but APIs and their usage will be same.

Accessing Numato Lab’s GPIO/Relay modules using  Visual C++ 2010 Express will require the following implemented.

  1. Open the serial port representing the device and obtain a handle to the port using CreateFile() Windows API. This handle can be used to communicate with the device.
  2. Use Writefile() Windows API to write commands to the device
  3. Use ReadFile() Windows API to read response from the device

The reader is encouraged to become familiar with the Windows APIs CreateFile(), WriteFile() and ReadFile() to make it easier to understand the code snippets presented here.

Port Name In Device ManagerTo open the port representing the attached device, we need to look up the port name from Windows Device Manager (Please see image to the right). The complete name of the device is not required, only the COMn part is required. If the port number is 9 or below (for example, COM9, COM2 etc..) the port name can be used as is in the program. If the port number is 10 or above (for example, COM10, COM35 etc..) , a different syntax needs to be used. The required syntax is .COMn (for example, COM35 cannot be used as is, rather .COM35 must be used). This syntax works with all port numbers including 9 and below. Microsoft has an informative KnowledgeBase article on this subject. The developer is recommended to visit this article before proceeding.

Once the port name is discovered, the CreateFile() Windows API can be used to open the port.

wchar_t PortName[] = L"\.COM35";

hComPort = CreateFile(PortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

if (hComPort == INVALID_HANDLE_VALUE)
{
    printf("Error: Unable to open the specified portn");
    return 1;
}

If you are wondering why there are more back slashes in the code as part of the port name, please read through http://en.wikipedia.org/wiki/Escape_sequences_in_C for more information.

If the above code is executed successfully, a handle to the port will be available in the variable hComPort. This handle can be used to further communicate with the port/device.

Communication with the device usually falls in to two categories.

  1. Writing to the device (For example, sending a command)
  2. Reading from the device (Fr example, reading the result of a previously sent command)

Setting/Clearing a GPIO is an example of Write operation. To set a GPIO (GPIO0 in this example), we will need to send the command gpio set 0. It is not sufficient to send the command alone, but the command must be terminated using Carriage Return symbol so the device can recognize the end of the command and execute it. The following code writes gpio set 0 command to the device. Please take special note of the line where CR character (0x0D) is added.

/* Copy the command to the command buffer */
strcpy(cmdBuffer, "gpio set 0");

/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;

/* Write the command to the GPIO module. Total 11 bytes including 0x0D  */

printf("Info: Writing command  to the GPIO modulen");

if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified portn");
    return 1;
}

printf("Info:  Command sent successfulyn");

Reading from the device is very similar. One can use the Windows API ReadFile() to read results back from the device. The following code snippet attempts to read data from the device.  Please note the third parameter which is the number of bytes to be read. This parameter must be set to a number larger than the number of bytes expected from the device.  Please note that the bytes returned from the device is not merely the result rather it includes the original command itself, command prompt and newline character etc.. This is because the device will echo all the data sent to it along with the command prompt character (>) along with the result to provide a seamless experience when used with a serial terminal software. So the number of bytes to read (third parameter) must be calculated accordingly. The easiest way to do this is to send the command manually using a Serial Terminal software and count the number of resulting data.  These additional bytes can be filtered out in the software by using string manipulation functions or Regex.

The following code snippet shows how to read bytes from the device.

/*Read back the response*/
if(!ReadFile(hComPort, responseBuffer, 16, &numBytesRead, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified portn");
    return 1;
}

Since the device always responds to a command initiated by the host and does not send any data on its own, for all practical purposes,  a read operation is usually preceded by a write operation where a command is sent to the device. The code snippet below shows a complete Write/Read sequence. This code attempts to send adc read 1 command to the device and read the result back.

/* Copy the command to the command buffer */
strcpy(cmdBuffer, "adc read 1");

/* Append 0x0D to emulate ENTER key */
cmdBuffer[10] = 0x0D;

/* Write the command to the GPIO module. Total 11 bytes including 0x0D  */

printf("Info: Writing command  to the GPIO modulen");

if(!WriteFile(hComPort, cmdBuffer, 11, &numBytesWritten, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified portn");
    return 1;
}

printf("Info:  Command sent successfulyn");

/*Read back the response*/
if(!ReadFile(hComPort, responseBuffer, 16, &numBytesRead, NULL))
{
    CloseHandle(hComPort);
    printf("Error: Unable to write to the specified portn");
    return 1;
}

The data returned will always have the original command itself, command prompt and newline character etc.. in addition to the result. This additional data can be filtered out using string manipulation techniques or Regex. The following code snippet extracts the actual analog data returned from the device.

/* Add a null character at the end of the response so we can use the buffer
with string manipulation functions.
*/
responseBuffer[numBytesRead] = '

JavaScript

This section describes how to write custom programs using JavaScript to control the USB GPIO device.

Node.JS

Node.JS has become one of the most popular framework for network and web based applications. Node.JS has the ability to work with Serial Ports when appropriate modules are installed and this makes Node capable of communicating with Numato Lab‘s USB devices. Node.JS works on Windows, Linux and Mac OS X. Install Node.JS, NPM and the SerialPort module for Node. More information on how to install these application can be found on the links below.

Once all the above prerequisites are installed, we can start writing the JavaScript code.

The very first step is to load the Serial Port module and create an object that represents the serial port corresponding to the device. The following code does this. The exact value of the baud rate doesn’t matter as long as it is a legal value. Also use device names such as COM4 on Windows and device node name such as /dev/ttyACM0 on Linux/Mac.

var SerialPort = require("serialport").SerialPort

//On Windows use the port name such as COM4 and on Linux/Mac, use the device node name such as /dev/ttyACM0
var port = "com4";

var portObj = new SerialPort(port,{
 baudrate: 19200
}, false);

This object can be used to open the port and communicate with the device. The objects Open() method opens the port for communication.

portObj.open(function (error){
  if ( error ) {
		console.log('Failed to open port: ' + error);
  } else {
   //Communicate with the device
}

The write() method can be used to write commands to the device if the port is already opened. The following code snippet shows how.

portObj.write("gpio set 0r", function(err, results){
    if(error){
        console.log('Failed to write to port: '+ error);
    }
});

The Serial Port modules data event can be used to receive response from the device. The following code snippet prints all data received from the device. The data received can be further processed to retrieve the required information such as analog value or GPIO status.

portObj.on('data', function(data){
	console.log('Data Returned by the device');
	console.log('--------------------');
        console.log(String(data));
	console.log('--------------------');
});

Finally a previously opened port can be closed by using the close() method.

portObj.close();

The following complete Node.JS code will open the port and send commands to the GPIO device to turn on GPIO 0 and turn it off after a few seconds.

var SerialPort = require("serialport").SerialPort
var port = "COM11";

var portObj = new SerialPort(port,{
  baudrate: 19200
}, false);

portObj.on('data', function(data){
	console.log('Data Returned by the device');
	console.log('--------------------');
        console.log(String(data));
	console.log('--------------------');
        portObj.close();
});

portObj.open(function (error){
  if ( error ) {
		console.log('Failed to open port: ' + error);
  } else {
		console.log('Writing command gpio set 0 to port');
		portObj.write("gpio set 0r", function(err, results){
			if(error){
				console.log('Failed to write to port: '+ error);
			}
		});
		
		console.log('Waiting for two seconds');
		setTimeout(
			function(){
				console.log('Writing command gpio clear 0 to port');
				portObj.write("gpio clear 0r", function(err, results){
					if(error){
						console.log('Failed to write to port: '+ error);
					}
				});
				
				setTimeout( function(){process.exit(code=0);}, 1000);
			}
		,2000);
  }
});

The image below shows the above script running on Windows. Please note the data returned by the device. The device echoes everything that is sent to it in addition to command prompt and optional result of operation.

Node.JS GPIO On Windows

The image below shows the same script running on Linux Mint.

Node.JS GPIO On Linux

And Mac OS X (This screenshot is taken on Yosemite)

Node.JS GPIO On Mac OSX

Latest files can be downloaded from our GitHub repository.

Analog inputs can be read using the same methods provided by the SerialPort module. Only the specific command needs to change and optionally parse the response from the device to extract the actual analog data. The code below shows how to send the command adc read 0 and parse the response to extract the analog data. The data we are interested is the count returned by the device. javascript’s substr() string function can be used for precise data extraction. Finally the data, which is still a string is converted to an integer by using Number() function.

var SerialPort = require("serialport").SerialPort
var port = "com9";

var portObj = new SerialPort(port,{
  baudrate: 19200
}, false);

portObj.on('data', function(data){
	console.log('--------------------');
    console.log('Analog data Returned by the device = ' + Number(String(data).substr(12, 4)));
	console.log('--------------------');
    
    portObj.close();
});

portObj.open(function (error){
  if ( error ) {
		console.log('Failed to open port: ' + error);
  } else {
		console.log('Writing command adc read 0 to port');
		portObj.write("adc read 0r", function(err, results){
			if(error){
				console.log('Failed to write to port: '+ error);
			}
		});
  }

});

Image below shows the above script running on Windows.

Node.JS Analog On Windows

Same script on Linux.

Node.JS Analog On Linux

And Mac OS X (This screenshot is taken on Yosemite)

Node.JS Analog On Mac OSX

Additional Information

Analog to Digital Converters (ADCs)

32 Channel USB GPIO Module do support Analog to Digital Conversion on some of the GPIO terminals. A list of GPIOs that supports analog function in this product is listed in GPIO/Analog Inputs in this document. There is no special command required to execute to switch between analog and digital mode. Executing “adc” command will set the GPIO to analog mode and executing “gpio” command will set the GPIO back to digital mode on the fly. Resolution of the ADC is 10 bits unless otherwise noted. The input voltage range of the ADC is 0 – VDD (this product uses 3.3V power supply, so the range will be 0 – 3.3V). The result will be returned as a number starting at zero and ending at 1023. Zero indicates zero volts at the ADC input and 1023 indicates VDD (3.3V for this product) at ADC input.

GPIO with Switches

USBGpio Switch connection diagramIt is possible to read the position of a switch that is connected to a GPIO. A SPST or SPDT switch is recommended to use with GPIOs. Push switches do maintain the contacts closed only for a very short time so using them is discouraged. The fundamental idea of using a switch with GPIO is to have the switch cause a voltage level change at the GPIO pin when pressed. Usually this is achieved by using an external pull-up resistor along with the switch. The pull up resistor is connected between the GPIO and VDD and the switch is connected between the GPIO and ground. When the switch is not pressed, the pull-up resistor will cause the GPIO to stay at VDD voltage level. When the switch is pressed, the GPIO is short circuited to ground and stays at zero voltage. This change in voltage and thus the position of the switch can be read using “gpio read” command.

Technical Specifications

ParameterValueUnit
Number of GPIOs32
Number of analog inputs (Multiplexed with GPIOs)7
Digital circuit power supply voltage (USB or external)3.3V
Maximum current drawn by digital circuitry. 300mA
IO Specifications
Maximum IO source current : IO0-IO7, IO16-1O202mA
Maximum IO source current : IO8-IO1525mA
Maximum IO source current : IO21-IO318mA
Maximum IO sink current : IO0 – IO7, IO16-1O202mA
Maximum IO sink current : IO8–IO1525mA
Maximum IO sink current : IO21–IO318mA
GPIO input low voltage 0V
GPOI input high voltage 3.3V
GPIO output low voltage 0V
GPIO output high voltage3.3V
ADC Specifications
Resolution10bits
Full scale range0 – VDDV
Reference voltageVDDV
Recommended Impedance of Analog Voltage Source2.5KΩ
Other Information
USB Vendor ID0x2A19
USB Product ID0x0802

Frequently Asked Questions (FAQs)

Q. What are the serial parameters I need to use when communicating with this board?
A. Since this module uses USB as the underlying transport mechanism, most of the serial parameters do not affect the communication. You can leave all parameters to any legal value (Eg: 2400, 4800, 9600 etc… for baud rate) except Flow control. Flow control needs to be set to “None”.

Q. Where do I find driver for this product?
A. Visit http://numato.com and navigate to the product page. There will be a link to download windows driver. Linux does not require driver installation since in most cases they are shipped with the driver pre-installed.

Q. Why there is no .sys or .exe file in the Windows driver package I downloaded?
A. This product uses USB CDC driver binary which is already present on Windows. All Windows versions (with the exception of Embedded Editions) has this driver binary installed by default. The .inf and .cat files present in the zip file helps Windows identify the device properly and associate appropriate driver (.sys) to the device

Q. Does this product work with Linux?
A. Yes, this product works with Linux. Please see more details on how to use this product with Linux elsewhere in this document.

Q. Does this product work with Mac OSX?
A. Yes, this product works with Mac OSX. Please see more details on how to use this product with Mac elsewhere in this document.

Q. What are the serial terminal software that this product work with?
A. This product works with a lot of different Serial Terminal software. Some examples can be found elsewhere in this document. Different Serial Terminal software are written by different developers with different purposes in mind. So you may encounter some software that may not work with this product. But usually alternatives are available in most if not all cases.

Q. The GPIO looses its previously set value when trying to read the status. Why it is so?
A. When a gpio is to output a value (high/low), that particular GPIO is put to output mode. When you are trying to read the GPIO, it needs to be put in input mode. In input mode, the GPIO will go to high impedance state and thus looses the previously set value.

Q. I’m using x language for programming. How do I find out if this language can be used to program and control the GPIO module?
A. Find out if the language of interest supports some kind of APIs/Functions/Components for serial communication. If it does, most likely you should be able to use that language with this module.

Q. What is the connector marked as ICSP on this module?
A. This connector is used to program the on-board microcontroller. This connector is primarily intended for factory use.

Q. I need a customized version of this product, can Numato do the customization for me?
A. Yes, we can definitely do customization but there may be minimum order requirements depending on the level of customization required. Please write to [email protected] for a quote.

Q. Where can I buy this product?
A. All Numato products can be ordered directly from our web store http://www.numato.com. We accept major credit cards and Paypal and ship to almost all countries with a few exceptions. We do have distributors in many countries where you can place your order. Please find the current list of distributors at http://numato.com/distrib.

Mechanical Dimensions

32gpiomodule-dimensions

Suggest Edit