Python Forum
Trouble writing over serial - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Trouble writing over serial (/thread-17316.html)



Trouble writing over serial - EngineerNeil - Apr-06-2019

Hello all,

I am trying to get my BeagleBone Black to communicate with a Microcontroller (CC1310 Launchpad) over serial.
When I connect the Microcontroller to Windows, I can Use Putty and make a serial connection to (For example COM 13 and baud rate 9600) and I send "90000" it will send back something through the terminal window.
Now I am trying to do the same but with a Python program. Here is my attempt:
import datetime
import serial
import os


def pwr_solenoid(solenoid0=0, solenoid1=0, solenoid2=0, solenoid3=0):
    # Defaults are for low signal values

    # compile output
    output = '9{solenoid0}{solenoid1}{solenoid2}{solenoid3}' \
        .format(solenoid0=solenoid0, solenoid1=solenoid1, solenoid2=solenoid2, solenoid3=solenoid3).encode()

    with serial.Serial('/dev/ttyACM0', baudrate=9600) as ser:
        print("created connection to '/dev/tty/ACM0'\n")
        print("going to send:\t'{}'".format(output))
        ser.write(output)
        ser.flush()
        ser.close()   # I don't think you need this, but you would need to double check

    # for testing to console
    print(output.decode())


def read_from_uart():
    # read from the serial connection
    try:
        with serial.Serial('/dev/ttyACM0') as ser:
            try:
                if not ser.in_waiting:
                    raise Exception("No Data")

                val = ser.readline()
                data = "{dts}\t\t{val}\n".format(dts=datetime.datetime.utcnow(), val=val)
                # output to file
                filename = "{name}.txt".format(name=datetime.datetime.utcnow().strftime("%a%d%m%Y"))
                with open(filename, "+w") as file:
                    file.write("{input}\n".format(input=data))
                print("data received: {data}".format(data=data))

            except (serial.SerialException, FileNotFoundError):
                print("Serialexception, mocking data *****")
                val = "85"
                data = "{dts}\t\t{val}\n".format(dts=datetime.datetime.utcnow(), val=val)
                print("data received: {data}".format(data=data))
            except:
                print("Unexpected error")
    except (serial.SerialException, FileNotFoundError):
        print("Serialexception, mocking data *****")
        val = "85"
        data = "{dts}\t\t{val}\n".format(dts=datetime.datetime.utcnow(), val=val)
        print("data received: {data}".format(data=data))


def main():
    os.system("clear")

    wait = True
    print("Enter solenoid values in form of 1/0 (1 == HIGH, 0 == LOW) or 'exit' to exit\n")
    print('\n')
    print("default value will remain '0000' until altered...\n")
    print("Note, after altered values are input, it will wait for input from UART||USB\n")
    print('\n')

    solenoid = '0000'
    while wait:
        solenoid = input("please input solenoid signal values.\n")

        if solenoid.lower() == "exit":
            break
        elif solenoid.lower() == "ports":
            import serial.tools.list_ports
            ports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
            print(ports)
        elif solenoid.isdigit():
            # checks to make sure all characters are digits (does not check for correctness of
            # individual characters
            pwr_solenoid(solenoid0=solenoid[0:1], solenoid1=solenoid[1:2], solenoid2=solenoid[2:3], solenoid3=solenoid[3:4])
            read_from_uart()
        else:
            continue


if __name__ == "__main__":
    main()
The program runs up to the point where it prints the output that is to be written over Serial , then says unexpected error, then prompts me to enter another input again. Any help would be appreciated there seems to be no syntax error in the code.


RE: Trouble writing over serial - j.crater - Apr-07-2019

Hello,

you get "Unexpected error" from exception handler in line #46.
Could you try to print any meaningful data/variables, before the exception happens?