Search code examples
pythonraspberry-pi3

List index out of range on Raspberry Pi


I'm getting the 'List index out of range' error when trying to get my NRF24L01 module working on Raspberry Pi 3b+. The code is written in python and I just can't seem to notice the error.

import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)

pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24 (GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize (32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()
while True :

    while not radio.available(0):
       time.sleep(1/100)

    a = []
    b = []
    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    a = receivedMessage[0]
    b = receivedMessage[1]
    print( "Temperature:" , a, "Humidity:" , b )

The error appears on lines a = receivedMessage[0] and b = receivedMessage[1]. Would love some fresh look and advices on how to fix this. Traceback:

Traceback (most recent call last):
  File "/home/pi/Desktop/NRF24L01/VEIIIK.py", line 34, in <module>
    a = receivedMessage[0]
IndexError: list index out of range

UPDATE Using the line print(radio.read(receivedMessage, radio.getDynamicPayloadSize())) gives the ouptut:

0
1
1
1
1
1
1
1
1
1
1

While the line print(receivedMessage) outputs [].


Solution

  • Why don't you do:

    if(receivedMessage):
        a = receivedMessage[0]
        b = receivedMessage[1]
        print( "Temperature:" , a, "Humidity:" , b )
    

    This might solve the problem.