This is a simple programming question. What is annoying is that I remember making this work once with local variables and passing the data to the functions. Then I continued tinkering on it until it was broken, and I made a critical error, I failed to save each iteration.
When I put the variable declarations in the void loop it resets them to the default values each time the loop runs. As such, writePin never increments. How do I rewrite this using local variables (note, I have no expectation of my students doing this, I expect them to use a brute force solution)
int lightDelay;
int writePin;
bool incDir = true;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
// int lightDelay
lightDelay = analogRead(A5);
if (incDir == true){
writePin++;
}
else if (incDir == false){
writePin--;
}
serialData();
blinkIt();
if (writePin == 7 && incDir == true){
incDir = false;
}
else if(writePin == 2 && incDir == false){
incDir = true;
}
}
void blinkIt(){
digitalWrite(writePin, HIGH);
delay(lightDelay);
digitalWrite(writePin, LOW);
delay(lightDelay);
}
void serialData(){
Serial.print("lightDelay = ");
Serial.println(lightDelay);
Serial.print("writePin = ");
Serial.println(writePin);
Serial.print("incDir = ");
Serial.println(incDir);
}
Here is a video of the end result.
I am a middle school teacher that had a "Hey, can you teach a 'Robotics 2' for students that have taken your robotics course and want more?"
With that, I was teaching a second robotics class with almost no budget. It is a bit heavy in electronics. Here is a snip I wrote for another purpose. . . This class is billed as a Robotics course, but it is an introduction to programming using Arduino. They are introduced to programming in the 6th and 7th grades using the Lego EV3, and its IDE. Then they have the option of taking Robotics 2 in the 8th grade. That class uses the standard Arduino IDE. Yes, I know they can use a scratch-like interface for the Arduino. However, this is preparing them for coding classes at the High School.
The Arduino is good for this class because they learn some basic electronics, and the programming is rather simple, even for a middle school student. Further, much like the EV3, they can see something happen when they get it right. Oh, and the best part is that the materials are cheap, so when they "let the smoke out" of a component, it isn't expensive, it is just a learning experince.
That said, my C courses were years, okay, decades, ago.