16. Serial
통신
Arduino 와 PC를 연결하는 방법
Serial.begin(9600);
Serial.print(“command”);
Serial.read()
serial = new Serial();
serial.readChar();
serial.writeChar();
19. Arduino Side
int pButtonState = 0;
void setup() {
pinMode(8, INPUT);
Serial.begin(9600);
}
void loop() {
int buttonPressed = digitalRead(8);
if(pButtonState == LOW && buttonPressed == HIGH) {
Serial.print('1');
}
pButtonState = buttonPressed;
}
Serial Monitor
20. Processing Side
import processing.serial.*;
Serial serial;
void setup() {
size(320, 200);
serial = new Serial(this, Serial.list()[0], 9600);
background(0);
}
void draw() {
if(serial.available() > 0) {
int ch = serial.read();
if(ch == '1') {
int red = (int)random(255);
int green = (int)random(255);
int blue = (int)random(255);
int x = (int)random(320);
int y = (int)random(200);
int size = (int)random(30, 100);
fill(red, green, blue, 180);
ellipse(x, y, size, size);
}
}
}
21. sample Arduino Side
void setup() {
Serial.begin(9600);
}
void loop() {
int value = analogRead(A1);
Serial.println(value);
delay(100);
}
22. sample Processing Side
void draw() {
background(200, 200, 200); //R, G, B
noStroke();
fill(255, 0, 0); //R, G, B
rect(r_x, 400, 100, 30); //X, Y, W, H
stroke(0, 0, 0);
fill(0, 255, 0);
ellipse(e_x, e_y, 20, 20); // X, Y, RX, RY
if(serial.available() > 0) {
String val = serial.readStringUntil(lf);
if(val != null) {
val = val.trim();
if(val.length() > 0) {
int val2 = Integer.parseInt(val.trim());
r_x = val2 * (640-100) / 1024;
}
}
}
e_x += e_add_x;
e_y += e_add_y;
if(e_x < 10 || e_x > 640-10) e_add_x = -e_add_x;
if(e_y < 10 || e_y > 480-10) e_add_y = -e_add_y;
if(e_x > r_x && e_x < r_x+100 && e_y > 400 && e_y < 400+30)
e_add_y = -e_add_y;
}
import processing.serial.*;
int lf = 10;
Serial serial;
int r_x = 0;
int e_x = 20, e_y = 20;
int e_add_x = 3, e_add_y = 3;
void setup() {
size(640, 480);
serial = new Serial(this, Serial.list()[0], 9600);
}
23. sample Arduino Side
int pinTrig = 7;
int pinEcho = 6;
void setup() {
Serial.begin(9600);
pinMode(pinTrig, OUTPUT);
pinMode(pinEcho, INPUT);
}
void loop() {
int value = distance();
Serial.println(value);
delay(300);
}
long distance() {
digitalWrite(pinTrig, LOW);
delayMicroseconds(2);
digitalWrite(pinTrig, HIGH);
delayMicroseconds(10);
digitalWrite(pinTrig, LOW);
long val= pulseIn(pinEcho, HIGH) * 17 / 100;
return val;
}
Processing
2001년부터 당시 MIT 미디어 랩에서 개발
비개발자들을 위한 프로그래밍 교육용
쉽고 간결한 문법
JVM 위에서 동작
시각적이고 인터렉션 작업에 특화
Processing IDE
간결하고 쉬운 사용법
Setup() , draw() 로 구성된 구조
Arduino IDE 개발에 영향을 미침
Java 문법을 차용하고 있음
Processing 설치
공식 사이트 : https://processing.org
왼쪽 메뉴에서 Download 선택
플랫폼에 맞는 인스톨러 선택
프로그램 구조
setup()첫 실행 시 한 번 호출 됨
draw()매 프레임마다 호출됨
print()콘솔 로그 출력
println()콘솔 로그 출력(new line)
Size
실행창의 크기를 지정
fullScreen
전체화면으로 실행
size와 함께 호출하면 안됨
background
배경색상을 지정(화면이 지워짐)
fill
내부 칠하는 색상을 지정
rect
사각형을 그림
변수 값 사용
rect(x, 100, 200, 200); // 변수값을 사용해서 위치 지정
draw()
매 프레임마다 호출됨
x += add; // 프레임마다 변수값이 계산
상자가 창의 양 끝에 닿을 때 방향 전환 : add = -add;
eclipse(x, y, rx, ry)
원 그리기, 중심(x,y), 가로크기(rx), 세로크기(ry)
공그리기
위치 이동 : e_x, e_y
이동 방향 : e_add_x, e_add_y
바 그리기
위치 이동 : r_x
이동 방향 : add
Class 를 사용한 방법
class Snow {
int x, y, speed, size;
Snow() {
x = (int)random(0, 320);
y = 0;
speed = (int)random(1, 4);
size = (int)random(1, 5);
}
}
Snow[] snow = new Snow[200];
void setup() {
size(320, 200);
for(int i=0; i<snow.length; i++) {
snow[i] = new Snow();
snow[i].y = (int)random(0, 200);
}
}
void draw() {
background(0);
for(int i=0; i<snow.length; i++) {
Snow s = snow[i];
ellipse(s.x, s.y, s.size, s.speed);
s.y += s.speed;
if(s.y >= 200) {
snow[i] = new Snow();
}
}
}
Reference
https://processing.org/reference/
마우스 이벤트를 처리하는 방법
mousePressed 값 확인
mousePressed() 함수 콜백
mouseButton 값 확인 (버튼 상태)
API Referencehttp://processing.github.io/processing-javadocs/core/
마우스 이벤트 패키지processing.event.MouseEvent
마우스 이벤트 종류mousePressed()mouseReleased()mouseDragged()mouseWheel()mouseMoved()
Mouse move 감지
Mouse Press 시이전 점부터 현재 점 까지 라인(LineElement) 생성
생성된 LineElement 를 배열(ArrayList) 에 추가
매 프레임 마다(1) 화면 지우기 : background(0)(2) 라인 히스토리 그리기 : for(LineElement l : lines)
키보드 이벤트 처리하는 방법
keyPressed 값 사용
keyPressed() 함수 콜백
keyCode 값 사용
키보드 이벤트 종류
keyPressed()
keyReleased()
keyTypes()
공그리기
위치 이동 : e_x, e_y
이동 방향 : e_add_x, e_add_y
바 그리기
위치 이동 : r_x
이동 방향 : 키이벤트에 의해서 처리
Aruino 는 Serial 통신을 수행
Serial 을 통해서 Arduino 와 통신함
Serial 통신이 가능한 모든 언어에서 사용 가능C/C++JavaPythonJavascript (Node.js)…
Processing 에서는 쉽게 Serial 통신을 수행할 수 있는 기능 제공
아두이노 제어하기 예제
Arduino 측 Serial 통신
Serial 연결
Serial.println : 시리얼 출력
Serial.read : 시리얼 입력
Serial.available : 입력이 있는지 확인
시리얼 모니터 창에서 “전송” 시 Serial 로 전달 됨
시리얼을 통해 ‘1’ 입력 시 LED 켜기, 그 외 LED 끄기
아두이노 제어하기 예제
Processing 측 Serial 통신
Serial 클래스 사용
Serial.list() 로 시리얼 포트에 연결된 목록 확인
Serial 목록 중에서 Arduino 가 연결된 항목을 선택해서 연결
Serial.write 로 시리얼로 데이터 전달
아두이노로 제어하기 예제
Arduino 측 Serial 통신
Serial 연결
Serial.println : 시리얼 출력
시리얼 모니터 창에서 전송되는 내용 확인 가능
버튼이 눌리면 시리얼을 통해 ‘1’ 전달
아두이노로 제어하기 예제
Processing 측 Serial 통신
Serial.read : 시리얼로 데이터 읽기
Serial.available : 시리얼 데이터가 있는지 확인
‘1’이 전달되면 (아두이노에서 버튼이 눌리면) 랜덤하게 원 출력
아두이노와 PC 연동 예제 (아두이노 측)
가변저항을 아두이노에 연결
analogRead 로 저항값 읽기(0 ~ 1023 사이의 값)
저항값을 시리얼로 전달함
아두이노와 PC 연동 예제 (PC 측)
Serial.read 로 전달 값 읽기
Serial 값으로 Bar 의 위치를 지정
아두이노와 PC 연동 예제 (아두이노 측)
초음파 센서를 아두이노에 연결
초음파 센서로 물체 거리 연산
거리값을 시리얼을 통해 PC 로 전달
아두이노와 PC 연동 예제 (PC 측)
Pimage 클래스를 통해 이미지 읽기image.jpg 파일은 프로세싱 소스 파일과 같은 경로에 있어야 함
Image 함수로 이미지 그리기image(이미지 객체, x좌표, y좌표, 이미지 가로 크기, 이미지 세로 크기)
시리얼을 통해서 얻은 거리값으로 그려낼 이미지 크기 계산 (zoom)min(A, B) : A, B 값 중 작은 값을 반환함max(A, B) : A, B 값 중 큰 값을 반환함max( min( ZOOM , 1.0 ) , 0.1 ) : ZOOM 값이 최소 0.1 ~ 최대 1.0 값으로 필터링 함
아두이노와 PC 연결 활용 사례
가속도센서로 핸들 신호 감지
빛 센서로 발바닥 움직임 감지
센서 정보를 PC 로 전달
PC 에서 신호에 따라 정해진 효과음 재생
Processing 에서 소리 재생
import processing.sound.*;
SoundFile file;
file = new SoundFile(this, "sample.mp3");
file.play();