MICROCONTROLLERS BASIC INPUTS and OUTPUTS (I/O)

Similar documents
MICROCONTROLLERS BASIC INPUTS and OUTPUTS (I/O)

INTRODUCTION to MICRO-CONTROLLERS

INTRODUCTION to MICRO-CONTROLLERS

INTRODUCTION to MICRO-CONTROLLERS

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

Arduino Lesson 1. Blink. Created by Simon Monk

Module: Arduino as Signal Generator

Lesson 3: Arduino. Goals

Coding with Arduino to operate the prosthetic arm

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

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

MAE106 Laboratory Exercises Lab # 1 - Laboratory tools

Lab 2: Blinkie Lab. Objectives. Materials. Theory

FABO ACADEMY X ELECTRONIC DESIGN

CPSC 226 Lab Four Spring 2018

Understanding the Arduino to LabVIEW Interface

Rodni What will yours be?

Welcome to Arduino Day 2016

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

Portland State University MICROCONTROLLERS

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

Sten-Bot Robot Kit Stensat Group LLC, Copyright 2013

Pulse Width Modulation and

TWEAK THE ARDUINO LOGO

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

Arduino: Sensors for Fun and Non Profit

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

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

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

INA169 Breakout Board Hookup Guide

1. Introduction to Analog I/O

Training Schedule. Robotic System Design using Arduino Platform

.:Twisting:..:Potentiometers:.

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

LED + Servo 2 devices, 1 Arduino

Arduino An Introduction

Application Note AN 102: Arduino I2C Interface to K 30 Sensor

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

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

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

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

1Getting Started SIK BINDER //3

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

MAKEVMA502 BASIC DIY KIT WITH ATMEGA2560 FOR ARDUINO USER MANUAL

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

Sten BOT Robot Kit 1 Stensat Group LLC, Copyright 2016

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

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

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

Microcontrollers and Interfacing

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

Application Note AN 157: Arduino UART Interface to TelAire T6613 CO2 Sensor

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

APDS-9960 RGB and Gesture Sensor Hookup Guide

ARDUINO / GENUINO. start as professional

Arduino

Practical Assignment 1: Arduino interface with Simulink

CONSTRUCTION GUIDE Capacitor, Transistor & Motorbike. Robobox. Level VII

EGG 101L INTRODUCTION TO ENGINEERING EXPERIENCE

MICROCONTROLLERS Stepper motor control with Sequential Logic Circuits

micro:bit Basics The basic programming interface, utilizes Block Programming and Javascript2. It can be found at

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

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

Touch Potentiometer Hookup Guide

Getting Started with the micro:bit

Arduino Setup & Flexing the ExBow

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

Light Emitting Diode IV Characterization

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

Lab Exercise 9: Stepper and Servo Motors

ZX Distance and Gesture Sensor Hookup Guide

Arduino Platform Capabilities in Multitasking. environment.

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

EVDP610 IXDP610 Digital PWM Controller IC Evaluation Board

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

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

Tarocco Closed Loop Motor Controller

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

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

Lecture 4: Basic Electronics. Lecture 4 Brief Introduction to Electronics and the Arduino

SCHOOL OF TECHNOLOGY AND PUBLIC MANAGEMENT ENGINEERING TECHNOLOGY DEPARTMENT

CONSTRUCTION GUIDE Light Robot. Robobox. Level VI

Blink. EE 285 Arduino 1

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

Adafruit 16-Channel Servo Driver with Arduino

CONSTRUCTION GUIDE Robotic Arm. Robobox. Level II

CONSTRUCTION GUIDE IR Alarm. Robobox. Level I

Name & SID 1 : Name & SID 2:

DFRduino Romeo All in one Controller V1.1(SKU:DFR0004)

ME 2110 Controller Box Manual. Version 2.3

SC16A SERVO CONTROLLER

MD04-24Volt 20Amp H Bridge Motor Drive

Veyron Servo Driver (24 Channel) (SKU:DRI0029)

Milli Developer Kit Reference Application Published on Silver Spring Networks STAGE (

Endurance R/C Wi-Fi Servo Controller 2 Instructions

Assignments from last week

Exercise 5: PWM and Control Theory

EE 314 Spring 2003 Microprocessor Systems

COMBINATIONAL and SEQUENTIAL LOGIC CIRCUITS Hardware implementation and software design

Lesson 2 Bluetooth Car

Transcription:

PH-315 Portland State University MICROCONTROLLERS BASIC INPUTS and OUTPUTS (I/O) ABSTRACT A microcontroller is an integrated circuit containing a processor and programmable read-only memory, 1 which is widely used as an interface between hardware and software systems. We will use the Arduino microcontroller. 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. 2 This laboratory session pursues obtaining familiarity with the Arduino microcontroller operation, namely installation of communication with your computer, downloading the proper software and programming code, and gaining familiarity with the Arduino boards to implement basic I/O tasks. 1. INTRODUCTION About the board. Microcontrollers are small computers designed to do real time controls. A microcontroller is essentially a small programmable computer contained on a single integrated circuit, consisting of a processor, read-only memory (ROM) used to store the program instructions, and a set of input and output pins which can be used to interact with an external circuit. The microcontroller IC is a digital device and, since the processor operates on transistor to transistor logic (TTL), only two logic states are acceptable: HIGH (~ +5 V) and LOW (~ 0 V). The microcontrollers 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, microcontrollers are general purpose computers. A 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. 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 that puts all of the necessary components in a convenient and ready to use package. 1

Arduino Microcontroller and its advantages This lab will be using the single board Arduino Leonardo Microcontroller. 3 It is similar to the Arduino Uno, 4 with the major difference being that the latter uses Surface Mount Technology (SMT) 5 instead of the older thru-hole 6 technology. The Arduino drastically lowers the difficulty of getting started with a microcontroller (compared to plain ATMEGA/PIC/ARM chips), as it provides all the necessary tools for making the microcontroller do interesting things, which would be daunting if staring with just a plain microcontroller chip. The 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++. It uses an integrated development environment (IDE) for writing, compiling and uploading your programs to the board. Figure 1. The Arduino Leonardo Microcontroller. 2 2. GETTING STARTED. How to talk to the board This lab is based off of the Arduino software, which can be downloaded for free from the Arduino website. 7 Unlike other embedded systems development environments 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 the primary goal is to come up with a working 2

prototype quickly and cheaply. There is a large community of Arduino users and there exists 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. Otherwise it will damage or destroy the microcontroller board. Also, avoid using the Arduino to power directly devices that draw high current. Instead opt for a separate power source and an NPN transistor, or something similar. Find a Computer You are free to use one of the classroom computers or your own laptop. Plug your Arduino into the computer using the micro USB cable. Please be careful with the delicate connectors. A. Download and Launch the Arduino Software Download the latest Arduino Integrated Development Environment (IDE) 7 available at the following site, http://arduino.cc/en/main/software The downloading process may take a few minutes. Then go to the downloads folder in your computer (typically located in the favorites section). Identify with your mouse the Arduino application file, and enter a left-click. After a few minutes, the monitor screen should pop-up the following message: Do you want to allow this program making change in your computer? Proceed accordingly. (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.) B. Selecting the Board The Arduino application software is now installed in your computer. It should be available from the Start menu (lower left corner) of your computer Click on the Arduino application to launch the Arduino Integrated Development Environment (IDE). It is time now to tell the Arduino IDE what particular Arduino board we will be using (i.e. to tell the IDE what hardware it will be compiling). 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. 3

NOTE: For Mac computers, it may be necessary to move the Arduino.exe program into the apps folder for it to run properly. C. Selecting a Serial Port This step varies from system to system. This step is to tell the computer which serial port the Arduino chip can be reached at, for both programing the board as well as talking to it during runtime. Figure 2: Port selection in Windows and OS X. C.1 Windows Select Toolbar Tools Serial Port COM5 where COM5 is the serial port that has been assigned to your Arduino by windows. (The computer may have assigned another port number to your Arduino, like COM4, for example; check it out). 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. The extra port that appears in the list is the Arduino s port. C.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. 4

NOTE: Sometimes, even if the port selection has been set through the Arduino program (as described above), the actual selection may not happen. It may be necessary then to specify the serial port though the following sequence: Left-click the Start button; right click on Computer, select Properties >> Leftclick on Device Manager >> Ports If you had Windows 10 operating system: Right click on the windows icon (bottom left corner of your screen >> Device Manager >> Universal Serial Bus Controller 3. PROGRAMMING the ARDUINO A. Compiling and uploading your first program. Example program: The Blink program We have chosen the blink program available in the Arduino library. For that purpose, navigate to, Toolbar File Examples 01. Basics Blink The program shown in Fig. 5 will appear in your screen. We proceed next to verify that it compiles, and then to upload it to your microcontroller board. A.1 Compiling your program lets the compiler check the program for syntax and structure errors. Press the verify button (the one displaying a check out mark), located at the top-left side of the screen (see Fig. 3). It will take a few minutes to compile the sketch and then to return the Done compiling message (see Figure 3). If you get an error, something went wrong. Fig 3. Left: The Verify and Upload buttons. Right: Successful-compile message. A.2 Once the compiling process is completed, go ahead and upload the program to the micro-controller board by pressing the upload button (located right next to the verify button). This process 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. 5

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. The LED labeled L is wired to Pin 13 on the Arduino; this is a digital pin with a resistor built in so that an LED 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. B. Actual code Arduino is based off Processing, 8,9 an open source programming language that 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. Figure 4 shows the bare minimum code you need for an Arduino program. 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 } Fig. 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 with the void setup() section; your program will execute any code that is inside the brackets, {}. Next, it will start executing the code inside the void loop() {}, until it gets to the end of the available instructions, at which point, the program starts back over 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. C. UNDERSTANDING the Blink Program 1 /* 2 Blink 6

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 // Pin 13 has an LED connected on most Arduino boards. 8 // Let s give it a name, led for example: 9 // Variables have to be declared at the beginning of the program, outside either loop 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(2000); // wait for two seconds 24 } Figure 5: The Blink Program in all its glory. C.1 Comments If a block of text is wrapped inside the symbols, /* */ (such as lines 1 thru 6 in Figure 5), or if a command line has the symbol, // in front of it (such as line 12), it means that the content is 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. 7

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. C.2 Variables int led = 13; First, notice that this code is not inside the void setup() nor the void loop(). That is because it is a variable and variables have to be declared at 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 at the beginning of the program. That is, variables are declared before your void setup() or void loop() sections. Line 10 declares a variable named led; it also declares it as an integer variable int; and then assigns the number 13 to that variable. This variable is used to reference the physical pin that 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; Example: int led = 13; The available variable types can be found on the Arduino website. 10 Please reference that list if you want to use values other than integers. C.3 Pin Modes The next piece of code in our program is void setup(). Stepping inside the curly braces of this structure, we come to the following line: pinmode(led, OUTPUT); Each pin on the Arduino has a name assigned to it. The name is printed next to the corresponding pin on the microcontroller board (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. C.3.1 Defining digital pins as output/input Digital pins can be either inputs or outputs Digital pins can either read or write digital signals (0 or 5V). 8

Before you do either, you must tell your program what you will be using the digital pin for. The command pinmode( led, OUTPUT); tells our program that the pin associated with the led variable will be a digital output. The general command to define the pin type is as follows: pinmode( [PIN-NUMBER], [PIN-TYPE]); Example to define the digital-pin led as an output: pinmode( led, OUTPUT); C.3.2 PWM digital signals Some digital pins can also output pulse-width-modulation (PWM) signals, which are square signals with different duty cycle). This is a way to produce a similar effect (when the pin is used to drive the illumination of an LED, for example) of an analog voltage. Digital pins with PWM capability have a tilt-symbol printed next to their name on the board. Digital mode pins produce outputs at either the high or low digital voltage level as expected. However, many external circuit components may require analog average voltage values. PWM is one way to produce output digital voltages whose net effect is similar to analog voltages in the range of 0 5 V. This is accomplished by outputting a periodic pulse signal, but with variable duration of the high and low voltage levels. When looking at the RMS value of this periodic signal of different duty cycle: i) Shortening the duration of the high-level (5V) will lower the RMS voltage (up to the point that when the HIGH pulse width is 0 seconds then its effect is that of a 0 V). ii) By increasing the duration of the high-level (5V) will raise the RMS voltage, (up to the point that when the LOW pulse width is 0 s, then the output is just 5 V). This has the net effect of simulating a continuous DC voltage range, using only digital voltages. The pin value still must be assigned (via the microcontroller software) in discrete steps between 0 and 255, giving possible output voltages that differ by steps of, V = 5V/ 255 (Recall the Arduino is based on an 8-bit Atmel AVR microcontroller; hence there are 2 8 = 256 values in base-2 available.) More about PWM output later. C.3.3 Analog pins Analog Pins can read in analog voltages between 0V and 5V, The Arduino has inside a 10-bit analog-to-digital converter circuit (2 10 = 1024) that reads this voltage and converts it to a single 10-bit value (a number between 0 and 1023). Here 0 represents 0V, and 1024 represents 5 V. This 10-bit value is what the software sees as the input on that pin. 9

The discrete values of the input and output pins are a limitation of the microcontroller when working with external systems that expect continuous values, such as LED and photoresistors. Analog pins do not need a pin mode set before reading within your program. Available pin modes can be found at the Arduino website. 11 C.4 Generating an output Once the pin mode is set, the program exit the void setup() and enters the void loop(), the part of the program that will run over and over in an infinite loop. The first command to execute is, digitalwrite( led, HIGH); The command 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 LOW would refer to 0V. Next the program tells the Arduino to wait for a given period, before executing the next line of code. This period is equal to 1000 ms. delay(1000); After waiting for 1000 ms, the code writes a value of LOW to the led pin, and then makes it wait for 2000 ms. digitalwrite( led, LOW); delay(2000); At this point, there is no more code left in our program, so it starts executing void loop() again. Congratulations, you now have some basic understanding of how an Arduino program is written. 4. MODIFYING the BLINK PROGRAM Now try 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. 4.1 Create a new variable Right below the led variable declaration, add a new variable named wait of type int and assign a reasonable value different than 1000 (like 100 for example). Add also a comment describing what this variable is used for. 4.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. 4.3 Verify and upload your modified program 10

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 amount declared in the wait variable 11 digitalwrite(led, LOW); 12 delay(wait); //Wait for the amount declared in the wait variable 13 } Figure 6: The modified Blink Program. 5. USING INPUTS to CONTROL OUTPUTS 5.1 Understanding Pulse Width Modulation (PWM) Arduino cannot output true analog signals. One way to output a digital signal that reflects the value of an analog signal is pulse-width-modulation (PWM) Compared to a square signal, where the duty cycle is 50% (i. e. half of the period HIGH and half of the period LOW), the PWM signal has a duty cycle in which the time during which the signal remains HIGH is proportional to the analog signal. For example, when driving an LED with a PWM signal one is able to vary the brightness of the LED by writing on the PWM-pin a proper (digital) value: An analog signal should be first read by the Arduino (which converts it to a value between 0 and 1023). [The Arduino has inside a 10-bit analog-to-digital converter circuit (2 10 = 1024) that reads this voltage and converts it to a single 10-bit value (a number between 0 and 1023).] That value has then to be converted into an 8 bit (0 to 255 range) number. [Its implementation is explained in section 5.2c below. See also line 12 in the program shown in Fig. 8]. The latter is used to write the PWM pin. The net result is the generation of a digital signals (switching on and off) that makes the photodiode emit power proportional to the duty cycle. 11

From the Arduino library Load the 01.Basic Fade example program and upload it to your Arduino board. Toolbar File Examples 01. Basics 0.1.Basic (a modified version of the program is shown in Fig. 8 below). Wire up the LED to the pin that is used in 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. You can leave the LED in place. Observe how the signal looks like on your oscilloscope. 5.2 Controlling the PWM output with a potentiometer We will control the PWM signal (i.e. we will control the duty cycle of the square signal) by reading the voltage from a potentiometer terminal connected to the analog input A0. Hook up a 10k potentiometer between the 5V and ground; connect the middle leg to the A0 analog input on your Arduino as seen in Figure 7. Modify the Fade program code to the one shown in Figure 8, so that a potentiometer controls the LED brightness. In the new program we have declared a few new variables to keep track of i) the analog input pin, ii) the variables used for storing values from our analog input readings, and iii) our PWM output values. See the comments in the code for more context. 5V 10 k D10 D9 D8 PWM LED A0 A1 PWM 330 Analog input GND Figure 7 Potentiometer and LED wired up to the Arduino. Pin 9 is a PWM output. 12

5.2.a Establishing serial communication In the void setup() loop we use Serial.begin(9600); to begin serial communications, at 9600 bits of data per second, between the Arduino and the computer (remember how we picked a serial port in Section 2C above). Outputting data to the serial line is a nice way to see (on the computer screen) 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. 5.2b Reading the analog signal from the potentiometer The next new piece of code is analogread(pot); It reads the analog input (0-5V range) on pin pot (in the program this pin has been declared as pin A0) and converts it to a discrete value between 0 and 1023 (210 discrete values range.) (Recall the Arduino has inside an analog-to-digital converter circuit that reads this voltage and converts it to a number between 0 and 1023). 5.2c Controlling the PMW Pin led (declared as pin 9 in the program) only outputs PWM values (i.e. square wave with different duty cycles). First, we have to solve the following issue: On one hand, the PWM can be controlled only by an 8 bit digital number (that is, one needs to write a value between 0 and 255 to the led pin). On the other hand, in our current experiment we have a number between 0 and 1023 read from the analog pin pot. We need to make a corresponding conversion then. One alternative is to use the command called map() which handles the analog-input-range to the PWM-output-range conversion. Its syntax is, map (valuetoscale, fromlow, fromhigh, tolow, tohigh) In our program we use, outputvalue = map(sensorvalue, 0, 1023, 0, 255); /* Map sensorvalue to 8 bits (0 to 255) */ See the map info page for more details. 12 Next we write the adjusted input value to our led pin using, analogwrite( led, outputvalue); 13

1 const int led = 9; // the PWM pin where the LED is attached to 2 const int pot = A0; // A0 will be the analog input channel 3 int sensorvalue = 0; // sensorvalue will store the value read from the pot 4 int outputvalue = 0; // outputvalue will be the (duty cycle) value to be 5 // sent to the PWM pin 6 void setup() { 7 pinmode(led, OUTPUT); // Declare the PWM 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 // a 8 bit number (0 to 255) 13 analogwrite(led, outputvalue); // write the analog out value to pin led 14 // outputvalue specifies the duty cycle 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. 5.2.d Displaying the input and output voltages Finally we print these input and output values the serial line using the command, Serial.print(outputValue); 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. 14

Figure 9. The serial monitor in action. 5.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 incident on it. Using the same code as in Section 5.2, observe the output of the photo resistor and the PWM output on pin 9 simultaneously on your oscilloscope. Vary the amount of light incident on the photo-resistor and observe and compare the PWM output and analog voltage across the photoresistor. Check also what happens, upon light incident on the photoresistor, when you interchange the position of the photoresistor with the 10 k resistor in the circuit. If there is any difference, explain why. 15

10 k Photoresistor A0 GND 5V D9 330 LED PWM Figure 10. Photo-resistor connected to the analog input A0. At the time of preparing your reports feel free to modify the circuit drawing (Fig. 11 offers some symbols ready for copy and paste). Feel free also to improve the programs. Figure 11. Symbols that may be helpful when designing your circuits. (To modify them, just copy and paste them into the PAINT application. 6. MORE on INPUTS and OUTPUTS Here we emphasize the different ways (professional and non-professional) to establish inputs and outputs. When a circuit requires logic 1 to operate, engineers may refer to this condition as positive logic. Thus, the more positive voltage causes the action to take place. On the other hand, if a circuit requires a logic 0 to cause action, this type circuit is referred to as negative logic. 13 A. Implementation of Outputs and Inputs Case: For non-very critical applications A1. Digital Output 16

A digital output typically constitutes a control signal. a) Let s control the state of an LED. We can capitalize on the Blink program, which does just that. Hence, run the Blink program following the procedure stated above on how to hook the LED. b) Just for testing purposes, other than digital pin 13 try, one at a time, digital pin 2,, to digital 12. A2. Digital Input Typically, digital inputs are signals coming from a sensor; hence, they are also referred to as Measurement signals. In non-critical application people just use a floating terminal (a hanging wire) to connect the input pin directly to i) 5V, ii) leave it floating, or iii) GND. (Three input states available). Figure 12. Circuit to demonstrate digital inputs. Connect digital 7 to i) 5V, then ii) leave it floating, and then iii) GND. Check if the output behaves as expected. Define the digital pin 7 to be the input, and the digital pin 4 to be the output. Make 2 new programs: In the first, if the input is high make the LED to light up. (According to the definition above, engineers refer to this condition as positive logic to operate the circuit). In the second, if the input is low make the LED to light up. (Engineers refer it as negative logic condition to operate the circuit). Watch carefully what happens with the LED. Compared this procedure with the one used in the next section. HINT: Make your own programs, as requested above. Alternatively, we show below an example of positive logic program (where 5V implies HIGH). void setup() { // put your setup code here, to run once: 17

pinmode(7,input); pinmode(4,output); } void loop() { // put your main code here, to run repeatedly: if (digitalread(7)==high) digitalwrite(4,high); else digitalwrite(4,low); // modify here! for your own measurement. delay(2); } Figure 13. Example of a positive logic program. // if the input is HIGH // the output is HIGH Note: We consider the circuit in Fig. 12 above as a not recommended procedure (although 99% of practitioners do it!). B. Positive and negative logic used to operate a circuit Recommended procedures to establish a digital input (for more critical applications) (In the circuits of Figs. 14 and 15 only the inputs setups are good, not the outputs). B.1 Positive-logic input connection The input is effective when the set to HIGH or The input circuit requires a logic 1 to cause action. Connect the circuit shown in Fig. 14. Use the positive logic program given in Fig. 13. One at a time, connect digital 7 to: 5V, float, GND. Compare the different results. Figure 14. Connection for implementing a positive-logic input. B.2 Negative-logic input connection Input is LOW effective or the input circuit requires a logic 0 to cause action. 18

Connect the circuit shown in Fig. 15. Use the negative logic program shown in Fig. 16. (It is called negative logic input because the input causes the desired effect when connected to a LOW state). Figure 15. Connection for implementing a negative-logic input. One at a time, connect digital 7 to: 5V, float, GND. Compare the different results. It turns out, there is some consensus that negative logic implementation has advantages over positive logic. [The advantages of the program in Fig. 16 below is not directly transparent. The advantages are actually in the hardware layer and signal level layer, not in the program. Technically, all programs are treated "equally" by the processor. So which is better can only be decided on the system level]. void setup() { // put your setup code here, to run once: pinmode(7,input); pinmode(4,output); } void loop() { // put your main code here, to run repeatedly: if (digitalread(7)==low) digitalwrite(4,high); else digitalwrite(4,low); // modify here! for your own measure. delay(2); } Figure 16. Negative logic program. Comments on good and bad measurements 19

Digital circuits are noisy! In section A above, when a port is floating, one cannot predict the value at the output port. It can be low or high, or easily influenced by the environments. In section B, the input port is connected by a pull up resistor to 5V, or pull down resistor to GND. That way one has a deterministic input. One can be sure the signal is due to input actions, not due to the noise! B.3 Positive-logic output connection to light up the LED. No recommended but OK for noncritical applications. A digital output typically constitutes a control signal. In Fig. 17 my control is HIGH effective ; the LED lights-up when the output D4 is HIGH. This connection is OK for non-critical applications. Figure 17. Pay attention to the implementation of the output signal. When driving devices of high impedance (hence low current flows) this is OK. But if you want to drive high power devices this configuration is not ideal; the microcontroller board will not be able to drive high levels of current. B.4 Negative-logic output connection to light up the LED. (Recommended) In Fig. 18 my control is LOW effective ; the LED lights-up when the output D4 is LOW. This strategy allows driving both low and high power terminals. (It is OK to drive high currents to GND). 20

Figure 18. Connection for implementing a negative-logic output. C. Microcontroller configured to be a digital voltmeter Use a potentiometer to provide a 0 to 5V analog input. You will be able to measure a voltage less than 5V, and display the readings on the serial port. Input the signal to the A5, and check the result from your monitor. Use a DMM to check your result. void setup() { // put your setup code here, to run once: pinmode(a5,input); Serial.begin(9600); } void loop() { int j; j=analogread(a5); float k; k=(float)j*5/1023; Serial.println(k); // modify here! for your own measure. delay(1000); } Figure 19. D. Build a counter to measure a sensor signal D.1 Build the circuit shown in Fig. 20, and upload the program shown in Fig. 21. Cover the photo resistor with your hands, or shine the photo resistor with your cellphone flash. Check the readings from your monitor. If the counter does not work, you may need to adjust a parameter value inside the program (see comment inside the program). What is physically going on when you change that parameter? What is the reason that a proper value of that parameter makes the counter to work? 21

Figure 20. D.2 After you find the threshold of your measurement from section D.1, use the counter to measure how many times you swing your hand over the sensor. (This program contains software implementation of latch, flip-flop and counters, which are sequential logic. The details of sequential logics will be covered after the combinational logic labs. ) // This program demonstrate a digital flip-flop // and a digital counter! void setup() { pinmode(a0,input); Serial.begin(9600); } } int s=0; void loop() { int j; j=analogread(a5); if ( j< 349 ) { delay(3); } if (analogread(a5)>350) Serial.println(++s); // Variable to monitor the counting // Change this number so your counter responds // to the events (your hand blocking the sensor). Figure 21. Counter of number of times the user blocks a photodiode. References 1 A ROM associates a specific output binary number with each input binary number according to its fixed internal logic. The fixed relationship between input and output distinguishes the ROM from other memory circuits. 2 Arduino.cc. Introduction. http://arduino.cc/en/guide/introduction, 2013. 3 Arduino.cc. Arduino leonardo. http://arduino.cc/en/main/arduinoboardleonardo, 2013. 4 Arduino.cc. Arduino uno. http://arduino.cc/en/main/arduinoboarduno, 2013. 5 Wikipedia. Surface-mount technology. http://en.wikipedia.org/wiki/surface-mount_technology, 2013. 6 Wikipedia. Through-hole technology. http://en.wikipedia.org/wiki/through-hole_technology, 2013. 7 https://www.arduino.cc/en/main/software 8 Processing programming language. http://processing.org/, 2013. 22

9 http://hello.processing.org/editor/ 10 Arduino.cc. Reference page. http://arduino.cc/en/reference/homepage, 2013. 11 Arduino.cc. Pinmode(). http://arduino.cc/en/reference/pinmode, 2013. 12 Arduino.cc. map(). http://arduino.cc/en/reference/map, 2013. 13 http://www.sealevel.com/support/article/aa-00509/0/what-is-the-difference-between-positiveand-negative-logic-in-digital-i-o-circuits.html 23