#!/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()
从机编号为1。一个server可以加入多个编号从机。