3Dオブジェクトを加速度センサーで回転させてみました(ロールとピッチのみ)

プログラム


// accel_practice_sample1

const int accel_pin[] = { 0, 1, 2 };

int accel_val[] = { 0, 0, 0 };

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

void loop() {
  for ( int i = 0; i < 3; i++ ) {
    accel_val[i] = analogRead( accel_pin[i] );
  }

  if ( Serial.available() > 0 ) {
    for ( int i = 0; i < 3; i++ ) {
      Serial.print( accel_val[i]/256, BYTE );
      Serial.print( accel_val[i]%256, BYTE );
    }
    Serial.read();
  }

  /*
  for  ( int i = 0; i < 3; i++ ) {
    Serial.println( accel_val[i] );
  }
  Serial.println();
  */

  delay( 50 );
}
			

// accel_3d_object_guriguri1

import processing.opengl.*;
import processing.serial.*;

Serial port;

int[] data = { 0, 0, 0 };
int[] cali  = { 0, 0, 0 };
float[] accel = { 0.0, 0.0, 0.0 };

float rollDeg, pitchDeg;

void setup() {
  size( 300, 300, OPENGL );
  smooth();

  port = new Serial( this, Serial.list()[0], 9600 );
}

void draw() {
  background( 0 );

  for ( int i = 0; i < 3; i++ ) {
    print( str( data[i] ) + " " );
  }
  println();

  for ( int i = 0; i < 3; i++ ) {
    accel[i] = ( data[i] - 1024/2 ) * ( 5.0 / 1024 );
    System.out.printf( "%5.2f, ", accel[i] );
  }
  println();

  rollDeg  = degrees( atan2( accel[1], accel[2] ) );
  pitchDeg = degrees( atan2( -accel[0], accel[2] ) );
  System.out.printf( "r = %5.2f, p = %5.2f\n", rollDeg, pitchDeg );

  println();

  translate( width/2, height/2);

  pushMatrix();
  rotateZ( radians( rollDeg ) );
  rotateX( radians( pitchDeg ) );
  drawCoord();
  drawObject();
  popMatrix();
}

void drawCoord() {
  strokeWeight( 5 );

  stroke( 255, 0, 0 );
  line( 0, 0, 0, 50, 0, 0 );

  stroke( 0, 255, 0 );
  line( 0, 0, 0, 0, 50, 0 );

  stroke( 255, 255, 0 );
  line( 0, 0, 0, 0, 0, 50 );
}

void drawObject() {
  noFill();
  stroke( 255 );
  strokeWeight( 5 );
  box( 100 );
}

void keyPressed() {
  if ( key == 's' ) port.write( '*' );
  if ( key == 'c' ) {
    for ( int i = 0; i < 3; i++ ) {
      cali[i] = data[i] - 1024/2;
    }
    cali[2] = cali[2] - 1024/5;
  }
}

void serialEvent( Serial p ) {
  if ( port.available() > 5 ) {
    for ( int i = 0; i < 3; i++ ) {
      data[i] = port.read() * 256 + port.read() - cali[i];
    }
    port.write( '*' );
  }
}
			

とりあえず実行してみよう

プログラムを理解しよう

Referenceへのリンク


back to home