$USD
  • EUR€
  • £GBP
  • $USD
TUTORIALS Arduino

How to Control Arduino with Python and PinPong Library

DFRobot Oct 18 2023 1763

The first challenge a Python programmer faces when programming an Arduino is that the language is different. The Arduino IDE works with a language inspired by C and C++. In fact, platforms like Arduino work well with Python, especially for applications that require integration with sensors and other physical devices. If you already know the basics of Python, then you’ll be able to get started with Arduino by using Python to control it.

The main goal of this tutorial is to show you how you can communicate with an Arduino using Python via PinPong Library to develop your own electronic projects.

 

Why is PinPong Library?

The PinPong library is a Python library for controlling open-source hardware development boards. It is based on the Firmata protocol and compatible with MicroPython syntax. With the PinPong library, you can use Python code to control various common open-source hardware devices. The underlying principle is to flash a specific firmware onto the hardware board, enabling communication between the board and the computer via serial communication to execute various commands.

The name of the PinPong library is composed of "Pin" and "Pong". "Pin" refers to the pin, while "Pong" is derived from the classic game Pong, symbolizing the back-and-forth transmission of signals.

The design of the PinPong library aims to free developers from being restricted by specific hardware models during the development process, allowing them to focus on software implementation. Even if you initially develop your program using Arduino, you can easily switch to another compatible board like the PinPong board by modifying the hardware parameters.

 

Key Features of PinPong Library

  • High Flexibility: It Supports Arduino boards including Uno, Leonardo, Mega2560, ESP32 boards (such as HandPy), micro:bit, Unihiker, and more. It also supports 50+ sensors and will support other development boards and expansion libraries gradually.
  • Compatibility with MicroPython: MicroPython is a variant of the Python programming language that is widely used and known for its simplicity and readability. By being compatible with MicroPython, PinPong simplifies the development process and allows developers to leverage their existing knowledge of Python to program and control their hardware.

 

How to Install PinPong Library

To confirm Python 3 is installed on your computer before installing the PinPong library.

 

Install PinPong Library on Windows

After the download is complete, follow the prompts to proceed with the installation. Pay attention to the installation process's final step, and check the option "Add to PATH" to add Python to the system's environment variables.

Install PinPong Library on Windows
 

1. Open the Command Prompt. Use the Win+R shortcut, type "cmd", and press Enter.

Open the Command Prompt
 

2. Install the PinPong library. Enter "pip install pinpong" in the Command Prompt window and wait for a moment for the installation to complete.

Install the PinPong library


3. Information Query. To obtain the current version information, official documentation website, library list, and port number, please enter "pingpong" in the “Help Command” prompt.

 

Install PinPong Library on Linux

Once Python 3 is installed, you can proceed with the PinPong installation by entering "sudo pip install pinpong" in the terminal.

Install PinPong Library on Linux
 

Install PinPong Library on Mac OS

Once Python 3 is installed, you can proceed with the installation of the PinPong Library by following these steps:

  • 1. Open any Finder window and press Shift+Command+U.
  • 2. Double-click on the "Terminal" application.
  • 3. In the Terminal, enter the command "sudo pip install pinpong" to install the PinPong library.

Install PinPong Library on Max OS
 

Essential PinPong Library Examples

Essential PinPong library samples, including basic, common, and extended library examples, are indispensable for beginners. These examples can assist beginners in understanding and learning how to utilize these libraries for developing PinPong-related applications or projects.

 

Basic PinPong Library Examples:

These example programs can help you quickly verify the usage of modules. Copy and paste the code into a Python editor, and modify the board initialization configuration according to the model of the board you are using. The modules in the basic library examples are imported through the Board library. The basic PinPong library contains the following items.

Example: LED blink

Connect an Arduino main control board to a Windows or Linux computer. Control the onboard LED of Arduino UNO to blink once every second.

-*- coding: UTF-8 -*-
Experiment effect: Control the onboard LED of the Arduino UNO to blink once per second
Connection: Use a Windows or Linux computer to connect to an Arduino main control board
import time
from pinpong.board import Board, Pin
 
Board("uno").begin()  # Initialization, select board type (uno, microbit, RPi, handpy) and port number. If no port number is entered, automatic detection will be performed
Board("uno", "COM36").begin()  # Initialization with specified port on Windows
Board("uno", "/dev/ttyACM0").begin()  # Initialization with specified port on Linux
Board("uno", "/dev/cu.usbmodem14101").begin()  # Initialization with specified port on Mac
led = Pin(Pin.D13, Pin.OUT)  # Initialize the pin for digital output
 
while True:
  # led.value(1)  # Output high level Method 1
  led.write_digital(1)  # Output high level Method 2
  print("1")  # Print information in the terminal
  time.sleep(1)  # Wait for 1 second to maintain the state
 
  # led.value(0)  # Output low level Method 1
  led.write_digital(0)  # Output low level Method 2
  print("0")  # Print information in the terminal
  time.sleep(1)  # Wait for 1 second to maintain the state

There are other PinPong library examples available that demonstrate how to use a button to control the onboard LED of Arduino UNO, vary the LED's brightness, and test the analog pin interrupt functionalities. For more details, please visit: https://wiki.dfrobot.com/basic_library_examples

 

Practical PinPong Library Examples:

The modules in the common library examples are imported through the board library.

Example: Control Servo Motor:

-*- coding: UTF-8 -*-
Connection: Connect an Arduino main control board to a Windows or Linux computer, and connect a servo to D4
import time
from pinpong.board import Board,Pin,Servo # Import Servo library

Board("uno").begin()  # Initialization, select the board type (uno, microbit, RPi, handpy) and port number. If no port number is entered, automatic recognition will be performed
#Board("uno","COM36").begin()  # Initialization by specifying the port under Windows
#Board("uno","/dev/ttyACM0").begin() # Initialization by specifying the port under Linux
#Board("uno","/dev/cu.usbmodem14101").begin()   # Initialization by specifying the port under Mac

s1 = Servo(Pin(Pin.D4)) # Initialize the servo pin by passing Pin into Servo

while True:
    #s1.angle(0) # Control the servo to turn to the 0 degree position Method 1
    s1.write_angle(0)  # Control the servo to turn to the 0 degree position Method 2
    print("0")
    time.sleep(1)

    #s1.angle(90) # Control the servo to turn to the 90 degree position
    s1.write_angle(90)  # Control the servo to turn to the 90 degree position Method 2
    print("90")
    time.sleep(1)

    #s1.angle(180) # Control the servo to turn to the 180 degree position
    s1.write_angle(180)  # Control the servo to turn to the 180 degree position Method 2
    print("180")
    time.sleep(1)

    #s1.angle(90) # Control the servo to turn to the 90 degree position
    s1.write_angle(90)  # Control the servo to turn to the 90 degree position Method 2
    print("90")
    time.sleep(1)

In addition to that, there are other practical examples available in the PinPong library. These examples cover controlling a buzzer for sound generation, reading data from an ultrasonic sensor, obtaining temperature and humidity readings from a DHT sensor, and managing WS2812 single-wire RGB LED lights. For more detailed information, please refer to the provided link.

https://wiki.dfrobot.com/common_library_examples

 

Extended PinPong Library Examples

The modules in the extended library examples are imported through the libs library. You can use the terminal to enter "pinpong" to query the supported list and usage methods. All example program codes can be found in the "examples" folder in the installation directory.

Example: Color recognition

Connect the TCS34725 color sensor to the I2C pins (SCL and SDA) of an Arduino board, which is connected to a Windows or Linux computer. Retrieve color values from the I2C TCS34725 color sensor.

-*- coding: UTF-8 -*-
Experiment effect: Read the values of the I2C TCS34725 color sensor
Wiring: Connect an Arduino main control board to a Windows or Linux computer, and connect the TCS34725 color sensor to the I2C port SCL and SDA

import time
from pinpong.board import Board
from pinpong.libs.dfrobot_tcs34725 import TCS34725 # Import the tcs34725 library from libs

Board("uno").begin()               # Initialization, choose the board type (uno, leonardo, xugu) and port number. If the port number is not entered, automatic recognition will be performed
#Board("uno","COM36").begin()      # Initialization with specified port on Windows
#Board("uno","/dev/ttyACM0").begin() # Initialization with specified port on Linux
#Board("uno","/dev/cu.usbmodem14101").begin()   # Initialization with specified port on Mac

tcs = TCS34725() # Sensor initialization

print("Color View Test!");
while True:
  if tcs.begin(): # Look for the sensor, return True if found
    print("Found sensor")
    break # If found, break the loop
  else:
    print("No TCS34725 found ... check your connections")
    time.sleep(1)

while True:
  r,g,b,c = tcs.get_rgbc() # Get the RGBC data
  print(r,g,b,c)
  print("C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b))

  '''
  # Data conversion
  r /= c
  g /= c
  b /= c
  r *= 256
  g *= 256
  b *= 256;
  print("------C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b))
  '''
  time.sleep(1)

Other extended PinPong library examples like reading values from the I2C TCS34725 color sensor, I2C ultrasonic sensor (URM09), I2C MLX90614 infrared temperature sensor, and reading card information using the NFC module with I2C, you can visit the link below for more details.

https://wiki.dfrobot.com/extended_library_examples

 

Arduino Projects with Python via PinPong Library

Automatic Plant Watering System

To ensure plants' healthy growth, regular watering is necessary. However, we often forget to water our plants, which can lead to withering. To avoid such issues, we can design an automatic plant watering system.

 

First Step for Automatic Plant Watering System

Drive the Relay

Hardware Setup:

  • 1. Controller: Arduino UNO, IO Sensor Expansion Board V7.1
  • 2. Module: Relay module
  • 3. Connection: Type A to B USB cable
  • 4. Connect the relay to digital pin 13

First Step for Automatic Plant Watering System Drive the Relay
 

Start Coding

The relay is controlled by toggling the digital pin's high and low states. We can refer to the "Digital Output" example in the official documentation of the base library. Running this program will make the relay produce a clicking sound as it switches along with the blinking of the LED.

Start Coding
 

Second Step for Automatic Plant Watering System

Controlling the Water Pump with the Relay

To implement the watering function, we need to use a water pump. However, most water pumps operate at 12V, while the output voltage of the Arduino UNO is 5V, which is insufficient to directly drive the water pump. In this case, we need to use a relay to control the water pump.

 

Hardware Setup

  • 1. Controller: Arduino UNO, IO Sensor Expansion Board V7.1
  • 2. Module: Relay module, water pump, 12V power supply
  • 3. Connection: Type A to B USB cable
  • 4. Connect the relay to digital pin 13.
  • 5. Connect the water pump to the relay.

Controlling the Water Pump with the Relay
 

Start Coding

You can use the time.strftime() function of the time module to determine the time. In the example, it sets "Watering" at 15:30:10 every day. In actual use, you can add the relay control function accordingly.

Start Coding

import time
while True:
    time_now=time.strftime("%H:%M:%S,time.localtime())
    if time_now == "15:30:10":
         print("浇花")
         time.sleep(1)

Add the relay to implement the daily scheduled watering function.

Start Coding

import time
from pinpong.board import Board,Pin
Board("uno").begin()
led = Pin(Pin.D13, Pin.OUT)
while True:
    time_set = time.strftime("%H:%M:%S",time.localtime())
    print(time_set)
    if time_set == "15:30:10":
        led.write_digital(1)
        print("浇花")
        time.sleep(5)
        else:
            led.write_digital(0)
            time.sleep(1)

Conclusion:

The PinPong library provides a convenient way for Python developers to control Arduino boards. It simplifies the communication process with Arduino, making it easier and more flexible to control Arduino using the Python programming language. Whether you are a beginner or an experienced developer, PinPong library is a valuable tool for building various IoT and embedded systems projects. So, if you're a Python programmer looking to explore the world of Arduino, this tutorial provides a great starting point for you.


REVIEW