AquaticTechTank.net

A forum dedicated to design and program aquatic tanks
It is currently Sat Dec 20, 2014 5:22 am

All times are UTC - 5 hours




Post new topic This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
PostPosted: Mon Dec 10, 2012 10:59 pm 
Offline
Site Admin

Joined: Fri Nov 30, 2012 1:54 pm
Posts: 238
Don't be intimidated by code. They are mere sets of instructions you tell your computer what to do. I'll go through the basics with you and it should be pretty easy. It's written with letters, number, and mathematical symbols but in actuality when the code is executed, it is compiled meaning it is translated to a bunch of bits (ones and zeros), the only language the computer understands and something us humans find really hard to understand. Although this is a general programming tutorial, I'll use Arduino code as examples. A side note, some languages don't compile but are interpreted like javascript and some aren't really programming languages like HTML which is a makeup language.

The Basics

Variables
Variables are containers that hold data like a number or a string of text. It has a physical address in memory and is persistent so if you need to call it later in the code, it would contain the same value. To define a variable, it's as easy as:
Code:
int a = 1;

Some languages like the Arduino language requires you to give the variable a datatype or tell the computer what type of data this variable will store. 'int' means that it is an integer with some range like -32,768 to 32,767. There are other datatypes like 'string', 'boolean', 'float' etc..

A variable can contain compound, dynamic values as well like:
Code:
int x = 5;
float myVal = 32/x;


Arrays
An array is a list of data unlike a variable where it can only store one data. Like variables, it can be any type of data like numbers or strings etc.., although it's rarely needed where you need to mix data types. Most language won't allow this anyway. Each piece of data in the array is defined by an index number to represent its position in the list. The first element is [0], the second is [1], and so on. The methods to create arrays vary with the different languages. The Arduino looks like this:

Code:
 
int myInts[6];  // myInts expects 6 integer values
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";

All codes above are valid.

Any line of code that has ( // ) will not be read by the compiler. It's called commenting and used to make notes. To comment out a big chunk with multiple lines of text use:
Code:
/* some comments
    more comments
    and something extra
*/


To access the values of the array:
Given:
Code:
int myArray[10]={1,3,2,4,3,2,7,8,9,11};
     // myArray[0]    contains 1
     // myArray[9]    contains 11
     // myArray[10]   is invalid and contains random information (other memory address)  and usually will throw an error.   



To assign a value to an array individually:
Code:
mySensVals[0] = 10;

To retrieve a value from an array:
Code:
x = mySensVals[4];



For Loops
The for statement is used to repeat a block of code. The structure has three parts: init, test, and update. Each part is separated by a semicolon ( ; ). The loop continues until the test part (condition) is false.

Code:
for (init; test; update) {
      statements
}


init statement executed once at the beginning of the loop
test if the test evaluates to true, the statements execute
update executes at the end of each iteration
statements collection of code

Let's say I want to print "hello 0, hello 1, hello 2, hello 3, hello 4", I would write this:
Code:
for(int i=0; i < 5; i++) {
    serial.println("hello " + i);
}


The variable i initially is 0 and is increased by one with every iteration until i is no longer less than 5. The variable i initially can be any value and the update part can increase by however many like i=i+2 instead of i++.

Ok, so this is interesting and all but when would you use this besides printing "hello"? One example would be to iterate through an array to get or set its values.

Code:
int myPins[] = {1,3,5,6,8};

for(int i=0; i<5;i++) {
    serial.println(myPins[i]);
}

The code above prints out the list of pins stored in myPins array to serial.

There are other types of loops to iterate through code like while loops and do... while loops. The structure is different from each other but the basic idea is the same.


Conditionals
Conditional allows the program to make decisions about which code to execute. This is the work-horse in programming. We touched on this a bit in the FOR loop.

IF
If the test evaluates to be true, then the statements enclosed within the block are executed otherwise nothing is executed.

Code:
if (test) {
    statements
}


Code:
for (int i=0; i < 5; i++) {
      serial.println("my value is " + i);
     if ( i == 3) {
           serial.println(" and 3 is special.");
     }
}


The above code loops through and print i and when i is equal to ( == ) 3, it prints out an additional text.
Note that the equality operator ( == ) is used in a conditional and ( = ) is used to assign values to a variable like int a = 3.

Here are all of the relational operators you can use in conditionals:
Code:
!= (inequality)
< (less than)
<= (less than or equal to)
== (equality)
> (greater than)
>= (greater than or equal to)



ELSE
Else extends the if condition to allow the program to choose between two or more block of code. It specifies a block of code to execute when the expression in if is false.

Code:
for (int i=0; i < 5; i++) {
      if (i == 3) {
            serial.println("3 is special!");
      } else {
           serial.println("nothing interesting");
      }
}


The above code prints 'nothing interesting' until i = 3;

You can extends if further (more than two blocks of code) with else if.
Code:
if (expression) {
  statements
} else if (expression) {
  statements
} else {
  statements
}


Code:
for(int i=0; i < 6; i++) {
     if(i < 2) {
          serial.println(i + ": I'm less than 2 ");
     } else if (i < 4) {
          serial.println(i + ": I'm 2 and greater but less than 4 ");
     } else {
          serial.println(i+": I'm 4 and greater.");
     }
}


The output from the code above would look like:

Code:
0: I'm less than 2
1: I'm less than 2
2: I'm 2 and greater but less than 4
3: I'm 2 and greater but less than 4
4: I'm 4 and greater.
5: I'm 4 and greater.


A similar statement similar to if else if is switch/case. The structure is different but the idea is the same.


Top
 Profile  
 
PostPosted: Wed Dec 19, 2012 9:23 pm 
Offline
Site Admin

Joined: Fri Nov 30, 2012 1:54 pm
Posts: 238
The Structure

Your program especially when it pertains to coding the Arduino, consists of two main parts; the initialization and the main body. The initialization is the setup() function where it is called when the program starts. It's used to initialize variables, pin modes, start up libraries, etc... The setup() function will only run once after each powerup or reset of the Arduino board.

The loop() function is the body. It loops consecutively allowing your program to change and respond as it runs, a bit like the FOR loop but runs infinitely as long as there's power.

The basic layout:
Code:
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
 
}


Variable Scope
We've gone over variables and how they're defined but now we need to talk about their scope. The scope of a variable is the context within which it is defined meaning that their existence is only defined within a block of code. They are either local or global variables. For example, a variable declared with a setup(), or a for loop, or a loop() may only be used in that block of code.
Code:
for (int i = 0; i < 5; i++) {
     serial.print(i);
}

serial.print(i); // error

i is a local variable. If you try to retrieve the value of i outside the for loop, you'd get an error of variable not defined. The same idea goes if you define a variable inside a setup() function and try to retrieve it inside a loop() function.

In many instances you need the variable to be global, meaning that you can assign or retrieve the variable from any block of code. To do this you need to define the variable outside all blocks of code.

Code:
int myPin = 5;

void setup() {
    myPin = 6; // note that I don't need to do int myPin = 6. That would re-define the variable not assign a value to it.
}

void loop() {
     serial.println(myPin);
}

myPin is a global variable and set or get from any block of code.


Functions
Functions are collections of code that allow programmers to create modular pieces of code that perform a task. A typical case for creating a function is when you need to perform the same action multiple times. You've already seen a little bit of it already. Setup() and loop() are functions that are called automatically by the program.

The structure of the function varies based on what you need to do. Typically it's:

Code:
void functionName() {
  statements
}


Notice the void keyword. It means the function does not return a value. We'll go more into it later.

Code:
int ledPin = 5;

void setup() {
    pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop() {
    setPinToHigh();                  // calls user defined function
    delay(1000);                      // waits for a second
    digitalWrite(ledPin, LOW);
    delay(1000);   
}

void setPinToHigh() {              // user defined function. It gets called from the loop() function
   digitalWrite(ledPin, HIGH);
}



The above code calls the setPinToHigh() function then wait for a second then set the pin to low.

Let's say we need a function where we pass in some values into it and it does some complicated math and then return the new value to the call. In this instance the structure of the function is a bit different than before.

Code:
int functionName(someValue) {
     statements with someValue;
     return value;
}


Notice the int datatype is in place of the void from before. This is because the function is expecting to return an integer with the return keyword in the function. Of course it can be any datatype like float, boolean, etc.. depending on what you want to return.

Code:
void loop() {
      myValue = multiplyFunction(4,5);  // myValue will equal 20
}

int multiplyFunction(int x,int y) {    // x & y are declared as integers.
     int result = x * y;               // x = 4 and y = 5 are passed into the function in the parameters
     return result;                    //returns the value where it is called
}



Notice that multiplyFunction has two integer parameters between the parentheses. The number of parameters can vary depending on your need. If it gets too much too handle, you can try passing an array instead.

The ( int x, int y ) in the parameter fields are local variables and arbitrary. You can use ( int a, int b ) and so on.


Libraries
Libraries provide extra functionality to your sketches. Libraries, where the Arduino is concerned, are written in the C language. They come with two files; a header file (someFile.h) and the main source file (someFile.cpp). To import a library that doesn't exist in your Arduino library, create and name a folder in the Arduino's libraries directory and place the .h file and the .cpp file into it.

Then you can select the newly placed library with Sketch > Import Library or you can manually type:
Code:
 #include <someFile.h>

It's placed on the very top of all code. Notice the header file is all that is needed to link the library to your sketch. Depending on what library you include, the functions to take advantage of the new functionality will differ. It's usually documented.

Here's an example of the WiFi library
Code:
#include <WiFi.h>

//SSID of your network
char ssid[] = "yourNetwork";
//password of your WPA Network
char pass[] = "secretPassword";

void setup()
{
 WiFi.begin(ssid, pass);
}

void loop () {}


So I think that is a good and brief initiation into programming for you. If you want more detailed reference, check out http://arduino.cc/en/Reference/HomePage

Also check out the basics here,
http://arduino.cc/en/Tutorial/HomePage

Happy coding.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group
Copyright 2noodles LLC 2012