python PLC_IP协议 Modbus应用(一)

在Python中与PLC建立通信,通常需要进行以下步骤:

1.确定PLC的通信协议:不同的PLC厂商和型号可能采用不同的通信协议,例如Modbus、OPC UA、Profinet等。需要确定您的PLC使用的是哪种通信协议(本文为modbustcp)。

2. 安装相应的Python库:根据您所选择的PLC通信协议,在Python中安装相应的库。本文使用Modbus协议,故安装`pymodbus`库

3. 连接到PLC:使用相应的库和代码,在Python中建立与PLC的连接。具体的连接方式和代码会因通信协议而异,以下是一个示例:

host = '192.168.1.5'
port = 502
client = ModbusTcpClient(host, port)

host为PLC设定的IP地址,

port为通信协议的端口

client= ModbusTcpClient(host, port)则与PLC建立连接,带入上面的host和port作为参数。

4. 读取或写入数据:根据您的需求,使用相应的库和方法来读取或写入PLC的数据。以下是一个示例:

读取PLC信号的方式:

def get_response_from_plc():
    result: ReadCoilsResponse = client.read_coils(address=2049 - 1, count=8)  # M0 接收信号
    var = result.bits[0]
    return var

写入PLC信号的方式:

def send_shake_hands_to_plc():
    time.sleep(1)
    client.write_coil(address=2052 - 1, value=True)  # shake hands M3
    time.sleep(0.1)
    client.write_coil(address=2052 - 1, value=False)  # shake hands M3

5.如下是一个实现与PLC简单通信的完整代码:

import time
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.bit_read_message import ReadCoilsResponse

host = '192.168.1.5'
port = 502
client = ModbusTcpClient(host, port)


def send_shake_hands_to_plc():
    time.sleep(1)
    client.write_coil(address=2052 - 1, value=True)  # shake hands M3
    time.sleep(0.1)
    client.write_coil(address=2052 - 1, value=False)  # shake hands M3


def send_fail_to_plc():
    client.write_coil(address=2053 - 1, value=True)  # FAIL M4
    time.sleep(0.1)
    client.write_coil(address=2053 - 1, value=False)  # FAIL M4


def send_pass_to_plc():
    time.sleep(1)
    client.write_coil(address=2054 - 1, value=True)  # PASS M5
    time.sleep(0.1)
    client.write_coil(address=2054 - 1, value=False)  # PASS M5


def get_response_from_plc():
    result: ReadCoilsResponse = client.read_coils(address=2049 - 1, count=8)  # M0 接收信号
    var = result.bits[0]
    return var


if __name__ == '__main__':

    while True:
        if get_response_from_plc():
            print(get_response_from_plc()) #持续监控PLC信号的状态,实现自动化的目的

文中M0,M3,M4,M5为PLC定义的信号,对应的地址需要根据实际情况确认。

本文使用环境为:Windows 10 ,python 3.10,pymodbus 2.5.3,PLC品牌是Δ的

————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
 

你可能感兴趣的:(tcp/ip,网络,python,模块测试)