Test Example-7a: Accessing Arduino GPIO Pins from Python

Test Example-7a: Accessing Arduino GPIO Pins from Python

This example demonstrates how to read/write GPIO pin values of Arduino Uno board (connected to the host computer through serial port) using a Python script on the host computer. Even through this test example uses Arduino Uno R3 board, same procedure can be adopted for other Arduino micro-controller boards supported by CASP.

Pre-Requisites

  • Arduino Uno R3 board with a USB cable.
  • CASP software is installed and functional.
  • CASP Python libraries are installed.
  • Arduino BSP is installed.
  • The project files are located at CASP installed directory ‘CASP/support/examples/casp_gpio_examples/arduino_boards/casp_gpio_uno_nano_leonardo_serial’. These are also available for download at this link.

Programming the Board

Before starting this example, the target board should be programmed with binary file that enables CASP GPIO communication protocol. Please follow below steps to program the target board with the binary file that enables CASP GPIO communication protocol.

  • Connect Arduino Uno board to the USB of the computer
  • Run CASP and click on Tools > Programmer
  • It opens a programmer dialog box. Set board as ‘Arduino Uno’, programmer as Programme0, select serial port to which the board is connected and select the binary file from CASP installed directory ‘CASP/support/examples/casp_gpio_examples/arduino_boards/casp_gpio_uno_nano_leonardo_serial/bin/casp_gpio_uno.hex’
  • Click ’Program’ button to program the board with the above selected binary file. Screen shot is shown below.

Accessing GPIO from Python

  • Open terminal in directory ‘CASP/support/examples/casp_gpio_examples/arduino_boards/casp_gpio_uno_nano_leonardo_serial/python’.
  • Start Python by typing ‘Python’ or ‘Python3’ in the terminal. Type following commands in Python to access GPIO values from the target board.
> import casp_gpio as casp #import CASP GPIO module

> import casp_gpio_pins as pins #import CASP GPIO Arduino Uno R3 pin description module ‘casp_gpio_pins.py’ located in the same directory where the terminal is running

> casp.Init() #initialize CASP GPIO client process on host computer

> casp_gpio.SerialPorts() #display available serial ports (used to identify the serial port to which the board is connected)

> casp.ConnectSerial("COM35") #starts communicating with the target board using GPIO protocol on COM35. Change the serial port as per your setup.

> casp.Write(pins.DO_13, 1) #on-board LED ON

> casp.Write(pins.DO_13, 0) #on-board LED OFF

> casp.Read(pins.ADC_A0) #Read ADC value from pin-A0

> casp.Read(pins.DI_2) #Read digital input pin-2 value

> casp.Write(pins.PWM_3, 500) #Write PWM value 500 (range 0 to 1000) to pin-3

> casp.Write(pins.SERVO_10, 45) #Write servo angle 45 (range -90 to 90) to pin-10
  • Below is the screen shot of above commands. You may try other pins from ‘casp_gpio_pins.py’

Related Links