아두이노와 프로세싱 IDE 간 상호작용을 위한 코드를 만들어 아두이노 보드에 업로드해야 합니다. 연결 작동 원리 이해를 위해 여기를 클릭해 아두이노와 프로세싱 튜토리얼을 방문하세요.
아두이노 소스 코드(각 줄 설명 포함):
// 서보 라이브러리 포함
#include <Servo.h>.
// 초음파 센서 Trig, Echo 핀 정의
const int trigPin = 10;
const int echoPin = 11;
// 지속 시간과 거리 변수
long duration;
int distance;
Servo myServo; // 서보 모터 제어용 서보 객체 생성
void setup() {
pinMode(trigPin, OUTPUT); // trigPin을 출력으로 설정
pinMode(echoPin, INPUT); // echoPin을 입력으로 설정
Serial.begin(9600);
myServo.attach(12); // 서보 모터가 연결된 핀 정의
}
void loop() {
// 서보 모터를 15도에서 165도까지 회전
for(int i=15; i<=165; i++) {
myServo.write(i);
delay(30);
distance = calculateDistance(); // 초음파 센서로 측정된 거리 계산 함수 호출
Serial.print(i); // 현재 각도 시리얼 포트 전송
Serial.print(","); // 프로세싱 IDE에서 인덱싱용 추가 문자 전송
Serial.print(distance); // 거리 값 시리얼 포트 전송
Serial.print("."); // 프로세싱 IDE에서 인덱싱용 추가 문자 전송
}
// 165도에서 15도까지 반복
for(int i=165; i>15; i--) {
myServo.write(i);
delay(30);
distance = calculateDistance();
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
}
}
// 초음파 센서로 측정된 거리 계산 함수
int calculateDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// trigPin을 10마이크로초 동안 HIGH 상태
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // echoPin 읽기, 음파 왕복 시간(마이크로초) 반환
distance = duration * 0.034 / 2;
return distance;
}
이제 SerialEvent() 함수를 사용해 아두이노 보드에서 각도와 거리 측값을 프로세싱 IDE로 수신하고, 각도와 거리 값을 iAngle, iDistance 변수에 저장합니다. 이 변수들은 레이더, 선, 감지된 객체, 텍스트 그리기에 사용됩니다.
레이더 그리기를 위해 drawRadar() 함수를 만들었습니다. arc()와 line() 함수로 구성됩니다.
void drawRadar() {
pushMatrix();
translate(960,1000); // 시작 좌표를 새 위치로 이동
noFill();
strokeWeight(2);
stroke(98,245,31);
// 호 선 그리기
arc(0,0,1800,1800,PI,TWO_PI);
arc(0,0,1400,1400,PI,TWO_PI);
arc(0,0,1000,1000,PI,TWO_PI);
arc(0,0,600,600,PI,TWO_PI);
// 각도 선 그리기
line(-960,0,960,0);
line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
line(-960*cos(radians(30)),0,960,0);
popMatrix();
}
레이더를 따라 움직이는 선 그리기를 위해 drawLine() 함수를 만들었습니다. 중심 회전은 translate() 함수로 설정하고, iAngle 변수를 사용하는 line() 함수로 각도마다 선을 다시 그립니다.
void drawLine() {
pushMatrix();
strokeWeight(9);
stroke(30,250,60);
translate(960,1000); // 시작 좌표를 새 위치로 이동
line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // 각도에 따라 선 그리기
popMatrix();
}
감지된 객체 그리기를 위해 drawObject() 함수를 만들었습니다. 초음파 센서에서 거리를 가져와 픽셀로 변환하고 센서 각도와 결합해 레이더에 객체를 그립니다.
void drawObject() {
pushMatrix();
translate(960,1000); // 시작 좌표를 새 위치로 이동
strokeWeight(9);
stroke(255,10,10); // 빨간색
pixsDistance = iDistance * 22.5; // 센서 거리 cm를 픽셀로 변환
// 범위 40cm로 제한
if(iDistance < 40) {
// 각도와 거리에 따라 객체 그리기
line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
}
popMatrix();
}
화면 텍스트를 위해 drawText() 함수를 만들었습니다. 특정 위치에 텍스트를 그립니다.
이 모든 함수는 메인 draw() 함수에서 호출되며, 화면을 계속 다시 그립니다. fill() 함수를 2개 매개변수로 사용해 움직이는 선의 모션 블러와 느린 페이드 효과를 시뮬레이션합니다.
void draw() {
fill(98,245,31);
textFont(orcFont);
// 움직이는 선의 모션 블러와 느린 페이드 시뮬레이션
noStroke();
fill(0,4);
rect(0, 0, width, 1010);
fill(98,245,31); // 녹색
// 레이더 그리기 함수 호출
drawRadar();
drawLine();
drawObject();
drawText();
}
레이더 최종 모습:
아두이노 레이더의 완전한 프로세싱 소스 코드:
import processing.serial.*; // 시리얼 통신 라이브러리 임포트
import java.awt.event.KeyEvent; // 시리얼 포트 데이터 읽기 라이브러리 임포트
import java.io.IOException;
Serial myPort; // Serial 객체 정의
// 변수 정의
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;
void setup() {
size(1920, 1080);
smooth();
myPort = new Serial(this,"COM4", 9600); // 시리얼 통신 시작
myPort.bufferUntil('.'); // '.' 문자까지 데이터 읽기. 즉 angle,distance 읽음
orcFont = loadFont("OCRAExtended-30.vlw");
}
void draw() {
fill(98,245,31);
textFont(orcFont);
// 움직이는 선의 모션 블러와 느린 페이드 시뮬레이션
noStroke();
fill(0,4);
rect(0, 0, width, 1010);
fill(98,245,31); // 녹색
// 레이더 그리기 함수 호출
drawRadar();
drawLine();
drawObject();
drawText();
}
void serialEvent(Serial myPort) {
// 시리얼 포트에서 데이터 읽기 시작
// '.' 문자까지 데이터 읽어 문자열 변수 "data"에 저장
data = myPort.readStringUntil('.');
data = data.substring(0, data.length()-1);
index1 = data.indexOf(","); // ',' 문자 찾아 "index1" 변수에 저장
angle = data.substring(0, index1); // 위치 "0"부터 index1 위치까지 데이터 읽기 = 아두이노가 시리얼 포트로 보낸 각도 값
distance = data.substring(index1+1, data.length()); // index1 위치부터 데이터 끝까지 읽기 = 거리 값
// 문자열 변수를 정수로 변환
iAngle = int(angle);
iDistance = int(distance);
}
void drawRadar() {
pushMatrix();
translate(960,1000); // 시작 좌표를 새 위치로 이동
noFill();
strokeWeight(2);
stroke(98,245,31);
// 호 선 그리기
arc(0,0,1800,1800,PI,TWO_PI);
arc(0,0,1400,1400,PI,TWO_PI);
arc(0,0,1000,1000,PI,TWO_PI);
arc(0,0,600,600,PI,TWO_PI);
// 각도 선 그리기
line(-960,0,960,0);
line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
line(-960*cos(radians(30)),0,960,0);
popMatrix();
}
void drawObject() {
pushMatrix();
translate(960,1000); // 시작 좌표를 새 위치로 이동
strokeWeight(9);
stroke(255,10,10); // 빨간색
pixsDistance = iDistance * 22.5; // 센서 거리 cm를 픽셀로 변환
// 범위 40cm로 제한
if(iDistance < 40) {
// 각도와 거리에 따라 객체 그리기
line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
}
popMatrix();
}
void drawLine() {
pushMatrix();
strokeWeight(9);
stroke(30,250,60);
translate(960,1000); // 시작 좌표를 새 위치로 이동
line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // 각도에 따라 선 그리기
popMatrix();
}
void drawText() {
// 화면에 텍스트 그리기
pushMatrix();
if(iDistance > 40) {
noObject = "Out of Range";
} else {
noObject = "In Range";
}
fill(0,0,0);
noStroke();
rect(0, 1010, width, 1080);
fill(98,245,31);
textSize(25);
text("10cm",1180,990);
text("20cm",1380,990);
text("30cm",1580,990);
text("40cm",1780,990);
textSize(40);
text("Object: " + noObject, 240, 1050);
text("Angle: " + iAngle + " °", 1050, 1050);
text("Distance: ", 1380, 1050);
if(iDistance < 40) {
text(" " + iDistance + " cm", 1400, 1050);
}
textSize(25);
fill(98,245,60);
translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
rotate(-radians(-60));
text("30°",0,0);
resetMatrix();
translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
rotate(-radians(-30));
text("60°",0,0);
resetMatrix();
translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
rotate(radians(0));
text("90°",0,0);
resetMatrix();
translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
rotate(radians(-30));
text("120°",0,0);
resetMatrix();
translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
rotate(radians(-60));
text("150°",0,0);
popMatrix();
}