Ok I wrote this because I want my robot to be able to be controlled by the joy stick on my nunchuck controller. I thought I figured it out and it seems to kind of work but then stops and doesn't seem to follow any specific path in the code and not giving data to the serial line. I'm going to guess I'm trying to move too much information at once and it freaks out, but maybe its a simple fix.
#include <nunchuck_funcs.h>
#include <Wire.h>
#include <ServoTimeTimer1.h>
#define servoPin1 9
#define servoPin2 10
int xjoy = 0;
int yjoy = 0;
int zbut = 0;
int x= 0;
unsigned long echo = 0;
int ultraSoundSignal = 11; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;
ServoTimeTimer1 servo1;
ServoTimeTimer1 servo2;
void setup()
{
nunchuck_init();
servo1.attach(servoPin1);
servo2.attach(servoPin2);
Serial.begin(9600);
pinMode(ultraSoundSignal,OUTPUT);
}
unsigned long ping(){
pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo
ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches
return ultrasoundValue;
}
void loop()
{
nunchuck_get_data();
zbut = nunchuck_zbutton();
xjoy = nunchuck_joyx();
yjoy = nunchuck_joyy();
Serial.println(xjoy, DEC);
Serial.println(yjoy, DEC);
Serial.println(zbut, DEC);
x = ping();
Serial.println(x);
delay(100);
if (zbut == HIGH)
{
if (x > 10)
{
servo1.write(500);
servo2.write(2500);
}
else
{
servo1.write(1000);
servo2.write(1000);
delay (1000);
}
}
if (zbut == LOW )
{
servo2.write(((xjoy-30)*10)+500);
servo1.write(((xjoy-30)*10)+500);
}
}