写了一个很简单API串口编程的源代码,调试通过,希望给需要的人有所帮助

本文提供了一个使用Windows API进行串口通信的C++示例程序。该程序演示了如何打开串口、设置波特率等参数,并从指定的串口(如COM4)读取数据。此外,还展示了如何处理可能发生的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// comconsole.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <windows.h>
void set_up_serial_port(HANDLE h, long baud);
int main(int argc, char* argv[])
{   char str[100]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    char str1[100]={'0','0','0','0',0,0,0,0,0,0,0,0,0,0,0,0,0};
    char* pChar=&str[0];
    DWORD nNumberOfBytesToRead=100;
 DWORD wCount;//读取的字节数
    LPDWORD lpEvtMask=NULL;
 LPOVERLAPPED lpOverlapped=NULL;
    HANDLE hCom;
    DWORD dwError;
    hCom = CreateFile("COM4", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hCom == (HANDLE)0xFFFFFFFF)
 {
      dwError = GetLastError();
      MessageBox(NULL, "dwError", NULL, MB_OK);
 }
    set_up_serial_port(hCom, 9600);
    if(FALSE==ReadFile(hCom,str, nNumberOfBytesToRead, &wCount,0))
 {     
  dwError = GetLastError();
  printf("%d",dwError);
  MessageBox(NULL, "dwError", NULL, MB_OK);
 }
 for(int i=0; i<wCount; i++)
 {
      printf("%s/n",str);
 }
 printf("Hello World!/n");
    CloseHandle(hCom);

 return 0;
}

void set_up_serial_port(HANDLE h, long baud)
{
 DCB properties;   /* Properties of serial port */

 /* Get the properties */
 GetCommState(h, &properties);

 /* Set the baud rate */
 switch(baud)
 {
 case 1200:
  properties.BaudRate = CBR_1200;
  break;
 case 2400:
  properties.BaudRate = CBR_2400;
  break;
 case 4800:
  properties.BaudRate = CBR_4800;
  break;
 case 9600:
  properties.BaudRate = CBR_9600;
  break;
 case 14400:
  properties.BaudRate = CBR_14400;
  break;
 case 19200:
  properties.BaudRate = CBR_19200;
  break;
 case 38400:
  properties.BaudRate = CBR_38400;
  break;
 default:
  fprintf(stderr, "Invalid baud rate: %ld/n", baud);
  exit(0);
  break;
 }
 
 /* Set the other properties */
 properties.Parity = NOPARITY;
 properties.ByteSize = 8;
 properties.StopBits = ONESTOPBIT;

 SetCommState(h, &properties);

 return;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值