RS-485是一种半双工的通信协议,经常用于工业控制模块间的通信,因其传输距离远,不容易出错的特点,应用广泛。
此为windows下示例,linux需做相应修改。
#pragma once
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
class Net485
{
public:
Net485(long baud_rate, wchar_t* port_name);
bool send(BYTE data[], int length);
protected:
void set_up_serial_port(long baud);
private:
HANDLE serial_port;
};
#include "Net485.h"
#include <iostream>
Net485::Net485(long baud_rate, wchar_t* port_name)
{
const wchar_t name[8] = L"COM4";
serial_port = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (serial_port == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "Error opening portn");
CloseHandle(serial_port);
}
else
{
set_up_serial_port(baud_rate);
}
}
bool Net485::send(BYTE