Posted By

liouys on 03/20/11


Tagged

windows serial-port


Versions (?)

windows下串口通信同步与异步方式


 / Published in: C
 

  1. #include <iostream>
  2. #include <windows.h>
  3. #include <assert.h>
  4.  
  5. using namespace std;
  6.  
  7. HANDLE g_hCom = INVALID_HANDLE_VALUE;
  8. const unsigned MAX_BUF_LEN = 32;
  9. const char* const g_pData = "hello";
  10.  
  11.  
  12. DWORD WINAPI ThreadRead( LPVOID lpParameter )
  13. {
  14. char szBuf[ MAX_BUF_LEN ] = { 0 };
  15. DWORD dwRead;
  16. if( !ReadFile( g_hCom, szBuf, strlen( g_pData ), &dwRead, NULL ) )
  17. {
  18. cout << "Read com failed." << endl;
  19. return 0;
  20. }
  21. if( dwRead != strlen( g_pData ) )
  22. {
  23. cout << "Failed to get all the data." << endl;
  24. return 0;
  25. }
  26. cout << "Read: " << szBuf << endl;
  27. return 1;
  28. }
  29.  
  30.  
  31. int main()
  32. {
  33. g_hCom = CreateFile( "com1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
  34. assert( g_hCom != INVALID_HANDLE_VALUE );
  35.  
  36. HANDLE hThread = CreateThread( NULL, 0, ThreadRead, NULL, 0, NULL );
  37. assert( hThread );
  38.  
  39. Sleep( 100 );
  40.  
  41. DWORD dwWritten;
  42. if( !WriteFile( g_hCom, g_pData, strlen( g_pData ), &dwWritten, NULL ) )
  43. {
  44. cout << "Write com failed." << endl;
  45. return 0;
  46. }
  47. if( dwWritten != strlen( g_pData ) )
  48. {
  49. cout << "Failed to write all the data." << endl;
  50. return 0;
  51. }
  52. cout << "Write: " << g_pData << endl;
  53. return 1;
  54. }

Report this snippet  

You need to login to post a comment.