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"
- Why this is happening and how to fix it
- 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);
}
}