Posted: Jun 28, 2018 4:13 am
by Calilasseia
Ah, of course. A little detail I forgot to mention.

C compilers require you to declare all variables that you are using. I forgot to put a declaration for 'scale' in the code, thinking you'd hit on that and insert it yourself. While I'm on this subject, here's another feature of C to take on board, centring upon how to declare variables.

You're already familiar with the fact that each variable has a type, and that the declaration takes the general form:

<varable_type> <variable_name>

examples thereof being:

int counter;
float newtons_g;

and in your code, you've also demonstrated that you're familiar with the fact that you can include an initialisation step in your declaration, such as:

int counter = 0;
float newtons_g = 6.6E-11;

assuming of course that your compiler supports floating point artihmetic above. :)

However, you have a choice of where to define your variables. If you want a variable to be available to every function in your code, you declare (and possibly initialise) that variable outside of all of your functions, as you did in your original code with the statement:

int step_speed = 5;

If, on the other hand, you only need a variable to be available to a particular function, then you declare it inside the function, as follows:

Code: Select all
myfunction()
{
int scale = 0;

//Rest of your function code goes here

}



The beauty of this is twofold. First, this allows you to have local variables known only to a particular function, as and when you need them. Second, it means you can use the same name for two different local variables in two different functions, and the compiler will recognise that they're local to each function, and treat them as distinct. Of course, this means that you need to make sure your local variables don't have names that clash with your global variables defined outside all of your functions!

Oh, I also assumed that step_speed in your code had to be bigger in order to make your motors run faster, which I now realise was an error, because you're using it as a delay counter. Which means the calculations for step_speed in my code need to be changed accordingly.

Incidentally, if you're looking for a decent book on C programming, the one I bought was the original - The C Programming Language by Brian W. Kernighan & Dennis M. Ritchie. These authors designed the C programming language in the first place, so their book is the 'go to' reference source for C as it was first defined. Later revisions (ANSI C, etc) and your particular compiler's idiosyncrasies you can cover after having a browse through this book. Likely to be expensive, so a library copy might be the way to go here.

In the meantime, leave this with me, because I'm actually having some fun with this, even though I'm using you as a remote debugger! :D