I'm in the process of building a Lego Technic Robotic arm. So far, we have 4 servos, 3 motors, 1 limit switch being used. Thus far, I have no major issues with programming. Everything seems to be functioning beautifully. Where I run into an issue is turning the joystick push buttons into toggle switches. So far, I can hold the button down for "HIGH" and release for "LOW". but when I try to integrate my known methods of "Toggle Switching" into the program, 1 of two things happen. either, it activates for a few seconds and then deactivates, back and forth on its own, or it just simply will not function at all. I've even attempted to add a pullup resister in the path of the switch wire. No difference.
To not risk messing up my main program, I've diverted back to an older and simpler IDE file to try and figure it out.
My first thought, is that the "else" is preventing things to run because I didn't add enough information to it. If so, then what do I need to add to it? Otherwise, maybe you guys can help me figure out my mistake?
#include <Servo.h>
Servo Xservo;
Servo Yservo;
int XSpin=11;
int YSpin=10;
int ledPin=7;
int buttonPin=2;
int buttonNew;
int buttonOld=1;
int ledState=0;
int XPin=A0;
int YPin=A1;
int SWpin=2;
int XVal;
int YVal;
int WVx;
int WVy;
int dt=100;
int dtB=100;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(XSpin,OUTPUT);
pinMode(YSpin,OUTPUT);
pinMode(ledPin,OUTPUT);
pinMode(XPin,INPUT);
pinMode(YPin,INPUT);
pinMode(buttonPin,INPUT);
Xservo.attach(XSpin);
Yservo.attach(YSpin);
}
void loop() {
// put your main code here, to run repeatedly:
XVal=analogRead(XPin);
WVx=(180./1023.)*XVal;
YVal=analogRead(YPin);
WVy=(180./1023.)*YVal;
buttonNew=digitalRead(buttonPin);
Xservo.write(WVx);
Yservo.write(WVy);
delay(dt);
Serial.print("X Value = ");
Serial.print(XVal);
Serial.print(" Y Value = ");
Serial.print(YVal);
Serial.print(" Switch State = ");
Serial.println(buttonNew);
delay(dtB);
if(buttonOld==0 && buttonNew==1){
if (ledState==0){
digitalWrite(ledPin,HIGH);
ledState=1;
}
else{
digitalWrite(ledPin,LOW);
ledState=0;
}
}
}
Thanks for any help guys!