Arduino与Python之间的串口通信,使用十六进制值的问题

Serial Communication between Arduino and Python, issue of using hexidecimal values

我正在尝试通过 Python 3.4 中的代码从计算机启动电机,使用 pySerial 与 Arduino Uno 通信。我已经将要发送的值打包为十六进制,所以我一次只有一个字节,但是当我在 Python 端发送时,在 Arduino 端获取正确的数字时遇到了问题。

PYTHON 代码:

import serial 
import struct


ser = serial.Serial(
    port ='COM4', 
    baudrate = 9600, 
    parity = serial.PARITY_ODD, 
    stopbits = serial.STOPBITS_TWO, 
    bytesize = serial.EIGHTBITS
    )

#ser.open()     #opens port 
ser.isOpen()    #returns true?


motorState = 0
wristBend = 'Left'

while True:
    #need to create options to send to arduino

    if wristBend == 'Left':
        motorState = 2
    elif wristBend == 'Right':
        motorState = 3
    else:
        motorState = 1

    motorChar = struct.pack('<B', motorState)          #returns the value as a character interger
    #motorChar = str(hex(motorState))

    print(motorChar)
    ser.write(motorChar)
    print(ser.read())
    break

ARDUINO 代码:

int motorPinLeft = 10;
int motorPinRight = 11; 
int motorSpeedLeft = 0;
int motorSpeedRight = 0;


void setup() {
  pinMode(motorPinLeft, OUTPUT);
  pinMode(motorPinRight, OUTPUT);
  Serial.begin(9600);
  while(!Serial); //waits for arduino to be ready, not neaded for duo
  Serial.println("Speed 0 - 255");
}

void loop() 
{
  if (Serial.available())
  {
    int ch = Serial.read();

      switch (ch)
      {
        case 1:
          motorSpeedLeft = 0;
          motorSpeedRight = 0;
          break;
        case 2:
          motorSpeedLeft = 127;
          motorSpeedRight = 0;
          break;
        case 3:
          motorSpeedLeft = 0;
          motorSpeedRight = 127;
          break;

      }

      Serial.write(ch);

      analogWrite(motorPinLeft, motorSpeedLeft);
      analogWrite(motorPinRight, motorSpeedRight);

      delay(2500);     //wait for 2.5 seconds to make the motor vibrate
      motorSpeedRight = 0;
      motorSpeedLeft = 0;

      analogWrite(motorPinLeft, motorSpeedLeft);
      analogWrite(motorPinRight, motorSpeedRight);

不仅没有任何东西与我的电路通信,而且我的 python 代码的输出,我在其中打印发送到 Arduino 的内容以及从 Arduino 发送的内容是这样的:

b'\x02'
b'S'

如果我将 switch case 代码更改为 83(S 的 ASCII 代码),或者将变量类型更改为 byte、int、uint8_t,我将得到完全相同的输出。我在这里做错了什么?对不起,如果它有点明显,我对 python 和 arduino 还很陌生。在此先感谢您的帮助!

这里是一个简单的例子并不难,从简单开始然后增加功能到你想要的通常是个好主意。

test_serial.py

import serial
ser = serial.Serial("COM4",timeout=5) # everything else is default
ser.write("\x45")
print "RECIEVED BACK:",repr(ser.read(5000))

test_serial.ino

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
}