Ce diaporama a bien été signalé.
Le téléchargement de votre SlideShare est en cours. ×

[3] 프로세싱과 아두이노

Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Prochain SlideShare
Know more processing
Know more processing
Chargement dans…3
×

Consultez-les par la suite

1 sur 25 Publicité

[3] 프로세싱과 아두이노

Télécharger pour lire hors ligne

프로세싱으로 아두이노와 PC를 연결합니다.
http://www.makecube.in/p/blog-page_12.html

프로세싱으로 아두이노와 PC를 연결합니다.
http://www.makecube.in/p/blog-page_12.html

Publicité
Publicité

Plus De Contenu Connexe

Publicité

Similaire à [3] 프로세싱과 아두이노 (20)

Plus par Chiwon Song (20)

Publicité

Plus récents (20)

[3] 프로세싱과 아두이노

  1. 1. Processing과 Arduino 송치원
  2. 2. https://processing.org/ Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts.
  3. 3. Console Hello World
  4. 4. Drawing 실행결과
  5. 5. Draw Frames 실행결과
  6. 6. Draw Frames void setup() { size(640, 480); //W, H } int r_x = 0; int add = 5; int e_x = 20, e_y = 20; int e_add_x = 3, e_add_y = 3; 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 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; r_x += add; if(r_x < 0 || r_x > 640-100) add = -add; } 실행결과
  7. 7. sample int count = 200; int snowx[]= new int[count]; int snowy[]= new int[count]; int speed[]= new int[count]; int size[]= new int[count]; void setup() { size(320, 200); for(int i=0; i<count; i++) { snowx[i] = (int)random(0, 320); snowy[i] = (int)random(0, 200); speed[i] = (int)random(1, 4); size[i] = (int)random(1, 5); } } void draw() { background(0); for(int i=0; i<count; i++) { ellipse(snowx[i], snowy[i], size[i], size[i]); snowy[i]+=speed[i]; if(snowy[i] >= 200) { snowy[i] = 0; snowx[i] = (int)random(0, 320); speed[i] = (int)random(1, 4); size[i] = (int)random(1, 5); } } } 실행결과
  8. 8. Drawing Functions
  9. 9. Mouse Event void setup() { } void draw() { if(mousePressed) { println("mouse pressed"); } } void setup() { } void draw() { } void mousePressed() { println("mouse pressed"); } void setup() { } void draw() { } void mousePressed() { if(mouseButton == LEFT) { println("Left mouse button pressed"); } else if(mouseButton == CENTER) { println("Center mouse button pressed"); } else if(mouseButton == RIGHT) { println("Right mouse button pressed"); } } Mouse Button Pressed Pressed Mouse Button
  10. 10. Mouse Event void setup() { } void draw() { } void mousePressed() { if(mouseButton == LEFT) { println("Left mouse button pressed"); } else if(mouseButton == CENTER) { println("Center mouse button pressed"); } else if(mouseButton == RIGHT) { println("Right mouse button pressed"); } } void mouseReleased() { if(mouseButton == LEFT) { println("Left mouse button released"); } } void mouseClicked() { if(mouseButton == LEFT) { println("Left mouse button clicked"); } } void mouseDragged() { println("Drag MouseX:"+mouseX+" , MouseY:"+mouseY); } void mouseWheel(processing.event.MouseEvent event) { int e = event.getCount(); println("Wheel:"+e); } void mouseMoved() { println("Move MouseX:"+mouseX+" , MouseY:"+mouseY); }
  11. 11. sample class LineElement { int x, y, x2, y2; } ArrayList<LineElement> lines = new ArrayList<LineElement>(); int p_x = -1, p_y = -1; void setup() { size(320, 200); stroke(255); strokeWeight(2); } void draw() { background(0); stroke(255); for(LineElement l : lines) { line(l.x, l.y, l.x2, l.y2); } stroke(0, 0, 255); if(p_x >= 0 && p_y >= 0) { line(p_x, p_y, mouseX, mouseY); } } void mousePressed() { if(p_x >= 0 && p_y >= 0) { LineElement l = new LineElement(); l.x = p_x; l.y = p_y; l.x2 = mouseX; l.y2 = mouseY; lines.add(l); } p_x = mouseX; p_y = mouseY; }
  12. 12. Keyboard Event void setup() { } void draw() { if (keyPressed) { if (key == 'b' || key == 'B') { background(0); } else { background(255); } } } int value = 0; void draw() { background(value); } void keyPressed() { if (key == 'b' || key == 'B') { value = 0; } else { value = 255; } } void draw() { } void keyPressed() { println("pressed " + key + "(" + keyCode + ")"); } void keyReleased() { println("released " + key + "(" + keyCode + ")"); } void keyTyped() { println("typed " + key + "(" + keyCode + ")"); } Key Pressed Pressed Mouse Button pressed a(65) typed a(0) released a(65)
  13. 13. sample void setup() { size(640, 480); //W, H } int r_x = 0; int e_x = 20, e_y = 20; int e_add_x = 3, e_add_y = 3; 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 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; } void keyPressed() { if(keyCode == LEFT) { r_x -= 10; if(r_x < 0) r_x = 0; } else if(keyCode == RIGHT) { r_x += 10; if(r_x > 640-100) r_x = 640-100; } }
  14. 14. Serial 통신 Arduino 와 PC를 연결하는 방법 Serial.begin(9600); Serial.print(“command”); Serial.read() serial = new Serial(); serial.readChar(); serial.writeChar();
  15. 15. Arduino Side void setup() { pinMode(8, OUTPUT); Serial.begin(9600); } void loop() { if (Serial.available() > 0) { char ch = Serial.read(); if(ch == '1') digitalWrite(8, HIGH); else digitalWrite(8, LOW); } } Serial Monitor
  16. 16. Processing Side import processing.serial.*; Serial serial; int pMouseX = 0; void setup() { size(320, 200); serial = new Serial(this, Serial.list()[0], 9600); } void draw() { fill(0); rect(0, 0, 160, 200); fill(255); rect(160, 0, 160, 200); if(pMouseX < 160 && mouseX >= 160) { serial.write('1'); } else if(pMouseX >= 160 && mouseX < 160) { serial.write('0'); } pMouseX = mouseX; }
  17. 17. 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
  18. 18. 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); } } }
  19. 19. sample Arduino Side void setup() { Serial.begin(9600); } void loop() { int value = analogRead(A1); Serial.println(value); delay(100); }
  20. 20. 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); }
  21. 21. 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; }
  22. 22. sample Processing Side import processing.serial.*; int lf = 10; float zoom = 0.1; Serial serial; PImage img; void setup() { size(800, 600); img = loadImage("image.jpg"); serial = new Serial(this, Serial.list()[1], 9600); } void draw() { background(0); if(serial.available() > 0) { String val = serial.readStringUntil(lf); if(val != null) { val = val.trim(); if(val.length() > 0) { float val2 = Float.parseFloat(val.trim()); zoom = max(min(val2 / 100, 1.0), 0.1); } } } float imageWidth = img.width * zoom; float imageHeight = img.height * zoom; image(img, (800 - imageWidth)/2, (600 - imageHeight)/2, imageWidth, imageHeight); } image.jpg
  23. 23. https://youtu.be/jjvy_jzGlAQ 아두이노 + 가속도센서 + 빛센서

Notes de l'éditeur

  • 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 Reference http://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++ Java Python Javascript (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();

×