当前位置:网站首页>Scoring system based on 485 bus
Scoring system based on 485 bus
2022-07-27 01:19:00 【lzl_ 0408】
Practical tasks
B Level task (80%)
requirement :
Use two STC Download the provided in the previous section .hex file , build 485 Dual computer communication circuit , stay linux Program code for scoring in .
step :
Read the flow chart of the program system , Clarify the functional requirements of dual computer communication .
Be familiar with the simulation in the previous section MODBUS Packet structure of the protocol , Relevant function codes and additional data definitions
| Function code | Read the function code of the lower computer | 0X03 |
| -------------- | -------------- | ---- |
| Detect function code | 0X08 | |
| Address error function code | 0X10 | |
| Reset function code | 0X01 | |
| Additional data | Error code | 0X6F |
| baotou | 0X5A | |
| Broadcast address | 0X00 | |
| Custom content | 0X13 | |
Check bytes in the Protocol , This scoring system adopts accumulation and coding .
3. review 485 Bus data transceiver experiment , Build a dual computer communication circuit . Refer to the previous section to ensure STC After setting the slave number and score , Press down KEY2、KEY3 Key symbol , The first 1 Position and number 8 position LED The light is on .
4. PC The end serial port settings are as follows :
Serial port baud rate :9600 Data bits :8 position Check bit : nothing Stop bit :1
5. Written PC The end program should complete a complete scoring process by referring to the communication protocol in the previous section :
- - You need to include the settings of the serial port
- The master node initiates the slave detection process : Send the normal detection packet of the specified slave number , Judge whether the response query packet conforms to the communication protocol in the previous section .
- The master obtains the scoring process of the slave : Send the data package related to the specified slave scoring , Judge whether the response query packet conforms to the communication protocol in the previous section .
- The host initiates the process of ending the scoring , If reset succeeds ,STC From the plane 1 Position and number 8 position LED The light will go out .
- Display serial port related information , Display the detected slave number and the score of the slave .
Code design
#include <cstdio>
#include <iostream>
#include <string>
#include <unistd.h>
#include <signal.h>
#include "serial.h"
#include <setjmp.h>
using namespace std;
typedef unsigned char uchar;
/* be based on RS485 Bus scoring system - Host program - Double machine scoring */
string format(const vector<uchar> &data); // Data is processed into strings
int check(serial &pipe, int addr); // Equipment inspection
int get_score(serial &pipe, int addr); // Get points
void reset(serial &pipe); // Slave reset
int main() {
serial pipe("/dev/ttyUSB0", B9600);
int addr, check_ret, score;
while(1){
cout<<" Enter description :\n Enter the legal slave address to query the score \n Input -2 Reset the slave \n Input -1 Exit procedure \n If the program does not work correctly , Cannot receive slave response , Please restart and try again \n Please enter the command :";
cin>>addr;
if(addr == -1) break;
if(addr == -2) {
reset(pipe);
continue;
}
check_ret = check(pipe, addr);
if(check_ret == 1){
cout<<" Equipment detection is normal "<<endl;
sleep(1);
if(!(score = get_score(pipe, addr)))
cout<<" Failed to get score "<<endl;
else
cout<<" fraction :"<<score<<endl;
}
else if(check_ret == 0){
cout<<" Wrong address , Please enter the address and try again "<<endl;
continue;
}
else{
cout<<" Data transmission error , Please restart the slave "<<endl;
}
//reset(pipe);
cout<<" The slave has been reset , Input -1 sign out "<<endl;
}
return 0;
}
/*****************************************************
Process data into strings
******************************************************/
string format(const vector<uchar> &data) {
std::string str(2 * data.size() + 1, '\x00');
for (int i = 0; i < data.size(); i++) {
sprintf(&str[i * 2], "%02X", data[i]);
}
return str;
}
/*****************************************************
Slave address detection :
Parameters :serial A serial port , Slave address
The host sends data for detection :5a + Slave address + Detect function code 08 + 13 + Check code
Return value :1( The address is correct );0( Wrong address );-1( Data error )
******************************************************/
int check(serial &pipe,int addr){
int check_code = 117 + addr, ret; // The check code is cumulative sum
vector<uchar> code = {0x5a, 0x08, 0x13};
vector<uchar> rec;
code.insert(code.begin()+1, (uchar)addr); // Insert slave address
code.push_back((uchar)check_code); // Insert the check code
//cout << format(code) << endl;
/* Write and receive response packets */
pipe.myWrite(code);
sleep(1);
rec = pipe.myRead(5);
if(format(rec) == format(code)) // Check whether the received packet is the same as the sent one , If it is the same, the slave address is correct
ret = 1;
else{
if(rec[3] == 0x6f) ret = 0;
else ret = -1;
}
return ret;
}
/*****************************************************
Get slave scores :
Parameters :serial A serial port , Slave address
The host sends for score acquisition :5a + 00 + Read function code 03 + Slave address + Check code
Return value : fraction ( The data is correct );-1( The slave is not ready );-2( Data error )
******************************************************/
int get_score(serial &pipe, int addr){
int check_code = 93 + addr, ret; // The check code is cumulative sum
vector<uchar> code = {0x5a, 0x00, 0x03};
vector<uchar> rec;
code.insert(code.begin()+3, (uchar)addr); // Insert slave address
code.push_back((uchar)check_code); // Insert the check code
//cout << format(data) << endl;
/* Write and receive response packets */
pipe.myWrite(code);
sleep(1);
rec = pipe.myRead(5);
if(rec[3] == 0x6f) ret = -1; // Check for errors
else {
ret = (int)rec[3]; // Turn to numbers
if(ret < 0 || ret > 100) ret =-2; // Check whether the number is legal
}
return ret;
}
/*****************************************************
Slave reset :
Parameters :serial A serial port , Slave score
Master sends for slave reset :5a + Broadcast address 00 + Reset function code 01 + 00 + Check byte
******************************************************/
void reset(serial &pipe){
vector<uchar> code = {0x5a, 0x00, 0x01,0x00,0x5b};
//cout <<"reset:"<< format(code) << endl;
/* Send packet */
for(int i=0;i<600;i++) {
pipe.myWrite(code);
}
return;
}
```
```c
//serial.h
#ifndef SERIAL_H
#define SERIAL_H
#include <cstring>
#include <vector>
#include <sys/termios.h>
class serial {
private:
int board = -1, epfd = -1;
public:
serial(const char *board_path, speed_t baud_rate);
~serial();
std::vector<unsigned char> myRead(size_t n) const;
void myWrite(const std::vector<unsigned char> &data) const;
};
#endif //SERIAL_H
```
```c
//serial.c
#include "serial.h"
#include <cerrno>
#include <cstdio>
#include <iostream>
#include <sys/epoll.h>
#include <sys/fcntl.h>
#include <sys/termios.h>
#include <sys/unistd.h>
#include <stdio.h>
#include <signal.h>
#define err_check(code) if ((code) < 0) { \
printf("Error: %s\n", strerror(errno)); \
_exit(1); \
}
serial::serial(const char *board_path, speed_t baud_rate) {
err_check(board = open(board_path, O_RDWR | O_NOCTTY ))
termios attrs {};
tcgetattr(board, &attrs);
// set baud rate
err_check(cfsetispeed(&attrs, baud_rate))
err_check(cfsetospeed(&attrs, baud_rate))
attrs.c_iflag &= ~( BRKINT | ICRNL | INPCK | ISTRIP | IXON | IXOFF );
attrs.c_oflag &= ~( OPOST | ONLCR | OCRNL );
attrs.c_lflag &= ~( ECHO | ICANON | IEXTEN | ISIG );
attrs.c_cflag &= ~( CSIZE | PARENB );
attrs.c_cflag |= CS8;
attrs.c_cc[VMIN] = 1;
attrs.c_cc[VTIME] = 0;
// Set terminal parameters , All changes take effect immediately
err_check(tcsetattr(board, TCSANOW, &attrs))
// Reopen the device file to apply the new terminal parameters
close(board);
err_check(board = open(board_path, O_RDWR | O_NOCTTY))
// Create a new epoll example , And return a file descriptor for control
err_check(epfd = epoll_create(1))
epoll_event event {
.events = EPOLLIN | EPOLLET, // An event is triggered when the opposite end becomes readable
.data = {
.fd = board
}
};
// Add this event to epoll In the listening list
err_check(epoll_ctl(epfd, EPOLL_CTL_ADD, board, &event))
}
serial::~serial() {
(~board) && close(board);
(~epfd) && close(epfd);
}
std::vector<unsigned char> serial::myRead(size_t n) const {
size_t count = 0;
std::vector<unsigned char> buffer(n);
while (count < n)
{
epoll_event event {};
// Wait for data from the opposite end of the serial port
epoll_wait(epfd, &event, 1, 5000); // Specify the timeout value , Avoid indefinite blocking waiting
// Reading data , Then decide whether to continue reading according to the amount of data read
count += ::read(board, &buffer[count], n);
}
//tcflush(board,TCIOFLUSH);
return buffer;
}
void serial::myWrite(const std::vector<unsigned char> &data) const {
size_t count = 0;
//tcflush(board,TCOFLUSH);
while (count < data.size()) {
// Write data to serial port
count += ::write(board, &data[count], data.size() - count);
}
}
Programming objectives : Deepen the understanding through this case RS485 communication mode , The main controller of the upper computer communicates with all the lower computers .
Description of program operation effect : adopt RS232/RS485 The converter will be multiple with 485 The MCU of the lower computer control program of the module is mounted on the bus . Use a single chip microcomputer as the upper computer , Download hex file , Another single-chip microcomputer is used as the lower computer , Download the lower computer program . After the MCU of the lower computer is powered on , The first two digits of the nixie tube display the slave number , The last three digits show the scoring results . First press the center button of the navigation button to enter the setting mode , The selected set decimal point of the nixie tube is lit ; Then by controlling the left and right directions of the navigation keys, the position selection of the nixie tube is realized , The up and down direction realizes the addition and subtraction of the numerical value on the nixie tube , Press the center button again to exit the setting mode . Then press KEY2、KEY3 Press the key to mark the completion of slave number and scoring setting , The first 1 Position and number 8 position LED The light is on ; Finally, by controlling the slave detection and multi machine scoring buttons of the master controller of the upper computer , Get the slave number and score set by the MCU , So as to realize the communication between the upper computer and the lower computer .
The test method
1. Through the DuPont line 51 SCM and RS232/RS485 Converter connection , Re pass USB turn RS232/RS485 Serial communication line and PC Machine connection , download hex file , And power on the MCU ;
2. If you directly use a single chip microcomputer as the host , The MCU needs to download the contact software in the upper computer program instead of the lower computer software ;
3. The initial phenomenon after downloading from the lower computer is : The leftmost two nixie tubes show 00 Indicates the slave number , Far right 3 A digital tube display 000 Indicates the score ;
4. Press the center button of the navigation key to enter the setting mode , Press the center key again to exit the setting mode after setting the slave number and scoring , Then press the KEY1,KEY2, Flag setting is complete ;
5. Control the upper computer to detect the slave computer and obtain the number of the lower computer , And get its score , The data is displayed on the main controller of the upper computer , Finally, finish scoring , Single chip microcomputer LED The light goes out .
Experimental experience
RS232 The interface only allows connections on the bus 1 A transceiver , Single station capacity . and RS485 The interface on the bus is allowed to connect up to 128 A transceiver . That is, it has multi station capability , So that users can take advantage of a single RS485 The interface makes it easy to set up a network of devices .RS485 It belongs to half duplex communication , Data can be transmitted in both directions of a signal carrier , But it cannot be transmitted at the same time . The level conversion adopts differential circuit mode ,A、B The voltage difference between the two lines is greater than 0.2 Think it's logic “1”, Less than -0.2 Think it's logic “0”, Only one of the two sides of the communication is sending , When one party is receiving , Communication can be carried out normally .RS485 Widely used in industrial automation control 、 Video surveillance 、 Access control intercom, building alarm and other fields .
This experiment makes us understand RS485 and RS232 With more understanding , Understand how they work .
边栏推荐
- Flink sliding window understanding & introduction to specific business scenarios
- Jenkins--基础--03--安装后设置向导
- 4. 欧洲冠军联赛
- Analysis of contentvalues
- Warning: IPv4 forwarding is disabled Networking will not work.
- In depth learning report (1)
- 快来帮您一分钟了解移动互联网
- Understanding of Flink checkpoint source code
- 解决Pytorch中Cuda无法GPU加速问题
- How does KS catch salt value? api,did?
猜你喜欢

物联网将彻底改变制造业,你准备好了吗?

Understanding of Flink interval join source code

5. Xshell connection server denied access, password error

Compile Darknet under vscode2015 to generate darknet Ext error msb3721: XXX has exited with a return code of 1.

下一代互联网:视联网

物联网改善我们生活的 6 种方式

Are you ready for the Internet of things to revolutionize manufacturing?

In depth learning report (3)

The difference between forward and redirect

Simple explanation of database table connection
随机推荐
Come and help you understand the mobile Internet in a minute
初中高三部曲音视频下载Pronunciation Pairs+Ship or Sheep+Tree or Three
Flink1.11 multi parallelism watermark test
玩客云搭配zerotier保姆级教学,保证学废
快来帮您一分钟了解移动互联网
ks 怎么抓salt值?api,did?
Tencent upgrades the live broadcast function of video Number applet. Tencent's foundation for continuous promotion of live broadcast is this technology called visual cube (mlvb)
Keil开发环境的搭建送安装包
FaceNet
Play guest cloud brush machine 5.9
How does KS catch salt value? api,did?
被围绕的区域
SQL学习(1)——表相关操作
Android -- Data Persistence Technology (III) database storage
10 - deploy MySQL on CentOS 7
Jenkins -- Basic -- 5.3 -- system configuration -- global security configuration
Verilog procedure assignment statement
李宏毅机器学习(2017版)_P14:反向传播
5.xshell连接服务器拒绝访问,密码错误
Play guest cloud with zerotier nanny level teaching to ensure learning waste