在使用Win32 API函数实现vc和arduino简单串口通信这篇文章中也许会有一些问题,根据需要如果所传的数据不是常量而是变量,我们应该如何去做了?其实很简单。
因为这里串口发送的数据类型为字符型,所以我们将变量的数据类型转换成char即可。例如:
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char test[100];
int a = 120;
int b = 90;
//memcpy(test,&a,sizeof(a));
sprintf(test,"%d,%d",a,b);
HANDLE hDevice = CreateFile(L"COM2",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
0,
0);
if (hDevice !=INVALID_HANDLE_VALUE)
{
printf("Port opened! \n");
DCB lpTest;
GetCommState(hDevice,&lpTest);
lpTest.BaudRate = CBR_9600;
lpTest.ByteSize = 8;
lpTest.Parity = NOPARITY;
lpTest.StopBits = ONESTOPBIT;
SetCommState(hDevice,&lpTest);
DWORD btsIO;
WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
CloseHandle(hDevice);
}
return 0;
}
如上code可以发现,定义了需要输出的两个整型变量a和b,然后将两个变量转换成char型的。sprintf的用法可以上百度去搜索,这里不展开篇幅。
至于arduino中接收并显示的代码,如上篇文章一样。
以上代码已经过编译运行,未出现错误不能运行。