您好,登錄后才能下訂單哦!
作為master端,讀取機(jī)器人寄存器數(shù)據(jù)、往機(jī)器人寄存器中寫入數(shù)據(jù)。
參數(shù)說明:
@slave=1 : identifier of the slave. from 1 to 247.
@function_code=READ_HOLDING_REGISTERS:功能碼
@starting_address=100:寄存器的開始地址
@quantity_of_x=3:寄存器/線圈的數(shù)量
@output_value:一個整數(shù)或可迭代的值:1/[1,1,1,0,0,1]/xrange(12)
@data_format:對接收的數(shù)據(jù)進(jìn)行格式化
@expected_length:(沒對這個設(shè)置過)
example 1:讀取寄存器數(shù)據(jù)
- 讀取寄存器數(shù)據(jù)
- 解釋一波:
接收后返回的值,是元組,元組中值的個數(shù)由quantity_of_x決定。
quantity_of_x最大值為127。
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as md
# 通過MODBUS方式獲取機(jī)器人心跳
# 需要有機(jī)器人的繼電器地址、端口號,接收的數(shù)據(jù)格式內(nèi)容。
def heart_status():
# 遠(yuǎn)程連接到slave端(從)
ip = "127.0.0.1"
port = 502
master = mt.TcpMaster(ip, port)
master.set_timeout(5.0)
while True:
# 獲取想要的寄存器的數(shù)據(jù)
status = master.execute(slave=1, function_code=md.READ_HOLDING_REGISTERS, starting_address=0,
quantity_of_x=5)
print("status== ", status) # 結(jié)果是一個元組,里面有5個值,由quantity_of_x決定的
if __name__ == "__main__":
heart_status()
example 2:向寄存器寫入數(shù)據(jù)
- 向寄存器寫入數(shù)據(jù)
- 解釋一波:
starting_address: 向哪個寄存器寫入數(shù)據(jù)的地址;多寫的話就是開始地址了;
output_value: 為想要寫入的值;
data_format: 根據(jù)實(shí)際情況去更改。
def robot_on():
ip = "127.0.0.1"
port = 502
# 向第9個寄線器的寫入值,這里寫入1
master = mt.TcpMaster(modbus_ip, modbus_port)
# WRITE_SINGLE_REGISTER寫入的是單個寄存器,所以值是一個,也可以寫成[1]
master.execute(1, md.WRITE_SINGLE_REGISTER, starting_address=9, output_value=1, data_format='BBBBB')
if __name__ == '__main__':
robot_on()
data_format的參考unpcak中的格式字符串內(nèi)容
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。