INTRODUCTION to MICRO-CONTROLLERS

Similar documents
INTRODUCTION to MICRO-CONTROLLERS

INTRODUCTION to MICRO-CONTROLLERS

MICROCONTROLLERS BASIC INPUTS and OUTPUTS (I/O)

MICROCONTROLLERS BASIC INPUTS and OUTPUTS (I/O)

EE-110 Introduction to Engineering & Laboratory Experience Saeid Rahimi, Ph.D. Labs Introduction to Arduino

Arduino Lesson 1. Blink. Created by Simon Monk

MAE106 Laboratory Exercises Lab # 1 - Laboratory tools

Lesson 3: Arduino. Goals

INA169 Breakout Board Hookup Guide

J. La Favre Using Arduino with Raspberry Pi February 7, 2018

For this exercise, you will need a partner, an Arduino kit (in the plastic tub), and a laptop with the Arduino programming environment.

Coding with Arduino to operate the prosthetic arm

FABO ACADEMY X ELECTRONIC DESIGN

Module: Arduino as Signal Generator

CPSC 226 Lab Four Spring 2018

Pulse Width Modulation and

Understanding the Arduino to LabVIEW Interface

TWEAK THE ARDUINO LOGO

Computational Crafting with Arduino. Christopher Michaud Marist School ECEP Programs, Georgia Tech

Arduino An Introduction

HAW-Arduino. Sensors and Arduino F. Schubert HAW - Arduino 1

Lab 2: Blinkie Lab. Objectives. Materials. Theory

Programming 2 Servos. Learn to connect and write code to control two servos.

CURIE Academy, Summer 2014 Lab 2: Computer Engineering Software Perspective Sign-Off Sheet

Arduino STEAM Academy Arduino STEM Academy Art without Engineering is dreaming. Engineering without Art is calculating. - Steven K.

LED + Servo 2 devices, 1 Arduino

Portland State University MICROCONTROLLERS

Programming a Servo. Servo. Red Wire. Black Wire. White Wire

Rodni What will yours be?

Getting Started with the micro:bit

Disclaimer. Arduino Hands-On 2 CS5968 / ART4455 9/1/10. ! Many of these slides are mine. ! But, some are stolen from various places on the web

On the front of the board there are a number of components that are pretty visible right off the bat!

1Getting Started SIK BINDER //3

Training Schedule. Robotic System Design using Arduino Platform

.:Twisting:..:Potentiometers:.

Lab 5: Arduino Uno Microcontroller Innovation Fellows Program Bootcamp Prof. Steven S. Saliterman

EGG 101L INTRODUCTION TO ENGINEERING EXPERIENCE

SCHOOL OF TECHNOLOGY AND PUBLIC MANAGEMENT ENGINEERING TECHNOLOGY DEPARTMENT

1. Introduction to Analog I/O

Welcome to Arduino Day 2016

Name & SID 1 : Name & SID 2:

Microcontrollers and Interfacing

Arduino: Sensors for Fun and Non Profit

LESSONS Lesson 1. Microcontrollers and SBCs. The Big Idea: Lesson 1: Microcontrollers and SBCs. Background: What, precisely, is computer science?

Introduction to. An Open-Source Prototyping Platform. Hans-Petter Halvorsen

Objectives: Learn what an Arduino is and what it can do Learn what an LED is and how to use it Be able to wire and program an LED to blink

Lab Exercise 9: Stepper and Servo Motors

APDS-9960 RGB and Gesture Sensor Hookup Guide

Attribution Thank you to Arduino and SparkFun for open source access to reference materials.

Community College of Allegheny County Unit 7 Page #1. Analog to Digital

Lesson 13. The Big Idea: Lesson 13: Infrared Transmitters

Embedded Test System. Design and Implementation of Digital to Analog Converter. TEAM BIG HERO 3 John Sopczynski Karim Shik-Khahil Yanzhe Zhao

You'll create a lamp that turns a light on and off when you touch a piece of conductive material

Application Note. Communication between arduino and IMU Software capturing the data

Tarocco Closed Loop Motor Controller

ISSN: [Singh* et al., 6(6): June, 2017] Impact Factor: 4.116

1 Introduction. 2 Embedded Electronics Primer. 2.1 The Arduino

Light Emitting Diode IV Characterization

Lab 4 Rev. 1 Open Lab Due COB Friday April 6, 2018

ARDUINO / GENUINO. start as professional

EE 314 Spring 2003 Microprocessor Systems

Arduino Microcontroller Processing for Everyone!: Third Edition / Steven F. Barrett

EARTH PEOPLE TECHNOLOGY. EPT-200TMP-TS-U2 Temperature Sensor Docking Board User Manual

Prelab: Introduction and Greenhouse Construction

Internet of Things Student STEM Project Jackson High School. Lesson 2: Arduino and LED

Workshops Elisava Introduction to programming and electronics (Scratch & Arduino)

Industrial Automation Training Academy. Arduino, LabVIEW & PLC Training Programs Duration: 6 Months (180 ~ 240 Hours)

EEC WINTER Instructor: Xiaoguang Leo" Liu. Application Note. Baseband Design. Duyen Tran ID#: Team DMK

MAKEVMA502 BASIC DIY KIT WITH ATMEGA2560 FOR ARDUINO USER MANUAL

ZX Distance and Gesture Sensor Hookup Guide

Community College of Allegheny County Unit 4 Page #1. Timers and PWM Motor Control

PWM CONTROL USING ARDUINO. Learn to Control DC Motor Speed and LED Brightness

Figure 1. Digilent DC Motor

Sweep / Function Generator User Guide

Touch Potentiometer Hookup Guide

CONSTRUCTION GUIDE IR Alarm. Robobox. Level I

Digital-to-Analog Converter. Lab 3 Final Report

PLAN DE FORMACIÓN EN LENGUAS EXTRANJERAS IN-57 Technology for ESO: Contents and Strategies

EVDP610 IXDP610 Digital PWM Controller IC Evaluation Board

GE423 Laboratory Assignment 6 Robot Sensors and Wall-Following

2.017 DESIGN OF ELECTROMECHANICAL ROBOTIC SYSTEMS Fall 2009 Lab 4: Motor Control. October 5, 2009 Dr. Harrison H. Chin

Practical Assignment 1: Arduino interface with Simulink

Demon Pumpkin APPROXIMATE TIME (EXCLUDING PREPARATION WORK): 1 HOUR PREREQUISITES: PART LIST:

Servomotor Control with Arduino Integrated Development Environment. Application Notes. Bingyang Wu Mar 27, Introduction

100UF CAPACITOR POTENTIOMETER SERVO MOTOR MOTOR ARM. MALE HEADER PIN (3 pins) INGREDIENTS

Lecture 6. Interfacing Digital and Analog Devices to Arduino. Intro to Arduino

Arduino Workshop 01. AD32600 Physical Computing Prof. Fabian Winkler Fall 2014

Arduino Platform Capabilities in Multitasking. environment.

OVEN INDUSTRIES, INC. Model 5C7-362

Experiment 1: Robot Moves in 3ft squared makes sound and

URM37 V3.2 Ultrasonic Sensor (SKU:SEN0001)

Arduino Digital Out_QUICK RECAP

ARDUINO / GENUINO. start as professional. short course in a book. faculty of engineering technology

PSoC and Arduino Calculator

Adafruit 16-Channel Servo Driver with Arduino

Arduino Setup & Flexing the ExBow

ME 461 Laboratory #5 Characterization and Control of PMDC Motors

Setup Download the Arduino library (link) for Processing and the Lab 12 sketches (link).

smraza Getting Start Guide Contents Arduino IDE (Integrated Development Environment)... 1 Introduction... 1 Install the Arduino Software (IDE)...

Lab 12 Laboratory 12 Data Acquisition Required Special Equipment: 12.1 Objectives 12.2 Introduction 12.3 A/D basics

Transcription:

PH-315 Portland State University INTRODUCTION to MICRO-CONTROLLERS Bret Comnes and A. La Rosa 1. ABSTRACT This laboratory session pursues getting familiar with the operation of microcontrollers, namely installation of communication with your computer, downloading the proper software, and programming code. An Arduino Leonardo microcontroller (see Fig. 1) will be used to implement simple, still, very instructive tasks. [The examples will require some knowledge of pulse-width-modulation PWM (a widely use technique for converting an analog signal into digital one). A short note on PWM is Attached at the end of this file.] Once familiarized with the microcontroller operation, you will be required to implement a PID controller to automate the response of a fan to the input signal from a thermistor. 2. INTRODUCTION Microcontrollers are small computers designed to go where desktop computers dare not to. They come in all shapes, sizes, and layouts. Usually, they are quite small and use less power than traditional computers. Microcontrollers are often deployed in appliances and serve an unmodifiable dedicated purpose, such as keeping track of what spin cycle your washing machine is on, or how much time is left before it should turn off your microwave oven. Make no mistake, however, these are general purpose computers. Another major difference between a microcontroller and traditional computers is that they come with an array of analog and digital inputs and outputs. These inputs and outputs can be used to read environmental data from sensors, talk to other computers or devices and electronically control other systems which provide environmental outputs such as a LCD screens, mechanical switches or servo motors etc. [13] Getting started with microcontrollers can be a tedious process, as they can require a number of supporting circuits, USB controllers, programmers, boot-loaders and power supplies just to load your first program onto the microcontroller chip. Often times you will start with a prototyping board which puts all of the necessary components in a convenient, ready to use package. 2.1 Arduino Microcontroller and its advantages This lab will be using the single board Arduino Leonardo Microcontroller[2]. It is similar to the Arduino Uno[4], with the major difference being that it uses Surface Mount Technology (SMT)[15] instead of the older thru-hole [16] technology in order to reduce cost. Arduino drastically lowers the difficulty of getting started with a microcontroller (compared to to plain ATMEGA/PIC/ARM chips), as it provides all the necessary tools to start making the microcontroller do interesting things, which would be daunting if staring with just a plain microcontroller chip. Arduino is based around an 8-bit Atmel AVR microcontroller, and has supporting systems like a boot loader for uploading programs, a USB controller as well as a barrel jack for external power. It is programmed using a language that is based off of C++ and uses an integrated development environment (IDE) for writing, compiling and uploading your programs to the board. Many example Arduino projects will rely on programs running on your computer using Processing (an open source programming language), but can interface with any serial enabled programs.[10]

Figure 1: Arduino Leonardo[2] 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.cc[5] 3. GETTING STARTED This lab is based off of the Arduino 1.0.3 software which can be downloaded for free from the Arduino website.[3] Unlike other embedded systems development environments, the Arduino software is quick to download and set up, and has zero cost associated with the software which makes it a convenient to work with when your primary goal is to come up with a working prototype quickly and cheaply. It also has a large community and a massive pool of example programs and libraries compared to other educational prototyping boards. Whatever you do, DO NOT APPLY MORE THAN 5V TO ANY PIN ON THE ARDUINO. It could damage or destroy the microcontroller board. Also, avoid powering directly with the Arduino devices that draw high current. Instead opt for a separate power source and an NPN transistor or something similar. Basically, avoid finding creative ways to break the equipment. 3.1 Find a Computer You are free to use your own laptop or one of the classroom computers. Plug your Arduino into the computer using the micro USB cable. Please be careful with the delicate connectors. You may be prompted to add hardware if you are on windows. If it asks for a driver, tell the windows driver wizard to look inside a folder called drivers inside the Arduino folder. If the computer you are using already has the Arduino software downloaded, look inside that folder usually found in Program Files or wherever you copied it or the shortcut on the desktop leads too. 3.2 Download and Launch the Arduino Software Download the latest Arduino Integrated Development Enviroment (IDE)[3] available at the following site, http://arduino.cc/en/main/software

If you have decided to use your own Arduino, make sure you find the necessary USB drivers if you have a board that is older than the Uno. You may also check around class to see if the Arduino software is available on someone s USB drive. 3.3 Selecting the Board We now need to tell the Ardiono IDE what hardware we will be compiling for. For that purpose, once the IDE is open, navigate to the toolbar and select the Leonardo board, Toolbar Tools Board Arduino Leonardo. If you are using a different board, select the one you have from this list instead. This step may vary from system to system as well, but pick the option most similar to this write up. 3.4 Selecting a Serial Port This step varies from system to system. In this step, we tell the computer which serial port the Arduino chip can be reached at, for programing the board, as well as talking to it during runtime. Figure 2: Port Selection in Windows and OS X 3.4.1 Windows Select Toolbar Tools Serial Port COM5 where COM5 is the serial port that has been assigned to your Arduino by windows. You may have more than one port in the list. To know which port is associated with the Arduino, you can check the list with the Arduino unplugged, and check it again with it plugged in, and the port that appears after is your Arduino. 3.4.2 OS X Usually the Arduino is the first item in the Serial Port list. Another way to tell is that it has tty in the name and does not have the world bluetooth in it. 3.5 Uploading your first program Next we will open an example program, verify that it compiles, and then upload it to your board.

Compiling your program lets the compiler check your work for syntax and structure errors. Navigate to Toolbar File Examples 01. Basics Blink. The program shown in Fig. 4 will appear in your screen. Press the verify button (top-left side of the screen). It should compile the sketch and return a Done compiling message; see Figure 3. If you get an error, something went wrong. Figure 3: Verify and Compile Button (Left). Compile Success Message (Right). Once the compiling is completed, go ahead and upload the program to the micro-controller board by pressing the upload button (located right next to verify button), which should provide a similar completion message after a few seconds. The LEDs on the Arduino will blink during the upload, but should settle down after a few seconds. Your program is now on the Arduino and running in a loop sequence. Once the program you uploaded is running, the tiny LED labeled L on your Arduino should be slowly blinking in response to the uploaded Blink program. This LED labeled L is wired to Pin 13 on the Arduino, a digital pin with a resistor built in that so that LEDs can be connected directly between that pin and ground. Go ahead and connect an LED between Pin 13 and GND. It should blink at the same rate as the L LED on the board. Congratulations! You now have a working Arduino that is talking to the Arduino IDE. 4. Programming Arduino Arduino is based off the Processing[10] programming language, and has some similarities to C, however much of the language has been simplified from C. In this section we will go over the basics of the language, look at some simple examples of code, and even write some of our own. 4.1 The Bare Minimum The bare minimum code you need for an Arduino program is presented in Figure 4. 1 void setup() { 2 // put your setup code here, to run once: 3 } 4 void loop() { 5 // put your main code here, to run repeatedly: 6 } Figure 4: The minimum amount of code for an Arduino Program There are two parts to this minimum program, the void setup() {} section and

the void loop() {} section. When your program runs, it starts executing your code, line by line, starting in the void setup() section, inside the brackets, {}, that follow. Your program will execute any code that is in this section, and when it gets to the end, will begin executing the code inside void loop() {}, until it gets to the end of the available instructions, at which point, the program starts back over in at the beginning of void loop() {}, retaining any variables or settings from prior lines of code. Let s look at a simple example that you should already have pulled up, the Blink program, which is found in Figure 5. If you still need to open this, refer to Section 2.5. 5. Understanding the Blink Program 1 /* 2 Blink 3 Turns on an LED on for one second, then off for one second, repeatedly. 4 5 This example code is in the public domain. 6 */ 7 8 // Pin 13 has an LED connected on most Arduino boards. 9 // give it a name: 10 int led = 13; 11 12 // the setup routine runs once when you press reset: 13 void setup() { 14 // initialize the digital pin as an output. 15 pinmode(led, OUTPUT); 16 } 17 18 // the loop routine runs over and over again forever: 19 void loop() { 20 digitalwrite(led, HIGH); // turn the LED on (HIGH is the voltage level) 21 delay(1000); // wait for a second 22 digitalwrite(led, LOW); // turn the LED off by making the voltage LOW 23 delay(1000); // wait for a second 24 } Figure 5: The Blink Program in all its glory 5.1 Comments If a block of text is wrapped in /* */ (such as lines 1 thru 6 in Figure 5), or has a // in front of it on one line (such as line 12), it means that the content iss a comment. Comments are little notes you leave in your code. They are not executed or interpreted by your program in any way. It is good practice to add comments to your code. They can help you think about your program, and will also remind you, and others that see your code, what the program does or how it works. Running down lines 1-9, we see a block of comments describing the function of the program, how it works, as well as the license. The first piece of code we see is on line 10. 5.2 Variables

int led = 13; The first thing to notice is that this code is not inside void setup() or void loop(). That is because it is a variable and variables can be declared in the beginning of our program outside either loop. Variables are incredibly useful tools. Variables store information that can be used later in the program as many times as you need. They can be updated during run-time and can be used to store values temporarily for repeated use. Any variable we decide to use has to be declared. Variables are declared before your void setup() or void loop() sections. (As far as we are concerned right now) Line 10 declares a variable named led; gives it a variable type of int, for integer; and then assigns it a value of 13. This variable is used to reference the physical pin we will be using in our program. It is used as an abstraction layer, so that if we ever go back and change which pin we want to use, we can update all the places in our program that reference this pin number simply by updating the initial variable value. The basic syntax of a variable declaration is: type variable_name = value; The available variable types can be found on the Arduino website.[8] Please reference that list if you want to use values other than integers. 5.3 Pin Modes The next piece of code we arrive at is our void setup(). Stepping inside the curly braces of this structure, we come to the following line: pinmode(led, OUTPUT); Digital pins can either read or write digital signals (0 or 5V ). Before you do either, you must tell your program what you will be using the digital pin for. This tells our program that the pin associated with the led variable will be a Digital output. pinmode([pin-number], [PIN-TYPE]); Available pin modes can be found a the Arduino website.[7] Each pin has a name assigned to it. Each pin on the Arduino has its name printed next to it, which can be seen in Figure 1. There are two primary types of pins: Digital and Analog. Digital pins simply have a number for a name, and analog pins have the letter A followed by a number for a name. Digital pins can read or write digital signals varying from either 0 or 5v. Some can also output PWM signals, a way to emulate analog voltage signals with a digital pin PWM capable digital pins have a printed next to their name on the board. See Section 6.1 for more information. Analog Pins can read in analog voltages between 0v and 5v and converts them to a value that your program can use between 0 and 1023. They do not need a pin mode set before reading within your program. 5.4 Generating Output Once the pin mode is set, we exit our void setup() and enter our void loop(), the part of the program that will run over and over in an infinite loop. The first thing we do is execute:

digitalwrite(led, HIGH); digitalwrite([pin], [VALUE]) lets us set the output value of a digital pin that has been set to an OUTPUT type. In this case, we write a value of HIGH, or 5V, to the pin referred to by the led variable. A value of HIGH would refer to 0v. The next part of the program tells the Arduino to wait for a period, before executing the next line of code. This period is equal to 1000ms, or 1 second. delay(1000); After waiting for a second, we then write a value of LOW to our led pin, and then wait 1 more second. digitalwrite(led, LOW); delay(1000); At this point, there is no more code left in our program, so it starts executing void loop() again. Congratulations, you now should have some basic understanding of how an Arduino program is written. 6 Modifying the Blink Program Now you will try your hand at modifying the blink program. What we are going to do is define a new variable called wait, give it a value, and then replace the delay time on the Arduino with our new variable. 6.0.1 Create a new variable Right below the led variable declaration, add a new variable named wait of type int and give it a reasonable value different than 1000 (like 100). Also, add a comment describing what this variable is used for. 6.0.2 Use your new variable We want to use this new variable to declare the time we wait in between turning our LED on and off. Go ahead and replace the old delay values with your new variable name. 6.0.3 Verify and Upload your modified program The Arduino should still be set up from when you first uploaded the first blink program. Verify your new program to see if it compiles. If you get an error, check your work for syntax error. Did you forget a semicolon or a brace? Once your program verifies, and you are able to upload it to your board, you should start to see your LED blink faster or slower, depending on the value you defined your variable. 1 int led = 13; 2 int wait = 100; // Time to wait before blinking 3 4 void setup() { 5 pinmode(led, OUTPUT); 6 } 7

8 void loop() { 9 digitalwrite(led, HIGH); 10 delay(wait); //Wait for the ammount declaired in the wait variable 11 digitalwrite(led, LOW); 12 delay(wait); //Wait for the ammount declaired in the wait variable 13 } Figure 6: The modified Blink Program 6.0.4 Final modification Once you make your modification, you will have code that looks similar to Figure 6. 7 Using Inputs to Control Outputs 7.1 Understanding PWM Arduino cannot output true analog signals. It can, however, generate Pulse Width Modulation (PWM) signals, which are similar to analog signals and can sometimes work interchangeably. Pulse-width modulation uses a rectangular pulse wave whose pulse width is modulated resulting in the variation of the average value of the waveform Wikipedia[12] Basically, if driving an LED with a PWM signal, you are able to vary the brightness of the LED by having it blink really fast while varying the duration of each blink, resulting a brighter or dimmer output. The result is that you can generate signals with similar properties as analog signals using pins only capable of switching between 0 and 5v. 7.1.1 Observing PWM Load the 01.Basic Fade example program and upload it to your Arduino Board, and wire up the LED to the pin that is used in the program (this requires reading the program). If it is a digital pin other than pin 13, you will need to add a 330Ω resistor in series with the LED. If you increase the delay time to 80, you should be able to observe the PWM flicker at lower brightness levels. Hook up your function generator to observe PWM output. You can leave the LED in place. Observe what the signal looks like on your oscilloscope. 7.2 Controlling output with a Potentiometer Now we will control the amplitude of the PWM signal by reading the voltage from a potentiometer being read in on analog input A0.

Figure 7: Potentiometer and LED wired up to the Arduino Hook up a 10k potentiometer between the 5v and ground and middle leg to the A0 analog input on your Arduino as seen in Figure 7. Modify your Fade code from Section 6.1.1 to the code in Figure 8. 7.2.1 Understanding the changes to Fade We declared a few new variables to keep track of an analog input pin and variables used for storing values from our analog input readings and our PWM output values. See the comments in the code for more context. We also used the Serial.begin(9600); line in our void setup() loop to tell the Arduino that we want to open a serial communication session with our computer (remember how we picked a serial port in Section 2.4?). Outputting data to the serial line is a nice way to see what is going on in your code while it is running, but remember that your program will run no faster than the speed of your serial line. The next new piece of code is analogread(pot);. This does what it sounds like. It reads the 0-5v input on pin pot and converts it to a value between 0 and 1023. We can only output PWM values analogous to 0 and 5v by writing a value between 0 and 255 to our led pin. Lucky we have a useful command called map () which handles the analog input range to PWM output range conversion for us. Its syntax is map (valuetoscale, fromlow, fromhigh, tolow, tohigh) See the map info page for more details.[6] Next we write the adjusted input value to our led pin using analogwrite(led, outputvalue);. Finally we print these input and output values the the serial line using the Serial.print(value); command. Open the serial monitor now to view these values in real time. Go to Tools

Serial Monitor. You should see the input and output values similar to Figure 9. 9

1 const int led = 9; // the pin that the LED is attached to 2 const int pot = A0; // A0 will be the analog input channel 3 int sensorvalue = 0; // this will store the value read from the pot 4 int outputvalue = 0; // this is the value sent to our pwm pin 5 6 void setup() { 7 pinmode(led, OUTPUT); // declare pin 9 to be an output 8 Serial.begin(9600); // Open a serial monitor at 9600 baud 9 } 10 void loop() { 11 sensorvalue = analogread(pot); // store pot value in sensorvalue 12 outputvalue = map(sensorvalue, 0, 1023, 0, 255); // map sensorvalue to correct range 13 analogwrite(led, outputvalue); // write the analog out value to led: 14 15 Serial.print("sensor = " ); // print the results to the serial monitor: 16 Serial.print(sensorValue); 17 Serial.print("\t output = "); 18 Serial.println(outputValue); 19 20 delay(2); // wait 2 milliseconds for daq to settle 21 } Figure 8: The Fade program modified to control the LED with a Potentiometer Figure 9: The serial monitor in action 10

7.3 Photo Resistor Remove the potentiometer and wire in a photo-resistor as seen in Figure 10. A photo-resistor has a variable resistance depending on how much light is hitting it. Figure 10: Photo-resistor wired to A0 Using the same code as in Section 6.2, observe the output of the photo resistor and the PWM output on pin 9 simultaneously on your oscilloscope. Vary the amount of light hitting the photo-resistor and observe and compare the PWM output and analog voltage across the photo-resistor. 7.4 Arduino Thermostat We will now use a TMP36 temperature sensor as an analog input to read in temperature data, and control an LED to indicate we have reached a particular temperature. The TMP36 provides an accurate, linear representation of temperature between the range of 40 C and 125 C using the factor of 10 mv C.[11] See the data sheet for more info.[1] Hook up the circuit in Figure 11. For our code, we will be reading the potentiometer as an analog input and use its position as our threshold value. We will compare this threshold value to the current temperature, and if the temperature is above the threshold, the LED will turn on, and if it is below, it will turn off. We will also be monitoring the values using the serial monitor so we can tell what is going on. See if you can write this program on your own, or look at Figure 12. 7.4.1 Testing the Thermostat Upload your program and open the the serial monitor. You should see a value from your TMP36 as well as your potentiometer and the state of the LED. Adjust the pot to where the LED turns on, with the threshold below the temperature value. Also try setting the threshold above the current temperature and confirming the LED turns off. Now, set the threshold a few integer values above the current temperature value. Pinch the temperature sensor with your fingers to increase its temperature and confirm that it turns on. 11

Figure 11: Circuit for Subsection 6.4 and TMP36 Pinout You now have a working temperature sensor controlling hardware. You could write a program on your computer to log the incoming data. You could hook up a fan using an NPM resistor (since the Arduino cannot provide enough current to motors typically) and turn on a fan if it gets to hot in here. You could also have the Arduino calculate the actual temperature using the TMP36 characteristics described in the beginning of Section 6.4 and print a more realistic value to the serial monitor. 8 Communicating With other Devices The last thing we shall attempt is having the Arduino communicate with an external program running on our computer. For this we will utilize processing, since it integrates well with Arduino and has a similar code syntax, but you could do this using any programming language you wanted such as Python or LabVIEW. While we have already talked to the Arduino using our computer and the handy serial monitor, here we will write a program the interfaces with the Arduino directly over the serial line. 8.1 Sending Data to an External Program This example is based off of the Graph example program found in File Examples 04. Communication Graph. We can use the same circuit as above, as all we are doing is sending the potentiometer signal out of the serial line again. Go ahead and upload this program to your Arduino and make sure it runs by watching the serial bus. Launch a program called Processing along side your Arduino IDE. It looks basically the same as the Arduino editor but is a different color. Enter the code from the comment in the Arduino Graph program into a new Processing sketch, remove the comment wrapper and make sure it compiles. If you did everything right, when you launch the Processing sketch, it should start plotting the value being read in from the potentiometer value. You may have to futz around with the serial port selection on the processing sketch. Now is your chance to troubleshoot! 12

1 const int threshold = A0; // threshold set with 10k pot 2 const int temp = A1; // TMP36 Temp sensor 3 const int led = 9; //LED Pin 4 5 int thresholdvalue = 0; // value used to store threshold value from the pot 6 int tempvalue = 0; // value used to store temp read from the temp sensor 7 boolean ledstate = false; // value used to write the led state 8 9 void setup() { 10 digitalwrite(led, ledstate); 11 Serial.begin(9600); 12 } 13 14 void loop() { 15 // read the pot value and map it to the right scale 16 thresholdvalue = map(analogread(threshold),0,1023,0,255); 17 tempvalue = analogread(temp); // read the temp 18 19 if (tempvalue > thresholdvalue) { 20 ledstate = true; //if temp > threshold, turn on LED 21 } 22 else { 23 ledstate = false; //if temp < threshold, turn off LED 24 } 25 digitalwrite(led,ledstate); // This writes the state determined above 26 27 // print the results to the serial monitor: 28 Serial.print("thresholdValue = " ); 29 Serial.print(thresholdValue); 30 Serial.print("\t tempvalue = "); 31 Serial.print(tempValue); 32 Serial.print("\t LED on?: "); 33 Serial.println(ledState); 34 35 delay(2); //Small settle delay for ADC 36 } Figure 12: Arduino Thermostat Program 13

8.2 Sending commands Arduino Externally In this example, we will be exploring two new concepts: the case structure as well as setting up the Arduino to respond to messages sent to it by a computer over the serial port. Note that these messages could conceivably come from any other device or program that can talk over a serial line. We will be able to send a command over the serial monitor and turn a specific LED on or off. 8.2.1 Wire up some LEDs Wire up two LEDs to two separate digital pin channels as see in Figure 13. Figure 13: Schematic for Serial switch program 8.2.2 The Serial Switch code Either type or copy in the following program. The code can be found at https://github.com/ bcomnes/315-lab-microcontroller/blob/master/code/serial_switch/serial_switch.ino. 1 const int led1 = 9; 2 const int led2 = 10; 3 4 boolean led1state = false; //Value used to store the state of LED1 5 boolean led2state = false; //Value used to store the state of LED2 6 7 void setup() { 8 // initialize serial communication: 9 Serial.begin(9600); //Start a serial session 14

10 pinmode(led1, OUTPUT); //set led1 and 2 pins as outputs 11 pinmode(led2, OUTPUT); 12 digitalwrite(led1, led1state); //Turn off both LEDs 13 digitalwrite(led2, led2state); 14 } 15 void loop() { 16 //Check to see if any incoming commands have been recived 17 if (Serial.available() > 0) { 18 int inint = Serial.read(); //Read what command it is 19 switch (inint) { //Decide what to do with the command 20 case 1: // If we get a 1 over serial 21 if (led1state == false) { //and led1 is off 22 led1state = true; //set its state to on 23 Serial.println("LED1 ON"); //and let us know 24 } 25 else { 26 led1state = false; //or if led1 is on turn it off 27 Serial.println("LED1 OFF"); //tell is that its turning off 28 } 29 digitalwrite(led1, led1state); //and update its actual state 30 break; //end case 1 31 case 2: //if we get an incoming 2 32 if (led2state == false) { //and if led2 is off 33 led2state = true; //set its state to on 34 Serial.println("LED2 ON"); // let us know 35 } 36 else { //or if its already on 37 led2state = false; //set its state to off 38 Serial.println("LED1 OFF"); //and let us know 39 } 40 digitalwrite(led2, led2state); //update its actual state 41 break; // end case 2 42 case 0: //if someone sends us a 0 43 led1state = false; //turn off both leds 44 led2state = false; 45 digitalwrite(led1, led1state); 46 digitalwrite(led2, led2state); 47 Serial.println("LEDS OFF"); //and let us know 48 break; //end case 0 49 default: 50 Serial.println(Serial.read()); //if we get something else just print it 51 } 52 } 53 } 8.3 Running the switch Verify that it compiles and upload the program to your Arduiono. Open the serial monitor and type in 1 and press send. LED 1 should turn on. Try sending 2 now. Now send 0. You Arduino is now responding to input during runtime! 15

APPENDIX Pulse-width Modulation Use the op amp LM358AP to compare two input volages: a) the sensor voltage, and b) a sawthooth voltage of constant frequency (try 100 Hz). We will mimic the sensor voltage by providing a manually-variable voltage (0 to 5 V range.) Notice in Fig.1 that a ground terminal replaces V CC. Monitor in the oscilloscope both, the sawtooth input voltage (channel 1) and the output voltage (channel 2.) Figure 3 show the expected signal corresponding to two different sensor voltages. Verify if your set up works as expected. Voltage comparator V C 5 Volts sawtooth (100 Hz) +12V - + A V out Sensor V sensor voltage LM358AP Fig. 1 Left: Comparator circuit. Right: Pin connections of the LM358AP. Notice that a ground terminal replaces V CC. V C (Volts) V max 4 3 2 1 V sensor V C (t) V max 4 3 2 1 V sensor T 0 2T 0 time T 0 2T 0 time V out V out V CC V CC T high T high T 0 2T 0 t(ms) T 0 2T 0 t(ms) Fig. 2 Left: Signals corresponding to a relatively low V sensor. Right: Signals corresponding to a higher V sensor signal. In both figures, T high stands for the interval of time during which the output voltage stays in the high digital level. Notice the higher the sensor-voltage V sensor, the longer the time T high the output voltage stays in the high level. To is the period of the sawtooth signal Vc.

V Notice in Fig. 3 that T max 0 V T sensor high. That is, T T 0 high V sensor Vmax where T high is the time the output voltage remain the high level. T 0 is the period of the sawtooth input signal The pulse-width modulator then convert the analog voltage sensor to an output that is digital in nature (high or low); the time during which the output is high is proportional to the voltage sensor. Implementation: a) Use the op amp LM358AP to implement the comparator circuit shown in Fig.1. Initially, use a sawtooth voltage of 100 Hz b) Verify that the circuit works as advertised in Fig.2 c) Increase gradually the frequency of the sawtooth signal, and estimate the bandwidth of the device. References [1] Tmp35/tmp36/tmp37 low voltage temperature sensors. http://dlnmh9ip6v2uc. cloudfront.net/datasheets/sensors/temp/tmp35_36_37.pdf. [2] Arduino.cc. Arduino leonardo. http://arduino.cc/en/main/arduinoboardleonardo, 2013. [3] Arduino.cc. Arduino software download. http://arduino.cc/en/main/software, 2013. [4] Arduino.cc. Arduino uno. http://arduino.cc/en/main/arduinoboarduno, 2013. [5] Arduino.cc. Introduction. http://arduino.cc/en/guide/introduction, 2013. [6] Arduino.cc. map(). http://arduino.cc/en/reference/map, 2013. [7] Arduino.cc. Pinmode(). http://arduino.cc/en/reference/pinmode, 2013. [8] Arduino.cc. Reference page. http://arduino.cc/en/reference/homepage, 2013. [9] Marshal Colville. Process control with a microcontroller pwm output, pid control, and hardware implementation. 2012. [10] processing.org. Processing programming language. http://processing.org/, 2013. [11] SparkFun. Tmp36 - temperature sensor. https://www.sparkfun.com/products/10988,

2013. [12] Wikipedia. Pulse-width modulation. http://en.wikipedia.org/wiki/pulse-width_ modulation, 2013. [13] Wikipedia. Microcontroller. http://en.wikipedia.org/wiki/microcontroller, 2013. [14] Wikipedia. Pid controller. http://en.wikipedia.org/wiki/pid_controller, 2013. [15] Wikipedia. Surface-mount technology. http://en.wikipedia.org/wiki/surface-mount_ technology, 2013. [16] Wikipedia. Through-hole technology. http://en.wikipedia.org/wiki/through-hole_ technology, 2013. 16