Chad - Servo Pan/Tilt Code

Go Back

Servo Pan/Tilt Code

Download: WiichuckServo.pde and nunchuck_funcs.h

/*

 * WiiChuck Servo

 */

 

#include <Servo.h>

#include <Wire.h>

#include "nunchuck_funcs.h"

 

int loop_cnt=0;

 

byte joyx,joyy,accx,accy,zbut,cbut;

int posx,posy;

 

Servo servox; // create servo object to control a servo (maximum of eight servo objects)

Servo servoy;

 

 

void setup()

{

    Serial.begin(19200);

    nunchuck_setpowerpins();

    nunchuck_init(); // send the initilization handshake

    servox.attach(9);  // attaches the servo on pin 9 to the servo object

    servoy.attach(10);  // attaches the servo on pin 10 to the servo object

 

    Serial.print("WiiChuckDemo ready\n");

}

 

void loop()

{

    if( loop_cnt > 100 ) { // every 100 msecs get new data

        loop_cnt = 0;

 

        nunchuck_get_data();

 

        joyx  = nunchuck_joyx(); // ranges from approx 24 - 224

        joyy  = nunchuck_joyy(); // ranges from approx 33 - 226

        accx  = nunchuck_accelx(); // ranges from approx 70 - 182

        accy  = nunchuck_accely(); // ranges from approx 65 - 173

        zbut = nunchuck_zbutton();

        cbut = nunchuck_cbutton();

 

        Serial.print("joyx: "); Serial.print((byte)joyx,DEC);

        Serial.print("\tjoyy: "); Serial.print((byte)joyy,DEC);

        Serial.print("\taccx: "); Serial.print((byte)accx,DEC);

        Serial.print("\taccy: "); Serial.print((byte)accy,DEC);

        Serial.print("\tzbut: "); Serial.print((byte)zbut,DEC);

        Serial.print("\tcbut: "); Serial.println((byte)cbut,DEC);

 

        if(zbut == 1){

          posx = map(accx, 70, 182, 7, 179);

          posy = map(accy, 65, 173, 15, 179); 

        }

        else {

          posx = map(joyx, 24, 224, 7, 179);

          posy = map(joyy, 33, 226, 15, 179);

        }

 

        servox.write(posx);

        servoy.write(posy);   

    }

    loop_cnt++;

    delay(1);

Go Back