溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

modbus-master-讀寫

發(fā)布時間:2020-07-24 14:21:06 來源:網(wǎng)絡(luò) 閱讀:3505 作者:白話 欄目:編程語言
  • 通過modbus_tk模塊包實(shí)現(xiàn)各功能

modbus的應(yīng)用場景

作為master端,讀取機(jī)器人寄存器數(shù)據(jù)、往機(jī)器人寄存器中寫入數(shù)據(jù)。

作為master端的應(yīng)用

主要的方法
  • exec(slave=1, function_code=READ_HOLDING_REGISTERS, starting_address=0, quantity_of_x=0, output_value=0, data_format="", expected_length=-1)
參數(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()
數(shù)據(jù)格式化

data_format的參考unpcak中的格式字符串內(nèi)容

modbus-master-讀寫

向AI問一下細(xì)節(jié)
推薦閱讀:
  1. QT xml 讀寫
  2. 終端讀寫

免責(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)容。

AI