如何在python中将第一个字节与串口的receivedata分开

时间:2015-04-10 05:54:17

标签: python raspberry-pi

我通过串口将raspberry pi连接到PIC。 RPI将从pic接收数据为c1,c2,c11,c14,s1,s2等。有没有办法将c和s与接收的数据分开? 我想用

if receiveddata='c':
      fun1()
if receiveddata='s':
       fun2()

我怎样才能在Python中执行此操作?

3 个答案:

答案 0 :(得分:2)

data = ["c1", "c2", "c11", "c14", "s1", "s2"] # emulate data collected from RPI
for r in data:
  prefix = r[0]
  if prefix == 'c':
    fun1()
  elif prefix == 's':
    fun2()

答案 1 :(得分:1)

receiveddata=ser.readline().strip()
for r in receiveddata:
     firstdata=r[0]
     seconddata=r[1]
if firstdata=='yourdata':
      fun1()

答案 2 :(得分:1)

如果您想对第一个数据进行特殊操作,next是您的朋友。

例如,如果我们模仿按Arie建议收集的数据:

data = ["c1", "c2", "c11", "c14", "s1", "s2"]
it = iter(data) # list does not directly accept next
first = next(it)
# deal with first item
...
for i in it: # you get here all items after first
    # other items
    ...

这样,您就不必在循环中放置测试。