1. Raspberry에 usb.c 파일을 만든다.
#include<stdio.h>
#include<fcntl.h>
#include<termios.h>
#include<unistd.h>
#include<string.h>
int main() {
int fd = -1;
int iSize = 0;
int idx = 0;
int i, j;
char buf[100];
struct termios options;
// 가상 시리얼 포트를 열고 데이터를 송수신하겠다.
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if(fd == -1) {
printf("fail open\n");
return 1;
}
memset(&options, 0, sizeof(options));
// 시리얼 통신을 위한 설정들
options.c_cflag = B9600;
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cflag &= ~(IXON | IXOFF | IXANY);
options.c_cflag &= ~OPOST;
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 1;
tcsetattr(fd, TCSANOW, &options);
for(i=0; i<5; i++) {
idx = 0;
buf[idx++] = 0x02;
buf[idx++] = '0';
buf[idx++] = '1';
buf[idx++] = 'W';
buf[idx++] = 'H';
buf[idx++] = 'O';
buf[idx++] = 0x0D;
buf[idx++] = 0x0A;
write(fd, buf, idx);
sleep(1); // 데이터를 쓰고 읽을 때 중간에 시간이 필요하다.
// 이 코드가 없이 돌리면 오류가 난다.
if(iSize = read(fd, buf, sizeof(buf))) {
for(j=0; j<iSize; j++) printf("%C", buf[j]);
printf("\n");
}
else {
printf("No response\n");
break;
}
}
close(fd);
return 0;
}
2. 실행파일을 만든다.
1) gcc: GNU C 컴파일러를 사용해서
2) usb.c: 소스 파일 usb.c를 컴파일하고
3) –o usb_test: 결과물을 usb_test라는 이름의 실행파일로 생성하라.
3. 실행하여 결과를 확인한다.
현재 디렉토리(./)에 있는 usb_test 실행파일을 실행하라.
'통신 > USB' 카테고리의 다른 글
[개념] USB 통신 (0) | 2025.04.23 |
---|