Reputation: 139
I am trying to create a six digit number constructed from serval modbus registers. I have no idea how modbus register work but was able to map certain numbers to decimal values.
Example:
'12336': '00',
'12592': '01',
'12848': '02',
'13104': '03',
.
.
.
'14649': '99'
I created a dictionary holding the full list of number from 00 to 99, I start reading 3 holdng registers and iterate over them and create an empty list that gets populated with the value corresponding to the key : value pair in the dictionary then I join them and cast to integer hoping to get the 6 digit number. It kind of works only if i have no leading zeros on my number, however if i do get leading zeros my number gets cut down to where that significant number start.
My code:
NUMBERS = {
'12336': '00', '12592': '01', '12848': '02', '13104': '03', '13360': '04', '13616': '05', '13872': '06', '14128': '07', '14384': '08', '14640': '09', '12337': '10',
}
def scanned_code():
code = client.read_holding_registers(1, 3, unit=0)
r = code.registers
print(r)
value = []
for i in r :
value.append(NUMBERS[str(i)])
return value
def numb(lista):
print(lista)
res = int("".join(map(str, lista)))
return res
scan_job = numb(scanned_code())
print(scan_job)
Let's say I have 3 holding registers with the following values: 12336, 13360, 14128 I would spect to generate this number 000407. instead I get 407
Actual values it get in terminal when executing script
[12592, 13360, 14128]
['01', '04', '07']
10407
[12336, 13360, 14128]
['00', '04', '07']
407
Upvotes: 1
Views: 442
Reputation: 3461
In Python (and pretty much any other programming language), numbers are stored as binary integers. So the concept of "leading zeroes" is meaningless: to the computer, 123
and 000123
would be stored exactly the same. (And, indeed, a mathematician would say those represent exactly the same value.)
If you want leading zeroes, you should store the value as a string. Just remove the int
call within your numb
function.
Upvotes: 3