First time programming with Arduino. I am a php web developer.
I am struggling with something I can do easily in PHP, but not sure how to achieve it with Arduino.
I have written a function and am sending it a single int. I want to use the int as part or a digitalWrite, but not sure how to. Any advice appreciated.
Basically.............
I have many Leds declared at the beginning of code:
int ledr_1_1 = 7;
int ledr_1_2 = 6;
int ledr_1_3 = 5;
int ledr_1_4 = 4;
I then have a program reading button pushes among other stuff. And in this code, I call a function and pass it a variable - (int):
void switchledrow(int cr){
digitalWrite(ledr_1_<variablehere>, HIGH);
}
I have simplified this a lot, but you will clearly see what I mean.
In the above, I want to include the variable as part of the digitalWrite. Is it possible?
Use an array for the ledpins; as far as I understand you, cr indicates which led needs to be switched so will be the index into the array (0..3).
Well, there are a couple of ways to do this.
You can compute the pin number:
digitalWrite(6+cr, HIGH);
Or a beter solution is to use an array. Remember that in C++, array indexes START FROM ZERO. That is, the array index is an offset into the array: the first element has offset zero.
byte ledrPin[] = { 7,6,5,4};
/** cr must be in the range 0-3 */
void switchledrow(int cr){
digitalWrite(ledrPin[cr], HIGH);
}
Note that any variable that holds a piin number, I name it with 'Pin' on the end. I think this is good practise and it forestalls a number of bugs. Pin numbers, also, are bytes (0-255).
Thank you guys. I have concluded its not possible, and you both saved me time searching. The array looks like it will be the best way to go.
I appreciate the fast responses, and the example.
Time to start learning c++ Arrays :o
Also, thanks for the 'Pin' tip - PaulMurrayCbr
brett1977:
I appreciate the fast responses, and the example.
Arrgh! My code had a typo. But since you program (even if it's only php) you probably spotted and fixed it yourself.
As to the pin thing, it forestalls a number of a problem I have seen a number of times on this forum - people confusing a pin number with a value read from or written to a pin.
I'm also a fan of suffixing any variable holding a physical measurement with the unit. It's elapsedTimeSec
or elapsedTimeMs
or elapsedTimeDays
- never simply elapsedTime
. This also forestalls a number of common sources of bugs.
I should apply the same logic to things holding angles in degrees/radians.