yxylxj 发表于 2015-8-7 23:32:20

求如何用C WIN32 API 写一个串口通信

求如何用C WIN32 API 写一个串口通信,
不好意思了,只会C语言 ,想在windos 控制台下实现个 串口通信,来协助调试单片机,有写过的 帮忙指导下

dou_yuyu 发表于 2015-8-8 02:38:01

可以,百度一下 win32 串口就有了。不过写起来长的,不如看看用C#什么的带的库写,分分钟的事情。

沉默胜过白金 发表于 2015-8-8 09:50:00

坛子里有个labview大神,这玩意更简单。不用代码。掌握规律后,分分钟的事。

yxylxj 发表于 2015-8-8 15:02:14

dou_yuyu 发表于 2015-8-8 02:38
可以,百度一下 win32 串口就有了。不过写起来长的,不如看看用C#什么的带的库写,分分钟的事情。 ...

就是为了好测试 ,都是C语言两个平台好移植啊

iskywolf 发表于 2015-8-8 15:23:41

pcommlite库

dou_yuyu 发表于 2015-8-8 17:25:52

yxylxj 发表于 2015-8-8 15:02
就是为了好测试 ,都是C语言两个平台好移植啊

你既然决定用win32 的api 来搞pc串口,最优选择就是vc++了,兼容纯c的。但是问题是,这样搞不省力的。其实还是建议用控件或者类库就可以了。

yxylxj 发表于 2015-10-25 10:49:19

搜集资料,自己尝试写了个,实测可以用

本帖最后由 yxylxj 于 2015-10-25 10:50 编辑

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <winbase.h>
#include <winerror.h>
#include <conio.h>



#define RX_SIZE        1024*8
#define true        1                //数据缓冲区大小
#define false 0
#define bool char





DCB    dcb;
COMMTIMEOUTS ct;
HANDLE hCommDevice;
bool   m_portopen,OpenCloseFlag;
OVERLAPPED m_ovread,m_ovwrite,m_ovwait;


int ProcessErrorMessage(char* ErrorText)
{

    char szBuf;
    LPVOID lpMsgBuf;
    DWORD dw = GetLastError();
    FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    dw,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) &lpMsgBuf,
    0,
    NULL );
    sprintf(szBuf,"%s 出错信息 (出错码=%ld): %s",ErrorText, dw,(char *) lpMsgBuf);
    LocalFree(lpMsgBuf);
    //输出提示。
    printf(szBuf);
    return 0;
}


void CCommPort(void)
{
hCommDevice = NULL;
m_portopen = false;
memset(&m_ovread,0,sizeof(OVERLAPPED));
memset(&m_ovwrite,0,sizeof(OVERLAPPED));
memset(&m_ovwait,0,sizeof(OVERLAPPED));
m_ovwait.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
m_ovwrite.hEvent= CreateEvent(NULL,TRUE,FALSE,NULL);
m_ovread.hEvent= CreateEvent(NULL,TRUE,FALSE,NULL);
}
//---------------------------------------------------------------------------
void CCommPort2(void)
{
   if (hCommDevice)
   CloseHandle(hCommDevice);
   CloseHandle(m_ovwait.hEvent);
   CloseHandle(m_ovwrite.hEvent);
   CloseHandle(m_ovread.hEvent);
}
//---------------------------------------------------------------------------
bool InitPort(LPCSTR comm)
{
    if (m_portopen)
       return m_portopen;
    bool result = false;
    hCommDevice = CreateFile(comm,
      GENERIC_WRITE|GENERIC_READ,
      0,    /* comm devices must be opened w/exclusive-access */
      NULL, /* no security attrs */
      OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
      FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, /* not overlapped I/O */
      NULL/* hTemplate must be NULL for comm devices */
      );    /* handle error */
    if(hCommDevice == INVALID_HANDLE_VALUE)
      {
         ProcessErrorMessage("INVALID_HANDLE_VALUE\r\n");
         printf(" open failed\r\n");
         result = false;
      }
      else
      {
          printf(" open success\r\n");
          OpenCloseFlag = 1;
         //Get the config of the modem connection
         GetCommState(hCommDevice, &dcb);
         //Set to 8 bits, no parity, 1 stopbit
         dcb.BaudRate = 115200;
         dcb.ByteSize = 8;
         dcb.Parity   = 0;//EVENPARITYNOPARITY;
         dcb.StopBits = ONESTOPBIT;
         dcb.fDtrControl = DTR_CONTROL_ENABLE;//DTR_CONTROL_DISABLE;//1;
         dcb.fRtsControl = RTS_CONTROL_ENABLE;//RTS_CONTROL_DISABLE;//1;
         dcb.fBinary = 1;
         dcb.fParity = FALSE;
         dcb.fOutxCtsFlow = FALSE;
         //Actually set the config
         SetCommState(hCommDevice, &dcb);

         if (!SetupComm(hCommDevice, 256, 256))
         {
             CloseHandle(hCommDevice);
             result = false;
         }
         else
         {
         //Get timeout information for the communications channel
         GetCommTimeouts(hCommDevice, &ct);
         ct.ReadIntervalTimeout=100;
         ct.ReadTotalTimeoutMultiplier=0;
         ct.ReadTotalTimeoutConstant=100;
         ct.WriteTotalTimeoutMultiplier=50;
         ct.WriteTotalTimeoutConstant=100;
         SetCommTimeouts(hCommDevice, &ct);
         COMSTAT com;
         DWORD Errors;
         ClearCommError(hCommDevice,&Errors,&com);
         if (com.cbInQue>0)
               PurgeComm(hCommDevice,PURGE_RXCLEAR|PURGE_TXCLEAR);
         SetCommMask(hCommDevice,EV_RXCHAR);
         result = true;
         m_portopen = true;
         }
      }
      return result;
}

//---------------------------------------------------------------------------
bool WritePort(PCVOID lpszSendBuffer,DWORD dwLength)
{
   BOOL      fWriteStat = 0;
   DWORD       dwBytesWritten = 0;
   DWORD       dwErrorFlags= 0;
   DWORD       dwBytesSent=0;
   COMSTAT   ComStat;
//   HANDLEm_hWriteEvent;
//   ResetEvent(m_hWriteEvent);

   ClearCommError( hCommDevice, &dwErrorFlags, &ComStat ) ;
   PurgeComm(hCommDevice,PURGE_RXCLEAR|PURGE_TXCLEAR);
   m_ovwrite.Offset=0;
   fWriteStat = WriteFile(hCommDevice, lpszSendBuffer,dwLength,&dwBytesWritten, &m_ovwrite) ;
   if (!fWriteStat)
      {
         if(GetLastError() == ERROR_IO_PENDING)
         {
            if (!GetOverlappedResult(hCommDevice,&m_ovwrite, &dwBytesWritten, true))
            {
               ClearCommError( hCommDevice, &dwErrorFlags, &ComStat ) ;
               return FALSE;
            }
            dwBytesSent += dwBytesWritten;
            if( dwBytesSent != dwLength)
            return FALSE;
            else
            return TRUE;
         }//Io pending Error
         else
         {
            ClearCommError( hCommDevice, &dwErrorFlags, &ComStat ) ;
            PurgeComm(hCommDevice,PURGE_RXCLEAR|PURGE_TXCLEAR);
            returnFALSE;
         }
      }
      return TRUE;
}


char Rxbuff;



DWORD WINAPIThread_Tx(LPVOID nParam)
{
   unsigned char buff;//= "hello world\r\n";
   char input,tmp;
   int i=0;
    printf("%s","/***********************************************\r\n");
    printf("%s","Please press '1' to Test CMD 0x01----Set Fed Prama\r\n");

   while(hCommDevice != INVALID_HANDLE_VALUE)
   {
   memset(buff,0x00,sizeof(buff));
   memset(buff,0x00,sizeof(input));
   i = 0;

      printf("\r\n ");
      while(1){
          scanf("%c",&tmp);
          if(tmp!='\n'&&tmp!=' '){
             input=tmp;
             if(i<1) i++;
          }
          else
          break;
      }
   switch(input)
   {
         case '1':
            buff=0x01;
            buff=0x02;
            buff=0x03;
            buff=0x04;

            buff=0X05;
            buff=0X06;
            buff=0X07;
            buff=0X08;
            buff=0X09;
            buff=0X0a;
            buff=0X0b;
            buff=0X0c;
            buff=0X0d;
            buff=0X0e;

            WritePort(buff,14);
            break;
            default : printf("0x0c cmd :Error cmd \r\n ");break;

   }
            printf("%02X cmd :\r\n ",buff);
            for(i=0;i<buff+4;i++)
            printf("0x%02X ",buff);
            printf("\r\n ");


            Sleep(100);
   }
   return 0;
}


void Deal_buff(unsigned char *buff,DWORD cnt)
{
    unsigned char *p =buff;
    while(cnt)
    {
      cnt--;
      printf("0x%02X",*p++);//      printf("%c",*p);
      printf(" ");
    }
      printf("\r\n");
}

DWORD WINAPIThread_Rx(LPVOID nParam)
{
    BOOL bRead =TRUE;
    BOOL bResult =TRUE;
    DWORD dwError =0;
    DWORD BytesRead ;
    COMSTAT ComStat ;
    unsigned char Rxbuff;

    for(;;)
    {

      ClearCommError( hCommDevice, &dwError, &ComStat);
      if(ComStat.cbInQue==0){
            continue;
      }

      if (bRead){
            bResult = ReadFile(hCommDevice, // Handle to COMM port
            &Rxbuff,// RX Buffer Pointer
            RX_SIZE,//RX_SIZE// Read one byte
            &BytesRead,//
            &m_ovread);


//            printf("0x%02X",Rxbuff);
//            printf(" ");

            if(!bResult){//读不成功
                switch (dwError = GetLastError())
                {
                  case ERROR_IO_PENDING:
                        bRead = FALSE;
                        break;
                  default: break;
                }

                } if(bResult){//读成功
                bRead = TRUE;
            }



      }if (!bRead) {
            bRead = TRUE;
            bResult = GetOverlappedResult(hCommDevice,   // Handle to COMM port
            &m_ovread,       // Overlapped structure
            &BytesRead,   // Stores number of bytes read
            TRUE);         // Wait flag

            if(BytesRead)//bResult
            {
                printf("Recived= %ld Bytes   ",BytesRead);
                Deal_buff(Rxbuff,BytesRead);
                memset(Rxbuff,0x00,sizeof(Rxbuff));

            }
      }
   }


}

int main ()
{
   InitPort("com5");
   CreateThread(NULL ,0,Thread_Tx,0,0,NULL);
   CreateThread(NULL ,0,Thread_Rx,0,0,NULL);//Thread_Rx
   while(1);
   return 0;
}

myxiaonia 发表于 2015-10-25 11:37:03

win32写的程序性能非常好,而且都非常短小,就是界面比较古老

radar_12345 发表于 2015-10-25 18:43:58

myxiaonia 发表于 2015-10-25 11:37
win32写的程序性能非常好,而且都非常短小,就是界面比较古老

win32写核心代码,封装成dll,MFC,C#,VB写界面,妥妥的

yxylxj 发表于 2015-10-25 20:40:41

myxiaonia 发表于 2015-10-25 11:37
win32写的程序性能非常好,而且都非常短小,就是界面比较古老

有空帮忙看下 ,上面的有没有问题
页: [1]
查看完整版本: 求如何用C WIN32 API 写一个串口通信