代码改变世界

Windows vc 读写串口

2011-03-27 15:33  kwjlk  阅读(1349)  评论(0编辑  收藏  举报
代码先:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void PrintCommState(DCB dcb)
{
    //  打印输出DCB中的部分设置项的值
    _tprintf( TEXT("\nBaudRate = %d, ByteSize = %d, Parity = %d, StopBits = %d\n"), 
              dcb.BaudRate, 
              dcb.ByteSize, 
              dcb.Parity,
              dcb.StopBits );
}


int main( int argc, TCHAR *argv[] )
{
   DCB dcb;
   HANDLE hCom;
   BOOL fSuccess;
   DWORD bytesWritten =0;
   BYTE bErrorFlag = 0;
   char buffer[] = "This is some test data to write to the file.";
   TCHAR *pcCommPort = TEXT("COM1"); //  大多系统都该有的COM1串口

   //  打开指定串口号的读写句柄
   hCom = CreateFile( pcCommPort,
                      GENERIC_READ | GENERIC_WRITE,
                      0,      //  必须以独占方式打开
                      NULL,   //  默认安全参数设置
                      OPEN_EXISTING, //  必须是打开已存在的
                      0,      //  不重叠I / O
                      NULL ); //  打开串口hTemplate必须设置为NULL

   if (hCom == INVALID_HANDLE_VALUE) 
   {
       //  Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   //  初始化 DCB 结构体.
   //SecureZeroMemory(&dcb, sizeof(DCB));	//VC6.0中无法定位该函数,根据字面意思更改为memset
   memset(&dcb, 0,sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);

   //  获取串口的初始设置值
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   //  设置DCB: 
   //  9,600 bps, 8 data bits, no parity, and 1 stop bit.
   dcb.BaudRate = CBR_9600;     //  baud rate
   dcb.ByteSize = 8;             //  data size, xmit and rcv
   dcb.Parity   = NOPARITY;      //  parity bit
   dcb.StopBits = ONESTOPBIT;    //  stop bit

	//设置端口的配置值 波特率什么的
   fSuccess = SetCommState(hCom, &dcb);
   
   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

	//向串口写数据
	bErrorFlag  = WriteFile(hCom,buffer,sizeof(buffer),&bytesWritten,NULL);

	//从串口读数据
	bErrorFlag = ReadFile(hCom,buffer,sizeof(buffer),&bytesWritten,NULL);
	_tprintf(buffer);
	

   //  再次获取COM端口的配置值.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb);       //  Output to console

   _tprintf (TEXT("Serial port %s successfully reconfigured.\n"), pcCommPort);
   
//关闭串口读写句柄
CloseHandle(hCom);
   
   return (0);

}
备注再:
再备注再:
参考连接都是英文的
Windows下向串口发送、读取数据。(最小支持Windows系统版本win2000,即win2000以上)。
这个vc6.0上跑过的代码,不知道还有没有其他方式读写串口。