串口读写工具 - Windows

MFC

2024-09-23

Written by: tdtc

Recommendation: Starting October 14, 2025, do not use ATL or MFC in new projects.

Program on Windows 8.1 - UI1 PC has no serial device

Program on Windows 8.1 - UI2 PC has serial device

程序介绍

界面分三块: 端口配置、发送区域、接收区域

1. 端口配置

1.1 在“Port Number”选择端口号;

1.2 Config

Program on Windows 8.1 - ui3 配置串口比如,串口号,波特率,数据位,停止位等等。

2. 发送

2.2-》2.3-》2.1
  2.3-》点击“Send”按钮。

2.1 Loop Send

当我们钩选此复选框时,必须选择“发送间隔”,然后才能执行循环发送数据。

### 2.2 间隔 选择其一:500、1000、2000毫秒。

Program on Windows 8.1 - ui4 Setting time

如果要更改读取自定义的时间频率:

请将SerialCommView.cpp-Ln292,更为:((CComboBox *)GetDlgItem(IDC_COMBO1Timer))->GetWindowTextA(strTemp);)

2.3 数据

发送的数据

3. 接收

配置完串口,默认为接收状态

3.1 16进制显示

Hex View: 是否16进制显示

3.2 清除

Clear: 清空接收框数据

3.3 保存

Save As: 保存接收框数据;
默认为rtf

测试(无硬件串口)

VMWare/VirtualBox

设置 “Serial Port”

Yield CPU on poll

connection

\\.\pipe\com_1
This end is the server
The other end is a virtual machine

设置 putty

connection type: Serial

\\.\pipe\com_1
9600

开始测试

Communications Port (COM1)
9600

发送数据

hello world
1000

yes:

Check the "Loop Send"

no:

Uncheck "Loop Send"

code

Visual Studio 2008 / Visual Studio 2010 / Visual Studio 2012 / Visual Studio 2013 / Visual Studio 2015, 
Visual Studio 2017 / Visual Studio 2019 / Visual Studio 2022 can all(皆可) open Visual Studio 2005 projects.

flow diagram

flow diagram

首先,如果有线程在运行则停止它。防止数据出现错读。
然后,建立事件以及把它们的值放到数组中。
这时要初始化临界区,准备进入临界编码。
如果要设定的串口打开了,我们要关闭它。
建立串口以及设置超时时间设定这时我们要设置等待事件,之后设置RTS为高。 获得通讯状态,配置DCB以及清空缓存。
最后退出临界区编码。

update

GetVersionEx

warning C4996: 'GetVersionExA': was declared deprecated

ConsoleApplication:

#pragma comment(lib, "netapi32.lib")

#include <iostream>
#include <windows.h>
#include <lm.h>

using namespace std;

bool GetWindowsVersion(unsigned long &major, unsigned long &minor)
{
	unsigned char * pinfoRawData;
	if (NERR_Success == NetWkstaGetInfo(NULL, 100, &pinfoRawData))
	{
		WKSTA_INFO_100 * pworkstationInfo = (WKSTA_INFO_100 *)pinfoRawData;
		major = pworkstationInfo->wki100_ver_major;
		minor = pworkstationInfo->wki100_ver_minor;
		::NetApiBufferFree(pinfoRawData);
		return true;
	}
	return false;
}

int main()
{
	unsigned long major = 0;
	unsigned long minor = 0;
	if (GetWindowsVersion(major, minor))
	{
		std::cout << "Major: " << major << "\nMinor: " << minor << endl;
	}
}

Ref