Học lập trình STM32 với Visual Code | Bài 10: Modbus Master

 

Học lập trình STM32 với Visual Code | Bài 10: Modbus Master


Modbus là một protocol dùng khá phổ biến trên thế giới. Hầu hết các thiết bị điện tử công nghiệp điều có hỗ trợ chuẩn giao tiếp này. Vì vậy trên các dòng Vi điều khiển lập trình cũng không thể thiếu việc đọc dữ liệu qua chuẩn giao tiếp này. Bài viết hôm nay sẽ giúp các bạn biến Kit STM32F103RC của mình thành một thiết bị Master giao tiếp bằng Protocol Modbus RTU.

Source code:

#include <Arduino.h>
#include <ModbusRtu.h>
#include <HardwareSerial.h>
#define LED PD2

HardwareSerial Serial_Master(PA10, PA9);

uint16_t au16data[16];
uint8_t u8state;

Modbus master(0, Serial_Master, 0); // this is master and RS-232 or USB-FTDI

modbus_t telegram;

unsigned long u32wait;

void setup()
{
pinMode(LED, OUTPUT);
Serial_Master.begin(19200); // baud-rate at 19200
master.start();
master.setTimeOut(2000); // if there is no answer in 2000 ms, roll over
u32wait = millis() + 1000;
u8state = 0;
digitalWrite(LED, HIGH);
}

void loop()
{
switch (u8state)
{
case 0:
if (millis() > u32wait)
u8state++; // wait state
break;
case 1:
telegram.u8id = 1; // slave address
telegram.u8fct = 3; // function code (this one is registers read)
telegram.u16RegAdd = 1; // start address in slave
telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
telegram.au16reg = au16data; // pointer to a memory array in the Arduino

master.query(telegram); // send query (only once)
u8state++;
break;
case 2:
master.poll(); // check incoming messages
if (master.getState() == COM_IDLE)
{
u8state = 0;
u32wait = millis() + 100;
}
break;
}

if (au16data[0] == 1)
{
digitalWrite(LED, LOW);
}
else
{
digitalWrite(LED, HIGH);
}
}

Link full source code: Download

Video hướng dẫn: 



No comments:

Post a Comment