树莓派学习笔记——实现modbus RTU从机
0.前言
1.modbus tk安装
2.简单的例子
#!/usr/bin/env python # -*- coding: utf_8 -*- import sys import logging import threading import modbus_tk import modbus_tk.defines as cst import modbus_tk.modbus as modbus import modbus_tk.modbus_rtu as modbus_rtu import serial import time import RPi.GPIO as GPIO logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") # 创建server server = modbus_rtu.RtuServer(serial.Serial("/dev/ttyAMA0", 9600)) slaver = server.add_slave(1) # BCM GPIO编号 pins = [17,18,27,22,23,24,25,4] def setup(): # 采用BCM编号 GPIO.setmode(GPIO.BCM) # 设置所有GPIO为输出状态,且输出低电平 for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) slaver.add_block("coil", cst.COILS, 0, 16) slaver.set_values("coil", 0, 16*[0]) def loop(): logger.info("running...") # 启动从机 server.start() while True: values = slaver.get_values("coil", 0, 8) #print values[0] for i in range(0, 8): if values[i] == 1: GPIO.output(pins[i], GPIO.HIGH) else: GPIO.output(pins[i], GPIO.LOW) # 必要的延时 time.sleep(0.5) def destory(): logger.info("destory") for pin in pins: GPIO.output(pin, GPIO.LOW) GPIO.setup(pin, GPIO.IN) # 停止从机 server.stop() if __name__ == "__main__": setup() try: loop() except KeyboardInterrupt: destory()
【2】slaver = server.add_slave(1)
3.测试
4.总结
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。