Hello fellow Makers,
I am working on a code that scans through a couple LEDS after each "knock" sensed by a piezo disc. With my limited coding knowledge (I usually do "coding" inside MaxMSP) I'm happy with what I have, but it's not perfect. Ideally I'd like each knock to step through three LEDS only (count 1, 0-2, count 2, 3-5, count 3 5-7). The code is a bit haywire, stepping through 5 LEDs on the 3rd piezo count. Any assistance would be greatly appreciated. Thank you and have a wonderful day....
code below:
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 75;
int sensorReading = 0;
int timer = 75; // The higher the number, the slower the timing.
int ledPins[] = {
2, 3, 4, 5, 6, 7, 8, 9
}; // an array of pin numbers to which LEDs are attached
int pinCount = 8;
int counter = 1;
void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
sensorReading = analogRead(knockSensor);
{
if (sensorReading >= threshold) counter++;
if (counter == 4) counter = 1;
}
// loop from the lowest pin to the highest:
for (int thisPin = (counter - 1); thisPin < (counter * 2.5); thisPin++)
{
// turn the pin on:
if (sensorReading >= threshold) {
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
}
Wow, thank you so much. It looks very nice. Only thing is I would need to add a ninth LED in order to get three LEDs illuminated for the 3rd count. I'd add an extra pin to the array as well, making the total number of LEDS 9 instead of 8, utilizing pins 2 -10. Yes?
I'm using a ULN2803A chip and just too lazy to add another transistor to the circuit ha. I may do it though....
Wow, brilliant - thank you. The array for starting LED # is badass. Its so funny, I can do this stuff with my eyes closed in MaxMSP, but the abstract nature of coding is so hard to wrap my gulliver around. Again, much appreciated.....
Just another newbie question: why put "3" inside the array startLED[3] ? For example, the ledPins array is left blank (ledPins []).
If it's directly related post it here, otherwise start a new thread.
... and yeah it's not required in this instance as the array is initialised with values, so the compiler can work out how big it is. But if you didn't initialise when declaring it then the value determines how much memory to allocate for it.
Starting a new thread is referred to as "cross posting" and essentially prohibited here.
Why? Because all the important information is in the original thread, a new thread would either have to include all the information previously provided by everyone, or you would be wasting people's time answering matters that were already answered or providing explanations that were already explained.