Sunday, February 28, 2010

Ascending then Descending Flash Rate (Task 19, 20)

This code has two separate loops that are entered depending on the value of a boolean:

int rate = 100;
boolean up = true;

void setup() {
pinMode(13, OUTPUT);
}

void loop()
{
if (up == true){
digitalWrite(13,1);
delay(rate);
digitalWrite(13,0);
delay(rate);
if (rate == 1000){
up = false;
}
else{
rate = rate + 100;
}
}
else
{
digitalWrite(13,1);
delay(rate);
digitalWrite(13,0);
delay(rate);
if (rate == 0){
up = true;
}
else{
rate = rate - 100;
}
}
}

This code starts with an if ... else loop. The first if checks if the up variable is true, if so it enters the ascending loop (if false it enters the descending loop). It then flashes with it's current rate (starts at 100ms) then increments the value by 100 until it reaches 1000. At that point the boolean value is switched to false and it enters the second loop. The LED then flashed with the current rate (1000 when entering the loop) and then decrements the value by 100 until it reaches 100 and switches the boolean again to start from the beginning.

This code can be altered so that the rate of flashing moves in 10ms increments down to 10ms instead of 100ms

int rate = 10;
boolean up = true;

void setup() {
pinMode(13, OUTPUT);
}

void loop()
{
if (up == true){
digitalWrite(13,1);
delay(rate);
digitalWrite(13,0);
delay(rate);
if (rate == 1000){
up = false;
}
else{
rate = rate + 10;
}
}
else
{
digitalWrite(13,1);
delay(rate);
digitalWrite(13,0);
delay(rate);
if (rate == 0){
up = true;
}
else{
rate = rate - 10;
}
}
}

No comments:

Post a Comment