1

So this is the script I am using to send each 2 seconds for four time the Time in microsecond to the microcontroller stm32f4 but unfoturnately it only sends some numbers(from 1-->4) which are not the same as when I do a print,it is like random numbers .

import time 
import serial from datetime 
import datetime from time 
import gmtime, strftime

ser = serial.Serial(
    port='/dev/ttyACM0',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS

)
ser.writeTimeout = 0 
ser.isOpen() 

TM1 = int(round(time.time()*1000000))   
ser.write(str(TM1).encode())
#ser.write( str(TM1)+"            \r\n")
time.sleep(2) 
TM2 = int(round(time.time()*1000000))
ser.write(str(TM2)+"            \r\n") 
time.sleep(2)
TM3 = int(round(time.time()*1000000))
ser.write(str(TM3)+"            \r\n") 
time.sleep(2) 
TM4 = int(round(time.time()*1000000)) 
ser.write(str(TM4)+"            \r\n")

1 Answer 1

1

I cannot see anything obviously wrong at first sight. I have a almost identical snippet of code running here that works. My guess would be that the settings of the serial port do not match. Double check that the baudrate, parity and stopbit settings match.

Second guess would be a mess-up with encodings. Have you set your default encoding in python to utf-8? If so you could try

ser.write(str(TM1).encode('ascii'))

Posting the output you get would help as well.

Edit: to avoid the microcontroller skipping some characters. You could use a small function like this. (I used that to send commands to a sensor that had the same issues. When I sent a command like this `ser.write("start logging") it would receive something like "sart lgging".

def write_safe(cmd):
    for x in cmd:
        ser.write(x)
        sleep(0.05)
    ser.write('\r\n')
Sign up to request clarification or add additional context in comments.

4 Comments

It is the same . The settings matches. For example i print the TM1 : 1464600660433102 and output on console is : 164064312 I changed the beaudrate to 9600 so it sends now more numbers
Ok, what you get looks to me like your micro-controller is skipping some characters/bytes. Might be from the stop bit (but you said the settings are matching), or that your uc is not ready to receive the next byte. You can try to send each character with a delay in between to isolate the problem.
How to send each character with a delay in between?
for example: for c in str(TM1): ser.write(c) time.sleep(0.5) Of course each command in its own line, I am not yet used to the editors on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.