Saturday, February 13, 2021

Raspberry Pi with Arduino

Over the last few months I was developing hard- and software for a project. While I won't disclose any details of the project here, I think it would be fun for the readers to see me learning Raspberry Pi, Arduino and Python.
And yes, the previous Raspberry Pi blog posts were all somewhat triggered by the project mentioned above. In fact, the main idea of the project was not only using Raspberry Pi hardware for the project itself, bu also as main hardware for the company running said project, including all staff. (I am diverting...)

On particular problem with Arduino boards hooked up to Raspberry Pi boards is that the device might change from /dev/ttyACM0 to /dev/ttyACM1 from one use to the other. When using cheap clones, the device might be /dev/ttyUSB0.
So, in a project using Arduino (clone) boards with a Raspberry Pi board, one needs to test which device is in use.

Here comes the learn Python with me. This might not be the most elegant way to do this, however, here is a solution that works for me:

def initialize():
    global SERIAL_PORT
    global ser
    # find a valid serial port
    try:
        TSER='/dev/ttyACM0'
        print('trying '+TSER)
        tser = serial.Serial(
            port=TSER,
            baudrate = 115200,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
        )
        print(TSER + ' found')
        SERIAL_PORT=TSER
        tser.close()
    except serial.serialutil.SerialException:
        try:
            TSER='/dev/ttyACM1'
            print('trying '+TSER)
            tser = serial.Serial(
                port=TSER,
                baudrate = 115200,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                bytesize=serial.EIGHTBITS,
                timeout=1
            )
            print(TSER+' found')
            SERIAL_PORT=TSER
            tser.close()
        except:
            print('no Arduino found, using clone')
            SERIAL_PORT='/dev/ttyUSB0'
            
    finally:
        print('using '+SERIAL_PORT)

    ser = serial.Serial(
        port=SERIAL_PORT,
        baudrate = 115200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
    )