为什么python pyserial把ø放在字符串发送的开头?

时间:2014-04-09 17:32:09

标签: python string pyserial

我有一个错误:o搜索很长时间但没有回答!

我的Rpi通过串行和pyserial librairie向我的Moteino网关发送命令。 我的Moteino gateaway等待这些命令并继续。

所以,我可以通过这两种方式发送和接收。

当我从Rpi发送一个字符串到Moteino时,pyserial在开头的时候放了一个“ none ”或“斜线零ø字符串。 例如:

Python代码

#!/usr/bin/python
# -*- coding: utf-8 -*- 
port =                 serial.Serial(port='/dev/ttyAMA0',baudrate=115200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=0)

port.flushOutput()
#Ecriture de la pré-commande "LMPCDE"
cde = "LMPCDE\r\n"
cde.encode('ascii','strict')
print cde
port.write(cde )
time.sleep(.1)
data = port.readline()
print data

#!/usr/bin/python
# -*- coding: utf-8 -*- 

port = serial.Serial(port='/dev/ttyAMA0',baudrate=115200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=0)

port.flushOutput()
#Ecriture de la pré-commande "LMPCDE"
cde = "LMPCDE\r\n"
print cde
port.write(cde)
time.sleep(.1)
data = port.readline()
print data

Moteino代码等待命令字符串读取并将其发送到RPI。

所以:     打印cde 提示 LMPCDE 和     打印数据 提示øLMPCDE

我使用的是Python 2.7.3。

为什么python pyserial把ø放在发送字符串的开头? :○

我可以修改moteino代码来删除第一个字符,但即使这是简单的方法,我也不认为这是好方法,因为我不明白为什么!

我发现了另一个错误!

我通过命令行(Putty)运行python脚本。

如果我打开另一个Putty实例并运行minicom“minicom -b 115200 -o -D / dev / ttyAMA0”并在第一个控制台python脚本中运行,则LMPCDE中没有添加ø命令。当然,当串行输入被重定向到minicom时,我需要通过minicom传递其他字符串命令。

以下是整个代码:

#!/usr/bin/python
# -*- coding: utf-8 -*- 
#Importation des librairies
import MySQLdb
import serial
import time
#import string

#Mes Fonctions
def convertstring(mystring):
    if len(mystring) == 3:
        mystring = "0" + mystring
    elif len(mystring) == 2:
        mystring = "00" + mystring
    elif len(mystring) == 1:
        mystring = "000" + mystring
    return mystring

#Connexion à la base de donnees
db = MySQLdb.connect(host="localhost", user="root", passwd="xxxxxxx",                db="logsensorsvalues")  #Password with specials char like (&,@,# ...)
# you must create a Cursor object. It will let,
# you execute all the queries you need
cursor = db.cursor() 
# Use all the SQL you like
cursor.execute("SELECT Far_Red,Red,Red_Orange,Green,Blue,UV_410,UV_395 FROM ledlampvalues Order by ID desc limit 1")
# Values received
rows = cursor.fetchall()
#Fermeture de la base de donnees
cursor.close()
db.close()
#lecture de rows
commandstring=""
for row in rows:
    FarRed = convertstring(str(row[0]*10))  #x10 pour conserver l'architecture du protocole
    Red = convertstring(str(row[1]*10))
    RedOrange = convertstring(str(row[2]*10))
    Green = convertstring(str(row[3]*10))
    Blue = convertstring(str(row[4]*10))
    UV1 = convertstring(str(row[5]*10))
    UV2 = convertstring(str(row[6]*10))
#Formatage de la chaine de caracteres
commandstring = "C" + "F" + FarRed + "R" + Red + "O" + RedOrange + "G" + Green + "B" + Blue + "U" + UV1 + "V" + UV2 + "E" #+ "\r\n"

#Serial Port http://pyserial.sourceforge.net/pyserial_api.html#serial.FileLike.readline
#Possible values for the parameter timeout:
#timeout = None: wait forever
#timeout = 0: non-blocking mode (return immediately on read)
#timeout = x: set timeout to x seconds (float allowed)
serialport = serial.Serial()

serialport.port = "/dev/ttyAMA0"
serialport.baudrate = 115200
serialport.bytesize = serial.EIGHTBITS #number of bits per bytes
serialport.parity = serial.PARITY_NONE #set parity check: no parity
serialport.stopbits = serial.STOPBITS_ONE #number of stop bits
serialport.timeout = 0            #non-blocking mode (return immediately on read)
serialport.xonxoff = False     #disable software flow control
serialport.rtscts = False     #disable hardware (RTS/CTS) flow control
serialport.dsrdtr = False       #disable hardware (DSR/DTR) flow control
serialport.writeTimeout = 0     #timeout for write

try:
    serialport.open()
except Exception , e:
    print "error open serial port: " + str(e)
    exit()

if serialport.isOpen():
    print "Port Open"
    try:
        #Pay attention to the flush order : Output before Input
        serialport.flushOutput() #flush output buffer, aborting current output and discard all that is in buffer
        serialport.flushInput() #flush input buffer, discarding all its contents
        #Ecriture de la pré-commande "LMPCDE"   /// cde.encode('ascii','strict')
        print serialport.write('LMPCDE')
        serialport.flushInput()
        time.sleep(.1)

                #----------------------------DEBUG ZONE----------------------------
        #data = serialport.readline()
        #print data
        while serialport.inWaiting() > 0:
        print serialport.read()
        #-------------------------------END--------------------------------

        while serialport.inWaiting() > 0:
            data = serialport.readline()
            if data.startswith("Expecting"):
                print data
                #Waiting for an acknowledgement from Node
                while serialport.inWaiting() > 0:
                    data = serialport.readline()
                    if data.startswith("ok"):
                        print "Sending Command"
                        serialport.write(commandstring)

        time.sleep(.1)

        #Waiting for an acknowledgement from Node
        while serialport.inWaiting() > 0:
            data = serialport.readline()
            if data.startswith("ok"):
                print data

        serialport.close()          
    except Exception , e1:
        print "error open serial port: " + str(e1)
        exit()
else:
    print "cannot open serial port "

1 个答案:

答案 0 :(得分:0)

您可以尝试调试此问题:

  • port.flushInput()

  • 之后立即使用命令port.flush.Output()刷新串行输入
  • 使用符号

  • 从串口读取的port.read()

while 1:

    ch = port.read()
    #Condition for end of line, any other condition may be here
    if ch = '\n'
        #Terminate while loop
        break