I am working on this robotics project and am working on making it more autonomous. I have some simple code for continuously rotating a servo to 180 deg and then to 0 deg. This very simple code is only running once then stopping. Why might that be? Please help.
where you read the input at every stage you need it through the code.
You should be reading ALL your digital inputs at the start of the code, storing them in variables, ad use the stored variable in any computation.
So
Ok. So now that I am a lot less tired I have been able to make some real progress. So I have a servo controlling a 90lbs magswitch(https://www.kjmagnetics.com/proddetail.asp?prod=MJ-95) that I will soon attach to a robotic arm. The problem is, often magnetized items stick to the magswitch when it is off. I often have to shake it. So, I am trying to get it so that the arm will shake a little when you hold the button for a certain duration. For testing purposes, I am having it rotate to random degs.
I am having some problems with the for loop involving z and the boolean "longPress". What happens is it works as it's supposed to in the beginning. However, once I hold it down for 1.2+ secs, it CONTINUOUSLY rotates to random deg until I stop holding it. I have tried various things and it is still doing this. What am I not seeing?
#include <Servo.h>
Servo srvB; //baser servo of arm
Servo srv2; //second servo arm
Servo srvM; //servo with magswitch(R) attached
boolean bsn = false; // button state NOW
boolean pbs = false;//PREVIOUS button state
int button = 2; //button pin
boolean magSt = false; //magswitch(R) on or off
boolean longPress = false; //when pressed for a long time
int i =0; //for repeating certain code only once
int z = 0;//^^^
unsigned long onTime; //for timing stuff with indep on/off times
unsigned long offTime;// ^^^
int interval = onTime;//^^^
unsigned long pMil=0; //previous millis recorded
void setup() {
srvB.attach(10);
srvM.attach(9);
srv2.attach(6);
pinMode(button, INPUT_PULLUP); }
void loop() {
bsn = !digitalRead(button);
unsigned long cMil = millis();
if (magSt){
srvM.write(180);
digitalWrite(LED_BUILTIN, HIGH);
}
else{
srvM.write(0);
digitalWrite(LED_BUILTIN, LOW);
}
if (bsn == true) {
z = 0;
for(i; i < 1; i++) {
pMil = millis();
}
if(cMil - pMil < 1200){
longPress = false;
pbs = true;
}
else {
longPress =true;
pbs = false;
}
}
else{
i = 0;
}
if (pbs && !bsn){
magSt = !magSt;
pbs = bsn;
}
if(longPress){
for(z; z < 1; z++){
srvB.write(random(0, 180));
srv2.write(random(0, 180));
}
}
}