Sie sind auf Seite 1von 47

Arduino

1|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Table of Contents
Introduction .................................................................................................................................................. 4
What is Arduino? .......................................................................................................................................... 4
The Arduino UNO .......................................................................................................................................... 5
Input and Output ...................................................................................................................................... 5
14 Digital Pins (Pins 0-13)...................................................................................................................... 5
6 Analog Input Pins (Pins A0-A5)........................................................................................................... 5
6 Analog Output Pins (Pins 3, 5, 6, 9, 10, 11) ........................................................................................ 5
Blink............................................................................................................................................................... 6
The Breadboard ............................................................................................................................................ 9
Building a Circuit ......................................................................................................................................... 10
Sensing ........................................................................................................................................................ 12
The Pushbutton....................................................................................................................................... 13
The Potentiometer .................................................................................................................................. 16
The Photocell .......................................................................................................................................... 18
Arduino IDE ................................................................................................................................................. 20
Blink......................................................................................................................................................... 20
Components of the Blink Sketch ............................................................................................................. 21
Comments ............................................................................................................................................... 21
Functions ................................................................................................................................................. 22
Lets make some changes ....................................................................................................................... 22
Photocell Controlling LED........................................................................................................................ 23
Listen to the Arduino .............................................................................................................................. 25
Arduino Libraries ......................................................................................................................................... 28
Measuring Temperature and Humidity ...................................................................................................... 28
Wiring the Sensor.................................................................................................................................... 29
Testing the Sensor................................................................................................................................... 30
Liquid Crystal Display Output ...................................................................................................................... 31
Wiring the LCD ........................................................................................................................................ 31
LCD Coding .............................................................................................................................................. 36
Weather Station .......................................................................................................................................... 36
2|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Data Logging................................................................................................................................................ 41
Resources: ................................................................................................................................................... 46
Works Cited ................................................................................................................................................. 46

3|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Introduction
In this document we will explore the Arduino hardware and software. We will create several circuits to
gain a better understanding of the Arduino programming language, the ModKit graphical programming
and a few of the Arduinos capabilities.

What is Arduino?
Arduino is a tool for making computers that can sense and control more of the physical world than your
desktop computer. It's an open-source physical computing platform based on a simple microcontroller
board, and a development environment for writing software for the board.
Arduino can be used to develop interactive objects, taking inputs from a variety of switches or sensors,
and controlling a variety of lights, motors, and other physical outputs. Arduino projects can be standalone, or they can communicate with software running on your computer (e.g. Flash, Processing,
MaxMSP.) The boards can be assembled by hand or purchased preassembled; the open-source IDE can
be downloaded for free.
The Arduino programming language is an implementation of Wiring, a similar physical computing
platform, which is based on the Processing multimedia programming environment. (Introduction, 2013)

4|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The Arduino UNO


The Arduino UNO is the primary Arduino we will work with, although everything which will be covered
can be readily implemented on many Arduino devices.

Input and Output


The primary means by which we interface the Arduino UNO with the outside world is though
input/output connectors, commonly referred to as IO pins. The number of IO pins varies greatly
amongst the different Arduino variants. The UNO has a total of 20 IO pins.
14 Digital Pins (Pins 0-13)
The digital pins can be set by the users to be either an output or an input. In general these pins are
limited to outputting or sensing a high or low state (on or off.) Pin 13 is internally connected to an LED
on the board.
6 Analog Input Pins (Pins A0-A5)
The analog input pins can be used as digital output pins but have the added feature of being able to
sense the voltage at the pin. The voltage at these pins within a range of 0-5 Volts is translated to a value
between 0-1023.
6 Analog Output Pins (Pins 3, 5, 6, 9, 10, 11)
The name analog output is deceptive in that the output is not truly an analog signal but a pulse-width
modulated signal. A pulse-width modulated or PWM signal is one in which the signal is quickly switch on
and off repeatedly with ratio of on-time to off-time being carefully controlled. These pins are marked
with a tilde ~.

5|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Blink
Lets begin by making the Arduino blink the LED internally connected to pin 13.

Begin by plugging in your Arduino UNO via USB and opening the MODKIT micro application.
Note: The images may differ slightly from the actual MODKIT application depending on which version is
being used.

Once open select continue, it may take a few minutes for MODKIT to detect your Arduino.

6|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Once the board is detected select the Arduino UNO.

The hardware screen is one place which the board can be configured; however, we will be working with
code blocks. Enter the blocks mode by selecting the Blocks tab at the top of the application. The
programs created with MODKIT are called sketches.

7|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

We will start our coding by configuring the pin to which the LED is connected to. The LED on the board is
internally connected to digital pin 13. From the Setup section drag a pinMode code block onto the
workspace. From the pinMode code blocks drop down menus select pin 13 and output. We have just
configured pin 13 as an output, as it will supply or output electricity to the pin.

From the control section, drag over a forever block and two delay blocks. Additionally from the output
section drag over two digitalWrite blocks.

You should now have these code blocks in you sketch. Configure the drop down menus of the
digitalWrite blocks to address pin13 and set one block to high and the other to low. Digital writing a pin
high turns the pin on by applying 5 volts to that pin and writing a pin low turns it off by applying 0 volts
to that pin. The delay block by default has a value in milliseconds of 1000 or equivalently 1 second. The
delay block simply adds a period of time in which the Arduino stays idle. Now lets configure the blocks
such that the LED is on for one second, then off for one second and follows this pattern indefinitely.
Keep in mind that the pinMode code block need only be run once and can remain outside of the forever
loop.

8|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Your code blocks should be similar to the ones above. Upload the sketch to the Arduino UNO board by
selecting the triangle play button towards the top of the MODKIT application. Uploading may take a few
seconds. Once uploaded the LED on the board should turn on or off once a second.
Experiment with different delay times or add more sequences.

The Breadboard
The breadboard (or protoboard) is a reusable prototyping platform that allows the rapid and temporary
connection of electronic components. The basic design of a bread board is such that the columns not
separated by a space are interconnected and the outer row pins are interconnected. The figure below
shows examples of interconnections. The interconnected columns are terminal strips and the
interconnected rows are bus strips. The common practice is to use terminal strips to connect
components and use bus strips to provide power and ground to components.

9|Page
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Building a Circuit
Now that weve made the blink sketch we will move on to building circuits on a breadboard

Using a 220 resistor and an LED build your circuit as shown below, ensuring that the longer leg
(positive leg) of the LED is connected to the resistor and the shorter leg (negative leg) to the ground pin.

Notice that the LED and resistor circuit are connected to pin 12. Create simple MODKIT sketch similar to
the last example. Change the sketch to blink the LED on pin 12 on or off every half second.

10 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The resistor in the circuit serves to limit the current in the circuit and protect the LED and our Arduino
UNOs. Use a much larger value resistor (ie. 10k ) and see if the LED still illuminates. Do not use a value
smaller than 220 .
Now use four resistors and four LEDs to and create a sketch that controls all four LEDs in some order. Be
creative and make use of the ground bus. One possibility follows.

11 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Sensing
A sensor, very simply, is any device that detects or measures a physical input (sound, touch, pressure,
light, humidity, etc.) and communicates this information to a control or measuring instrument.
In addition output, the UNO can also interact with the world around it through input or sensing its
environment. The Arduino UNO can sense through both digital IO pins and analog pins.

12 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The digital pins can only differentiate between two states, a high state and a low state. Voltages of
greater than 3 Volts on a digital pin are read as high states (assigned a value of 1) and voltages of less
than 2 Volts are read as low states (assigned a value of 0.)
The analog pins can read any value between 0 Volts and 5 Volts. The read voltages between 0 and 5
Volts are then converted to a numerical integer value between 0 and 1024. Think of this as a simple
conversion from one unit such as inches to another such as feet.
The functions to read the values of the digital and analog pins are digitalRead() and analogRead()
respectively.

The Pushbutton
Begin by building a circuit with a resistor and pushbutton in series. Connect the unconnected resistor
end to ground and the unconnected pushbutton end to 5V. Connect a wire form the
pushbutton/resistor junction point to pin 7. The pushbutton circuit is now complete, when the
pushbutton is not pressed 0 Volts are present at the pin, and 5 Volts are present at the pin when the
push button is pressed. The resistor prevents a direct short from 5V to ground (0V.) Complete the circuit
by connecting an LED as we have before, with the driving pin being digital pin 6.
The circuit should be similar to the one below.

13 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

We will begin as we have before with but this time we will use a variable to store the value of the
pushbutton pin when we read it. Start by dragging in the setup components and the forever loop.

14 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Choose the appropriate drop down menu values. Keep in mind that pin 7 is now an input as we are
reading from it.

From the variables section create a new variable by the name button_value and drag both blocks that
are created for the variable.

The next step is to assign button_value an actual value. We will use the digitalRead function from the
input section and place it within the button_value assignment block. Ensure you select the correct pin
from the drop down menu in the digitalRead function, in our case the correct pin is pin7.

Now that we have assigned button_value a value lets make us of it. Lets create a sketch that turns the
LED connected to pin 6 on if the button is pressed and off when it is not pressed. We will make use if an
if-else block from the control section and a == block from the operator section. The double equal
operator checks for equality and returns a 1 if true and a 0 if false. Similarly the if-else block evaluates
whatever is within its input if the contents of the input equal 1 or true the first block of code is run
otherwise (else) the second block of code is run. Remember to add the digitalWrite code blocks to
control the LED. Configure the code blocks as follows.

15 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Upload the code to the Arduino UNO and press the button to verify the expected operation.

The Potentiometer
The potentiometer, often referred to simply as a pot, is a common type of resistor whose resistance can
be varied. The outer leads of a pot have a fixed resistance and the center lead is a wiper that runs from
one end of the pot to the other as the knob is turned. Connecting the outer leads to 5V and ground
allows the voltage at the center lead to vary from 0V to 5V as the pot knob is turned.
Remove pushbutton and the 10k resistor from the circuit and add a 10k potentiometer to the circuit.
Connect the outer leads of the pot to 5V and ground and the center lead to analog pin A0. Leave the LED
portion of the circuit unchanged.

16 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Create a new integer variable named pot_value and drag in the two associated blocks. Since the center
lead of the pot is connected to an analog pin we now require an analogRead function in the place of the
17 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

digitalRead function. Additionally we will replace the == operator with a < or > operator since the
analogRead function can return a value between 0 and 1024 instead of a 0 or 1. Attempting to turn on
an LED when one value out of 1024 is reached would be very difficult.
Modify the sketch to turn on the LED when a value greater than 512 is read from the pot. Remember to
configure the pins accordingly.

Attempt to modify the code block such that the LED turns on when the read-in value is greater than 300
and less than 800. What behavior would this circuit exhibit?

The Photocell
The photocell is a is similar to a potentiometer in that its resistance varies. How much the phoptocells
resistance varies depends on how much light it receives. Begin by removing the potentiometer from the
circuit while leaving the LED components in place. Add to the breadboard a photocell in series with a
10k resistor. Connect the outer lead of the resistor to ground and connect the outer lead of the
photocell to 5V. Connect the junction between the photocell and the 10k resistor to pin A0 for reading.

18 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Use the same code blocks used for the potentiometer example in which the LED turned on when a value
greater than 512 was read. Modify the variable name to be descriptive.

19 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Cover the photocell to see if the LED turns off.

Arduino IDE
The Arduino integrated development environment (IDE) is similar to MODKIT but is text-based and more
versatile. The Arduino IDE promotes the quick reutilization of code.

Blink
Let us begin with the task of making an LED blink. This will help us become familiar with the
Arduino integrated development environment (IDE) and its programming language. You must have the
Arduino IDE properly installed before proceeding.
Programs written in the Arduino IDE are commonly referred to as sketches; our first sketch will be blink.
Begin by connect your Arduino UNO via USB and wait for the computer to recognize the Arduino. Once
the Arduino is recognized locate the Arduino launcher and open the Arduino IDE.

20 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

From the top menu bar select Tools Board Arduino UNO, additionally select Tools Serial Port
the appropriate port (there may be more than one.)
Now we will open the blink sketch by selecting File Examples Basics Blink.
Depending on your configuration or operating system another Arduino IDE window may have opened.
On the IDE window with the blink sketch click on the check mark icon, this is the verify button.
Verification checks the code for errors and attempts to help locate them. Verification is commonly
referred to as compilation. You should receive notification at the bottom of the IDE if the code compiled
successfully or a warning if there was an error. Once this is done upload the code to your Arduino by
clicking on the right arrow icon. Once the sketch has been successfully loaded to the Arduino you should
see the onboard LED blinking. If the sketch failed to upload the possibility exists that the wrong port was
selected.

Components of the Blink Sketch


Now that you have successfully uploaded a sketch let us take a moment to understand some
components of a sketch.

Comments
Comments are used to make the code more readable and supply pertinent information to the reader. All
Arduino sketches should be well commented to help others and yourself when reading your code.
Comments come in two forms, line comments and block comments. Line comments are prefaced with
// and block comments are encapsulated in /* */
//

This is a line comment

/*

These are block comments


These are block comments

21 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

These are block comments

*/

Functions
Functions are blocks of code grouped together in a set of braces {} which allow a programmer to
modularize segments of code which perform a set task. All Arduino sketches require two specific
functions to compile properly; a setup function and a loop function. All code within the setup function is
executed once before anything other code. All code within the loop function is executed consecutively
and indefinitely.

void setup() {
// Code in this function executes first and only once.
}
void loop() {
// Code in the loop function runs over and over again forever.
}

Lets make some changes


As with all Arduino sketches you are encouraged to change, repurpose, recycle and experiment with the
code. Read through the code, especially the comments to gain an understanding of what the code is
doing. Experiment with the values of the delay() function to speed up or slow down the blinking,
keeping in mind that the original value 1000 is in milliseconds.

void loop() {
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}

//
//
//
//

turn
wait
turn
wait

the
for
the
for

LED on (HIGH is the voltage level)


half a second
LED off by making the voltage LOW
half a second

Also note that each line of code must terminate in a semicolon.


In viewing this code you should notice clear parallels to the MODKIT code blocks. Lets recreate the last
MODKIT sketch involving the PHOTOCELL and LED.

22 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Photocell Controlling LED


Configure the Arduino and breadboard as shown if not currently so.

Begin by creating a new sketch and save it using a descriptive name such as photocell_controlled_led.
23 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Add a comment block with some information about what the sketch does and who the author is, the
date, perhaps revision number and any other information which may be helpful such as:
/*
This sketch controls an LED by observing the input from a photocell
This sketch was part of an Arduino training session
An LED is connected in series with a 220 OHM resistor
Negative side to ground, Positive side to the Arduino digital pin
A photocell is connected in series with a 10K OHM resistor
Resistor end is connected to ground
Photocell end is connected to 5V
Junction between the two is connected to an Arduino analog input pin
Created 7/11/2013 By The Diligent Student

*/

Next add global variables. Global variables are variable which can be seen and possibly modified from
any function within our code. Variables can be used to store values which change or to make our code
more readable. In our case instead of remembering that pin 6 is the LED and pin A0 the photocell input
we will create descriptive variables for them.
const int ledPin = 6;
const int photocellPin = A0;

// This is the pin the LED + is connected to


// This is the pin connected between to
// photocell and 10k Resistor

We have created two integer variable whose names represent the integer 6 and the integer A0. Despite
A0 not being an actual integer,A0 is in fact already an integer variable associated with the analog pin
A0. We use the qualifier const to make our variables constant or read-only. If either of these variables
needed to be overwritten at any time in our code we would leave out the const qualifier.
Next add the two required functions to our sketch, setup () and loop ().
void setup(){
}
void loop(){
}

Semicolons are not required at the end of code blocks. Code blocks are encapsulated in curly braces.
At this point compile the code and check for errors. The code should be compiled often to avoid
compounding errors. If the code compiles error-free move on to configuring the pins.
In MODKIT we configured pin 6 as an output and pin A0 as an input. This is the text version:
void setup(){
pinMode(ledPin, OUTPUT);
pinMode(photocellPin , INPUT);
}

// Configure ledPin as an output


// Configure photoCellPin as an input

24 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The configurations are entered in the setup function. Remember that the setup function is only run once
before the loop function. Be mindful of the camel-case of the pinMode function, capitalization of the
input and output keywords and semicolons and the end of lines of code.
Now we will create an integer variable by the name of photocell_value to which we will assign the value
of the analogRead at pin A0.
void loop(){
int photocell_value; // Create integer variable
photocell_value = analogRead(photocellPin); // Assign value from pin A0
}

The first line creates a local integer variable by the name photocell_value. The second line assigns a
value to photocell_value .The only thing that remains is writing the if-else statement.
void loop(){
int photocell_value; // Create integer variable
photocell_value = analogRead(photocellPin); // Assign value from pin A0
if (photocell_value > 512){
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
}

// If true turn on LED


// Otherwise turn off LED

Compile, upload and verify expected operation of the code created.

Listen to the Arduino


The Arduino has the ability to communicate with a computer via a USB port. This ability is extremely
useful for debugging code. We will add this ability to the code just created. Add the following code:
To the setup function add:
Serial.begin(9600);

// Initialize Serial at 9600

This line initializes the serial communications at a rate of 9600 baud. Other speed are available but 9600
works well for most applications
To the loop function, after the line photocell_value = analo add:
Serial.print("The Value of pin A0 = "); // Print this line exactly
Serial.println(photocell_value);// Print VALUE of photocell_value + new line
delay(500); // delay output for easier reading

These two commands are the most commonly used for serial data output. The only difference between
Serial.print and Serial.println is that the latter advances the cursor to the next line when done printing.
Within the parentheses of either function if quotes are used the literal text is printed and if no quotes
are used the value represented by the variable entered is printed. The half second delay will make the
output easier to read.
25 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The code should now be as follows:


/*
This sketch controls an LED by observing the input from a photocell
This sketch was part of an Arduino training session
An LED is connected in series with a 220 OHM resistor
Negative side to ground, Positive side to the Arduino digital pin
A photocell is connected in series with a 10K OHM resistor
Resistor end is connected to ground
Photocell end is connected to 5V
Junction between the two is connected to an Arduino analog input pin
Created 7/11/2013 The Diligent Student
*/
const int ledPin = 6;
const int photocellPin = A0;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(photocellPin , INPUT);
}

// Initialize Serial at 9600


// Configure ledPin as an output
// Configure photocellPin as an input

void loop(){
int photocell_value;
// Create integer variable
photocell_value = analogRead(photocellPin); // Assign value from pin A0
Serial.print("The Value of pin A0 = ");
// Print this line exactly
Serial.println(photocell_value); // Print photocell_value + new line
delay(500);
// delay output for easier reading
if (photocell_value > 512){
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
}

// If true turn on LED


// Otherwise turn off LED

Compile and upload the code and verify the circuit still works as expected.

26 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Open the serial monitor by selecting the magnifying glass icon in the upper-right-hand corner of the IDE.

If the expected data is not updating every half a second check that the data rate selected matches the
9600 configured in the code.

Cover the light sensor and observe the change in the serial output.

27 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Arduino Libraries
The Arduino environment can be extended through the use of libraries, just like most programming
platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or
manipulating data. A number of libraries come installed with the IDE, but you can also download or
create your own. (Libraries, 2013)
Libraries allow Arduino users to build off the work of others and work more efficiently by not
reinventing the wheel.

Measuring Temperature and Humidity


To measure temperature and humidity we will be using either the DHT11 or DHT22 (also known as
RHT03) temperature and humidity sensor. Before beginning we must download the DHT library from
https://github.com/adafruit/DHT-sensor-library . No login is required simply select the zip option from
the web page as shown in the figure below.

Once the library zip file downloads, navigate to the download location and extract all the files. Once
extracted navigate into the folder which contains two files named DHT, one with a .h extension and one
with a .cpp extension as well as a readme.txt file and an example folder. The immediate folder
containing these files must be renamed DHT and placed into the Arduino libraries folder. In Windows
operating systems, this folder is commonly located in Documents/Arduino/ in Linux operating systems
this folder is commonly in ~/sketchbook. If the libraries folder does not exist simply create one in the
sketchbook location. For details on where your specific sketchbook folder is located open the Arduino
IDE and select File Preferences and it should be the first thing displayed.
28 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Once the DHT folder is in the libraries folder its associated example should be accessible through the
Arduino IDE. If the Arduino IDE was open during the addition to the libraries folder it should be restarted
so that it can recognize the new library. Verify the library was properly installed by selecting from the
Arduino IDE File Examples and there should be a folder DHT with a sketch DHTtester.

Wiring the Sensor


Wire the sensor as shown in figure 3, with the leftmost pin connected to 5V, the rightmost pin to ground
and the second pin from the left connected to the Arduino pin 8 and a 10k resistor to 5V. There is no
connection to the third pin of the sensor.

29 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Testing the Sensor


Open the DHTtester example in the DHT library, examine the code and make the following changes:

Change to the correct pin, in our case DHTPIN will be pin 8, so change the 2 to a 8

Uncomment the line with the correct sensor and comment the remaining two lines

Add a three second delay after the last line in the loop function for readability

// Example testing sketch for various DHT humidity/temperature sensors


// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 8

// what pin we're connected to

// Uncomment whatever type you're using!


//#define DHTTYPE DHT11
// DHT 11
#define DHTTYPE DHT22
// DHT 22 (AM2302)
//#define DHTTYPE DHT21
// DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow
sensor)
float h = dht.readHumidity();
float t = dht.readTemperature();
// check if returns are valid, if they are NaN (not a number) then
something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
delay(3000);
}
}

30 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Once the code is correct, compile and upload the code then open the Arduino serial monitor. Ensure
that the serial monitor is configured to 9600 baud. The output should be similar to that shown in the
figure below.

Modify the code to display the temperature in Fahrenheit.

Liquid Crystal Display Output


All recent Arduino versions include the Liquid Crystal so we will begin with wiring of the LCD.

Wiring the LCD


Begin by placing a 10K potentiometer and the LCD as shown in the figure below.

31 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

As the LCD is shown in the figure above, the pins are numbered 1 to 16 from left to right. It will be
necessary to know each pin function to use the LCD library. A list of pin functions is commonly referred
to as a pinout. The most common pinout of 16x2 LCD displays is that of the Hitachi HD44780 LCD
controller or a clone of it. The pinout is as shown in the following table but can be readily found by
performing an internet search for LCD pinout.
Pin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Name
VSS
VDD
VO
RS
R/W
E
D0
D1
D2
D3
D4
D5
D6
D7
Backlight +
Backlight -

Function
Ground
5V
Contrast Adjust
Register Select
Read/Write Select
Enable Signal
Data 0 (Not used in 4 bit operation)
Data 1 (Not used in 4 bit operation)
Data 2 (Not used in 4 bit operation)
Data 3 (Not used in 4 bit operation)
Data 4
Data 5
Data 6
Data 7
LED +
LED 32 | P a g e

Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Lets begin by wiring the power and ground connections. Connect directly to ground one of the
potentiometer outer pins and the LCD pin 1. Connect directly to 5V the other outer potentiometer pin
and LCD pin 2. Lastly connect the center leg of the resistor to the LCD pin 3. Your circuit should look as
shown in the figure below.

If the Arduino is powered on adjust the potentiometer until the first line of boxes is visible, being careful
not to turn the potentiometer past its limit. If the first line of boxes is not visible after adjusting the
potentiometer check the connections to the potentiometer as well as power and ground

33 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Lastly we will connect all the remaining LCD pins, make the following connections:

LCD pin 4 (RS) to Arduino pin 12

LCD pin 6 (Enable) to Arduino pin 11

LCD pins 7-10 (D0-D3) will not be used and have no connection

LCD pin 11 (D4) to Arduino pin 5

LCD pin 12 (D5) to Arduino pin 4

LCD pin 13 (D6) to Arduino pin 3

LCD pin 14 (D7) to Arduino pin 2

LCD pin 5 (R/W) to ground, we will not utilize this pin but it must be grounded for proper
operation

34 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The wiring is now complete and should look similar to the figure below.

35 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

LCD Coding
Begin by opening the Hello World example sketch by selecting File Examples LiquidCrystal
HelloWorld from the Arduino IDE menu.
Compile and upload the code to your Arduino. The LCD should display hello, world! on the first line
and a running count of how long the sketch has been running in seconds.

Read through the code to become familiar with it and think about how you might reutilize this code.

Weather Station
Reutilizing the previous Arduino sketches create a sketch that reads light levels via a photocell,
temperature and humidity via a DHT sensor, and outputs all three to an LCD screen and the serial
monitor approximately every 30 seconds. Additionally output the temperature in Fahrenheit.
The following is one of many possible solutions:
/*
This code is for a small weather station which logs temperature, humidity,
and light levels
Components utilized are a standard Hitachi 16x2 LCD, DHTXX sensor, a 10KO
photocell, 10KO POT,
and 10kO resistor
This code was pieced together for an Arduino UNO but is readily adapted for
other Arduino platforms
The LCD circuit:
* LCD RS pin to digital pin
* LCD Enable pin to digital
* LCD D4 pin to digital pin
* LCD D5 pin to digital pin
* LCD D6 pin to digital pin
* LCD D7 pin to digital pin
* LCD R/W pin to ground
* 10K Potentiometer:
* ends to +5V and ground

12
pin 11
5
4
3
2

36 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

* wiper to LCD VO pin (pin 3)


The DHT circuit:
*
*
*
*

Connect
Connect
Connect
Connect

pin 1
pin 2
pin 4
a 10K

(on the left) of the sensor to +5V


of the sensor to whatever your DHTPIN (8)
(on the right) of the sensor to GROUND
resistor from pin 2 (data) to pin 1 (power) of the sensor

The Photocell circuit: (photocell)


* Connect PHOTOCELL in series with 10K resistor
* Connect PHOTOCELL free end to 5V
* Connect 10k resistor free end to ground
* Connect PHOTOCELL/resistor junction to pin A0
Code pieced together by The Diligent Student 6/17/2013
Components taken from ADAFRUIT DHT Library and Arduino Liquid Crystal
Library
This example code is in the public domain.
*/
#include <LiquidCrystal.h>
#include "DHT.h" // ADAFRUIT DHT or compatible branch library required
// Define Global variables
const int DHTPIN = 8; // Pin the humidity/temp sensor is connected to
const int photocellPin = A0; // Pin the photocell is connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11
// DHT 11
//#define DHTTYPE DHT22
// DHT 22 (AM2302)
//#define DHTTYPE DHT21
// DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE); // Initialize dht with parameters (pin
number,sensor type)
LiquidCrystal lcd(12,11,5,4,3,2);// initialize lcd (RS,EN,D4,D5,D6,D7)
void setup() {
Serial.begin(9600);// Start serial (baud rate)
dht.begin();
// Start DHT
lcd.begin(16, 2); // Start LCD (columns,rows)
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow
sensor)
//Read Sensors
float h = dht.readHumidity();
// Read Humidity data
float t = dht.readTemperature();
// Read temperature data
float t_f = (t*1.8)+32; // Perform simple conversion to Fahrenheit
int lightLevel = analogRead(photocellPin)/10; // Divide by ten for rough
scale of 0-100

37 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

// check if returns are valid, if they are NaN (not a number) then
something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT"); // Something went wrong
lcd.clear(); // Clear lcd screen and set cursor to (0,0)
lcd.print("DHT READ ERROR");
} else {
// Print to serial
Serial.print("Light: ");
Serial.print(lightLevel);
Serial.print(" \t");
// Insert a tab
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
// Insert a tab
Serial.print("Temperature: ");
Serial.print(t_f);
Serial.println(" *F");
// Print to LCD
lcd.clear();
// Clear old data and reset cursor
lcd.print("Light:");
lcd.print(lightLevel);// Write light level to lcd
lcd.print(" RH:");
lcd.print(h);
// Write relative humidity to lcd
lcd.print("%");
lcd.setCursor(0,1);
// Set cursor to first position of second line
(x,y) zero-indexed
lcd.print("T:");
lcd.print(t_f);
// Write temperature in Fahrenheit to lcd
lcd.print("F ");
delay (30000);
// Wait 30 seconds
}
}

38 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The wiring is shown in the following diagram:

39 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

40 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Sample serial output:

Notes:

The light level was divided by 10 for a rough scale of 0-100.

Data Logging
Data logging is a process by which data is sampled and saved for analysis. In this last section we will
modify our code to use the serial monitor as a basic data logging tool. For prolonged data collection this
method is not advised but its principles can be easily implemented with a SD-card shield.
For this method we will require a computer which is configured to not go into a sleep state but turn off
the monitor if necessary. Additionally this method will require Microsoft excel or any other spreadsheet
software capable of creating plots from tab delimited data(ie.octave, open office, libre-office.)There are
many free and open source alternatives to excel which will work.
The configuration will be the same as the example in the previous section but we will alter the format of
the serial output to be easier to import to excel and add a time output.

41 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

The new format is as follows, changes have been highlighted.


/*
This code is for a small weather station which logs temperature, humidity,
and light levels
Components utilized are a standard Hitachi 16x2 LCD, DHTXX sensor, a 10KO
photocell, 10KO POT,
and 10kO resistor
This code was pieced together for an Arduino UNO but is readily adapted for
other Arduino platforms
The LCD circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K Potentiometer:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
The DHT circuit:
*
*
*
*

Connect
Connect
Connect
Connect

pin 1
pin 2
pin 4
a 10K

(on the left) of the sensor to +5V


of the sensor to whatever your DHTPIN (8)
(on the right) of the sensor to GROUND
resistor from pin 2 (data) to pin 1 (power) of the sensor

The Photocell circuit: (photocell)


* Connect PHOTOCELL in series with 10K resistor
* Connect PHOTOCELL free end to 5V
* Connect 10k resistor free end to ground
* Connect PHOTOCELL/resistor junction to pin A0
Code pieced together by The Diligent Student 6/17/2013
Components taken from ADAFRUIT DHT Library and Arduino Liquid Crystal
Library
This example code is in the public domain.
*/
#include <LiquidCrystal.h>
#include "DHT.h" // ADAFRUIT DHT or compatible branch library required
// Define Global variables
const int DHTPIN = 8; // Pin the humidity/temp sensor is connected to
const int photocellPin = A0; // Pin the photocell is connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11
// DHT 11
//#define DHTTYPE DHT22
// DHT 22 (AM2302)

42 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

//#define DHTTYPE DHT21

// DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE); // Initialize dht with parameters (pin


number,sensor type)
LiquidCrystal lcd(12,11,5,4,3,2);// initialize lcd (RS,EN,D4,D5,D6,D7)
void setup() {
Serial.begin(9600);// Start serial (baud rate)
dht.begin();
// Start DHT
lcd.begin(16, 2); // Start LCD (columns,rows)
Serial.println("Time since start (s) \t Light Level \t Relative Humidity
(%) \t Temperature (F)");
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow
sensor)
//Read Sensors
float h = dht.readHumidity();
// Read Humidity data
float t = dht.readTemperature();
// Read temperature data
float t_f = (t*1.8)+32; // Perform simple conversion to Fahrenheit
int lightLevel = analogRead(photocellPin)/10; // Divide by ten for rough
scale of 0-100
// check if returns are valid, if they are NaN (not a number) then
something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT"); // Something went wrong
lcd.clear(); // Clear lcd screen and set cursor to (0,0)
lcd.print("DHT READ ERROR");
} else {
// Print to serial
Serial.print(millis()/1000); // print time since start in seconds
Serial.print(" \t");
// Insert a tab
Serial.print(lightLevel);
Serial.print("\t");
// Insert a tab
Serial.print(h);
Serial.print("\t");
// Insert a tab
Serial.println(t_f);
// Print to LCD
lcd.clear();
// Clear old data and reset cursor
lcd.print("Light:");
lcd.print(lightLevel);// Write light level to lcd
lcd.print(" RH:");
lcd.print(h);
// Write relative humidity to lcd
lcd.print("%");
lcd.setCursor(0,1);
// Set cursor to first position of second line
(x,y) zero-indexed
lcd.print("T:");
lcd.print(t_f);
// Write temperature in Fahrenheit to lcd
lcd.print("F ");

43 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

delay (30000);

// Wait 30 seconds

}
}

The changes include an addition to setup() and modification of the serial print section of code within
loo(). The changes in setup print a single header line of four tab delimited titles; "Time since start (s),
Light Level, Relative Humidity (%) and Temperature (F). The changes to the serial print code in the
loop format each output line to be four tab delimited values consisting of time and our 3 sensor
readings.
To begin data-logging simply upload the sketch and open the serial monitor. Do not close the serial
monitor or the Arduino IDE at any point during data-logging, this will cause total data loss.
Here is a sample serial output, we neednt worry that the data doesnt appear to line up with the titles
as the delimiting factor is the tabs and not spacing.

Click within the center text area of the serial monitor and use the shortcut keys CTRL+A (CMD+A for
Macs) to select all data and then use the shortcut keys CTRL+C A (CMD+C for Macs) to copy all data. The
serial monitor will not respond to right-clicks so the shortcuts keys must be used. Do not close the
terminal or Arduino IDE until the data has been placed into Excel or similar software.

44 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Using Excel or similar software paste the data into the first cell in the upper-left corner.

Select all the data including the headers then select Insert Scatter select an appropriate plot. The
following scatter plot omits the light reading to highlight the inverse relationship between temperature
and humidity.

45 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

90
80
70
60
50

Relative Humidity (%)

40

Temperature (F)

30
20
10
0
0

20000

40000

60000

80000

100000

Simple techniques can be used to further refine the plot such as adding slope lines or dividing the time
column by an appropriate amount to display time in minutes or hours. However for prolonged periods
of data-logging a dedicated data-shield is recommended.

Resources:

http://arduino.cc/en/Tutorial/HomePage
http://arduino.cc/en/Reference/HomePage

Works Cited
Introduction. (2013, June 18). Retrieved from Arduino.cc: http://arduino.cc/en/Guide/Introduction
Libraries. (2013, August 05). Retrieved from Arduino.cc: http://arduino.cc/en/Reference/Libraries

46 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

47 | P a g e
Fab Lab Professional Learning by Active Learning Lab is licensed under a Creative Commons AttributionNonCommercial 4.0 International License.

Das könnte Ihnen auch gefallen