Average rainfall 2001-2016, global tropics

Map: Average rainfall 2001-2016, global tropics

project: Arduino and Python

Introduction

Serial connect Arduino and Python

Arduino sketch

The simple Arduino code below reads a number, adds one (1) to the number and returns the number via Serial.print.

int x;
void setup() {
 Serial.begin(115200);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 Serial.print(x + 1);
}

Python module

Import the pyserial package. If. like me, you use Anaconda for managing your Python environments, use conda to get pyserial:

$ conda install pyserial

or get it via pip:

$ pip install pyserial

You can now use python to identify the serial ports on your machine:

$ python -m serial.tools.list_ports

Copy the port that harbours your Arduino board and paste it into the code snippet:

import serial

import time

arduino = serial.Serial(port='/yourPortType/yourPortId', baudrate=115200, timeout=.1)

def write_read(x):

    arduino.write(bytes(x, 'utf-8'))

    time.sleep(0.05)

    data = arduino.readline()

    return data

while True:

    num = input("Enter a number: ") # Taking input from user

    value = write_read(num)

    print(value) # printing the value

If all worked your Python script should connect to Arduino, ask for a number that will be returned by Arduino + one.

Resources