简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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