Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <windows.h>
- void main ()
- {
- // CreateFile
- HANDLE rs232 = CreateFileA ("\\.\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
- if (rs232 == INVALID_HANDLE_VALUE)
- {
- printf ("fail CreateFile: %dn", GetLastError ()); system ("pause"); return;
- }
- // Get & Set CommState
- DCB port_configuration;
- int err = GetCommState (rs232, &port_configuration);
- if (err <= 0)
- {
- printf ("fail GetCommState: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
- }
- port_configuration.BaudRate = 19200;
- port_configuration.ByteSize = 8;
- port_configuration.Parity = 0;
- port_configuration.StopBits = 0;
- port_configuration.DCBlength = sizeof (port_configuration);
- err = SetCommState (rs232, &port_configuration);
- if (err <= 0)
- {
- printf ("fail SetCommStaten"); CloseHandle (rs232); system ("pause"); return;
- }
- // SetCommTimeouts
- COMMTIMEOUTS timeout_configuration;
- timeout_configuration.ReadIntervalTimeout = 1;// MAXDWORD;
- timeout_configuration.ReadTotalTimeoutMultiplier = 1;// 0;
- timeout_configuration.ReadTotalTimeoutConstant = 1;// 0;
- timeout_configuration.WriteTotalTimeoutMultiplier = 1;// 0;
- timeout_configuration.WriteTotalTimeoutConstant = 1;// 0;
- err = SetCommTimeouts (rs232, &timeout_configuration);
- if (err <= 0)
- {
- printf ("fail SetCommTimeouts: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
- }
- // WriteFile
- DWORD buffer_size_w;
- char buffer_w[128] = "*IDN?n";
- err = WriteFile (rs232, buffer_w, strlen (buffer_w), &buffer_size_w, 0);
- if (err <= 0)
- {
- printf ("fail WriteFile: %dn", GetLastError ()); CloseHandle (rs232); system ("pause"); return;
- }
- printf ("written %d characters: %sn", buffer_size_w, buffer_w);
- // ReadFile
- for (int x = 0; x < 10; ++x)
- {
- DWORD buffer_size_r;
- char buffer_r[128] = {0};
- err = ReadFile (rs232, buffer_r, 128, &buffer_size_r, 0);
- if (err <= 0)
- {
- printf ("fail ReadFile: %dn", GetLastError ()); Sleep (250); continue;
- }
- printf ("read %d characters: %sn", buffer_size_r, buffer_r);
- Sleep (250);
- }
- CloseHandle (rs232);
- system ("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement