VC++ 与Arduino串口通讯

实验动机

本来在Python中使用pyserial package快乐写串口,但是由于系统迁移需要改为C++,于是开始了C++菜鸟痛苦写串口过程。实现目标为PC作为上位机,Arduino作为下位机控制电机驱动使步进电机移动。全项目包括串口通讯模块Serial,电机控制模块Motor,和调用两个模块的main.cpp。本文具体记录串口通讯的调用,以及发送长字符串如何debug。 

C++串口通讯代码

代码参考别的博文,做了面向对象的分离。系统为Windows,编译环境为VS2019。串口函数主要用到了windows.h中包含的定义。关于这个库的介绍可以看这里(1条消息) C++ windows.h详解_张耘嘉的博客-CSDN博客_c++ windows.h

话不多说,上代码。

Serial.h

#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED

#define ARDUINO_WAIT_TIME 200
#include <windows.h>
#include <stdlib.h>
#include <conio.h>  


class Serial
{
private:
	HANDLE hSerial; //Serial comm handler
	bool connected; //Connection status
	COMSTAT status; //Get various information about the connection
	DWORD errors; //Keep track of last error

public:
	//Initialize Serial communication with the given COM port
	Serial();
	Serial(const char *portName);
	//Close the connection
	~Serial();
	//Read data in a buffer, if nbChar is greater than the
	//maximum number of bytes available, it will return only the
	//bytes available. The function return -1 when nothing could
	//be read, the number of bytes actually read.
	int ReadData(char *buffer, unsigned int nbChar);
	//Writes data from a buffer through the Serial connection
	//return true on success.
	bool WriteData(char *buffer, unsigned int nbChar);
	//Check if we are actually connected
	bool IsConnected();
};
#endif // SERIALCLASS_H_INCLUDED

Serial.cpp

#include "Serial.h"
#include <stdio.h>

Serial::Serial() {

}

Serial::Serial(const char *portName)
{
	this->connected = false;

	this->hSerial = CreateFileA(portName,
		GENERIC_READ | GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);

	if (this->hSerial == INVALID_HANDLE_VALUE)
	{
		if (GetLastError() == ERROR_FILE_NOT_FOUND) {
			printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
			return;
		}
		else
		{
			printf("ERROR!!!");
		}
	}
	else
	{
		//If connected we try to set the comm parameters
		DCB dcbSerialParams = { 0 };
		
		// Try to get the current
		if (!GetCommState(this->hSerial, &dcbSerialParams))
		{
			printf("failed to get current serial parameters!");
		}
		else 
		{
			// Define serial connection parameters for the arduino board
			dcbSerialParams.BaudRate = CBR_115200;
			dcbSerialParams.ByteSize = 8;
			dcbSerialParams.StopBits = ONESTOPBIT;
			dcbSerialParams.Parity = NOPARITY;
			// Setting the DTR to Control_Enable ensures that the Arduino is properly
			// reset upon establishing a connection
			dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;

			//Set the parameters and check for their proper application
			if (!SetCommState(hSerial, &dcbSerialParams))
			{
				printf("ALERT: Could not set Serial Port parameters");
			}
			else
			{
				//If everything went fine we're connected
				this->connected = true;
				//Flush any remaining characters in the buffers 
				PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
				//We wait 2s as the arduino board will be reseting
				Sleep(ARDUINO_WAIT_TIME);
			}
		}
	}	

}

Serial::~Serial() {
	//Check if we are connected before trying to disconnect
	if (this->connected)
	{
		//We're no longer connected
		this->connected = false;
		//Close the serial handler
		CloseHandle(this->hSerial);
	}
}

int Serial::ReadData(char *buffer, unsigned int nbChar) {
	//Number of bytes we'll have read
	DWORD bytesRead;
	//Number of bytes we'll really ask to read
	unsigned int toRead;

	//Use the ClearCommError function to get status info on the Serial port
	ClearCommError(this->hSerial, &this->errors, &this->status);

	//Check if there is something to read
	if (this->status.cbInQue > 0)
	{
		//If there is we check if there is enough data to read the required number
		//of characters, if not we'll read only the available characters to prevent
		//locking of the application.
		if (this->status.cbInQue > nbChar)
		{
			toRead = nbChar;
		}
		else
		{
			toRead = this->status.cbInQue;
		}

		//Try to read the require number of chars, and return the number of read bytes on success
		if (ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL))
		{
			return bytesRead;
		}

	}

	//If nothing has been read, or that an error was detected return 0
	return 0;
}

bool Serial::WriteData(char *buffer, unsigned int nbChar) {
	DWORD bytesSend;

	//Try to write the buffer on the Serial port
	if (!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
	{
		//In case it don't work get comm error and return false
		ClearCommError(this->hSerial, &this->errors, &this->status);

		return false;
	}
	else
		return true;
}

bool Serial::IsConnected() {
	//Simply return the connection status
	return this->connected;
}

main.cpp (修改后没有调试,可能有bug)

#include "Serial.h"
#include <iostream>
#include <tchar.h> 
#include <stdio.h> 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])//输入一组50以内的字符串,输出到arduino上
{
	Serial* SP = new Serial("COM3");//COM9是我的arduino2560串口,使用时要改成你自己的
	char* incomingData = " ";
	char n[50];
	int dataLength = 50;

	while (1) {
		cin >> n;
		incomingData = SP->ReadData();
		SP->WriteData(incomingData, dataLength);
		cout << incomingData << endl;
	}
	return 0;
}

调试过程

调试串口的时候最好有两个串口模块,一个收PC消息,一个传回PC消息,看看发的消息是不是正确的。用到的调试软件是SSCOM串口通信工具,审核通过的话应该能在我的资源库里找到。

遇到问题:报错:找不到COM口;怎么修改代码都没有反应;重启VS也没有用

调试的时候用了COM5端口,后面改为COM3端口;修改了代码,但还是一直在报找不到COM5的错。

解决方案:重新生成解决方案,发现代码就能正常工作了。(所以我总感觉嵌入式的开发是个经验活)

小tips:在串口通讯的时候,可以看RX灯是否闪烁,闪烁表示收到信号,同样发送消息TX灯也会闪烁。

总结

Serial代码的编写,SSCOM调试工具的使用,如何从芯片看串口是否接受到信息。

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Matlab与Arduino之间的串口通讯可以通过Matlab中的串口对象serial来实现。首先,你需要定义一个串口对象,并设置波特率。然后,使用fopen函数打开串口对象。接下来,你可以使用fgetl函数从串口缓冲区读取数据,并将其转换为数字。在Arduino端,你需要编写相应的代码来发送数据到串口。例如,你可以使用Serial.println函数将数据发送到串口。在Matlab中,你可以使用plot函数实时绘制数据,并使用drawnow函数更新图形。最后,使用fclose函数关闭串口对象。这样,你就可以实现Matlab与Arduino之间的串口通讯了。\[1\]\[2\] #### 引用[.reference_title] - *1* *2* [Arduino 与matlab串口通讯](https://blog.csdn.net/weixin_42913113/article/details/97901622)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Matlab与Arduino连接(一):MATLAB与Arduino的串口通信](https://blog.csdn.net/qq_40969179/article/details/115468503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值