つけじょにーのすぱげていコード

主に、競技プログラミング、セキュリティのお勉強の際に書いたすぱげていコードを書き込みます

Arduino&Processingのシリアル通信による、楽器作成

競技プログラミングやセキュリティとは異なりますが・・・
授業でやったのでメモ書きf:id:tukejonny:20141124232644p:plain

Arduino

void setup() {
  Serial.begin(19200);
}

void loop() {
  int val = analogRead(0);
  Serial.println(val);
  delay(250);
}

・Processing

import processing.serial.*;
import ddf.minim.*;
import ddf.minim.signals.*;

PFont myFont;
Minim minim;
Serial arduino;
AudioOutput out;
int currentTime, prevTime;
int x = 250, y = 250;
void setup() {
  size(500, 500);
  arduino = new Serial(this, Serial.list()[2], 19200);
  arduino.bufferUntil('\n');
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
  prevTime = millis();
  //delay(5);
  currentTime = millis();
}


void fadeToBlack() {
  noStroke();
  fill(0, 10);
  rectMode(CORNER);
  rect(0, 0, width, height);
}

void draw() {
  for(int r = 0; r <= 360; r++) {
    ellipse(x * cos(r), y * sin(r), 5, 5);
    fill(255, 0, 0);
  }
  fadeToBlack();
}
String indata = "";

void serialEvent(Serial port) {
  try {
    indata = port.readStringUntil('\n');
    if(indata != null) {
      indata = trim(indata);
      int cdsVal = Integer.parseInt(indata);
      /*
      if(cdsVal >= 700) {
        currentTime = millis();
        if(currentTime - prevTime > 1) {
          out.playNote("C4");
        }
        prevTime = currentTime;
      }
      */
      // many sounds
      if(cdsVal >= 900) {
        out.playNote("A3");
        x = 100; y = 100;
      } else if(cdsVal >= 850) {
        out.playNote("B4");
        x = 200; y = 200;
      } else if(cdsVal >= 800) {
        out.playNote("D4");
        x = 300; y = 300;
      } else if(cdsVal >= 750) {
        out.playNote("F#4");
        x = 400; y = 400;
      } else if(cdsVal >= 700) {
        out.playNote("G3");
        x = 500; y = 500;
      }
      
    }
  } catch(Exception e) {
    e.printStackTrace();
  }
}

写真、伝わりますでしょうか・・・
すっごい汚い上に、回路図の記法もろくに知らない無知さが露呈してしまっているのですが・・・
大きさの都合上、図形の中に文字を避けたのがいくつかあります
まぁ、こんな感じの回路を組んで、Processing, Arduino、それぞれ別のポートを選んでいただいて、cdsの上に手をかざしたりすると音が鳴ります
また、暗さによって音が変化します