If you’ve gone through the Arduino Pin by Pin tutorial, you’ve already used the Arduino IDE (Integrated Developing Environment). Understanding how to manipulate the hardware side of things using code is the key to using the UNO as a sensing platform. As programming is better “learned” than “taught” we’ll just jump in straight away^1 If you’re experienced in programming, you can pretty much skip everything in this document. Even so, make sure that you do understand the peculiarities of programming for microcontrollers vs. fully fledged computers!
First things first, open up the Arduino IDE (version 3). Connect the UNO and select in the IDE using Tools->Port->your UNO port . Hopefully on your screen you’re seeing the code below
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
The comments^2 Comments start with two forward slashes (//) and are not evaluated, they’re there only to explain parts of code, sprinkle comments liberally within your code so that other people (and future you) can understand what’s going on explain the basic structure of our code very well. The setup chunk runs only once and anything in the loop section runs repeatedly.
As an example project we’ll be combining the PWM feature of the UNO and the Analog inputs to make a dimmable LED. A good way to start out is to write down, in broad terms, what we’ll need to code for this to work.
The wiring will look like this, use a 100-200 ohm resistor to limit LED current also watch out for LED polarity.
So lets be direct and write what we want down. Maybe the IDE is smart enough to parse English.
void setup() {
Set pin A0 as input, set pin 3 as output.
}
void loop() {
Read pin A0 adjust pin 3 accordingly
}
Copy this in and press the uplad button (arrow on the top left corner). A second later you should get an error message at the bottom that reads like this.
Users/Emre/Documents/Arduino/sketch_sep10b/sketch_sep10b.ino: In function 'void setup()':
sketch_sep10b:3: error: 'Set' was not declared in this scope
Set pin A0 as input, set pin 3 as output.
^
/Users/Emre/Documents/Arduino/sketch_sep10b/sketch_sep10b.ino: In function 'void loop()':
sketch_sep10b:8: error: 'Read' was not declared in this scope
Read pin A0 adjust pin 3 accordingly
^
exit status 1
'Set' was not declared in this scope
Not great, we seemed to have made a couple of mistakes. Lets fix them!
The error we got told us that ‘Set’ was not declared in this scope. We didn’t really expect the code to work (mainly because it wasn’t code) but it’s interesting nevertheless, that the IDE tells us that the reason it stopped was it couldn’t find ‘Set’ the first word of code we wrote in this sketch. Error messages can be very useful, to understand what it meant google “was not declared in this scope + arduino” and look at the first couple of links.
It should not come as a surprise, whereas we were using human language, the IDE^3 Rather the compiler was expecting Arduino language. Arduinos are programmed in a subset of C/C++ languages, custom fit to be compatible with the little microcontroller.
To get a good overview of the language and a nice start, read through this document. I’ll repeat some parts here so don’t worry if you don’t understand it all.
Lets have a look at the “right” code4 Invariably, there are millions of ways to achieve the same thing with code, the snippets you see here will not necessarily be the “best” way of doing things. If you can spot something that can be improved, improve it!
void setup() {
//Set pin A0 as input
pinMode(A0, INPUT);
/*Every declaration or function call in C is ended with a semicolon,
this is our way of telling the compiler that our sentence is over,
and it might parse it to make it machine readable.
Note the curly brackets, they indicate a "chunk" of code,
the internals of a function or a loop. Where the setup() function ends with the bracket
loop() begins*/
//set pin 3 as output
pinMode(3, OUTPUT);
/* Before using the pins as input or output,
we have to make sure that UNO knows our intention beforehand.
pinMode function lets us tell the UNO which pin is going to be used as input or output.
The parantheses after pinMode signify that this is a function call.
pinMode function is a basic functon that was written by the Arduino developers.
Functions keep us from reinventing the wheel while programming.
Haiku
Any function must end,
with parantheses. Inside,
lie the arguments.
The values "3" and "OUTPUT" in the parantheses are the arguments of this function.
Order of arguments matter */
}
void loop() {
int x =0;
/* We have declared a variable named x, and assigned the value 0 to it.
int suggests that the variable is going to be an INTeger.
A declaration is what the name suggests.
Tanka
We have declared that,
We will need an integer,
The name will be x,
and the value, just zero.
And it ends, semi-colon.
Any time we type x, we will be referring to this variable.
= is the assignment operator.
It is good practice to assign a value when we declare a variable.*/
x=analogRead(A0);
/* Another function, you should remember analogRead from the previous tutorial.
We have given the A0 pin as its argument.
The function will read the A0 value using the ADC.
The read value will be returned and stored in x.
Note the lack of "int", as we have declared the value before.
Haiku
To read a signal,
And to store it in x too,
No int, just equals.*/
x=x*(255.0/1023.0);
/* If you check the documentation for analogRead and analogWrite, (use Google)
you can see that analogRead returns a value between 1023 and 0.
analogWrite takes an argument in the range 0 to 255,
we rescale x to fit in the analogWrite range.
Haiku
a function, to work,
needs more than just a name. check
documentation.*/
analogWrite(3,x);
/*This time we write the rescale x value to pin 3 as a PWM signal,
the brightness of the LED will change as the PWM value changes.
Tanka
read a value and,
modify it. line of code.
with analogWrite,
dim. light emmiting diode.
zen? pulse width modulation.*/
}
In short, it takes just 5 lines of code to get this working. If anything is not clear, go back and read the linked pdf at the beginning of this chapter.
void setup() {
//Set pin A0 as input
pinMode(A0, INPUT);
//set pin 3 as output.
pinMode(3, OUTPUT);
}
void loop() {
int x = analogRead(A0);
//Read the voltage from potentiometer. Declaration and assignment in a single line
x=x*(255.0/1023.0);
//Scale appropriately
analogWrite(3,x);
//Write value to pin 3, PWM output.
}
We’ve now managed to get analog output and input running. What about digital pins? We’ll get to it right away. We’ll be building a humid-o-meter that turns LEDs on to show what level of humidity the sensor is measuring. First, wire the Arduino as shown below. You’ll notice the breadboard, in a breadboard a “row” of pins are connected together and each column is isolated. Breadboards make it easy to prototype your designs without permamently attaching things together with solder.
Watch the polarity of LEDs. As we’ll be turning the LEDs on one by one, just a single resistor is enough. What would happen if we were to turn multiple LEDs on at the same time? The sensor you have might not be the same as shown here, check the datasheet and make sure you’re wiring the power pins correctly
We can put our previous exercises to good use here. The humid-o-meter needs to do these things; * Read humidity value from the sensor * Compare it to known values to see if it is very low - low - medium - high - very high. * Turn on the associated LED
Lets start with reading the humidity value from the sensor, you can check the datasheet of the sensor to see how the UNO should communicate5 This curious piece of sensor uses a single data line to communicate digitally, most sensors will need two wires to send and receive data. If the 5 step communication protocol looks daunting, you’re not alone!
Luckily, this sensor has been used by many people before us. To make things easier, people have written “libraries” of code and made them publicly available. To get the DHT-11 library, open up the Arduino IDE, go to Sketch-> Include Library -> Manage Libraries and search for DHT. The Adafruit library will come up, install it.
There are two goals of t