is there a problem on this simple code

John Machin sjmachin at lexicon.net
Mon Mar 14 23:06:15 CET 2005


jrlen balane wrote:
> why is it that here:
>
> 1)rx_data = ser.read(10)
>     (rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1,
> pyra2, voltage, current, rx_checksum) = unpack('10B', rx_data)
>     print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1,
> pyra2, voltage, current, rx_checksum
>
> >>> type (rx_command)
> <type 'int'>
>
> but here:
>
> 2)rx_data_command = ser.read()

Are you sure you have really have read() -- which will read all
available data -- or read(1) -- which will read just one byte???

>     (rx_command) = unpack('1B', rx_data_command)
>
> >>> type (rx_command)
> <type 'tuple'>
>
> how can i make rx_command of type 'int' if i am to use 2)?

unpack returns a tuple. In 1) you unpack it. In 2) you don't unpack it.

either do this:

(rx_command,) = unpack('1B', rx_data_command) # unpack tuple

or this:

rx_command = unpack('1B', rx_data_command)[0] # grab 1st element of
tuple

or, simply, to get what you want, just do this:

rx_command = ord(ser.read(1))

>
> @sir John
> the reason why my first post all starts with '70' , which is what i
> really wanted to happen, is that it is buffered. the microcontroller
> sends data at a very fast rate, that the program just retrieve data
> from the buffer. so basically, they are not "real time". but there
are
> also cases where the command is in other position. the good thing is,
> it remains in that position throughout...

It wasn't doing that before; In the second posting with examples, there
were some that were a MIXTURE of (a) 70 as the first byte of 10 (b) 70
as the fourth byte of 10 (128 128 103 70 2 6 64 64 192 0)

>
> i want to make the program show data in "real time" so everytime i am
> able to read data, i immediately use flushInput(), to erase data from
> the buffer.

How large is the buffer?

>
> so i what i want to do now is to search for the rx_command first
> ('70') just so i know where my data should start.

OK, so NOW you are saying that the microcontroller is pumping out data
continuously, it's not one response to each of your "67" commands???

In that case what I'd suggest you do is to read 19 bytes from the
serial port (with time-out, I'd suggest; give up if you don't get 19
bytes returned), and for each k in range(9), test for:

(a) byte[k] == 70
(b) byte[k+2] == 6
(c) checksum(byte[k:k+10]) == 0

If you don't get a valid data packet, give up.

This should snatch one valid data packet (if there are any) from the
torrent.




More information about the Python-list mailing list