I have basically two problems.First, I want to repeat a line of code in the "if" statement a number of times.
Second, I want a led to turn on according to the sensor value at the same time the rest of the code runs. I already looked at the blinkwithouthdelay example but I don't understand how to use it with "if" and "else".
Here's the code:
const int m1r=3;
const int m1l=4;
const int m2f=9;
const int m2b=11;
const int threshold = 200;
const int threshold1= 900;
const int sensorMin = 100;
void setup(){
pinMode(m1r, OUTPUT);
pinMode(m1l, OUTPUT);
pinMode(m2f, OUTPUT);
pinMode(m2b, OUTPUT);
}
void loop(){
int analogValue = analogRead(0);
int analogValue1 = analogRead(1);
//Motor control
if (analogValue > threshold) {
digitalWrite(m2b,LOW);
digitalWrite(m2f,HIGH);
delay(1000);
[b]//Here I want to repeat the following lines six times[/b]
digitalWrite(m1r,HIGH);
digitalWrite(m1l,LOW);
digitalWrite(m2b,LOW);
digitalWrite(m2f,HIGH);
delay(700);
digitalWrite(m2b,HIGH);
digitalWrite(m2f,LOW);
digitalWrite(m1r,LOW);
digitalWrite(m1l,HIGH);
delay(1000);
digitalWrite(m2b,HIGH);
digitalWrite(m2f,LOW);
digitalWrite(m1r,LOW);
digitalWrite(m1l,HIGH);
delay(1000);
}
[b]//Until here[/b]
else{
digitalWrite(m2f,LOW);
digitalWrite(m2b,HIGH);
digitalWrite(m1r,HIGH);
digitalWrite(m1l,HIGH);
}
}
You just write
for([variable used to count]; [counting variable][comparing statement][maximum value]; [increment]){
repeated statement
}
For the variable used to count, I usually just type "int i = 0", where 0 is there the counting starts from.
The comparing statement is things like >, <, >=, <=, != ...
Maximum value is the number that the counting variable will be compared to. The for loop will stop when the statement is true.
Increment is the ammount you are adding to the counting variable.
for a for loop, you will use:
for(int i =0; i < 4; i++){
(code)
}
This will run the code block until i is greater than four.
I hope this helps, not makes it more confusing.
Onions.
I tried it and it worked. Now I just want to know how to run simultaneously a code that turns on or off a led based on the value of the sensor and I can get on with my life :). I don't know how to use the blinkwithuthdelay example with an "if" statement.
I have written a library that should help with this.
Try something like this:
#include <"Timing.h">
class StateMachine
{
int state = 1;
public:
void next()
{
switch(state){
case 1: digitalWrite(13,HIGH); events.add(1000,next); break;
case 2: digitalWrite(13,LOW); events.add(1000,next); break;
default: state = 1;}
state++;
}
};
// You also need some code that uses this class
For example the for loop would be replaced with:
if(state < 4){something; state++;}
EDIT: You posted while I was writing. Use this code if you add another thing with delays.