Hey everyone,
I am starting a project with arduino and python. My current task is to just to communicate over serial from my python program to my arduino and back.
I believe i am writing the data correctly but am unsure since the data i get back from the arduino is the print out, b ' ', where i am only sending "1" and should be returning that a string that states "serial available, X\n", where X is a string of the data sent from the python program.
I have tried using serial.read and serial.readline and both have the same outcome.
Looking at examples on the website i do not see what i am doing wrong. Though my serial interface is in a class on the python side of things.
Arduino code
#define BAUD_RATE 115200
#define MSG_BUFF 256
#define S_IN_BUFF 10 // serial input buffer size
uint8_t serial_in[S_IN_BUFF] = {'\0'};
char serial_msg[MSG_BUFF] = {'\0'};
void setup()
{
Serial.begin(BAUD_RATE);
while (!Serial) {} // wait for serial interace to connect
Serial.setTimeout(1);
}
void loop()
{
int i = 0;
int num_recv = 0;
if (Serial.available()) {
num_recv = Serial.readBytes(serial_in, S_IN_BUFF-1); // room for '\0'
serial_in[num_recv] = '\0';
sprintf(serial_msg, "serial available, %s\n", serial_in);
Serial.print(serial_msg);
}
}
Python code
import serial
import time
class arduino_com:
def __init__(self, port, baudrate, rtimeout, encoding):
self.port = port
self.baudrate = baudrate
self.rtimeout = rtimeout
self.arduino = 0 # will be serial object
self.encoding = encoding
def begin(self):
self.arduino = serial.Serial(port=self.port, baudrate=self.baudrate,
timeout=self.rtimeout);
def write(self, msg, delay=0.05):
self.arduino.write(bytes(msg, self.encoding))
time.sleep(delay)
def read(self):
return self.arduino.read()
def read_line(self):
return self.arduino.readline()
Python main
from arduino_serial import arduino_com
BAUD_RATE = 115200
SERIAL_PORT = "/dev/ttyACM0"
RTIMEOUT = 0.1 # read serial timeout
ENCODING = "utf-8"
if __name__ == "__main__":
arduino_serial = arduino_com(SERIAL_PORT, BAUD_RATE, RTIMEOUT, ENCODING)
arduino_serial.begin()
arduino_serial.write("1")
print(arduino_serial.read_line())
Any suggestions would be appreciated.
Also it happens with anything i send, "1" or "x" etc. the printout is b ' '