最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

windows C语言读串口数据

运维笔记admin5浏览0评论
(1)这种方式真的很奇怪,乍一看咋都不像打开串口的,但是真的可以打开。不过在这段代码里并没有配置串口,所以必须借助串口助手才可以,就是先用串口助手打开串口,然后这段程序才可以正常运行。可能是因为在串口助手里已经配置好了串口。
#include<stdio.h>
#include<windows.h>

int main()
{
	FILE *fp;
	if ((fp = fopen("com6", "r")) == NULL)
	{
		printf("cannot open com!\n");
	}
	else
		printf("open com successful!\n");

	char str;

	while (1)
	{
		fscanf(fp, "%c", &str);
		printf("%c ", str);

		Sleep(100);
	}

	return 0;
}

(2)这是可以打开串口并且应该是通用的方法

#include <Windows.h>
#include <stdio.h>

HANDLE hCom;

int main(void)
{
	hCom = CreateFile(TEXT("com6"),//COM1口
		GENERIC_READ, //允许读
		0, //指定共享属性,由于串口不能共享,所以该参数必须为0
		NULL,
		OPEN_EXISTING, //打开而不是创建

		FILE_ATTRIBUTE_NORMAL, //属性描述,该值为FILE_FLAG_OVERLAPPED,表示使用异步I/O,该参数为0,表示同步I/O操作
		NULL);

	if (hCom == INVALID_HANDLE_VALUE)
	{
		printf("打开COM失败!\n");
		return FALSE;
	}
	else
	{
		printf("COM打开成功!\n");
	}

	SetupComm(hCom, 1024, 1024); //输入缓冲区和输出缓冲区的大小都是1024

	/*********************************超时设置**************************************/
	COMMTIMEOUTS TimeOuts;
	//设定读超时
	TimeOuts.ReadIntervalTimeout = MAXDWORD;//读间隔超时
	TimeOuts.ReadTotalTimeoutMultiplier = 0;//读时间系数
	TimeOuts.ReadTotalTimeoutConstant = 0;//读时间常量
	//设定写超时
	TimeOuts.WriteTotalTimeoutMultiplier = 1;//写时间系数
	TimeOuts.WriteTotalTimeoutConstant = 1;//写时间常量
	SetCommTimeouts(hCom, &TimeOuts); //设置超时

	/*****************************************配置串口***************************/
	DCB dcb;
	GetCommState(hCom, &dcb);
	dcb.BaudRate = 9600; //波特率为9600
	dcb.ByteSize = 8; //每个字节有8位
	dcb.Parity = NOPARITY; //无奇偶校验位
	dcb.StopBits = ONESTOPBIT; //一个停止位
	SetCommState(hCom, &dcb);

	DWORD wCount;//实际读取的字节数
	bool bReadStat;

	char str[2] = { 0 };

	while (1)
	{
		//PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR); //清空缓冲区
		bReadStat = ReadFile(hCom, str, sizeof(str), &wCount, NULL);

		if (!bReadStat)
		{
			printf("读串口失败!");
			return FALSE;
		}
		else
		{
			//str[1] = '\0';
			printf("%c\n", str[0]);
		}
		Sleep(100);
	}

	CloseHandle(hCom);
}


在用readFile和WriteFile读写串口的时候需要考虑超时问题,超时的作用是在指定的时间内没有读入或发送指定数量的字符,ReadFile和WriteFile的操作仍然会结束。要查询当前的超时设置应该调用GetCommTimeouts函数,该函数会填充一个COMMTIMEOUTS

结构,调用SetCommTimeouts可以用某一个COMMTIMEOUTS来设置超时。

读写串口的超时总共有两种,间隔超时和总超时。间隔超时是指读取两个字符之间的延时,总超时是指读写操作总共花费的时间。写操作只支持总超时,读操作两种超时都支持。

typedef struct _COMMTIMEOUTS { 

         DWORD ReadIntervalTimeout; //读间隔超时

         DWORD ReadTotalTimeoutMultiplier; //读时间系数

         DWORD ReadTotalTimeoutConstant; //读时间常量

         DWORD WriteTotalTimeoutMultiplier; // 写时间系数

         DWORD WriteTotalTimeoutConstant; //写时间常量

} COMMTIMEOUTS,*LPCOMMTIMEOUTS; 

COMMTIMEOUTS的成员都以ms为单位。

ReadFile函数的最后一个参数,当是重叠操作时,该参数指向一个OVERLAPPED结构,同步操作时,该参数为NULL。

参考连接:点击打开链接http://blog.csdn/l_andy/article/details/51131232


发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>