【问题标题】:Sending multiple bytes through Serial Communication通过串行通信发送多个字节
【发布时间】:2015-06-02 18:52:06
【问题描述】:

我将 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'。两者都应该工作吗?

【问题讨论】:

  • “我使用 'a' (97) 的 ascii 代码而不是实际输入 'a'。两者都应该工作吗?”是的,因为它们完全一样。

标签: python arduino bytearray serial-communication


【解决方案1】:

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

delay(10) 

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

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多