python modbus协议---点亮LED灯
Posted 初五霸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python modbus协议---点亮LED灯相关的知识,希望对你有一定的参考价值。
点亮LED灯
#!/usr/bin/env python
# -*- coding: utf_8 -*-
'''
简介:modbus协议,点亮LED灯
'''
import os
import sys
if not os.getegid() == 0:
sys.exit('Script must be run as root')
from time import sleep
from pyA20.gpio import gpio
from pyA20.gpio import port
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_tcp as modbus_tcp
import serial
#创建服务器
LOGGER = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
# server里的address需要写的树莓派的IP和需要开放的端口,注意开放相应的端口
SERVER = modbus_tcp.TcpServer(address="0.0.0.0", port=502)
SLAVE1 = SERVER.add_slave(1)
led = port.PA15 #red led PA17
def setup():
#配置IO口
gpio.init()
gpio.setcfg(led, gpio.OUTPUT)
# 建立第一个从机
SLAVE1.add_block('A', cst.HOLDING_REGISTERS, 0, 4)#地址0,长度4
#SLAVE1.add_block('B', cst.HOLDING_REGISTERS, 4, 14)
def loop():
LOGGER.info("running...")
# 服务启动
SERVER.start()
while True:
SLAVE1.set_values('A', 0, 4*[0])
while True:
values = SLAVE1.get_values('A', 0, 4)
if values[0] == 0:
gpio.output(led, 0)
else:
gpio.output(led, 1)
def destory():
LOGGER.info("destroy...")
SERVER.stop()
if __name__ == "__main__":
setup()
try:
loop()
except KeyboardInterrupt:
destory()
串口对应关系
- pin 8 ,10 对应 ttyS1 tx rx
- pin 11,13 对应 ttyS2 rx tx
| 描述 | pin | 描述 | pin |
| -------- | -----: | -----: | :----: |
| 1 |3.3V | 2 | 5V |
| 3 | TWI0_SDA / PA12 / GPIO12 | 4 | 5V |
| 5 |TWI0_SCK / PA11 / GPIO11 | 6 | GND |
| 7 |PWM1 / PA06 / GPIO6 | 8 | UART1_TX / PG06 / GPIO198 |
| 9 | GND | 10 |UART1_RX / PG07 / GPIO199|
| 11 | TUART2_RX / PA01 / GPIO1 | 12 | SIM_CLK/PA_EINT7 / PA07 / GPIO7 |
| 13 |UART2_TX / PA00 / GPIO0 | 14 | GND |
| 15 | UART2_CTS / PA03 / GPIO3 | 16 | TWI1-SDA / PA19 / GPIO19
|
| 17 |3.3V | 18 |TWI1-SCK / PA18 / GPIO18
|
| 19 |SPI1_MOSI / PA15 / GPIO15 | 20 | GND |
| 21 |SPI1_MISO / PA16 / GPIO16 | 22 | UART2_RTS / PA02 / GPIO2
|
| 23 |SPI1_CLK / PA14 / GPIO14 | 24 | SPI1_CS / PA13 / GPIO13
|
| 25 |GND | 26 | SIM_DET/PA_EINT10 / PA10 / GPIO10
|
以上是关于python modbus协议---点亮LED灯的主要内容,如果未能解决你的问题,请参考以下文章