processingでシリアル通信

Microbitなどからのデータをシリアル通信で受信してProcessingで利用するためのサンプル。
ただし、JavaなのでPythonに移植しないとね〜

import processing.serial.*;

int NUM = 256;
PVector[] location = new PVector[NUM];
float angle, velocity, radius;

Serial microbit;
float val = 0;

void setup() {
  size(800, 800, P3D);
  frameRate(60);
  background(0);
  noFill();
  angle = 0.0;
  velocity = 2.0;
  radius = height / 4.0;
  for (int i = 0; i < NUM; i++) {
      location[i] = new PVector(0, 0);
  }

  String portName = Serial.list()[1];
  println(portName);
  microbit = new Serial(this, portName, 115200);
  microbit.clear();
  microbit.bufferUntil(10);
}

void draw() {
  background(0);
  translate(width / 2.0, height / 2.0);
  for (int i = 0; i < NUM; i++) {
    location[i].x = cos(radians(angle) / NUM * (i+1)) * radius;
    location[i].y = sin(radians(angle) / NUM * (i+1)) * radius;
    stroke(val, val, val);
    float diameter = i * (height / 2) / float(NUM);
    ellipse(location[i].x, location[i].y, diameter, diameter);
  }
  angle += velocity;
}

void serialEvent(Serial microbit) {
  String str = microbit.readStringUntil('\n');
  str = trim(str);
  println(str);
  int sensors[] = int(split(str, ' '));
  println("sensors[0], "+ sensors[0]);
  val = sensors[0] * 5;
}

コメントする