Arduino UNO와 Serial 통신하기.
여러가지 방법이 있지만, 가장 간단한 방법은 라즈베리파이의 USB 포트에 연결된 Arduino UNO와 직접 통신하는 방법이 가장 간단하다.
Arduino UNO에 올라갈 스케치는 아래와 같다.
먼저 Arduino IDE를 실행하여 스케치를 Arduino UNO에 올린다.

라즈베리 파이에 올라갈 Code는 아래와 같다.
Pi_Serial_Test.cpp 파일로 저장하고, Build한다.

생성된 Binary를 실행한다.
실행에 앞서 열려있는 Arduino IDE는 모두 닫아야 한다.(ttyUSB0를 open하고 있을 수 있다.)

sudo를 사용해서 실행해야만 ttyUSB0에 접근할 수 있는 것 같다.
(Code 내에서 root 권한을 갖는 방법도 있었던것 같은데, 기억나지 않는다.)
Arduino UNO에 올라갈 스케치는 아래와 같다.
void setup() { Serial.begin(9600); } void loop() { Serial.println("Hello World!"); delay(10000); }1초 간격으로 "Hello World!"를 출력한다.
먼저 Arduino IDE를 실행하여 스케치를 Arduino UNO에 올린다.

라즈베리 파이에 올라갈 Code는 아래와 같다.
/*
Pi_Serial_test.cpp - SerialProtocol library - demo
Copyright (c) 2014 NicoHood. All right reserved.
Program to test serial communication
Compile with:
sudo gcc -o Pi_Serial_Test.o Pi_Serial_Test.cpp -lwiringPi -DRaspberryPi -pedantic -Wall
sudo ./Pi_Serial_Test.o
*/
// just that the Arduino IDE doesnt compile these files.
#ifdef RaspberryPi
//include system librarys
#include <stdio.h> //for printf
#include <stdint.h> //uint8_t definitions
#include <stdlib.h> //for exit(int);
#include <string.h> //for errno
#include <errno.h> //error output
//wiring Pi
#include <wiringPi.h>
#include <wiringSerial.h>
// Find Serial device on Raspberry with ~ls /dev/tty*
// ARDUINO_UNO "/dev/ttyACM0"
// FTDI_PROGRAMMER "/dev/ttyUSB0"
// HARDWARE_UART "/dev/ttyAMA0"
char device[]= "/dev/ttyACM0";
// filedescriptor
int fd;
unsigned long baud = 9600;
unsigned long time=0;
//prototypes
int main(void);
void loop(void);
void setup(void);
void setup(){
printf("%s \n", "Raspberry Startup!");
fflush(stdout);
//get filedescriptor
if ((fd = serialOpen (device, baud)) < 0){
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
exit(1); //error
}
//setup GPIO in wiringPi mode
if (wiringPiSetup () == -1){
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
exit(1); //error
}
}
void loop(){
// Pong every 3 seconds
if(millis()-time>=3000){
serialPuts (fd, "Pong!\n");
// you can also write data from 0-255
// 65 is in ASCII 'A'
serialPutchar (fd, 65);
time=millis();
}
// read signal
if(serialDataAvail (fd)){
char newChar = serialGetchar (fd);
printf("%c", newChar);
fflush(stdout);
}
}
// main function for normal c++ programs on Raspberry
int main(){
setup();
while(1) loop();
return 0;
}
#endif //#ifdef RaspberryPi
Pi_Serial_Test.cpp 파일로 저장하고, Build한다.
$ sudo gcc Pi_Serial_Test.cpp -o Pi_Serial_Test -l wiringPi -DRaspberryPi

생성된 Binary를 실행한다.
실행에 앞서 열려있는 Arduino IDE는 모두 닫아야 한다.(ttyUSB0를 open하고 있을 수 있다.)

sudo를 사용해서 실행해야만 ttyUSB0에 접근할 수 있는 것 같다.
(Code 내에서 root 권한을 갖는 방법도 있었던것 같은데, 기억나지 않는다.)
댓글
댓글 쓰기