PaulMurrayCbr:
I like to use classes for this sort of thing.
const int potPin = 0; // pot on analog 0
class Lamp {
public:
const int buttonPin;
const int lampPin;
boolean buttonDown = false;
boolean lampOn = false;
unsigned long onAtMs;
unsigned long durationMs;
Lamp(int buttonPin, int lampPin) :
buttonPin(buttonPin),
lampPin(lampPin)
{
// don't need to do anything here
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(lampPin, OUTPUT);
}
void loop() {
int buttonNow = digitalRead(buttonPin);
if (buttonNow && !buttonDown) {
onAtMs = millis();
lampOn = true;
durationMs = analogRead(potPin); // you might want to scale this
digitalWrite(lampPin, HIGH);
}
else if (lampOn && millis() - onAtMs >= durationMs) {
lampOn = false;
digitalWrite(lampPin, LOW);
}
else {
// do nothing
}
buttonDown = buttonNow;
}
};
So now we have a thing that we can attach to a button and a lamp. It has it's own loop method which can control the behaviour of a lamp. NOtice that we have to declare potPin **before** the class and outside it.
If you have many lamps, it makes sense to use an array. Here is an array of four lamps. Buttons are on pins 2-5, and lamps are on pins 9-12.
Lamp lamps[] = {
Lamp(2,9),
Lamp(3,10),
Lamp(4,11),
Lamp(5,12)
};
Ok! In our setup, we need to call set up for each of our lamps, and in the loop we call the loop for each of the lamps. Notice the expression in the for() statement - "take the size of the entire lamp array, and divide it by the size of a single element of the array". This gives the number of items.
void setup() {
for(int i = 0; i<sizeof(lamps)/sizeof(*lamps); i++) {
lamps[i].setup();
}
}
void loop() {
for(int i = 0; i<sizeof(lamps)/sizeof(*lamps); i++) {
lamps[i].loop();
}
}
And - well, that's it.
this is beautifully efficient and something I will have to go through and impliment, at the moment I've just written a lot of unnecessary code to get the whole thing working as I want. I'll upload the sketch when I'm back from work but as you'll see in the main loop I'm checking for each button state and calling it's associated function, eg
if (buttonstatebrake == HIGH){
Brakebuttonpush ();
}
If (buttonstatefog == HIGH){
fogbuttonpush();
}
Etcetc
where in the brakebuttonpush () function I'm trying to do the stuff.
As I say, the buttons, pots and lcd are behaving as I want but these are just visual, it's not actually doing anything yet but you'll understand more when I put the sketch up this afternoon