C/Serial Monitor
[C] Serial Monitor Step 3 - 데이터 읽기
미친해커
2021. 12. 27. 01:34
반응형
이제는 데이터를 읽을 차례이다. Windows에서 Baud Rate는 기본적으로 9600으로 설정되는 모양이다. 하지만 나는 직접 115200을 설정해 사용할 생각이다. 우선 다음과 같은 코드를 아두이노에 업로드했다.
void setup()
{
Serial.begin(115200);
}
void loop()
{
Serial.println("Hello World Arduino!");
delay(1000);
}
간단하게 설명하자면 begin 함수를 Baud Rate를 설정하는 함수이다. 그리고 1초에 한번씩 "Hello World Arduino!"라는 문자열을 시리얼 포트로 보낸다. 우리는 이 데이터를 Windows에서 읽어 출력하면 성공이다.
ReadFile function (fileapi.h) - Win32 apps
Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device.
docs.microsoft.com
Windows에서 Handle을 이용해 데이터를 읽는 함수는 ReadFile 함수가 있다. 우리는 이 함수를 이용해 데이터를 읽어올 것이다.
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[])
{
HANDLE hComm = CreateFileA("\\\\.\\COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hComm == INVALID_HANDLE_VALUE)
{
printf("CreateFileA Failed\n");
printf("GetLastError : %d\n", GetLastError());
return -1;
}
DCB state = { 0, };
GetCommState(hComm, &state);
state.BaudRate = 115200;
SetCommState(hComm, &state);
while (TRUE)
{
char buffer[32] = { 0, };
if (ReadFile(hComm, buffer, 32, NULL, NULL))
printf("%s", buffer);
}
CloseHandle(hComm);
}
아두이노는 반복적으로 "Hello World Arduino!" 문자열을 시리얼 포트로 전송하기 때문에 위와 같이 반복문을 만들어 계속해서 출력시킨다면 "Hello World Arduino!" 문자열이 1초에 한번씩 출력될 것이다.
반응형