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


/ Published in: C
Save to your folder(s)



Copy this code and paste it in your HTML
  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. OVERLAPPED ov;
  17. memset( &ov, 0, sizeof( ov ) );
  18. ov.hEvent = CreateEvent( NULL, TRUE, TRUE, NULL );
  19. assert( ov.hEvent );
  20.  
  21. if( !ReadFile( g_hCom, szBuf, strlen( g_pData ), &dwRead, &ov ) )
  22. {
  23. if( GetLastError() != ERROR_IO_PENDING )
  24. {
  25. cout << "Read com failed." << endl;
  26. return 0;
  27. }
  28. WaitForSingleObject( ov.hEvent, INFINITE );
  29. GetOverlappedResult( g_hCom, &ov, &dwRead, TRUE );
  30. }
  31. if( dwRead != strlen( g_pData ) )
  32. {
  33. cout << "Failed to get all the data." << endl;
  34. return 0;
  35. }
  36. cout << "Read: " << szBuf << endl;
  37. return 1;
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. g_hCom = CreateFile( "com1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL );
  44. assert( g_hCom != INVALID_HANDLE_VALUE );
  45.  
  46. HANDLE hThread = CreateThread( NULL, 0, ThreadRead, NULL, 0, NULL );
  47. assert( hThread );
  48.  
  49. Sleep( 100 );
  50.  
  51. DWORD dwWritten;
  52. OVERLAPPED ov;
  53. memset( &ov, 0, sizeof( ov ) );
  54. ov.hEvent = CreateEvent( NULL, TRUE, TRUE, NULL );
  55. assert( ov.hEvent );
  56.  
  57. if( !WriteFile( g_hCom, g_pData, strlen( g_pData ), &dwWritten, &ov ) )
  58. {
  59. if( GetLastError() != ERROR_IO_PENDING )
  60. {
  61. cout << "Write com failed." << endl;
  62. return 0;
  63. }
  64. WaitForSingleObject( ov.hEvent, INFINITE );
  65. GetOverlappedResult( g_hCom, &ov, &dwWritten, TRUE );
  66. }
  67. if( dwWritten != strlen( g_pData ) )
  68. {
  69. cout << "Failed to write all the data." << endl;
  70. return 0;
  71. }
  72. cout << "Write: " << g_pData << endl;
  73.  
  74. Sleep( 100 );
  75. return 1;
  76. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.