IndexError:列表索引超出范围-Python / Arduino

时间:2019-03-29 20:20:16

标签: python arduino pyserial

在我最近的项目中,我尝试将Arduino的串行数据发送到Python。使用pyserial可以完美完成。但是我这里有一个问题。我无法拆分数据。所有这些都存储在Python coed中的一个变量中,但我想将其拆分。

Aduino代码:

#define sw1 6
#define sw2 5
#define sw3 4
#define sw4 3

int vote1 = 0;
int vote2 = 0;
int vote3 = 0;
int vote4 = 0;

void setup()
{
  Serial.begin(9600);

  pinMode(sw1, INPUT);
  pinMode(sw2, INPUT);
  pinMode(sw3, INPUT);
  pinMode(sw4, INPUT);

  digitalWrite(sw1, HIGH);
  digitalWrite(sw2, HIGH);
  digitalWrite(sw3, HIGH);
  digitalWrite(sw4, HIGH);
}

void loop()
{
  if (digitalRead(sw1) == 0)
  {
    vote1++;
    Serial.print(vote1);
    Serial.print(("\t"));
    Serial.print(vote2);
    Serial.print(("\t"));
    Serial.print(vote3);
    Serial.print(("\t"));
    Serial.print(vote4);

    while (digitalRead(sw1) == 0);
  }
  if (digitalRead(sw2) == 0)
  {
    vote2++;
    Serial.print(vote1);
    Serial.print(("\t"));
    Serial.print(vote2);
    Serial.print(("\t"));
    Serial.print(vote3);
    Serial.print(("\t"));
    Serial.print(vote4);

    while (digitalRead(sw2) == 0);
  }
  if (digitalRead(sw3) == 0)
  {
    vote3++;
    Serial.print(vote1);
    Serial.print(("\t"));
    Serial.print(vote2);
    Serial.print(("\t"));
    Serial.print(vote3);
    Serial.print(("\t"));
    Serial.print(vote4);

    while (digitalRead(sw3) == 0);
  }
  if (digitalRead(sw4) == 0)
  {
    vote4++;
    Serial.print(vote1);
    Serial.print(("\t"));
    Serial.print(vote2);
    Serial.print(("\t"));
    Serial.print(vote3);
    Serial.print(("\t"));
    Serial.print(vote4);

    while (digitalRead(sw4) == 0);
  }
}

在这里,我试图使用四个按钮将四个不同的值从Arduino发送到Python。

Python代码:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

while 1:
    arduinoData = ser.readline().decode('utf-8')
    data = arduinoData.split("\t")

    a = data[0]
    b = data[1]
    c = data[2]
    d = data[3]

我收到如下错误:

  

回溯(最近通话最近):文件   “ /home/pi/serialConnection_2.py”,第11行       b =数据[1] IndexError:列表索引超出范围

如果我像下面那样更改python代码:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

while 1:
    arduinoData = ser.readline().decode('utf-8')
    data = arduinoData.split("\t")

    print(data)

然后我就可以像下面这样的列表形式接收所有四个值:

['']
['']
['']
['']
['']
['']
['']
['']
['']
['1 , 0 , 0 , 0']
['2 , 0 , 0 , 0']
['3 , 0 , 0 , 0']
['4 , 0 , 0 , 0']
['4 , 1 , 0 , 0']
['4 , 1 , 1 , 0']
['4 , 1 , 2 , 0']
['4 , 1 , 2 , 1']
['4 , 1 , 2 , 2']
['4 , 1 , 2 , 3']
['']
['']
['']

每当我按下按钮时,该列表的值就会正确更新。我不知道为什么我无法访问列表的成员。

1 个答案:

答案 0 :(得分:0)

当输入string is empty时,Python中的

<div class="file-input-wrapper"> <button class="btn-file-input">Mah Custom Uploadz Button</button> <input type="file" name="file" /> </div> 返回split。然后,您尝试访问['']内部不存在的索引(即data等),因为您的序列接收到许多空字符串,因此请在处理数据之前尝试检查是否存在:

data[1]