2012年11月15日木曜日

次回11/20 Arduino+Processing

次回11/20は最後の授業となります。
ひきつづきArduinoとProcessingを連携させた応用実験を行います。

各自利用したいセンサ、あるいは出力デバイスなど持参し、ひとつの入出力デバイスの仕組みを各自の設定において構築したいと思いますので、次回までに各自の入出力デバイスのサンプルを考えて来て下さい。
授業内では、さらに他の人との入出力デバイスとの連携やワイヤレス化など、発展させたいと思います。

必要なもの:
・各自の入出力デバイスの案
・各自の入出力デバイスに必要なセンサや出力装置
・Arduino(マイコンボード、ブレッドボード、その他部品など)
・Processing (Webカメラなど含む)

2012年11月1日木曜日

次回11/06 Webカメラ+Arduino

次回11/06は、前回に引き続きWebカメラの応用実験(Webカメラを使ってArduinoを操作する)を行いたいと思います。

必要なもの:
・各自のノートパソコン
・Processingのインストール
・Webカメラ(パソコン内蔵カメラでも可)
・Arduinoボード
・USBケーブル
・ブレッドボード
・ジャンパワイヤ(オス-オス)



以下、授業内で使用したサンプル
import processing.video.*;
import processing.serial.*;

Serial myPort;
Capture video;

int w=240;//320;
int h=180;//240;

int tolerance=20;

PFont font;
color targetColor=color(255,0,0);

boolean videoImage=true;
float x;
float y;
float fx;
float fy;

int sumX,sumY;
int pixelNum;
boolean detection=false;

void setup(){
  size(w, h);
  smooth();

  video = new Capture(this, w, h);
  font=createFont("Monaco",10);
  textFont(font);
  noStroke();
  myPort=new Serial(this,"/dev/tty.usbserial-A9005baQ",9600);
}

void draw() {
  if(video.available()){
    video.read();
    if(videoImage){
      image(video, 0, 0);
    }else{
      background(0);
    }

    detection=false;
    
    for(int i=0;i<w*h;i++){

      float difRed=abs(red(targetColor)-red(video.pixels[i]));
      float difGreen=abs(green(targetColor)-green(video.pixels[i]));
      float difBlue=abs(blue(targetColor)-blue(video.pixels[i]));
      if(difRed<tolerance && difGreen<tolerance && difBlue<tolerance){
        sumX+=(i%w);
        sumY+=(i/w);
        pixelNum++;
        detection=true;
      }
    }
    
    if(detection){
      x=sumX/pixelNum;
      y=sumY/pixelNum;
      sumX=0;
      sumY=0;
      pixelNum=0;
    }
  }
  
  fx+=(x-fx)*0.2;
  fy+=(y-fy)*0.2;
  myPort.write(int(fx));
  fill(255,0,0);
  ellipse(fx,fy,20,20);
  fill(targetColor);
  rect(0,0,10,10);
  text(tolerance,20,10);
  String s;
  if(detection){
    s="detect";
  }else{
    s="none";
  }
  text(s,40,10);
}
void mousePressed(){
  targetColor=video.pixels[mouseX+mouseY*w];
  //println(int(red(targetColor))+","+int(green(targetColor))+","+int(blue(targetColor)));
}
void keyPressed(){
  if(key=='c'){
    video.settings();
  }
  if(key=='v'){
    if(videoImage){
      videoImage=false;
    }else{
      videoImage=true;
    }
  }
  if(key==CODED){
    if(keyCode==LEFT){
      tolerance-=1;
    }
    if(keyCode==RIGHT){
      tolerance+=1;
    }
  }
}