Notifications
Clear all

Arrays ... I know I should be using them

11 Posts
4 Users
6 Likes
693 Views
(@hayttom)
Member
Joined: 3 years ago
Posts: 61
Topic starter  

Has Bill introduced us to Arduino arrays?  I did a search and see he's used them at least half a dozen times but I don't think I caught an introductory article or video.

I've written a sketch that listens to six IR speed sensors with six instances of digitalRead, six comparisons with six previous values, and six outputs (currently Serial.prints but eventually I2C outputs).  I felt guilty coding it because I knew that there must be a more elegant and flexible and cool way.  I am sure I should be looping through a six-step counter and doing stuff with the current count.

Where is the best place for me to learn about arrays?

Tom 

Tom


   
Quote
jker
 jker
(@jker)
Member
Joined: 3 years ago
Posts: 82
 

The Cherno gives a pretty decent overview of the most important parts in his video on the topic...

. He talks quickly with fast cuts in what seems to be the standard approach for a lot of youtube guides... which Bill is a welcome relief from.  You may want to reduce the playback speed to x0.75 or so. In spite of that, he gives a pretty decent coverage of the topic, including the way that arrays are paired with for loops for easy use.

For those who aren't used to "desktop C++", the whole std::cout << (thing) << std::endl; is the equivalent of our Serial.print(<thing>) in arduino-land.

 

Your complication with sensors is that it's not obvious how you link your sensors with your array indices. The usual approach is to define your sensor pins in an array that never changes.

const int IR_SENSOR_PINS[6] = {4, 5, 6, 9, 3, 1};

int SensorReadings[6];

void loop() {
for (int i=0; i < 6; ++i) {
SensorReadings[i] = analogRead(IR_SENSOR_PINS[i]);
}
}

"A resistor makes a lightbulb and a capacitor makes an explosion when connected wrong"
"There are two types of electrical engineers, those intentionally making antennas and those accidentally doing so."


   
ReplyQuote
(@hayttom)
Member
Joined: 3 years ago
Posts: 61
Topic starter  

jker, I'm truly grateful for the link but I'm afraid I had to turn it off before minute 2.

 

I'll try to work with your guidance, thank you very much.

Tom


   
ReplyQuote
(@dronebot-workshop)
Workshop Guru Admin
Joined: 5 years ago
Posts: 1053
 
Posted by: @hayttom

Has Bill introduced us to Arduino arrays?  I did a search and see he's used them at least half a dozen times but I don't think I caught an introductory article or video.

That's an excellent point, I have mentioned arrays and used them several times but you're correct, I haven't specifically covered them.

It's a good idea for a future episode!

Posted by: @jker

He talks quickly with fast cuts in what seems to be the standard approach for a lot of youtube guides... which Bill is a welcome relief from.

Thanks!  I get an occasional comment that I talk too slow (and one fellow said I never smile, which I don't think is true), but for every one complaint, I get at least 10 people who tell me that they like the speed I talk because they can understand it. This seems especially true for my viewers who have a first language other than English.

I can thank my late father for that, he was hard of hearing and developed the ability to read lips. So to speak with him I had to slow down and articulate.

@jker - That's a nice code sample, straight and to the point. It should help Tom reduce the code for his IR sensors.

😎

Bill

"Never trust a computer you can’t throw out a window." — Steve Wozniak


   
hayttom reacted
ReplyQuote
(@hayttom)
Member
Joined: 3 years ago
Posts: 61
Topic starter  

Yup, Bill, you enunciate nicely and your pace is a relief!

 

I'm looking forward to your introduction to arrays.  I know that there are resources out there - and your examples usage - but the best thing would be one of your dedicated articles and videos.

 

Tom

Tom


   
ReplyQuote
(@hayttom)
Member
Joined: 3 years ago
Posts: 61
Topic starter  

 

Here's my hard-coded six-sensor sketch.  It works perfectly but it's inelegant and scaling it to more sensors would risk errors and get longer and longer.  I believe it would be a candidate for using an array but actually I also wondered about creating a processing function and just passing it the sensor numbers 1 to 6...

 

Tom

Tom


   
ReplyQuote
jker
 jker
(@jker)
Member
Joined: 3 years ago
Posts: 82
 

@hayttom

With programming, there are always entirely too many choices in how to do something. 🙂

I would start by observing that you have three different "variables" that you are trying to collect for each of 6 sensors. That indicates that we should combine our variables into arrays (more or less, any time you see yourself making sets of variables named "Variable1", "Variable2", "Variable3"... it's a good idea to consider if an array is the right solution.

In this case:

const int Pins[6] = {5, 6, 7, 8, 9, 10};
int Previous[6] = {99, 99, 99, 99, 99, 99};
int Sensor[6];

...will get us started. (Don't worry too much about the odd syntax... 'const' just makes the compiler give you an error if you try to write to a variable, and the funny {} syntax is just a way of setting the initial value easily)

There are roughly a million different ways you can go from here. You can write a function that accepts an integer index, basically copying your first pin handler and replacing Sensor1 with Sensor[index], Previous1 with Previous[index], and Pin1 with Pins[index]. Then call this new function a bunch of times with the indexes 0, 1, 2, 3, 4 and 5.

An alternative way is to have basically the same code, but leave the code in the main loop() function in a `for(int i=0; i<6; ++i)`... it depends a bit on which way you find easier to think about.

---

On a slightly different topic, I recommend simplifying your handling of `Change`. If I were you, I would set Change to false as the first line inside the loop() function.  From then on, you only set it to true if something did change. That should get you to a "clean" state at the start of every call to loop(), which I believe is what you want.

"A resistor makes a lightbulb and a capacitor makes an explosion when connected wrong"
"There are two types of electrical engineers, those intentionally making antennas and those accidentally doing so."


   
hayttom reacted
ReplyQuote
frogandtoad
(@frogandtoad)
Member
Joined: 5 years ago
Posts: 1458
 

@jker

Posted by: @jker

On a slightly different topic, I recommend simplifying your handling of `Change`. If I were you, I would set Change to false as the first line inside the loop() function.  From then on, you only set it to true if something did change. That should get you to a "clean" state at the start of every call to loop(), which I believe is what you want.

I think it's better to put it at the end of the change conditional statement:

if (Change == true) {

    // [snip] ...

    Change = false;
 }

...otherwise, there will be an unnecessary assignment operation through every cycle of the loop where no change occurred.


   
hayttom reacted
ReplyQuote
jker
 jker
(@jker)
Member
Joined: 3 years ago
Posts: 82
 

Technically speaking... Change should probably be a local variable declared inside of loop.

There is no state you need to preserve from one iteration of the loop to the next, and you should generally localize variables to the needed scope.

I didn't go there because there are certain popular youtubers introducing people to arduino coding (no, not you Bill), who treat code almost as "magic", and have some interesting "rules", among which is declaring all variables at the top in global space. There was no reason to get into that here.

"A resistor makes a lightbulb and a capacitor makes an explosion when connected wrong"
"There are two types of electrical engineers, those intentionally making antennas and those accidentally doing so."


   
hayttom reacted
ReplyQuote
frogandtoad
(@frogandtoad)
Member
Joined: 5 years ago
Posts: 1458
 

@jker

Posted by: @jker

Technically speaking... Change should probably be a local variable declared inside of loop.

There is no state you need to preserve from one iteration of the loop to the next, and you should generally localize variables to the needed scope.

I agree with, and advocate for the defining of variables to the tightest possible scope, and personally adhere to that mantra as much as I possibly can.

Posted by: @jker

I didn't go there because there are certain popular youtubers introducing people to arduino coding (no, not you Bill), who treat code almost as "magic", and have some interesting "rules", among which is declaring all variables at the top in global space.

Indeed... there are many popular youtubers, not just for arduino, but also C++ in general, who advocate the use of bad practices!

It's unfortunate that arduino provides us with the setup() and loop() functions by default, rather than providing the traditional main() function in an empty sketch, because it leads to defining a whole bunch of variables at global scope, which essentially makes a mockery of using pass by reference semantics!

I'd much prefer a default main() function, allowing me to employ my own setup and loop functions.

And although we can actually use a main() sketch, it's not as simple as just incorporating a main() function, expecting everything else to gel together.


   
hayttom reacted
ReplyQuote
(@hayttom)
Member
Joined: 3 years ago
Posts: 61
Topic starter  

Thanks!

 

I am delighted to be reminded of the best practice of defining variables as locally as possible.

 

I will show the implementation of the advice in this thread <wink><quote>soon</quote><wink> in my Haythornthwaite and Westby Tea Railway - automation thread....  

#H&WTR

#ModelRailroad

This post was modified 3 years ago 2 times by hayttom

Tom


   
frogandtoad reacted
ReplyQuote