Advertisement
Guest User

Untitled

a guest
Mar 27th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <windows.h>
  3.  
  4. void main ()
  5. {
  6. // CreateFile
  7. HANDLE rs232 = CreateFileA ("\\.\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  8. if (rs232 == INVALID_HANDLE_VALUE)
  9. {
  10. printf ("fail CreateFile: %dn", GetLastError ()); system ("pause"); return;
  11. }
  12.  
  13. // Get & Set CommState
  14. DCB port_configuration;
  15. int err = GetCommState (rs232, &port_configuration);
  16. if (err <= 0)
  17. {
  18. printf ("fail GetCommState: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
  19. }
  20. port_configuration.BaudRate = 19200;
  21. port_configuration.ByteSize = 8;
  22. port_configuration.Parity = 0;
  23. port_configuration.StopBits = 0;
  24. port_configuration.DCBlength = sizeof (port_configuration);
  25. err = SetCommState (rs232, &port_configuration);
  26. if (err <= 0)
  27. {
  28. printf ("fail SetCommStaten"); CloseHandle (rs232); system ("pause"); return;
  29. }
  30.  
  31. // SetCommTimeouts
  32. COMMTIMEOUTS timeout_configuration;
  33. timeout_configuration.ReadIntervalTimeout = 1;// MAXDWORD;
  34. timeout_configuration.ReadTotalTimeoutMultiplier = 1;// 0;
  35. timeout_configuration.ReadTotalTimeoutConstant = 1;// 0;
  36. timeout_configuration.WriteTotalTimeoutMultiplier = 1;// 0;
  37. timeout_configuration.WriteTotalTimeoutConstant = 1;// 0;
  38. err = SetCommTimeouts (rs232, &timeout_configuration);
  39. if (err <= 0)
  40. {
  41. printf ("fail SetCommTimeouts: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
  42. }
  43.  
  44. // WriteFile
  45. DWORD buffer_size_w;
  46. char buffer_w[128] = "*IDN?n";
  47. err = WriteFile (rs232, buffer_w, strlen (buffer_w), &buffer_size_w, 0);
  48. if (err <= 0)
  49. {
  50. printf ("fail WriteFile: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
  51. }
  52. printf ("written %d characters: %sn", buffer_size_w, buffer_w);
  53.  
  54. // ReadFile
  55. for (int x = 0; x < 10; ++x)
  56. {
  57. DWORD buffer_size_r;
  58. char buffer_r[128] = {0};
  59. err = ReadFile (rs232, buffer_r, 128, &buffer_size_r, 0);
  60. if (err <= 0)
  61. {
  62. printf ("fail ReadFile: %dn", GetLastError ()); Sleep (250); continue;
  63. }
  64. printf ("read %d characters: %sn", buffer_size_r, buffer_r);
  65. Sleep (250);
  66. }
  67.  
  68. CloseHandle (rs232);
  69. system ("pause");
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement