独立时pySerial不工作

时间:2014-01-26 21:41:53

标签: python arduino pyserial

好吧,我正在尝试使用Python脚本与Arduino Uno进行通信。基本上问题与this相同,其中解决方案是添加time.sleep(xx)(对我来说不起作用)。

我已经在Archlinux(2014年1月26日)和OSX 10.9.1上尝试了相同的结果,使用Python 3.3.3。

(!),如果我在启用Arduino监视器时运行.py,或者如果我在ipython / python控制台上运行相同的命令,或者在运行(pdb)代码时运行得很好(!?!?)......

这是我的.ino:

char incomingByte;
const int comDelay = 200;
int count;
const int led = 3;              

void imHere(int led, int time, int blinks){ // blink led for bug control
  for (count  = 1; count <= blinks; count++){
    digitalWrite(led, HIGH);
    delay(time);
    digitalWrite(led, LOW);
    delay(time);
  }
}

void setup(){
  Serial.begin(9600); 
  pinMode(led, OUTPUT);
}

void loop(){   
  if( Serial.available() > 0){  
    incomingByte = Serial.read();
    delay(comDelay);    
    switch (incomingByte){
    case 't':                      // -t | 'test': communication test flag       
      imHere(led, 500, 2);         // incomingByte received witness 
      Serial.print('0');
      imHere(led, 50, 10);         // response sent witness
      //Serial.flush();
      break;
    default:
      imHere(led, 1500, 1);        // communication error witness
      Serial.print('-1');
      break; // error?
    }
  }
}

这是我的.py

#!/usr/bin/env python

import serial
import time
import sys
import os
import re
import pdb

def port_check():

    ## Check for the traditional Arduino port's on Linux and OSX, and check communication ##
    if sys.platform == 'linux':
        for file in os.listdir('/dev/'):
            if re.match('ttyA',file):
                port_name = '/dev/' + file

    elif sys.platform == 'darwin':
        for file in os.listdir('/dev/'):
            if re.match('tty.usbmodem',file):
                port_name = '/dev/' + file

    pdb.set_trace() ### DEBUG BEGINS

    ## create serial communication
    ser = serial.Serial(port_name, 9600) ## create serial communication
    #ser = serial.Serial(port_name, 9600, timeout = 3, interCharTimeout = 5) 

    print('\nDevice ' + port_name + ' detected')
    print('Stablishing communication throught ' + port_name)

    if ser.writable():
        print('Device writable')
        print('Testing communication ... ', end = "")
        ser.write(bytes('t','utf-8'))
        time.sleep(2)
        ser.flushInput()
    else:
        print('Device non writable')
        return -1

    time.sleep(2)
    response = 'no response'

    while ser.inWaiting() > 0:
        response = ser.read().decode('utf-8') 

    print(response)

    if response == '0':
        print('Done! :)\n')
        return ser
    else:
        print('Failed :(\n')

    ser.flush()
    ser.close() ## rember to take this out after debugging

if __name__ == "__main__":
    #check port configuration
    ser = port_check()

基本上.py发送't',。。收到它并返回'0'。

1 个答案:

答案 0 :(得分:1)

尝试在打开串口后添加延迟。数据输入/输出时可能还没有完全准备好。为安全起见,请在两个平台上进行操作!

基本上睡眠/延迟:

ser = serial.Serial(port_name, 9600)

Serial.begin(9600);