Week 1 Arduino Environment
Lesson 1
Lecture 1.1 Arduino Platform
A development board
- 8-bit microcontroller
- programming hardware
- USB programming interface
- I/O pins
Arduino Environment
A software environment
- cross-compiler
- debugger
- simulator
- programmer
Special-purpose "Shields"
- daughter boards
- unique functionalities
- easy to attach
- good libraries provided
The Arduino Decelopment Board
- Has a microcontroller and USB interface to a PC
- Large open source community
Power/reset: Reset button; USB connector; Power connector
Lecture 1.2 Arduino Board
- Input/Output Pins: Digital I/O; Power/reset pins; Analog inputs
- Microcontrollers
- ATmega328 is the processor programmed by the user
- ATmega16U2 handles USB communication
- Two types of code executing on a simple mocrocontroller:
- Application code
- Executes the system's main functionality
- We write this code
- Firmware
- Low-level code: supports the main function
- USB interface, power modes, reset, etc.
- The distinction is a matter of perspective
- Arduino firmware is pre-programmed
- Application code
Lecture 1.3 Direct Programming
Bootloader
- Firmware on a microcontroller
- Allows the Flash and EEPROM to be programmed
- Manages USB communication, since application programming is via USB
In-Circuit Serial Programming (ICSP)
- A special programming method to program the firmware
- Needed because the bootloader can't reprogram itself
Lesson 2
Lecture 2.1 Arduino Schematics
Arduino UNO Schematic
- Arduino designs are open source
- Design is available
- You can build your own
Lecture 2.2 Arduino IDE
Arduino Integrated Development Environment(IDE)
Lecture 2.3 Compiling Code
Compiling Code
- Verify and Upload both compile
- Message window will show either completion message or error messages
- Error messages will show line numbers
Serial Monitor
- Displays serial data sent from the Arduino
- Allows serial data to be sent to the Arduino from the keyboard
- Library functions in the serial library
Lesson 3
Lecture 3.1 Arduino Shields and Libraries
Arduino Shields
- Add-on boards that interface with another device/IC
- Can be stacked directly on top of the Arduino
- Libraries exist to make interfacing simple
- Open source hardware, but most can be purchased
- Large variety of shields available
- Big advantage of the Arduino platform
Some Arduino Shields
Ethernet Shield; Color LCD shield; Synhesizer Shield(generate music and connect to a speaker)
Ethernet Shield Library Example
- Used by a client to establish a connection
- Call the function, ignore the detail
Lecture 3.2 Arduino Basic Setup
Week 2 C Programming
C_Lesson1
C_Lesson2
C_Lesson3
C_Lesson4
C_Lesson5
Lesson 1
Lecture 1.1 Setting Up Your Environment
Getting Started
- Prints "hello, world" to the screen
- Type this in with a text editor and save it as hello.c
Running a Program
- You will need a text editor and a compiler
- Debugger will be needed later
- I use GNU tools
- emacs text editor
- gcc C compiler
- gdb C debugger
- Can run on Windows but MacOS and Linux are easier
- Eclipse Integrated Development Environment(IDE)(Windows)
- Puts all tools together in a nice graphic user interface
- Need Java Runtime Environment(JRE) to run it
- Can also use Microsoft Visual Studio (not free)
Lecture 1.2 Hello World
Breaking Down Hello.c
#include <stdio.h>
- Tells the compiler to use the library functions described in
stdio.h
-
printf
(the print function) is insidestdio
- Beginning of the main function
- All code execution starts at main
{}
- Curly brackets group lines of code
- All functions start and end with curly brackets
printf(...);
- Prints to the screen
- The argument is in parenthesis
- The argument is what is printed
- Note the semicolon at the end
main() {
printf("hello, ");
printf("world");
printf("\n");
}
"hello, world\n"
- This is the argument to printf which appears on the screen
- It's a string because it's in quotes("")
-
\n
is a special character that indicates newline
Lecture 1.3 Variables
Variables
- Names that represent values in the program
- Similar to algebraic variables
- All variables have a type which must be declared
int x;
float y;
- Type determines how arithmetic is performed, how much memory space is required
Types and Type Qualifiers
- Several built-in types,different sizes
Type | Size | Notes |
---|---|---|
char | 1 byte | Fixed size |
int | Typically word size | 16 bit minimum |
[float | Floating point | 64 bits, typical |
double | Double-precision | 64, 128 typical |
- Type qualifiers exist: short, long
- Char is 8 bits on all platforms
Variable Names
- A sequence of visible characters
- Must start with a non-numerical character
- No C language keywords
Lesson 2
Lecture 2.1 Basic C Operators
Constants
- Can use
#define
compiler directive
#define ANSWER 42
- Any instance of the string is substituted at compile time
- Character constants
- Written as a single character in single quotes
-
#define
TERMINATOR 'x' - Integer equal to the ASCII value of the character
- Some characters are not easy to represent(i.e. bell)
Arithmetic/Relational Operators
+,-,*,/
-
%
is the modulo operator, division remainder - Ex.
9%2=1;9%3=0
-
++
(increment),--
(decrement) ==,<,>,<=,>=,!=
- Ex.
if(x<5)
...
Logical Operators
-
&&
(AND),||
(or),!
(Not) - Treat argument as 1-bit binary values
-
0 is
FALSE
, not-0 isTRUE
-
0 is
if((A==1)&&!B)
Lecture 2.2 Conditionals
Conditional Statements
if
if (expression)
statement1
else
statement2
if (expression)
statement1
else if (expr2)
statement2
else
stat3
-
else
is optional -
expression
is evaluated- Executed statement1 if
TRUE
, statement2 ifFALSE
- Executed statement1 if
-
expr2 evaluated if expr1 is
FALSE
Switch
switch (expr) {
case const_expr1: stat1
case const_expr2: stat2
default: stat3
}
- expression is evaluated, compared to const_expr
- Statements are executed corresponding to the first matching expression
-
default
is optional - Without a
break
statement the case will not end
Lecture 2.3 Loops
While and For Loops
for (expr1; expr2; expr3)
statement
expr1;
while(expr2) {
statement
expr3;
}
do {
statement
expr3;
} while (expr2);
- Initialization and increment are built into the for loop
- Condition checked at the top of a for/while loop
- Condition checked at the bottom of a do-while loop
Break and Continue
- Break jumps to the end of a for, while, do,case
-
Continue
jumps to the next iteration of a loop
Lesson 3
Lecture 3.1 Functions
Functions
- Functions can replace groups of instructions
- Define a function; call a function
- Naming is important
Function Arguments
Data can be passed to functions as arguments
Function Return Value
- Functions can return a value to the caller
- The type of the return value must be declared
Lecture 3.2 Global Variables
Global Variables
- A variable is global if it's defined outside of any function
- A global variable must be declared as an extern in any function using it
- Extern not needed if global declaration is before the function
- Variables can be global across files
Globals Are Dangerous
- Global variables can propagate bugs
- Bug in foo can cause bar to crash
- Debugging can become harder
- Reduce modularity of code
Week 3
BuildProcess
Setup
Loop
PinMode
DigitalWrite
DigitalRead
AnalogRead
Lesson 1 Arduino Programs
Lecture 1.1 Arduino Toolchain
Verify and Upload
Combine and Transform
- All program files are combined into one
- An
#include
is added to reference basic Arduino libraries - Function prototypes are added
- A
main()
function is created
Lecture 1.2 Cross-Compilation
Compile and Link
-
avr-gcc is invoked to cross-compile the code
- Resulting code executes on AVR, not Intel
- Generates an object file(.o)
- Object file is linked to Arduino library functions
Hex File Creation and Programming
- avr-objcopy is invoked to change the format of the executable file
- A .hex file is generated from the .elf file
Lecture 1.3 Arduino Sketches
Arduino Programs
- A program is called a sketch
- C++ program using Arduino library functions
- C++ is a superset of C
- All C programs are legal C++
- C++ also includes classes
Object-Oriented Programming
- Organize your code through encapsulation
- Group together data and functions that are related
- User-defined type is specific to an app
- Ex. ints have data(the number) and functions (+,-,*)
Lesson 2
Lecture 2.1 Classes
Classes and Members
class X {
public:
int m;
int mf(int v) { int old = m; m=v ; return old; }
};
X var;
var.m = 7;
int é = var.mf(9);
- Declaration of a variable creates an object
- .Operator used to access members
- Data and functions
- Functions can be defined inside the class
Classes in Libraries
Ethernet.begin(mac);
Serial.begin(speed);
client.print("Hello");
Serial.print("Hello");
- We don't need to know a lot about classes
- We will not define classes
- We will use classes defined in libraries
Lecture 2.2 Sketch Structure
Setup() Function
- A sketch does not have a main() function
- Every sketch has a
setup()
function- Executed once when Arduino is powered up
- Used for initialization operations
- Returns no value, takes no arguments
Loop() Function
- Every sketch has a
loop()
function- Executed iteratively as long as the Arduino is powered up
-
loop()
starts executing aftersetup()
has finished -
loop()
is the main program control flow - Returns no value, takes no arguments
Lecture 2.3 Pins
Pins
- Pins are wires connected to the microcontroller
- Pins are the interface of the microcontroller
- Pins voltages are controlled by a sketch
- Pin voltages can be read by a sketch
Output Pins
Output pins are controlled by the Arduino
- Voltage is determined by your sketch
- Other components can be controlled through outputs
Input Pins
- Input pins are controlled by other components
- Arduino reads the voltage on the pins
- Allows it to respond to events and data
Digital vs. Analog
- Some pins are digital-only
- Read digital input, write digital output
- 0 volts or 5 volts
- Some pins can be analog inputs
- Can read analog voltages on the pin
- Useful for analog sensors
- Analog-only pins are clearly labeled
- No pins can generate an analog output
Lesson 3
Lecture 3.1 Input and Output
Input/Output(I/O)
-
These functions allow access to the pins
void pinMode(pin, mode)
Sets a pin to act as either an input or an output
-
pin is the number of the pin
- 0-13 for the digital pins
- A0-A5 for the analog pins
-
mode is the I/O mode the pin is set to
- INPUT, OUTPUT, or INPUT_PULLUP
- INPUT_PULLUP acts as input with reversed polarity
Digital Input
int digitalRead(pin)
- Returns the state of an input pin
- Returns either LOW(0 volts) or HIGH(5 volts)
Digital Output
void digitalWrite(pin, value)
- Assigns the state of an output pin
- Assigns either LOW(0 volts) or HIGH(5 volts)
Analog Input
int analogRead(pin)
- Returns the state of an analog input pin
- Returns an integer from 0 to 1023
- 0 for 0 volts, 1023 for 5 volts
Lecture 3.2 Blink Examples
Delay
void delay(msec)
- Pauses the program for msec milliseconds
- Useful for human interaction
Blink Example
- Blink is the generic simple example for embedded systems
- Like "hello, world"
Week 4
Lesson 1
Lecture 1.1 Debugging
Debug and Trace
Controllability and observability are required
Controllability
- Ability to control sources of data used by the system
- Input pins. input interfaces(serial. ethernet, etc)
- Registers and internal memory
Observability
- Ability to observe intermediate and final results
- Output pins output interfaces
- Registers and internal memory
I/O Access Is Insufficient
Observation of I/O is not enough to debug
Properties of a Debugging Environment
- Run control of the target
- Start and stop the program execution
- Observe data at stop points
- Real-time monitoring of target execution
- Non-intrusive in terms of performance
- Timing and functional accuracy
- Debugged system should act like the real system
Lecture 1.2 Debug Environment
Remote Debugger
- Fronted running on the host
- Debug Monitor hidden on target
- Typically triggered when debug events occur
- Hitting a breakpoint, receiving request from host, etc.
- Debug monitor maintains communication link
Remote Debug Tradeoffs
Advantages:
- Good run control using breakpoints to stop execution
- Debug monitor can alter memory and registers
- Perfect functional accuracy
Disadvantages:
- Debug interrupts alter timing so real-time monitoring is not possible
- Need a spare communication channel
- Need program in RAM(not flash) to add breakpoints
Embedded Debug Interfaces
- Many modern processors include embedded debug logic
- Typically an optional IP block
- Embedded trace macrocell (ARM)
- Background debug mode (Freescale)
- Debug logic permanently built into the processor
- A few dedicated debug pins are added
Debug and Trace Features
- Breakpoints, stopping points in the code
- Watchpoints, memory locations which trigger stop
- On-the-fly memory access
- Examine/change internal processor values
- Single- step through the code
- Export exceptions to the debugger(hit a watchpoint)
- Export software-generated data(printf)
- Timestamp information for each event
- Instruction trace(special purpose HW needed)
Lecture 1.3 Debug via Serial
Serial Protocols
- Data is transmitted serially
- Only 1 bit needed (plus common ground)
- Parallel data transmitted serially
- Original bytes/words regrouped by the receiver
- Many protocols are serial to reduce pin usage
- Pins are precious
UART
- Universal Asynchronous Receiver/Transmitter
- Used for serial communication between devices
- UART is asynchronous: no shared clock
- Asynchronous allows longer distance communication
- Clock skew is not a problem
UART
- Used by modems to communicate with network
- Computers used to have an RS232 port. standard
- Not well used any more, outside of embedded systems
- Replaced by USB, ethernet, I2C, SPI
- Simple, low HW(Hardware) overhead
- Built into most microcontrollers
Lesson 2
Lecture 2.1 UART Protocol
Simple UART Structure
- Data is serialized by Tx, deserialized by Rx
- Status indicates the state of the transmit/receive buffers
- Used for flow control
UART Timing Diagram
- First bit is the Start Bit: initiates the transfer
- Next bits are the data
- Last are the Stop Bits
Bit Duration
- Each bit is transmitted for a fixed duration
- The duration must be known to Tx and Rx
- Baud rate(f) determines the duration(T)
- Baud rate is the number of transitions per second
- Typically measured in "bits per second(bps)"
- T = 1/f
- F = 9600 baud, T = ~104 microsec
- Transmission rate is less than baud rate
Lecture 2.2 UART Synchronization
UART Synchronization
- Receiver must know the exact start time
- Imprecise start time corrupts data
Start Bit, Synchronization
- Detection of the start bit is used to synchronize
- Synchronization based on falling edge of start bit
- Start bit is a falling edge
- Following 0 must be long duration to screen out noise
- Receiver samples faster than baud rate(16x typical)
- Start bit indicated by a 0 of at least half period
Lecture 2.3 UART Parity and Stop
Parity Bit
- Transmission medium is assumed to be error-prone
- E-M radiation noise, synchronization accuracy
- Parity bit may be transmitted to check for errors
- Even Parity: Number of 1's is even
- Odd Parity: Number of 1's is odd
- Parity bit is added to ensure even/odd parity
- After data, before stop bit(s)
- Data = 011011010
- Parity bit = 1, total parity is odd
Stop bit
- Receiver expects a 1 after all data bits and parity bits
- If 1 is not received, an error has occurred
Data throughput vs. Baud
- Every transmission involves sending signaling bits
- Stop, start, parity
- Data throughput rate is lower than baud rate
- Signaling bits must be sent
- 8 data bits, 1 parity bit, baud rate = 9600
- Send 1& bits to send 9 data bits
- Transmission efficiency = 8/11 = 73%
- Data throughput rate = 9600*0.73 = 6981.8 bps
Lesson 3
Lecture 3.1 Serial on Arduino
Arduino Serial Communication
- UART protocol used over the USB cable
- Initialize by using
Serial.begin()
-
Serail.begin(speed)
orSerial.begin(speed, config)
- speed is the baud rate
- config sets the data bits, parity, and stop bits
Serial.begein(9600)
-
Serial.begein(9600, SERIAL_8N1)
- 8 data, no parity, 1 stop
- Usually call Serial.begin() in the setup function
Sending Text Over Serial
- Use
Serial.print()
orSerial.println()
to print text in the monitor - Strings are converted to ASCII and sent using UART
- Use
Serial.write()
- Serial monitor still interprets data as ASCII
- 42 is the ASCII value for '*'
Lecture 3.2 Reading from Serial
Reading Data Over Serial
- Data can be sent to the Arduino via the serial monitor
- When data is sent it goes into a buffer in the Arduino until it is read
-
Serial.available()
is used to see how many bytes are waiting in the buffer
Serial.read()
-
Returns 1 byte from the serial buffer
int bval = Serial.read();
Returns -1 if no data is available
Serial.readBytes()
writes several bytes into a buffer
char buff[10];
Serial.readBytes(buff, 10);