modbus readDiscreteInputs



I’m sorry about this I’m fairly new to Lua

What is the format of the return value from readDiscreteInputs()?

local vals = mb:readDiscreteInputs(11,00,32)
printf("modbus value: %s ",  vals)

Any hints on how to extract the bit data?

Thanks in advance



Hi Ted,

The value is most likely returned in a numeric format that you can manipulate to extract or examine individual bits.

Keep in mind that Lua provides variable “coercion”. In other words, because you are asking to print it as a string “%s” Lua simply does the conversion and prints the result in ASCII. I think if you perform bitwise or logical math on the same variable you will get the results you desire.



Hi Tanda

Thanks you are correct = the following works:

local mb ="/dev/ttyS0")
	-- Read 32 modbus digital inputs
	local vals = mb:readDiscreteInputs(11,00,32)
	-- Print the values
	if(vals) then
		for offset = 1,(32/8) do
			value = string.byte(vals,offset)
			printf("modbus value: 0x%x",  value)
		print("No modbus device found")


Thank you both for your answer.

You may find the module ‘pack’ useful to manipulate binary data, especially when dealing with various element size and endianness coming from the device.
You can find the documentation of this module there : … F_API.aspx

(The initial question of this threads indicates the modbus module doc has room for improvements, I’ve noted that point :wink: ).