Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble writing over serial
#1
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.
Reply
#2
Hello,

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 3,308 Aug-24-2023, 07:56 AM
Last Post: gowb0w
Question Having trouble writing an Enum with a custom __new__ method stevendaprano 3 4,007 Feb-13-2022, 06:37 AM
Last Post: deanhystad
  Writing commands to serial python_beginner 8 63,473 Jun-23-2020, 08:59 PM
Last Post: cvh
  trouble writing to file after while loop Low_Ki_ 21 13,132 Jan-10-2017, 06:44 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020