Sensing wheel position with the accelerometer

I’ve come up with some preliminary code where I modified the “Accelerometer level example” pattern to use the gyro in the Pico 6-axis accelerometer, and it’s quite simple! The correction factor on line 14 is not really required for my purposes, but it gives better accuracy over long periods time. I’m using the Z axis.

Note that by using the gyro instead of the g-force values, there is no need to compensate for the g-forces generated by the spinning wheel.

// Modified from "Accelerometer level example" pattern

export var sixAxis
export var gyro
export var currentAngleDegs
export var currentAngleRads

export function beforeRender(delta) {
  
  // get the current value of the Z gyro
  gyro = sixAxis[5]
  
  // add error correction (varies by device)
  gyro += -0.9

  // calculate the current wheel angle in degrees
  currentAngleDegs = mod (currentAngleDegs + ((gyro * (delta) / 1000)), 360)
  
  // convert angle from degrees to rads
  currentAngleRads = currentAngleDegs * (PI / 180) 

  //you may need to reverse this angledepending on the 
  //sensor board orientation relative to the LEDs
  //currentAngleRads = -currentAngleRads
  
  //apply this angle as a rotation
  //first reset the transform
  resetTransform ()
  //center coordinates so we rotate around the center, not the corner
  translate (-.5, -.5) 
  //rotate by the correction angle
  rotate (currentAngleRads)
}

export function render2D(index, x, y) {
  //draw a vertical line
  var v = clamp (1 - abs (y * 5), 0, 1)
  hsv (x + .5, 1, v * v)
}

export function render(index) { hsv(0,1,1); }   // all red

4 Likes