#!/usr/bin/env python
import serial
import time
#-------------------------------------------------------------------------------
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr:
# hex.append( "%02X " % ord( aChar ) )
#
# return ''.join( hex ).strip()
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip()
#-------------------------------------------------------------------------------
def HexToByte( hexStr ):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join( hexStr.split(" ") )
# return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
# for i in range(0, len( hexStr ), 2) ] )
bytes = []
hexStr = ''.join( hexStr.split(" ") )
for i in range(0, len(hexStr), 2):
bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )
return ''.join( bytes )
#-------------------------------------------------------------------------------
# USB D- = RXD TTL STICK
# USB D+ = TXD TTL STICK
### POORT INSTELLINGEN
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 9600
ser.parity=serial.PARITY_NONE
ser.stopbits=serial.STOPBITS_ONE
ser.bytesize=serial.EIGHTBITS
ser.timeout=1
try:
ser.open()
print("Connected to: " + ser.portstr)
except Exception, e:
print "error open serial port: " + str(e)
exit()
while 1:
### METHODE #1
ser.write([0xAA, 0x41])
### METHODE #2
#ser.write(serial.to_bytes([0xAA,0x41]))
### METHODE #3
#ser.write("\xAA\x41")
### METHODE #4
#ser.write(chr(0xAA))
#ser.write(chr(0x41))
### METHODE #5
#msg = bytearray([0xAA, 0x41])
#ser.write(msg)
#data = ser.read(8) ### AANTAL BYTES LEZEN
data = ser.readline() ## HELE LIJN LEZEN
#data = ser.readall() ### ALLES LEZEN
print "SIZE: ", len(data)
print "RAW: " + data
print "HEX1: " + ByteToHex(data)
print "HEX2: " + data.encode('hex')
time.sleep(2)