I'm talking with servo by "Modbus RTU", but to understand what exactly happen I need to print received hex numbers with proper transformation like below.
Convert receiving values in this way:
- hex 7f convert to bin gives(01111111)
- next negate the value gives(10000000)
- rol 2-place gives(00000010)
- and back to hex gives(02)
This what come from servo after home command:
007f7d5fefff858f007f7d5f2fe0076f0000000000000000000000000000
Here is my code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import numpy
port= serial.Serial('/dev/ttyS0', 9600, timeout=2,
xonxoff=False, rtscts=False, dsrdtr=False)
port.flushInput()
port.flushOutput()
time.sleep(0.01)
if port.isOpen():
print(port.name + ' is open...')
flag = port.isOpen()
print flag
#MODBUS_ACTIVE=b"\x01\x05\x04\x27\xFF\x00\x3D\x01"
#port.write(MODBUS_ACTIVE)
#print
"sending=>MODBUS_ACTIVE<=>",MODBUS_ACTIVE.encode("hex")
time.sleep(0.01)
command=raw_input('Enter your command ie.home: ')
if( command == 'home' ):
HOME_INITIAL=b"\x01\x05\x04\x0B\x00\x00\xBD\x38"
#command home first time
port.write(HOME_INITIAL)
print "sending=>HOME",HOME_INITIAL.encode("hex")
time.sleep(0.5)
HOME_FINAL=b"\x01\x05\x04\x0B\xFF\x00\xFC\xC8"
#command home second time
port.write(HOME_FINAL)
time.sleep(0.5)
#While True:
rcv = port.read(30)
print type(rcv)
rcv = rcv.encode('hex')
#rcv = int(rcv,16)
#rcv = "{0:012b}".format(0xfff ^ rcv)
#numpy.right_shift(rcv, 30)
#format(rcv if rcv >= 0 else (1 << 16) + rcv, '016b'
#binary_repr(rcv)
#time.sleep(0.1)
#rcv = bin(rcv^1)
#print bin(str(rcv))
#''.join(format(ord(c), '08b') for c in 'rcv')
#rcv = str(rcv)
#rcv = rcv >>= 1
#print type(rcv)
#print int('rcv')+1
#print 'rcv'
#int(''.join(bin(x)[:1:-1]), 2)
#bin((i ^ (2 ** (i.bit_length()+1) - 1)))[3:]
#bin((rcv ^ (2 ** (rcv.bit_length()+1) - 1)))[3:]
#bin((int(s, 2) ^ (2**(len(s)+1) - 1)))[3:]
#bin((int(rcv, 16) ^ (2**(len(rcv)+1) - 1)))[3:]
#s.replace('1', '2').replace('0', '1').replace('2', '0')
#rcv.replace('1', '0').replace('0', '1').replace('2', '0')
#bin((rcv ^ (2 ** (rcv.bit_length()+1) - 1)))[3:]
print ''.join('1' if x == '0' else '0' for x in 'rcv')
#flip = {'1':'0', '0':'1'}; ''.join(flip[b] for b in s)
#rcv = {'1':'0', '0':'1'}; ''.join(rcv[b] for b in rcv)
#print "{0:012b}".format(2**12-1-a)
#result = int(a, 16) ^ int(b, 16) # convert to integers and xor them
#return '{:x}'.format(result) # convert back to hexadecimal
#result = int(rcv, 16) ^ int(rcv, 16)
#print rcv.encode('hex')
#print format('rcv')
#print (rcv)
command=raw_input('Enter your command ie.home: ')
As you can see I tried many ways to print on the screen the converted Value, but without good result.