Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serial port getting engaged after reading single command in python. #20

Open
eronenergy opened this issue Jan 6, 2020 · 11 comments
Open

Comments

@eronenergy
Copy link

eronenergy commented Jan 6, 2020

I am making a connection with python using pyserial with a UART port. As I send the command using serial.write my output is received but my serial port does not break connection. As I need to send a second command also to receive the output. Please guide me on this.

I have also used ser.close still I am not able to close the port.

import serial

ser = serial.Serial(
port='COM5',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout= 10)
print("connected to: " + ser.portstr)

ser.write(b'\reeprom\r')
seq = []
count = 1

while True:
for c in ser.readline():
seq.append(chr(c)) # convert from ANSII
joined_seq = ''.join(str(v) for v in seq) # Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break

ser.close()

Can you please guide what is going wrong. I am expecting that I should get my output of the fired command to UART and then code should exit rather than continue running. Also I wanted to know if this works can I again make connection and fire the second command to UART. Please help me on this.

@desprit - I have take this cutting of code from your stack overflow contribution. Can you help me guide what is wrong at my end that i am not able to release port.

@desprit
Copy link

desprit commented Jan 6, 2020

@eronenergy

but my serial port does not break connection

You mean it doesn't exit the for c in ser.readline(): loop?

p.s. please, fix the formatting of the code block in your message

@eronenergy
Copy link
Author

@desprit yes sir,

i am not sure is it the loop or the python issue as i can see at some serial ports pages and links.
That py-serial no more works with v2.6 and further. i am here using python 3.7

what i am really facing is i am able to send the command from the above mentioned code which is i am sending in bytes format [ ser.write(b'\reeprom\r')] and receive the response on my console but what further i am facing is port stays engaged and script continues to run

what i am trying to achieve is send the command what i am already doing and then get the response from the command that i fired and then the port should break and i should be able to fire the second command to the serial port or by other way i could just make connection once and able to fire two-three commands continuously and get response for the individual commands fired by me and then break the connection from the serial port.

@desprit i am really not able to why i am in this situation . it will be very kind if you can provide some guidance.

@desprit
Copy link

desprit commented Jan 6, 2020

@eronenergy

Try to change the write command to this:

ser.write(b'\reeprom\r\n')

And fix the formatting, please. "edit" your message and wrap the whole code block into ```

@eronenergy
Copy link
Author

eronenergy commented Jan 6, 2020

hi @desprit

yes, the above mentioned ser.write pattern works fine.

Below is the attached code

import ctypes, sys
import mysql.connector
from xlwt import Workbook
import pyvisa as visa
import serial
import os
import click
import logging
import time
import mysql.connector
import pymysql


if click.confirm('Do you want to flash the self test cli?', default=True):
    os.system("st-link_cli -ME")
    print("FLASHING THE SELF TEST CLI ON THE BOARD")
    #os.system("st-link_cli.exe -P D:/nishant/Self_Test_CLI_Application.hex  0x08000000 ske skpv -V while_programming")
    os.system("st-link_cli.exe -P D:/nishant/CLIv1.9_9600BPS-8N1_28-11-2019_fx.hex  0x08000000 ske skpv -V while_programming")


####Device getting reset after flashing#######

os.system("st-link_cli -Rst")

if click.confirm('Do you want to test board?', default=True):
    #os.system("st-link_cli -Rst")
    print("Mcu is  Reseting to give test board results")
    logging.basicConfig(filename='D:/nishant/acc20.txt', level=logging.DEBUG)
    ser = serial.Serial(
        port='COM5', \
        baudrate=9600, \
        parity=serial.PARITY_NONE, \
        stopbits=serial.STOPBITS_ONE, \
        bytesize=serial.EIGHTBITS, \
        timeout= 1)

    print("connected to: " + ser.portstr)

    
    ser.write(b'\r1\r\n')
    #ser.write(b'\reeprom\r\n')
    #ser.write(b'\r1\n\r')
    # this will store the line
    seq = []
    count = 1

    while True:
        for c in ser.readline():
            seq.append(chr(c))  # convert from ANSII
            joined_seq = ''.join(str(v) for v in seq)  # Make a string from array

            if chr(c) == '\n':
                print("Line " + str(count) + ': ' + joined_seq)
                seq = []
                count += 1
                break

    ser.close()

hope this looks fine.

@desprit
Copy link

desprit commented Jan 6, 2020

@eronenergy

https://pyserial.readthedocs.io/en/latest/shortintro.html#readline

Be careful when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

Not sure why timeount didnt work for you.

@eronenergy
Copy link
Author

@desprit

i have gone through this and same i explained in my first snippet . As they have mentioned it doesn't work for python versions above 2.6 . They have also mentioned for using io module . do you have idea how to use that.

the above mentioned code is cutting of your code on stack overflow.

PFA Link : https://stackoverflow.com/questions/16077912/python-serial-how-to-use-the-read-or-readline-function-to-read-more-than-1-char

@desprit what you suggest me to do in this case. can you give some idea how below can be achieved.

what i am trying to achieve is send the command what i am already doing and then get the response from the command that i fired and then the port should break and i should be able to fire the second command to the serial port or by other way i could just make connection once and able to fire two-three commands continuously and get response for the individual commands fired by me and then break the connection from the serial port.

@desprit it will be great help. if you can support me on this . i have been stuck since a week in this issue.

@desprit
Copy link

desprit commented Jan 6, 2020

@eronenergy

What did you mean when you said

yes, the above mentioned ser.write pattern works fine.

It seems like you need two separate scripts. One will read data coming on the serial port and another one that should occasionally write data.

The "reader" is exactly as shown on stackoverflow.
Launch it in a separate window and let it keep running.

Then create a "writer" script that will connect to the serial, write a message and exit.

Then, show me the result.

@eronenergy
Copy link
Author

eronenergy commented Jan 7, 2020

@desprit - first of all apologies for the late reply as office hours were over.

it was only a acknowledgement that this way writing ser.write( ) also works fine.

Thanks above mentioned suggestion is also very nice and i can find clues for it easily for doing this way on google but there is also issue regarding one serial port for two script simultaneously.

Also point is tere is need of single script . As we are saving every response in the database for future records of each every arduino connected and we are going to run the script through UI. so it is necessary that script should be single which is running in the background.

Also i am watching despite my using ser.close The port is not getting closed. what could be the possible and same thing is happening with timeout in the script.
If we can catch anything on ser.close or timeout by your help . i think it will be achievable or by any of your suggested way which could serve the purpose.

@eronenergy
Copy link
Author

eronenergy commented Jan 8, 2020

@desprit I have made some changes at firmware level.

now current problem is i dont need to fire multiple commands . I will just be sending one particular command and then will gets its output which is working.
The only thing remains stuck is i am not able to close port. can you suggest something on that. ?

@desprit -it will be great help if you me on this?

@desprit
Copy link

desprit commented Jan 8, 2020

@eronenergy

You should communicate with your code to understand the source of the problem. Add debug messages on every step of the loop and see where it stuck.
First of all, make sure it exits from the for c in ser.readline(): loop.
When done, make sure to exit while True:. Right now I don't see anything that would stop the while True:. It loops forever and thus never gets to ser.close().

@eronenergy
Copy link
Author

@desprit

thanks for support. i will try this and confirm you on the results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants