How to something inside loop only once if...

Hello.

Pretty new to arduino. Tried search, not so brilliant in English.

Problem: I need to control motor, one direction only and regenerative? brake. Potentiometer to control speed and when to brake. Brake needs to be certain time on, and then it have to "let go".

Now speed control part of program works (very first easy test), but brake will not "let go". For test purposes I have only LED:s to see the output. Later when this works there will be FET:s and drivers for them.

I tried to use delay, but it didn't help.

So, the loop must be rolling all the time checking is there throttle or brake, and when braking, brakes should be "on" only once, certain time. And when throttle goes "on", brake must be off even thought there is brake time still going.

Later the brake will be also driven with pwm, here in test condition its enough to know it works or not...

Here is the code, which is not completely mine (some copy-paste and so on).

-eemeli-

ps sorry about my bad english.

int ledPin = 9; // LED connected to digital pin 9 int analogPin = 0; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value int brakePin = 8; // brake led int state = 0; // throttle or brake

void setup() { pinMode(ledPin, OUTPUT); // sets the pin as output pinMode(brakePin, OUTPUT); // sets the pin as output }

void loop() { val = analogRead(analogPin); // read the input pin if (val > 30) { state = 1; } else { state = 0; }

switch (state) { case 0: digitalWrite(ledPin, LOW); digitalWrite(brakePin, HIGH); break; case 1: digitalWrite(brakePin, LOW); analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 break;

} }

You need to setup a state machine.

Create a variable called "brakeTime." When the brake turns on, start incrementing brakeTime each time through the loop. When it has been "on" for long enough you can clear brakeTime and turn off your brake.

I tried to use delay, but it didn't help.

Where did you try to put the delay, and which effect didn't that have?

Do you see both LOW and HIGH values on brakePin when you vary the input?

Hep.

Delay was after digitalWrite HIGH to brakePin, and then back to LOW.

Later it is very important to vary the brake time with potentiometer, in range of 0,05 to 1 second which I suppose to be enough.

Yes, brakePin goes low and high OK with that program, only it stays high forever when analogRead < 30 if throttle is not activated by turning the pot.

Also brake have to go “off” when throttle gets value more than 30, othervice some smoke near fets will be available more than I personally need :wink:

This may be done by writing brekpin low when throttle goes on.