Arduino and Python Serial Communication

Hello,
I am trying to use Arduino and Python, but I have a problem. When I am sending something from the Arduino to the python, it works fine.
But when I am trying to send a number (1 byte) from the Python to the Arduino, the Arduino receives this:
"\x00\x00\x00\x00\x00\x00\x00"

  1. Why this is happening and how to fix it
  2. How can I send from Python multiple bytes (Strings)?

Thanks in advance!!!

The Python Code:

import serial
import time
arduino = serial.Serial('COM6', 9600)
while True:
	msg = arduino.readline()
	print(msg)
	msg = msg.rstrip()
	msg = msg.decode('utf-8')
	try:
		if int(msg) == 3:
			print("Sleep Mode")
		elif int(msg) == 4:
			print("Manual Mode")
			'''
			Here, i will wait until I recieve  a Value from a sensor
			so i replaced it with a simple wait command for now
			'''
			time.sleep(2)
			arduino.write(7)
		elif int(msg) == 5:
			print("Auto Mode")
	except:
		print(msg)

And the Arduino Code Simplified:

#define buzzerpin 12
#define motorled1 10
#define motorled2 11
#define swcpin 2

String readStrings = "";
int swcv = 0;
void setup() {
  Serial.begin(9600);
  pinMode(swcpin, INPUT);
  pinMode(motorled1, OUTPUT);
  pinMode(motorled2, OUTPUT);
  pinMode(buzzerpin, OUTPUT);
}

void loop() {
  swcv = map(pulseIn(swcpin, HIGH), 990, 1770, 1, 3);

  ////////////////////////////////////////////////////////
  if (swcv != oldswcv) {
    tone(buzzerpin, 1108);
    delay(100);
    noTone(buzzerpin);
    oldswcv = swcv;
    if (swcv == 1) {
      Serial.println(5);
    }
    else if (swcv == 2) {
      Serial.println(4);
    }
    else if (swcv == 3) {
      Serial.println(3);
    }
  }
  ////////////////////////////////////////////////////////
  if (swcv == 2) {
    analogWrite(motorled1, 0);
    analogWrite(motorled2, 0);

    readStrings = "";
    while (Serial.available())
    {
      if (Serial.available() > 0)
      {
        char c = Serial.read();  //gets one byte from serial buffer
        readStrings += c; //makes the string readString
      }
    }
    if (readStrings.length() > 0)
    {
      //Serial.print("Arduino received: ");
      Serial.println(readStrings); //see what was received
      tone(buzzerpin, 2216);
      delay(150);
      noTone(buzzerpin);
      delay(200);
    }
  }

  
  else if (swcv == 3) {
    analogWrite(motorled1, 0);
    analogWrite(motorled2, 0);
  }
  
  else { //Mode1
    analogWrite(motorled1, 0);
    analogWrite(motorled2, 0);
  }

}
        char c = Serial.read();  //gets one byte from serial buffer
        readStrings += c; //makes the string readString

You send a binary byte 7 (BEL in ASCII) from Python to the Arduino and read it there to add to a string? That doesn't make sense. The way around you don't use the write() method to send the values but you use println() which converts the value to an ASCII string before sending. And readString is never reset, so it accumulates all received bytes.

BTW: you should not use the String class on AVR Arduinos as it fragments the memory in short time frame.

This Simple Python - Arduino demo should help get you started

The Python code should work on Windows if you edit it to use the Windows style of COM ports.

See also Serial Input Basics - simple reliable non-blocking ways to receive data.

...R

You can interface Python with Arduinos via USB serial easily using the compatible libraries: pySerialTransfer and SerialTransfer.h.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE’s Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

Example Python Script:

from time import sleep
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM13')
        
        link.open()
        sleep(2) # allow some time for the Arduino to completely reset
    
        link.txBuff[0] = 'h'
        link.txBuff[1] = 'i'
        link.txBuff[2] = '\n'
        
        link.send(3)
        
        while not link.available():
            if link.status < 0:
                print('ERROR: {}'.format(link.status))
            
        print('Response received:')
        
        response = ''
        for index in range(link.bytesRead):
            response += chr(link.rxBuff[index])
        
        print(response)
        link.close()
        
    except KeyboardInterrupt:
        link.close()

Example Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  myTransfer.txBuff[0] = 'h';
  myTransfer.txBuff[1] = 'i';
  myTransfer.txBuff[2] = '\n';
  
  myTransfer.sendData(3);
  delay(100);

  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");
    Serial.println(myTransfer.status);
  }
}