We are trying to read data from a microcontroller and interface it through serial port. The output is then displayed in Python using Pyserial or the hyperterminal, the former is more important

When you touch the input pins of the microcontroller the value changes real time in hyper terminal. But In the case of the pyserial module, even though you touch the input pins, the value does not change. We have actually noticed that python records and prints the input to the pins of the microcontroller before the code is executed in python. Hence, it does not record and print new inputs once the code was been executed.

What could possibly be wrong with this?

CODE:
import serial,csv,sys


print('Tactile Sensing Feedback for Medical Palpation in MIS\n Pyserial Testing Module\n')
ch= raw_input("Enter a to initialize pyserial module, b to quit:")

if ch == 'a':
print 'Initializing Pyserial module'
ser = serial.Serial(0,baudrate=57600,timeout=0,xonxoff=0)
print ser.portstr
ser.flushInput()

for x in range (0,100):
s = ser.readline()
print repr(s)
ser.close()

elif ch == 'b':
print 'closing port......\n'
quit()

else:
print 'Invalid option please input a or b only'

Dani AI

Generated

Brief summary of the real issue and a practical plan.

The behaviour you described — HyperTerminal shows live changes but the Python script keeps printing the value that was present when the script started, and using a flush made values change but appear disorganized — is almost always a framing/timing problem, not a hardware fault. Incoming serial bytes are collected asynchronously into the OS/driver buffer; how your Python code opens the port, how it reads (blocking vs non‑blocking), and whether it discards or realigns the stream determines whether you see a steady, ordered sequence or stale/partial frames.

Why this happens (concise):

  • If you start reading mid‑stream you will pick up a partial record; subsequent reads can appear to repeat or be out of sync.
  • Constantly discarding the input buffer will remove needed bytes and make output look scrambled.
  • Very short or zero timeouts lead to immediate returns with whatever is buffered (possibly nothing or a partial frame).
  • Closing or reinitializing the port inside the read loop breaks the byte stream and resets alignment.

Concrete checklist to fix it

  1. Open the port once and keep it open for the whole read session; move any close operation to the end.
  2. If the device sends newline-terminated records, align to that boundary: perform one initial discard to get to the next newline, then read complete records only. If no terminator exists, switch to fixed-length frames or add a start marker so you can detect and re-sync frames.
  3. Use a small blocking wait when reading so the code blocks until a full frame or a short timeout, instead of busy-looping with immediate returns.
  4. Do not flush the input on every iteration; a single initial purge is OK to discard stale data.
  5. If needed, use the port API to check how many bytes are available before reading so you only read full frames.
  6. At the MCU side, prefer sending framed packets or only sending on sensor-change; hardware flow control or a simple software protocol (start byte + length) makes parsing robust.

Notes on earlier replies
was right that inserting a short pause reduces polling races when the MCU updates slowly. ’s point about readable, formatted code is helpful for further debugging. Following the framing + single-purge + blocking-read approach will give ordered, up-to-date samples rather than the stale or scrambled output you saw.

Recommended Answers

All 8 Replies

Please use code tags.
They work like this:

[code=<language>] My Code goes here!

[/code]

Where <language> is any of the languages on DaniWeb (C, Perl, Python, HTML, PHP, etc.)

Hi can you check what could be possible wrong with the code?

Thanks,
Bryan

My Code goes here!

import serial,csv,sys


print('Tactile Sensing Feedback for Medical Palpation in MIS\n Pyserial Testing Module\n')
ch= raw_input("Enter a to initialize pyserial module, b to quit:")

if ch == 'a':
print 'Initializing Pyserial module'
ser = serial.Serial(0,baudrate=57600,timeout=0,xonxoff=0)
print ser.portstr
ser.flushInput()

for x in range (0,100):
s = ser.readline()
print repr(s)
ser.close()

elif ch == 'b':
print 'closing port......\n'
quit()

else:
print 'Invalid option please input a or b only'

My Code goes here!

import serial,csv,sys


print('Tactile Sensing Feedback for Medical Palpation in MIS\n Pyserial Testing Module\n')
ch= raw_input("Enter a to initialize pyserial module, b to quit:")

if ch == 'a':
print 'Initializing Pyserial module'
ser = serial.Serial(0,baudrate=57600,timeout=0,xonxoff=0)
print ser.portstr
ser.flushInput()

for x in range (0,100):
s = ser.readline()
print repr(s)
ser.close()

elif ch == 'b':
print 'closing port......\n'
quit()

else:
print 'Invalid option please input a or b only'

LOL
1) Don't use the <> characters on the language... it would just be code=python
2) Put your code in place of the "My code goes here!" part.

We have actually noticed that python records and prints the input to the pins of the microcontroller before the code is executed in python. Hence, it does not record and print new inputs once the code was been executed.

I'm kinda confused by that statement... could you explain a little further, maybe provide an example of expected input -> output, and actual input -> output?

Possibly, one hundred loops of a for() statement happens so fast that it is done before any other data is received. Try this example which sleeps for half of a second and see if the data changes.

for x in range (0,100):
   s = ser.readline()
   print x, repr(s)
   time.sleep(0.5)

I'm kinda confused by that statement... could you explain a little further, maybe provide an example of expected input -> output, and actual input -> output?

Example.

When I touch the pins of the microcontroller it outputs a certain value. And then when I execute the program in python it outputs that data from the microcontroller. But when I release my hand or input a certain voltage to the pins of the microcontroller(while the code is running), the output (which is a continuous stream) does not change and still prints the data when the pins were touched.

So no matter how you change the output of the MCU (which is the input to the serial line), output in python does not change and will just retain the value of the output of the MCU at the instant the script in python was executed. So its like the serial line isn't accepting new inputs.

New Findings:

I have actually used the flushInput() command and is incorporated in the code

for x in range (0,100):
s = ser.readline(16)
flushInput()
print (s)
ser.close()

I have noticed that the value now changes when I touch the pins of the MCU. This leads me to the conclusion that the Input buffer does not dumped the initial data it recorded. Now by using flushInput(), the input buffer dumped the old data and accepts new ones but the data printed is disorganized. Why did the input buffer not update when there was new data????

So I have a new problem, which is to organize the data. haha

Actually I don't need to use flushInput() I just need interrupts that would trigger the CPU to get the data. Any suggestions?

Possibly, one hundred loops of a for() statement happens so fast that it is done before any other data is received. Try this example which sleeps for half of a second and see if the data changes.

for x in range (0,100):
   s = ser.readline()
   print x, repr(s)
   time.sleep(0.5)

The flushInput() successfully solved the output changing part. It was not a matter of reading the data but actually what data was being read in the Input buffer. Data seem not to change because the Input buffer was not accepting new ones. I don't know why.. I initially thought that when new data came in, the Input buffer was updated but in this example it didn't.

Any thoughts on this?

Thanks for the Help anyways.

Possibly, one hundred loops of a for() statement happens so fast that it is done before any other data is received. Try this example which sleeps for half of a second and see if the data changes.

for x in range (0,100):
   s = ser.readline()
   print x, repr(s)
   time.sleep(0.5)

The flushInput() successfully solved the output changing part. Data seem not to change probably because...

Here are my theories:
1. The Input buffer was not accepting new ones. Since there was not interrupt to signal the CPU to read the contents of the Input buffer
2. Pyserial was reading the data in the input buffer way too slowly. But its so weird how the data can be read this slow.


Any thoughts on this?

Thanks for the Help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.