I am trying to write a code that ONLY INCREMENTS by one while an action is being done. Here's what I got:
I have a force sensor that I want to increment a counter by one as long as a force is being applied. I only want the increment to go up by ONLY ONE in the loop until the force is release and reapplied.
However, my following code continues to increment as the force is being applied. How do I stop it from increment.
Here is code:
void loop()
{
int forceValue = analogRead(forcePin);
int switchValue = analogRead(switchl);
int potValue = analogRead(potPin);
if (forceValue != lastForce)
{
if (forceValue >= potValue)
{
forceCounter++;
}
else
{
//do nothing
}
}
lastForce = forceValue;
if (switchValue >1000)
{
if (forceCounter % 2 == 0 || forceValue >= potValue)
{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
Serial.println("ON");
Serial.print("# Press: ");
Serial.println(forceCounter);
}
else //if (ledPin == HIGH &&
{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
Serial.println("OFF");
Serial.print("# Press: ");
Serial.println(forceCounter);
//forceCounter = 0;
}
delay (500);
}
else
{
if (forceValue >= potValue)
{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
}
}
You should post your code within code tags per the sticky at the top of this forum.
If you think about the flow of your code, it is working exactly how you would expect it to. If you want it to go off above a certain threshold, wait for it to drop, then look for the value to go above the threshold again, you are looking at a mini state machine.
The easiest way to fix it would be to include a flag that checks if you've done your counter addition for this round and wait for the next one.
Also, you don't need an else if you are going to do nothing inside it.
Sorry I am a newby at forums! I am also a newby at coding so my code lingo is sparse.
Here is code tagged:
void loop()
{
int forceValue = analogRead(forcePin);
int switchValue = analogRead(switchl);
int potValue = analogRead(potPin);
if (forceValue != lastForce)
{
if (forceValue >= potValue)
{
forceCounter++;
}
else
{
//do nothing
}
}
lastForce = forceValue;
if (switchValue >1000)
{
if (forceCounter % 2 == 0 || forceValue >= potValue)
{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
Serial.println("ON");
Serial.print("# Press: ");
Serial.println(forceCounter);
}
else //if (ledPin == HIGH &&
{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
Serial.println("OFF");
Serial.print("# Press: ");
Serial.println(forceCounter);
//forceCounter = 0;
}
delay (500);
}
else
{
if (forceValue >= potValue)
{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
}
}