0

I wrote a Python script in which I can send fixed bytes through a COM port.

ser.write(bytes('0123456789',encoding='ascii')) 

I want to parameterize the number of bytes that the script can send.

Can anyone please suggest me how I can do this?

Thanks.

2
  • Have you tried creating a random-length bytes value and passing it to your ser.write() function? If not, what have you tried? Commented Aug 19, 2015 at 22:51
  • Do you mean you want to restrict the number of bytes sent to a specific value? Suppose that ser.write has another parameter numBytes. What happens if NumBytes is 6 in your example? What if numBytes is 16? Commented Aug 19, 2015 at 23:57

1 Answer 1

1

By "random" I think you mean "arbitrary", i.e. how to send an arbitrary number of bytes...

You can generate a sequence of repeating digits like this:

>>> ''.join([str(i%10) for i in range(21)]) '012345678901234567890' 

The number of bytes required can be passed to the script as a command line argument. Its value will be available in the sys.argv[] list.

import sys import serial try: num_bytes = int(sys.argv[1]) except (IndexError, ValueError): sys.stderr.write('Usage: {} num-bytes\n'.format(sys.argv[0])) sys.exit(1) ser = serial.Serial() # set up your serial port digits = ''.join(str(i%10) for i in range(num_bytes)) num_written = ser.write(bytes(digits, 'ascii')) 

Invoke the command like this:

$ python3 send_bytes.py 42 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.