Help With Arduino Code

Hello everyone! I’m making a little project based on Arduino. I’ll need to use a Wii Nunchuck to control servo motors. I can move 2 servos with the accelerometer of the Nunchuck (servo1 is axis X, servo2 is axis Y). THis works fine, but it’s not what I need. I need to move 1 servo with axis X of the accelermoeter of the Nunchuck, and the other servo with a button of the Nunchuck (I mean that if you press the button, the servo rotates 180 degrees. I don’t care if it’s button C or Z). Sorry for my bad english :confused:

PD: Here’s the code I used to move 2 servos with the accelerometer:

#include <Servo.h>
Servo servo1;
Servo servo2;
#include <Wire.h>

#define ZEROX 530
#define ZEROY 530
#define ZEROZ 530

#define WII_NUNCHUK_I2C_ADDRESS 0x52

int counter;

uint8_t data[6];

void setup()
{

servo1.attach(10);
servo2.attach(11);

Wire.begin();

Wire.beginTransmission(WII_NUNCHUK_I2C_ADDRESS);
Wire.write(0xF0);
Wire.write(0x55);
Wire.endTransmission();

Wire.beginTransmission(WII_NUNCHUK_I2C_ADDRESS);
Wire.write(0xFB);
Wire.write(0x00);
Wire.endTransmission();
}

void loop()
{

Wire.requestFrom(WII_NUNCHUK_I2C_ADDRESS, 6);

counter = 0;

while(Wire.available())
{

data[counter++] = Wire.read();
}

Wire.beginTransmission(WII_NUNCHUK_I2C_ADDRESS);
Wire.write(0x00);
Wire.endTransmission();

if(counter >= 5)
{

double accelX = ((data[2] << 2) + ((data[5] >> 2) & 0x03) - ZEROX);
double accelY = ((data[3] << 2) + ((data[5] >> 4) & 0x03) - ZEROY);
double accelZ = ((data[4] << 2) + ((data[5] >> 6) & 0x03) - ZEROZ);

int value = constrain(accelY, -180, 180);

value = map(value, -180, 180, 0, 180);

servo1.write(value);

value = constrain(accelX, -180, 180);
value = map(value, -180, 180, 0, 180);
servo2.write(value);

delay(20);
}
}

Hi,

You can take a look at this tutorial and use its Arduino code instead.
The nunchuck_print_data() function checks if the buttons Z or C are pressed.
You can add an *if statement *in your main loop so that if a button is pressed, the servo will rotate 180°.
Please note that we didn’t test this Arduino code, therefore, we can’t guarantee that it will work as you expect.

Hope this helps,