[Python] Issue sending data from raspberry pi to phone app via bluetooth using python

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    Just having an issue with sending data collected from sensors in an excel sheet on the raspberry pi to a mobile phone device. The code works but its not consistent and there is a lot of connection dropping/ failures.

    The whole system works as RaspPi collects sensor data -> Data is stored in spreadsheet -> Phone connects to bluetooth module connected to RaspPi -> Phone sends command over bluetooth to ask for data to be sent line by line

    Could anyone see a problem with how I've coded this and recommend fixes or alternative ways to code this?

    Bluetooth connection made using the import serial library

    if __name__ == '__main__':

    path = r"/home/pi/Scans/"
    scans = os.listdir(path)
    ser = serial.Serial('/dev/ttyS0', 115200, timeout=1)
    ser.flushInput()
    ser.flushOutput()

    while True:

    line = ser.readline().decode('UTF-8').rstrip()
    ser.reset_input_buffer()

    ############## Request scan list #################
    # Command = scans
    if ('scans') in line:
    ser = serial.Serial('/dev/ttyS0', 115200, timeout=1)
    ser.write(('[').encode('UTF-8'))
    filelist = [ f for f in os.listdir(newpath) if f.endswith(".csv") ]
    for f in filelist:
    with open((newpath + '/' + f), 'r', encoding="utf-8", errors="ignore") as scraped:
    final_line = scraped.readlines()[-1][0:3]
    if (',') in final_line:
    final_line = final_line[0:2]
    ser.write(('[' + str(f) + ', ' + str(final_line) + ']').encode('utf-8'))
    ser.write((']\r\n').encode('UTF-8'))


    ############## Select scan number #################
    # Put as many as necessary

    if ('01') in line:
    number = '01'
    if ('02') in line:
    number = '02'
    if ('03') in line:
    number = '03'
    if ('04') in line:
    number = '04'
    if ('05') in line:
    number = '05'
    if ('06') in line:
    number = '06'
    if ('07') in line:
    number = '07'
    if ('08') in line:
    number = '08'
    if ('09') in line:
    number = '09'
    if ('10') in line:
    number = '10'

    ############## Request file #################
    # Command = download
    if ('download') in line:
    if number !=0:
    ser = serial.Serial('/dev/ttyS0', 115200, timeout=1)
    with open("/home/pi/Scans/Scan " + number + ".csv", mode = 'r')as file:
    csvFile = csv.reader(file)
    ser.write(('[').encode('UTF-8'))
    for lines in csvFile:
    time.sleep(0.01)
    ser.write((str(lines) + '\n').encode('utf-8'))
    ser.write((']\n').encode('UTF-8'))

    Continue reading...

Compartilhe esta Página