繁体   English   中英

ValueError: 以 10 为基数的 int() 的无效文字:''(串行端口通信字符串到整数错误)

[英]ValueError: invalid literal for int() with base 10: '' (Serial port communication string to integer error)

我正在尝试编写一个代码,将从 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

当我尝试使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM