python - 通过串行通信发送多个字节

标签 python arduino bytearray serial-communication

我将 Arduino 和 Python 3.4 与 pySerial 一起使用,并试图通过串行通信发送多个字节,但由于我的代码正在运行,所以我遇到了问题,但是我在某些地方用于调试目的的打印语句正在输出字符串,我我没有期待。我已经尝试编写此代码的简化版本并且它可以正常工作,所以我不确定我做错了什么! 此外,为了解决这个问题,我加入了一个 if 语句,这大大降低了代码速度。非常感谢任何有关如何简化代码以提高速度和/或如何发送和接收正确数据的建议!

python :

#sources:
#http://stackoverflow.com/questions/676172/full-examples-of-using-pyserial-package for more info
#http://pyserial.sourceforge.net/pyserial_api.html

import serial 
import time

#sets the connection parameters, relook at when know more
ser = serial.Serial(
    port ='COM4', 
    baudrate = 9600, 
    parity = serial.PARITY_ODD, 
    stopbits = serial.STOPBITS_TWO, 
    bytesize = serial.EIGHTBITS,
    timeout = 5
    )

def decToPercent (decimal):
    #maps value from 0-1 to 0-255 and makes into an interger, then to hex
    intPercent = round(decimal*255)
    return intPercent

ser.isOpen()    #returns true?

firstContact = False 
inByte = 0
wrist = 0.9         #setup of variables which I will get from dictionary of other code once integrate
elbow = 0       #assuming variables will be included in (0-1)   

wristPerc = decToPercent(wrist)
elbowPerc = decToPercent(elbow)

forceBytes = bytearray([wristPerc, elbowPerc])      #puts the motor values into an array as hex
print(forceBytes)

#set up initial contact with the arduino 
inByte = ser.read(1)
print(inByte)

while True:
    if (firstContact == False):

        if inByte == b'A' :
            firstContact = True
            ser.write('a'.encode())
            inByte = ser.read(1)

    else:

        ser.write(forceBytes)
        time.sleep(0.05)
        print(ser.readline())

最初我让代码开始,并在使用这段代码后返回整个 while 语句,但我把它去掉了,因为我认为它使代码流稍微弄乱了输出:

    #starts the process over again, clears so that have time to get information
    firstContact = False        
    inByte = ser.read(1)
    print(inByte)

Arduino 代码:

//See Arduino Cookbook chapter 4 for info on sending and recieving multiple messages in one
//See example of serial call response for strategy on how to process information faster
int motorPinLeft = 10;
int motorPinRight = 11; 
int motorSpeedLeft = 0;
int motorSpeedRight = 0;

int fieldIndex = 1;
char values[2];    //array holding values for the fields we expect 
char newByte = 0;

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

void loop() 
{
  while (Serial.available()>0)    //checks to see if anything needs to be sent,
  {                            //denoted by recieveing signal from pySerial
      char inByte = Serial.read();

      switch (inByte)
      {
        case 97:
          inByte = 0;
          break;

        default:

          values[0] = inByte;
          //could just call Serial.read and asign 2nd byte, but loop allows to send more variables later
          if (fieldIndex < 2)
          {
            newByte = Serial.read();
            values[fieldIndex] = newByte;
            fieldIndex++;
          }

          else
          {
            Serial.print(values[0], DEC);    //debugging purposes 
            Serial.print(values[1], DEC);

            motorSpeedLeft = values[0];
            motorSpeedRight = values[1];

            //Serial.print(motorSpeedLeft);
            //Serial.print(motorSpeedRight);

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


            delay(3000);     //  to make the motor vibrate for 1 second

            motorSpeedRight = 0;
            motorSpeedLeft = 0;

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

            delay(1000);
          }
      }

      //Serial.print('A');


  }
}


//allows arduino to be ready before pySerial sends any messages
void establishContact()
{
  while (Serial.available()<=0) 
  {
    Serial.print('A');
    delay(300);
  }
}

输出:

bytearray('b\xb2\x00')
b'A'
b'0K\xfe'
b'-\x13j10k\xfe'
b'-\x13j10k\xfe'

每次出现打印语句时我的电机都在运行,所以我不确定是否只是我的打印语句出错,而不是实际的串行通信?

我不确定的另一件事是,在我的 arduino 代码中的 switch-case 语句中,我使用的是 'a' (97) 的 ascii 代码,而不是实际放置 'a'。两者都应该有效吗?

最佳答案

经过更多的折腾,我得到了通过在 arduino 代码中从 Serial.print() 切换到 Serial.write() 来打印出正确输出的代码,因为我很确定这是主要问题,我回到我的原始代码,没有 if 语句来减少运行代码所需的时间。我确实在打印出两个输出时遇到了一些麻烦,但是通过放置:

delay(10) 

在 Serial.write 语句之间,它解决了这个问题。

关于python - 通过串行通信发送多个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604257/

相关文章:

python - 为什么 python 整数缓存范围 [-5, 256] 不能在所有平台上以类似的方式工作?

python - 如何像 Pandas 老板一样切片、排名和争吵

arduino - 将 typedef 函数指针作为参数传递在 Arduino 1.6.5 中不起作用

c - Keyboard.print() 等同于 C on Teensy?

java - 获取 Java InputStream 后面文件的字节数

python - Python 中的重构(在 Eclipse 中提取新方法)

python - mongodb批量插入、更新值

c++ - PlatformIO 的范围问题(?)

c# - C#-将* .wav文件加载到字节数组时伪造数据

gwt - 二进制数据和GWT