I am creating a program that uses PIC and pySerial to communicate serial.
When I run a program similar to the following, I get an "IndexError: index out of range" error.
Please tell me how to solve it.
#import sys
import serial
from serial import SerialException
import datetime
# Decompose seconds into hours, minutes, and seconds
def get_hms(td):
m,s = divmod(td.seconds,60)
h,m = divmod(m,60)
return(h,m,s)
# English format conversion for datetime
def get_endate(dt):
weekList=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' 'Sun']
monthList=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
weekNo=dt.weekday()
monthNo = dt.month
US>%s='{0}{1}{2}\n'.
weekList [weekNo],
monthList [monthNo-1],
dt.strftime ("%d%H:%M:%S%Y")
returns
# program initiation
N_Smpl = 10000
N_data=20000
# argv = sys.argv;
#######exit()
fname_out="data1.txt"# destination file
portName="COM3"# Variable to store COM port numbers
Variable to store BaudRate=int(115200)# BaudRate
flowcontrol="CTSRTS"#Variables that store the flow control type
if(flowcontrol!="CTSRTS" and flowcontrol!="none"):
print("Invalid flow control type. Please specify one of CTSRTS, none")
print("\n\n")
# print("%s max min step blk fname1 fname2comN baud flow\n\n", argv[0])
print("max Eb/No maximum\n")
print("min Eb/No minimum\n")
print("step Eb/No step value\n")
print("blk transmit blocks\n")
print("fname1 output filename\n")
print("fname2 output filename (from PIC)\n")
print("comN COM port number example COM1\n")
print("baud baud rate value\n")
print("flow Type of Flow Control to Use CTSRTS, none\n")
exit()
ByteSize=serial.EIGHTBITS #StopBitLength
Parity=serial.PARITY_NONE#parity
StopBits=serial.STOPBITS_ONE #StopBits
RtsCts=False#RTSCTS Enabled/Disabled
if(flowcontrol=="CTSRTS"):
RtsCts = True
# Apply COM port settings
ser=serial.Serial("COM3",baudrate=115200,parity=serial.PARITY_NONE,timeout=None)
# Clearing Buffers
ser.reset_input_buffer()
# Open file in postscript mode
fp = open(fname_out, 'a')
# Obtaining the current time
starttime=datetime.datetime.now()
s='# Program start time: {0}\n'.format(get_endate(starttime))
fp.write(s)
#s='# Run command: {0} {1}{2}{3}{4}\n'.format(argv[0], argv[1], argv[2], argv[3], argv[4])
fp.write(s)
# Port Open Processing
if(ser.is_open==False):
try:
ser.open()
exceptSerialException:
print(" output file open error!!")
exit()
print("Communicate with PIC")
TXstarttime=datetime.datetime.now()
j = 0
while (True):
# if(j%1000) == 0:print("{}").format(j)
# start of data reception
toReadBytes=N_data
D_PIC = ser.read (toReadBytes)
# file addition process
forkin range(1,N_Smpl):
flag = 0
if((D_PIC[2*k]&128)==128):
flag = 1
d=(3&D_PIC[2*k])*256+D_PIC[2*k+1]
c=j*N_Smpl+k
s='{0}{1}\n'.format(d,c)
fp.write(s)
# Show elapsed time
td = datetime.datetime.now() - TXstarttime
s='#{0}Time elapsed: {1:d}[sec]\n'.format(j,td.seconds)
fp.write(s)
if(flag==1):
break
j + = 1
# COM port closed
ser.close()
# Show end time
endtime = datetime.datetime.now()
s='# Program end time: {0}\n'.format(get_endate(endtime))
fp.write(s)
# Show elapsed time
day = td.days
(hour, min, sec) = get_hms(td)
s='# Processing time: {0} days {1} hours {2} minutes {3} seconds \n'.format (day, hour, min, sec)
fp.write(s)
s='=============================================\n'
fp.write(s)
fp.close()
print("Finish data retrieval: (exit with return key)")
input()
C:\python>python LogPIC32Py2.py
Start communicating with the PIC
Traceback (most recent call last):
File "C:\python\LogPIC32Py2.py", line 103, in<module>
if((D_PIC[2*k]&128)==128):
IndexError: index out of range
We have changed the process of adding files on the program as follows:
for kin range(1,N_Smpl):
flag = 0
try:
if((D_PIC[2*k]&128)==128):
flag = 1
d=(3&D_PIC[2*k])*256+D_PIC[2*k+1]
c=j*N_Smpl+k
s='{0}{1}\n'.format(d,c)
fp.write(s)
except IndexError:
print('Error')
print(len(D_PIC))
print(2*k)
os.system('PAUSE')
C:\python>python LogPIC32Py2.py
Start communicating with the PIC
Error
0
2
Press any key to continue.
Error
0
4
Press any key to continue.
Error
0
6
Press any key to continue.
The error occurs when you attempt to access more than the number of elements in an array or list.
Stop running when the error occurs and check the number of elements in the list and the number of indexes you want to access
In the survey results, len(D_PIC)
is 0, so the data read from the serial port is 0 bytes.
This is a bytes object with no data, so no matter where you try to read it, it will be an error.
You may want to check if the DPIC=ser.read(toReadBytes)
results are loading data successfully, or if in_waiting has sufficient data in the buffer.
If a program has a proven track record of running on other devices, try to find out how it differs from the one that worked.
If this is the first phenomenon that occurred after the programming, please check with a tool other than Python to see if it can communicate with the PIC in the first place.
536 Uncaught (inpromise) Error on Electron: An object could not be cloned
548 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
708 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
546 Understanding How to Configure Google API Key
547 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.