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

时间:2015-06-02 18:52:06

标签: python arduino bytearray serial-communication

我正在使用带有pySerial的Arduino和Python 3.4并尝试通过串行通信发送多个字节,但是自从我的代码运行以来我遇到了问题,但是我在某些地方用于调试目的的打印语句输出字符串,我我没想到。我试过写这个代码的简化版本,它工作正常,所以我不确定我做错了什么! 另外,为了解决这个问题,我在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语句中,我使用ascii代码'a'(97)而不是实际放'a'。两者都应该有用吗?

1 个答案:

答案 0 :(得分:0)

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

delay(10) 

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

相关问题