[英]ValueError: invalid literal for int() with base 10: '' (Serial port communication string to integer error)
I'm trying to write a code that will print the data I get from Arduino to both the console screen and a database,at the same time i need to convert values into integers for plotting but I'm getting ValueError: invalid literal for int() with base 10: '' error when converting string to integer我正在尝试编写一个代码,将从 Arduino 获得的数据打印到控制台屏幕和数据库,同时我需要将值转换为整数以进行绘图,但我收到ValueError: invalid literal for int () 以 10 为基数:将字符串转换为整数时出现''错误
import sqlite3 as sql
from itertools import count
import time
import serial
index = count()
x_value = 0
total_1 = 1000
total_2 = 1000
arduino = serial.Serial(port='COM5', baudrate=9800, timeout=.1)
arduino.flushInput()
def read_data():
time.sleep(1)
ser_bytes = arduino.readline()
decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode("utf-8")
return decoded_bytes
with sql.connect('altitude_database.db') as db:
cur = db.cursor()
cur.execute("DROP TABLE IF EXISTS Distances")
timer = []
k = 0
l = 0
while True:
value = read_data()
value = int(str(value))
print(value) # printing the value
cur.execute("CREATE TABLE IF NOT EXISTS Distances (Time,Distances)")
cur.execute("INSERT INTO Distances (Time,Distances) VALUES(?,?)",(k,value))
db.commit()
k = k+1
When I try to print the value of decoded_bytes in read_data() function with Andy Knight's suggestion ""https://stackoverflow.com/users/2668284/andy-knight"" I realized that the first few data is blank.I solved the problem by checking if value is empty当我尝试使用 Andy Knight 的建议 ""https://stackoverflow.com/users/2668284/andy-knight"" 在 read_data() 函数中打印 decoded_bytes 的值时,我意识到前几个数据是空白的。我解决了通过检查值是否为空来解决问题
with sql.connect('altitude_database.db') as db:
cur = db.cursor()
cur.execute("DROP TABLE IF EXISTS Distances")
timer = []
k = 0
l = 0
while True:
value = read_data()
if value: #####solution of the problem#######
value = int(str(value))
print(value) # printing the value
cur.execute("CREATE TABLE IF NOT EXISTS Distances (Time,Distances)")
cur.execute("INSERT INTO Distances (Time,Distances) VALUES(?,?)",(k,value))
db.commit()
k = k+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.