ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

ProcessingでArduinoから複数の値を受けて可視化する

f:id:hungrykirby:20170521211413g:plain
f:id:hungrykirby:20170521211407g:plain

方位センサ(取得値三つ)とフォトリフレクタ4つのときの挙動比較。

import processing.serial.*;
Serial myPort;

int[][] data;

final int N = 4; //ここを受信する数値の数にする

void setup(){
  size(1000, 1000);
  myPort = new Serial(this, "COM4", 19600);
  
  data = new int[width][N];
  
  for(int i = 0; i < width; i++){
    for(int j = 0; j < N; j++){
      data[i][j] = 0;
    }
  }
}

void draw(){
  background(255);
  for(int i = 0; i < width - 1; i++){
    for(int j = 0; j <N; j++){
      strokeWeight(2);
      colorMode(HSB);
      stroke(j * 40, 255, 255);
      line(i, convToGraphPoint(data[i][j], j), i + 1, convToGraphPoint(data[i + 1][j], j));
      colorMode(RGB);
      stroke(150, 100, 100);
      strokeWeight(4);
      line(i, convToGraphPoint(0, j), i + 1, convToGraphPoint(0, j));
    }
  }
}

void serialEvent(Serial p){
  try{
    if(N + 1 == myPort.available()){
      if(myPort.read() == 'a'){
        for(int i = 0; i < width - 1; i++){
          for(int j = 0; j < N; j++){
            data[i][j] = data[i + 1][j];
          }
        }
        for(int i = 0; i < N; i++){
          data[width - 1][i] = myPort.read();
        }
      }
    }
  }
  catch(RuntimeException e) {
    
  }
}

float convToGraphPoint(int value, int j){
  return value + j*height/N + height/(N*2); //ここで適当にmapするときれいになるかな。
}