Reading Arduino data over serial with python3

Hello all,

I am attempting to use a Python3 function to send and receive data from an Arduino.  Here is the function I am trying to use:
def communicating_with_arduino(character_variable):
    import serial
    import time
    arduino = serial.Serial('/dev/ttyACM0', 115200)
    arduino.write(bytes(character_variable, 'utf-8'))
    print(character_variable)
    returned_data = arduino.readline()
    returned_data = returned_data.decode('utf-8')
    return returned_data

The character_variable is something that is "A", "B", "9", etc.

I have confirmed good code that sends and receives data just fine from my Arduino. The only difference that I can think of is that my good code is not a function, but a simple Python3 script.

I THINK my Python3 function is writing to my Arduino since I placed a print line under the arduino.write(bytes(character_variable, 'utf-8')) line and it printed out data, but it did not print out data under the returned_data = arduino.readline() line.

this

will likely reboot your arduino if you have a UNO or MEGA or similar... so it's possible it's not ready when you send the character as the setup takes a bit of time to run and Serial be ready

I figured out a solution! I created a class and function. Within the class I defined a variable that sets the "arduino = serial.Serial('/dev/ttyACM0', 115200)" and then I created a function that sends and receives data. Here is my sample code for Python3:

import serial
class arduino_communication:
    # Class variable
    arduino = serial.Serial('/dev/ttyACM0', 115200)
    
    def simple_demo(self, character_variable):
        arduino = self.arduino
        arduino.write(bytes(character_variable, 'utf-8'))
        returned_data = arduino.readline()
        returned_data = returned_data.decode('utf-8')
        return returned_data

Here is my Arduino code:

void loop(){
	incomingByte = Serial.readStringUntil('\n');
	Serial.println(incomingByte);
}

It is good practice to always choose such names for variables so that they do not create confusion:

Your variable named incomingByte, but by the code, it has a String type.
This is so that no one guesses? :slight_smile:

I will be honest, that is just bad practice on my part. :wink:

yeah man, fuck'em!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.