控制台 串口调试工具 打印串口信息

调试程序我那个串口工具老是死机,我自己抽空写了一个控制台串口打印信息程序,代码很简单

 

#include "stdafx.h"
#include "windows.h"
HANDLE  hCom;
DWORD WINAPI ThreadRead(LPVOID lp)
{
  char readBuf[1024];
  DWORD dw;
  while(1)
  {
 
     ZeroMemory(&readBuf,1024);
  if(!ReadFile(hCom,readBuf,1023,&dw,NULL))  //参数4必须设置一个接受变量 如果为NULL 就会出现内存错误
  {
   printf("read buffer error!!!!\n");
   return 0;
  }
  else
  {
   if(dw != 0)
   {
     printf("%s\n",readBuf);
     PurgeComm(hCom, PURGE_TXABORT|
      PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
   }
  }
  Sleep(1000);
  }
  return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
 system("color 70");
 printf("*****************************************************************\n");
 printf("\n");
 printf("ComMfc5158 all right owned by mfc5158!\n");
 printf("                        2011年11月25日\n");
    printf("\n");
 printf("使用说明:设置好参数如果连接失败,重新设置参数,连接成功\n");
 printf("          开始接受串口消息,接受消息时按回车推出程序\n");
 
 printf("\n");
 printf("\n");
 printf("**********参数设置************\n");
here:printf("1.please input your COM num:\n");
    int ComNum;
 scanf("%d",&ComNum);
 //printf("your com is:  COM%d:\n",ComNum);
 printf("2.please input your 波特率:\n");
 DWORD bote;
    scanf("%dd",&bote);
    TCHAR str[10];
 _stprintf(str,L"COM%d:",ComNum);
    hCom = CreateFile(str,GENERIC_WRITE|GENERIC_READ,NULL,NULL,OPEN_EXISTING,NULL,NULL);
    if(hCom == INVALID_HANDLE_VALUE)
 {
  printf("open com error!\n");
  printf("\n");
  CloseHandle(hCom);
  goto here;
  //Sleep(4000);
  //return 0;
 }
 else
  printf("open com successed!\n");
 printf("\n");
 printf("\n");
 printf("*****************************************************************\n");
 SetupComm(hCom,1024,1024);
 COMMTIMEOUTS TimeOuts;
 //设定读超时
 TimeOuts.ReadIntervalTimeout=MAXDWORD;
 TimeOuts.ReadTotalTimeoutMultiplier=0;
 TimeOuts.ReadTotalTimeoutConstant=0;
 //在读一次输入缓冲区的内容后读操作就立即返回,
 //而不管是否读入了要求的字符。


 //设定写超时
 TimeOuts.WriteTotalTimeoutMultiplier=100;
 TimeOuts.WriteTotalTimeoutConstant=500;
 SetCommTimeouts(hCom,&TimeOuts); //设置超时

 DCB dcb;
 GetCommState(hCom,&dcb);
 dcb.BaudRate=bote; //波特率为115200
 dcb.ByteSize=8; //每个字节有8位
 dcb.Parity=NOPARITY; //无奇偶校验位
 dcb.StopBits=ONESTOPBIT ; //1停止位
 SetCommState(hCom,&dcb);
   
 PurgeComm(hCom,PURGE_TXCLEAR|PURGE_RXCLEAR);  //清空缓冲区
   
 //读取串口信息 并打印
 HANDLE hthread = CreateThread(NULL,0,ThreadRead,NULL,NULL,NULL);
  
 getchar();
 getchar();
 CloseHandle(hthread);
 CloseHandle(hCom);
 return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老猿的春天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值