Hexzahlen von Python am Arduino empfangen und verarbeiten

Hey!

Entweder stell ich mich zu doof an oder ich weiß auch nicht..

Ich möchte gern per Python hexzahlen an den Arduino senden und dadurch LEDS aufleuchten lassen.

Verstehe nicht warum das Ganze nicht funktioniert - hier mein Code:

Von Python ans Arduino:

import serial
import time

ser = serial.Serial('COM3', 9600)
time.sleep(2)
ser.write(0x1B)

if not ser.isOpen():
    ser.open()
print('com3 is open', ser.isOpen())

Arduino Code:

char serialData;

void setup() 
{
  
  Serial.begin(9600);
  pinMode(3, OUTPUT);   //Fach1 - rot
  pinMode(4, OUTPUT);   //Fach1 - blau
  pinMode(5, OUTPUT);   //Fach1 - grün
  pinMode(6, OUTPUT);   //Fach2 - rot
  
}

void loop() 
{
    if(Serial.available())
    {
       
        switch(Serial.read())
      {
        case 0x01: digitalWrite(3, HIGH);
                  break;
        case 0x02: digitalWrite(4, HIGH);
                  break;
        case 0x1A: digitalWrite(5, HIGH);
                  break;
        case 0x1B: digitalWrite(6, HIGH);
                  break;
        default: break;
      }
    }
}

Würde mich sehr über Hilfe freuen!

Grüße

eule

Sorry in english:

I just want to receive hex numbers from python via Pyserial to light up some LEDs.

And I don't know where the bug in my script is.

How can I receive hex numbers and read them?

Thanks alot!

Greetings

Bitte in English.. Von python kannst du nicht sicher sein das nur 1 byte mit serial.write(..) gesendet wird. Bitte versuche mit "serial.write(chr(0x1B))".

You cannot be sure that serial.write in python only writes one byte. 0x1B may be a 4 byte (32 bit) data type. You need to specifically tell python only to transmit one byte with something like "serial.write(chr(0x1B))". You can check the return value of "serial.write()" to see how many bytes are send from python.

EDIT: Oh.. And you should probably make sure that serial is opened in python before sending anything :wink:

TypeError: unicode strings are not supported, please encode to bytes: '\x1b'

ser.write(chr(0x1B))

I got this Error now.

Just change it to "ser.write(chr('\x1B'))" as suggested - and remember to open the serial connection before writing to it, looks like you are writing to it before opening it :slight_smile:

Der Thread wurde ins Deutsch Forum verlegt - jetzt können wir Deutsch quatschen =)

Wenn ich ser.write(b'1') übertrage funktioniert das Ganze, also ist der Port offen.

Es funktioniert mit deinem Tipp leider auch nicht:

File "C:/Users/kevin/PycharmProjects/Arduino/Arduino.py", line 6, in
ser.write(chr('\x1B'))
TypeError: an integer is required (got type str)

My python is rusty, so is my German! :wink: From python try to send with "ser.write(b'\x1b')" this should send one byte with hex value 0x1B (27 decimal).

Yes it runnnnnsss!

Thanks alot!

Greetings!