Innovation Fellows Program Arduino Uno Microcontroller Overview, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota
Arduino Uno
Power & Interface Reset Button USB Interface 7 to 12 VDC Input Debug LED Digital I/O Pins ICSP Connector ATMega Microcontroller Power & Auxiliary Pins Analog to - Digital Converter Pins
USB Connection to Computer
Example Modules Sensors Ultrasonic Sensor - HC-SR04 IR Sensor 2Y0A21 Sharp Digital Distance Sensor MAX6675 Module + K Type Thermocouple Temperature Sensor Diymall Bme280 Pressure Temperature Sensor Module with IIC I2c SunFounder Accelerometer ADXL335
9-Axis Absolute Orientation Sensor Sensor fusion combines the following measurements Absolute Orientation (Euler Vector, 100Hz) Three axis orientation data based on a 360 sphere. Absolute Orientation (Quaterion, 100Hz) Four point quaternion output for more accurate data manipulation. Angular Velocity Vector (100Hz) Three axis of 'rotation speed' in rad/s. Acceleration Vector (100Hz) Three axis of acceleration (gravity + linear motion) in m/s^2. Magnetic Field Strength Vector (20Hz) Three axis of magnetic field sensing in micro Tesla (ut). Linear Acceleration Vector (100Hz) Three axis of linear acceleration data (acceleration minus gravity) in m/s^2. Gravity Vector (100Hz) Three axis of gravitational acceleration (minus any movement) in m/s^2. Temperature (1Hz) Ambient temperature in degrees celsius. Courtesy of Adafruit
Actuators Standard Size - High Torque - Metal Gear Servo Stepper Motor DC Motor with Gear 2-Channel 5 V Solid State Relay Module
User Interface Diymall 0.96" Inch I2c IIC Serial 128x64 Oled LCD LED White Display Module 7-Segment Serial Display - Red Adafruit 1.8 Color TFT LCD Display with MicroSD Card Breakout ST77 35R1.8" Color TFT LCD display with MicroSD Card Breakout - ST7735R Mini ISD2548 Digital Voice Recorder
Consider this Device Concept Task: Make a digital thermometer consisting of an enclosure, microcontroller board, thermocouple sensor, digital display, sound alert, slide switch, pushbutton and battery. http://store-usa.arduino http://www.thermometricscorp.com http://www.globalsources.com
Formulate an Algorithm 1. When the pushbutton is pressed Measure the temperature, Beep when the reading is good, Display the value for ten seconds, and finally Save the value to memory. 2. Start all over again. 3. Now flowchart this
Flowchart the Algorithm Start Monitor for Button Press No Button Pressed? Yes Read Temperature Store Value Valid Reading? No Yes Stop Clear Display Delay 10 Sec. Display Temperature & Beep
Software & Programming 1. Software is the smart in your smart device. 2. An algorithm displayed as a flowchart, transforms your problem into various input, processing, decision and output steps 3. Lines of code are written to implement your algorithm. 4. Code may be written in assembly language and/or higher level languages such as C, C++, and C#. 5. A compiler converts your code into machine language that the microcontroller understands. 6. The compiled code is then uploaded into a board containing the microcontroller, memory and various interface circuits. 7. Errors are then fixed by debugging. 8. You may write your own code and/or incorporate code that has been written by others ( sketches ).
Integrated Development Environment (IDE) Editor To write your code in C (.c) and/or assembly (.a) language. A finished program is called a sketch. Compiler Turns your code into machine readable instructions or object files (.o). A Linker combines this code with the standard Arduino Libraries, producing a single hex file (.h). Means to Upload Transferring the hex file to the Arduino board program memory. This is done via the USB or serial connection with the aid of the bootloader. Means to Run Executing the Program Means to Debug Finding & Correcting Errors
Arduino Programming Components 1. Structures A. Setup & loop B. Control statements C. Syntax D. Arithmetic operators E. Comparison operators F. Bitwise operators G. Compound operators 2. Variables A. Constants B. Data Types C. Variable Scope D. Qualifiers E. Conversion F. Utilities We will discuss today only the items above in blue. 3. Functions A. Digital I/O B. Analog I/O C. Due & Zero only D. Advanced I/O E. Time F. Math G. Trigonometry H. Characters I. Random numbers J. Bits and bytes K. External interrupts L. Interrupts M. Communication N. USB
1. Structures: Setup() Example 1) Initialize variables 2) Assign pins 3) Runs once, after powerup or reset. int buttonpin = 3; void setup() { Serial.begin(9600) ; //serial baud rate pinmode(buttonpin), INPUT); //assign pin 3 to be an input void loop() {
Loop() Example 1. Occurs after setup. 2. Loops consecutively 3. Initialize variables 4. Assign pins 5. Runs once, after powerup or reset. 6. Variations: if, ifelse; if-else-if int buttonpin = 3; void setup() { Serial.begin(9600) ; //serial baud rate pinmode(buttonpin), INPUT); //assign 3 to be an input void loop() { if(digitalread(buttonpin) == HIGH) Serial.write( H ); else serial.write( L ); delay(1000);
Control Statements Loop Statements For While Do-While Decision Statements Break and Continue If If-Else, if-else-if Switch-Case Directional Goto Return
Arrays 1. The first element is indexed with zero, e.g. a[3] has 3 elements, a[0], a[1], and a[2]. 2. Declare as usual, e.g. int a[3], float a[3], and char a[3]. 3. Initialize: int a[3] = {2, 6, 1. 4. Ok to initialize using a for loop. 5. If number of elements is not stated, the initialization will determine it, e.g. int a[ ] = {2, 6, 1 elements will be three. 6. Arrays may be multidimensional, e.g. a[3, 5]. 7. Two dimensional (rows and columns) can also be written, e.g. int M[4] [5] (remember there is a zero row and column). 8. Number of elements may be determined by variable in which case range check first.
For Statement (a Loop) Statement Format for (initialization; condition; increment) {program statement(s); Example Code Example What is the value of the a[49] element? int a[100]; for (int n = 0; n < 100; n = n + 1) { a[n] = n * 2;
While Statement (a Loop) while (expression a boolean that is true or false) {program statement(s); Example What is the value of a[30] element? int a[100]; int n = 0; while (n < 100) { a[n] = n * 3; n = n + 1; // Could also use ++n
Do-while Statement (a Loop) do {program statement(s) while (test condition); Example What is the value of a[75] element? int a[100]; int n = 0; do { a[n] = n * 4; n = n + 1; while n < 100;
If Statement (a Decision) if (expression) {program statement(s); Example What is the value of n? int a = 4, n = 0; if a <= 5 { n = n + 50;
If-Else Statement (a Decision) if (expression) {program statement(s); else {program statement(s); Example What is the value of n? int a = 10, n = 0; if a <= 5 { n = n + 50; else { n = n + 25;
Switch Case Statement (a Decision ) switch (expression) { case label1: program statements; break; case label2: program statements; break; default: program statements; break; For example: int a; Bool buy; a = 2; switch (a) { case 1: // if a =1 buy = true; break; case 2: // if a =2 buy = false; break;
Syntax ; Used to end a statement { Enclose statements, keep balanced // Start comment until end of line /* */ Multi-line comment #define #include Assigning a value to a constant name Follows C rules and no semicolon afterwards Use const type variable = value (e.g. const float pi = 3.14) when able instead. To include outside libraries
Arithmetic & Boolean Operators = assignment operator + addition - subtraction * multiplication / division % modulo && and or! not
Comparison & Pointer Operators == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to * dereference & reference
2. Variables: Constants 1. true false (typed in lower case) 1. false is defined as zero 2. true is defined as one, or any boolean test of an integer that is non-zero. 2. Integer constants: Decimal 123 Binary B11110000 (leading B) Octal 0173 (leading zero) Hexadecimal 0x7B (leading 0x)
5. Floating point constants: Constant Evaluates to Also 10.0 10 2.34E5 2.34 * 10^5 234000 67e-5 67.0 * 10^-5.00067
Data Types 1. boolean (8 bit) - simple logical true/false (1 byte = 8 bits) 2. byte (8 bit) - unsigned number from 0-255 3. char (8 bit) - signed number from -128 to 127. The compiler will attempt to interpret this data type as a character in some circumstances, which may yield unexpected results 4. unsigned char (8 bit) - same as byte ; if this is what you re after, you should use byte instead, for reasons of clarity 5. word (16 bit) - unsigned number from 0-65535 (1 word = 2 bytes) 6. unsigned int (16 bit)- the same as word. Use word instead for clarity and brevity. https://learn.sparkfun.com/tutorials/data-types-in-arduino
7. int (16 bit) - signed number from -32768 to 32767. This is most commonly what you see used for general purpose variables in Arduino example code provided with the IDE. 8. unsigned long (32 bit) - unsigned number from 0-4,294,967,295. The most common usage of this is to store the result of the millis() function, which returns the number of milliseconds the current code has been running. 9. long (32 bit) - signed number from -2,147,483,648 to 2,147,483,647 10. float (32 bit) or double- signed number from -3.4028235E38 to 3.4028235E38. Floating point on the Arduino is not native; the compiler has to jump through hoops to make it work. If you can avoid it, you should. https://learn.sparkfun.com/tutorials/data-types-in-arduino
Variable Scope 1. A global variable is one that can be seen by every function in a program. Local variables are only visible to the function in which they are declared. In the Arduino environment, any variable declared outside of a function (e.g. setup(), loop(), etc. ), is a global variable. For loop variables are local. 2. Static - the static keyword is used to create variables that are visible to only one function.
3. Functions: Digital I/O (Digital Pins) Digital pins on the Arduino can be defined as being Inputs or Outputs using the function pinmode(). The state of a digital pin can be determined with the function digitalread(). The state of an output can be set as High or Low with the function digitalwrite().
digitalwrite() digitalwrite() writes a HIGH or a LOW value to a digital pin. If the pin has been configured as an OUTPUT with pinmode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT, digitalwrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinmode() to INPUT_PULLUP to enable the internal pull-up resistor. See the digital pins tutorial for more information. e.g. digitalwrite(ledpin, HIGH)
digitalread() digital read() reads the value from a specified digital pin, either HIGH or LOW. e.g. digitalread(inpin);
Example: Blinking an LED const int LED = 10; int blinks = 5; bool done = false; void setup() { pinmode(led, OUTPUT); digitalwrite(led, LOW); // blink 5 times; //set pin 10 as an OUTPUT // Initialize off void loop() { while (done!= true) { for (int i = 1; i<= blinks; ++i) // ++i same as i = i+1 { digitalwrite(led, HIGH); // Turn on LED delay(500); //Pause digitalwrite(led, LOW); // Turn off LED delay(500); //Pause done = true;
Schematic
Example: Debouncing a Pushbutton const int LED = 9, BUTTON = 2; bool laststate = LOW, currentstate = LOW, lit = false; void setup() { pinmode(led, OUTPUT); pinmode(button, INPUT); boolean debounce(boolean last) //function { boolean state = digitalread(button); if(last!= state) // has button settled down { delay(5); //delay if not state= digitalread(button); //and read again return state; void loop() { currentstate = debounce(laststate); //call function if (laststate == LOW && currentstate == HIGH) { lit =!lit; //toggle LED laststate = currentstate; digitalwrite(led, lit); //update LED
Debouncing a Pushbutton
analogreference() analogreference() - configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are: DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards) INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega) INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only) INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only) EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.
analogread() analogread() reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or,.0049 volts (4.9 mv) per unit. The input range and resolution can be changed using analogreference(). It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second
analogwrite() analogwrite() writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogwrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogwrite() (or a call to digitalread() or digitalwrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
analogreadresolution() analogreadresolution() is also an extension of the Analog API for the Arduino Due and Zero. Sets the size (in bits) of the value returned by analogread(). It defaults to 10 bits (returns values between 0-1023) for backward compatibility with AVR based boards. The Due and the Zero have 12-bit ADC capabilities that can be accessed by changing the resolution to 12. This will return values from analogread() between 0 and 4095.
Example: Reading a Potentiometer Igoe, Tom. If statement tutorial. Arduino 2012
Reading a Potentiometer const int analogpin = A0; const int ledpin = 13; const int threshold = 400; void setup() { pinmode(ledpin, OUTPUT); Serial.begin(9600); void loop() { int analogvalue = analogread(analogpin); if (analogvalue > threshold) { digitalwrite(ledpin, HIGH); // pin that the potentiometer is attached to // pin that the LED is attached to on UNO // an arbitrary threshold level that's in the range of the analog input // initialize the LED pin as an output // initialize serial communications // read the value of the potentiometer // if the analog value is high enough, turn on the LED else { digitalwrite(ledpin, LOW); Serial.println(analogValue); delay(1); // print the analog value // delay in between reads for stability Igoe, Tom. If statement tutorial. Arduino 2012
I 2 C or Inter-Integrated Circuit Serial Interface SDA SCL Only two bus lines are required; a serial data line (SDA) and a serial clock line (SCL). Each device connected to the bus is software addressable. Serial, 8-bit oriented, bidirectional data transfers can be made.
Summary Arduino Uno, sensors and actuator examples. Using an IDE, programs are typically written in C and assembly language, compiled, linked with libraries and uploaded onto the Arduino board memory as hexadecimal code. Structures, variables and functions comprise an embedded program. Digital pins are defined as INPUT or OUTPUT and having levels of HIGH and LOW. Digital and analog functions. Examples: blinking light, debouncing a pushbutton and reading a potentiometer. I 2 C Serial Interface.