BEGINNERS: Think of everything as a function()

When you start writing a sketch, a good starting point is to consider each part of you problem as a separate function()

For example, checking a switch/sensor/button to turn on an output for 2-seconds...

At the top of your sketch, before setup - declare all your 'global' variables to be shared across other functions.

void setup() will initialise all your variables to their starting values.

Within loop() make a call to determine the input state... e.g. getInputState()
That function should take care of everything associated with polarity, debounce (and anything else) related to detecting the input state.

With that input state known, you can make a confident, well informed decision whether to trigger the output pin(s).
If it's more than just on/off, you might implement another function setOutputState().
That will also isolate the requirements of output polarity and 'start time' if needed.

In loop(), calling another checkOutputState() may be use millis() to turn the outputs off/on relative to setOutputState()

In pseudo-code this looks like -

bool inputState;
unsigned long outputMillis;

void setup() {
  // set pin directions
  // set initial values
}

void loop() {
  getInputState();  // check the input pin(s)
  if (inputState != prevInputState) { // input has changed state
    setOutputState();  // set outputs and start millis() timer if needed
    prevInputState = inputState;  // keep a copy of previous input state
  }
  checkOutputState();  // if millis() has elapsed - reset affected outputs
}
// you need to write the in/out functions to suit your project!

It's that easy! And to isolate, fix or replace each function separately - do exactly that - without affecting the functionality of everything else.
e.g for debugging, if you think the code is faulty, simply comment out that line, and assign a temporary value to test the rest of the code.

Of course, there is more to the actual code required above (not much), but it was left out so you can see how to isolate your logic for faster debugging.

Keep backups between edited versions!

Pretty similar to the Five Program Steps. See #12 here.

Oh how I wish the person that created my team's most mission-critical piece of software was a believer of this philosophy. Based on Excel macros (a nightmare in and of itself with regards to exception handling), I saw one function with over 800 lines and 9 levels of Hell indentation.

And did I mention no comments? It is like staring into an abyss of madness.

Jiggy-Ninja:
Oh how I wish the person that created my team's most mission-critical piece of software was a believer of this philosophy. Based on Excel macros (a nightmare in and of itself with regards to exception handling), I saw one function with over 800 lines and 9 levels of Hell indentation.

And did I mention no comments? It is like staring into an abyss of madness.

One time I did a consulting job and came across a 31-level deep cascading if statement; one for each day of the month. Each day there was a batch job using that code for about 7 million bank customers, each of which had to, on average, fall through 15 false conditions rather than use a switch/case. In a code walk-through programmers meeting, I pointed this out as one of the best examples of RDC (i.e., Really Dumb Code) I had ever seen. I noticed several programmers cringe when I said it. I was fired the next day. Evidently the person who hired me also wrote the code.

I had a friend working with a very large bank (in their Oracle team), and some of the code they were using was really poor quality first year stuff.
But the people that 'care' can't get a job!

This and your other BEGINNER thread here are good stuff, and I'm wondering if there's not a better place / way to publish them? First they're not questions, but answers :wink: but more importantly threads by the very nature of a forum rise and fall in the index with time.

Pinning might be an option, but then a) there are loads of (unread?) pins here already and b) you might be planning a series of dozens of BEGINNERS chats.

Sorry I don't have a suggestion, but can't help thinking this way isn't the best one.

"What's a function?"

I mean, it's fine advice, but functions are a relatively advanced concept in programming, especially for the arduino target audience - we regularly see questions like "how can I make another void, like loop?"

westfw:
"What's a function?"

I mean, it's fine advice, but functions are a relatively advanced concept in programming, especially for the arduino target audience - we regularly see questions like "how can I make another void, like loop?"

A valid question, but I was trying to keep the OP as short but complete as possible.
Feel free to post a new BEGINNERS: What is a function? thread that describes functions - calling, return values etc.

Maybe I'll do one if no-one else does! (9K posts - you have plenty of spare time...! :))

lastchancename:
Feel free to post a new BEGINNERS: What is a function? thread that describes functions - calling, return values etc.

Functions are already adequately described on this very site, right here.

The function of a function is to do some function.

.

westfw:
"What's a function?"

I mean, it's fine advice, but functions are a relatively advanced concept in programming, especially for the arduino target audience - we regularly see questions like "how can I make another void, like loop?"

I hope I have given some basic guidance on this in Planning and Implementing a Program which @econjack was kind enough to link to in Reply #1

IMHO adult education can be very challenging because the "teacher" cannot dictate a program of lessons that must be followed one after the other with a test at the end.

My approach is to provide a simple but not trivial example in the hope that it may expose the reader to some techniques that s/he may find useful - if only to cause them to say "what do you mean by that?"

A big problem for an adult beginner in any subject is not knowing the arcane jargon used by the experts. Computer science is no different from Law or Accounting in that respect. And I have often been amazed at how otherwise well-educated and (apparently) intelligent people are afraid to say "I don't understand"

...R

PS it is much worse when experts are not prepared to say "I don't know" when asked a question in their own field of knowledge :slight_smile:

westfw:
...functions are a relatively advanced concept in programming, especially for the arduino target audience ...

Hmmm...

they a basic part of every language; certainly not an advanced concept.

""functions are a relatively advanced concept in programming, especially for the arduino target audience""
And that's exactly why i didn't go in too deep!
Show simple functions in context, then encourage the newbies explore and discover.
If they aren't willing to do the work, then send 'em back to primary, with plywood, batteries, bulbs and spring terminals!

westfw:
"What's a function?"

I mean, it's fine advice, but functions are a relatively advanced concept in programming, especially for the arduino target audience - we regularly see questions like "how can I make another void, like loop?"

+1

I have to agree. Sometimes the best advice is bad advice to new people.

make everything a global is a perfect example.

The people who want to learn code will learn. The people who just want to make a led flash are more interested In the end result and are already struggling learning the basics of electronics so why complicate things to the point that they want to quit.

I know some people especially the ones who have a back ground in c++ believe that you either write it correctly or you should quit.

I believe this is a open forum so you have to realize that there's going to be some newbees that really need mentoring rather than a instructor. Telling them there code is jacked isn't assisting.

Had I found this forum when I started to learn I would probably have considered that it was to much of a hassle to learn and a lot of people on here are arse holes.

I still wouldn't dare post my first 2000 line code that's been running a incubator for the last 2 years and hatched 100's of chicks.

Respect to the guys that can code especially the ones that can write a dumb code 100's of lines long that are designed to be read by a newbee when I know they could have just typed a few lines that would take a newbee a week to understand.

+1 for Reply #13

Most of my Arduino programs use global variables for most things.

There is a huge difference between one person writing programs on his/her own and working as part of a team of programmers.

And I am a firm believer in the value of using functions. The challenge is to get the concept across to a newbie without alienating him/her in the process. Rapping knuckles with a wooden ruler does not work to incentivize adults :slight_smile:

...R

gpop1:
...can write a dumb code 100's of lines long that are designed to be read by a newbee when I know they could have just typed a few lines that would take a newbee a week to understand.

I agree. My experience is that examples are best retained if the beginner: 1) can relate to the example, or 2) enjoys how ridiculous it is. For example, I explain a function call in terms of them "walking through" the code. If they see this:

int x;
int y;
// some code that sets the coordinates

  • lcd.setCursor(x, y);*

I tell them when they see this last line, take the two bytes for x and put it in your backpack, take the two bytes for y and also put it into your backback. Now scurry off and find the house named lcd. Once you find the lcd object in memory, use your key (i.e., the dot operator) to open the front door and find the room with setCursor() on it and knock on the door. (I refer to class properties as people sitting in the living room.) A hand will quickly appear from the door, grab your backpack, quickly disappear, and the door closes. A few milliseconds later, the door will open and the hand gives you your backpack, and you are instantly transported back to that line where the journey began. You look in your backpack, and find it's empty (void), so you move to the next line.

While this example is silly to us, it is easily grasped by a 12 year old because they have experience with backpacks and being told to go somewhere. It also reinforces the idea of encapsulation by referring to the dot operator as a key that lets you gain access to the "house" (i.e., object) and that methods and properties are only available once you're inside the house.

My experience is that super-bright people are often crappy teachers because they can't appreciate how some things are difficult for beginners to understand. Fortunately, some people (e.g., Nick) are both bright and good teachers, but they are rare.

I nowadays mostly write C# code for Windows systems for a living. My code is basically just C with some C# sauce.

I agree, I should quit and do some woodworking :slight_smile:

econjack:
I pointed this out as one of the best examples of RDC (i.e., Really Dumb Code) I had ever seen. I noticed several programmers cringe when I said it. I was fired the next day. Evidently the person who hired me also wrote the code.

At which point, every other proogramer there should have immediately started looking for another job.

westfw:
"What's a function?"

I mean, it's fine advice, but functions are a relatively advanced concept in programming, especially for the arduino target audience - we regularly see questions like "how can I make another void, like loop?"

I know not everyone agrees, but when I see a thread like this my response is always "go do a free C++ tutorial - there are thousands to pick from".

PaulMurrayCbr:
I know not everyone agrees, but when I see a thread like this my response is always "go do a free C++ tutorial - there are thousands to pick from".

I certainly agree: (OP here)... but the masses don't even think of searching for a suitable tutorial - let alone actually spend time doing one! I'm just trying to trickle feed some of dubious experience!