14.06 проверка на другом компе

This commit is contained in:
Дмитрий Экономов 2024-06-14 18:13:18 +03:00
parent 803fef1412
commit 992b620014
3 changed files with 67 additions and 50 deletions

View File

@ -2,5 +2,5 @@
"sketch": "project\\project.ino",
"output": "build",
"board": "arduino:avr:uno",
"port": "COM4"
"port": "COM6"
}

61
main.py
View File

@ -1,37 +1,46 @@
from fastapi import FastAPI
from pymodbus.client import ModbusSerialClient as ModbusClient
import uvicorn
from pymodbus.client import ModbusSerialClient
import threading
import time
import logging
serial_port = "COM6"
baud_rate = 9600
modbus_client = ModbusSerialClient(serial_port, baudrate=baud_rate)
modbus_data = "0"
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
def poll_modbus():
global modbus_data
modbus_client.connect()
while True:
try:
response = modbus_client.read_discrete_inputs(10001, 1, slave=1)
#print(response)
if not response.isError():
modbus_data = response.registers[0]
print(modbus_data)
except:
pass
threading.Thread(target=poll_modbus, daemon=True).start()
app = FastAPI()
# Create a Modbus client instance
client = ModbusClient(method='rtu', port='COM4', baudrate=9600, timeout=1)
client.connect()
# Shared variable to store the Modbus register value
line = '0'
def read_modbus_value():
global line
while True:
# Read holding register (adjust the register address as needed)
result = client.read_holding_registers(address=1, count=1, unit=1)
if not result.isError():
line = str(result.registers[0])
time.sleep(1) # Poll every 1 second
# Start the Modbus reading in a separate thread
threading.Thread(target=read_modbus_value, daemon=True).start()
@app.get("/stat")
async def get_stat():
return {'state': line}
@app.get("/modbus_data")
async def get_modbus_data():
return {"modbus_data": modbus_data}
@app.get("/")
async def root():
return {'message': 'hello world'}
return {"message": "Welcome to FastAPI with Modbus"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=12346)
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=12345)

View File

@ -1,20 +1,28 @@
#include <ModbusSerial.h>
const int GPIOCoil = 0;
// Define pins
#define PIN_INPUT 3
#define PIN_LED 13
#define MySerial Serial // define serial port used, Serial most of the time, or Serial1, Serial2 ... if available
// Create Modbus object
ModbusSerial mb(Serial, 1); // Assuming slave ID is 1
bool coils[10];
int pinToRead = 2;
ModbusSerial mb (MySerial, 1);
void setup() {
Serial.begin(9600);
pinMode(PIN_INPUT, INPUT);
pinMode(PIN_LED, OUTPUT);
MySerial.begin (9600, MB_PARITY_NONE); // prefer this line in accordance with the modbus standard.
while (! MySerial)
;
mb.config (9600);
}
void loop() {
int sensorVal = digitalRead(PIN_INPUT);
mb.task(); // Update Modbus communication
delay(500);
// mb.setIsts(0, digitalRead(pinToRead));
// mb.task();
int r = Serial.read();
if (r >= 0){
Serial.write(r);
Serial.write(r);
}
}