2. ENGINEERS NEVER FAIL
I have not failed. I've
just found 10,000 ways
that won't work.
[Thomas A. Edison]
3. INTRO QUOTE
“The Internet of Things tells us that
a lot of computer-enabled
appliances and devices are going to
become part of this system, too:
appliances that you use around the
house, that you use in your office,
that you carry around with yourself
or in the car. That's the Internet of
Things that's coming”
Vint Cerf, one of the
fathers of the Internet
4. GOALS OF THIS TUTORIAL
Having Fun
Learning how to use Open Source
Hardware/Software for building IoT
devices
Getting to know microcontroller boards
Building your own IoT device using low
cost hardware such as Arduino with
sensors/actuators
Focusing on the embedded side assuming
most of you are rather familiar with
desktops, servers
5. WHY DO WE USE ARDUINO IN THIS TUTORIAL?
Arduino provides low-cost, open source hardware
arduino.cc and vendors (Intel, TI, ...) offer compatible
boards
Big product ecosystem available (shields, boards,
displays, ...)
Large community exists
Low level programming with C/C++ helps learn the
fundamental concepts
It is much easier to learn & use more powerful boards
such as Raspberry Pi after understanding Arduino
WHY DO WE USE ARDUINO IN THIS TUTORIAL?
Arduino provides low-cost, open source hardware
arduino.cc and vendors (Intel, TI, ...) offer compatible
boards
Big product ecosystem available (shields, boards,
displays, ...)
Large community exists
Low level programming with C/C++ helps learn the
fundamental concepts
It is much easier to learn & use more powerful boards
such as Raspberry Pi after understanding Arduino
6. AGENDA
PART I: Presentation
What the heck is IoT good for?
Introduction to IoT hardware/software
Fundamentals of electronics
Some best practices
PART II: DIY - Experiments
Learning Arduino
PART III: Hackathon- teams of 3-4
Develop an IoT device
Refine and extend it
Present it to the other participants and get feedback
What you will need
Notebook (Linux, MacOS, Windows)
WiFi - provided by the conference organization
Arduino Starter Kit and components
Open Source Software to be downloaded from the
Internet
A Book on Arduino Practice
7. OPEN SOURCE SOFTWARE DOWNLOADS
Arduino IDE Download
https://www.arduino.cc/en/Main/Software
Processing IDE Download
https://processing.org/download/
Twitter 4J Download
http://twitter4j.org
Tutorial Processing and Twitter
http://codasign.com/tutorials/processing-and-twitter/
Node.js: http://nodejs.org
Johnny-Five JS: http://johnny-five.io
Java mail https://java.net/projects/javamail/pages/Home
Java RXTX Serial Communication
http://rxtx.qbang.org/wiki/index.php/Download
Eclipse for Java Developers
http://www.eclipse.org/downloads/packages/eclipse-ide-
java-developers/mars2
Arduino library for Processing
http://playground.arduino.cc/Processing2-arduino/Zip
Fritzing Circuit Modeling: http://fritzing.org
8. IOT DEVICES
Basic Recipe
Take a microcontroller or CPU board
Add sensors and actuators
Connect device to the Internet or use
Internet-based protocols
Control and monitor device using a Web
Interface
Different form factors from wearables, mobile
devices up to workstations Sensors CPU+Microcontroller Board
& Actuators
9. CONSUMER USAGE SCENARIOS
Wearables (watches, classes) that connect
users with each other and and with their
digital environment
Robots (e.g., for mowing the lawn or cleaning
rooms)
Control of lighting using mobile devices and
geofencing
Myriads of toy stories such as coffee machines
or cat feeding devices that can be controlled
remotely
10. OPENHAB
Most products (Philips Hue, NEST, Osram
Lightify, …) use proprietary approach
openHAB* as alternative
Open Source integration solution for home
automation systems
Based on Event Driven Architecture
Only precondition: availability of a JVM runtime
*HAB = Home Automation Bus
11. INDUSTRIAL CHALLENGE
How (i.e., with which system
architecture) can we integrate
from 100s to millions of devices
into large systems?
Magic Number: 50 Billions
If you think that is not relevant: large
factories in Japan may use up to 2 million
nodes
12. CASE STUDY I - CONTAINERS
Containers for transport of goods can get damaged
or lost
It is surprising how many containers disappear
Scenario:
Container integrates IoT device
On loading device gets information such as items,
recipients
Container regularly tracks GPS position and sends it
to sender
On changes such of pressure, temperature, moisture
or forces, IoT device sends events
13. CASE STUDY II –TRAFFIC INFRASTRUCTURE
Additional Scenario:
Traffic signals use IoT to measure traffic flow
Measurements over longer time period are stored in
Cloud
Data Analytics application analyzes data for optimization
of traffic control (using goals such as less traffic jams, less
pollution, …)
Decision Support System derives tactical optimizations to
improve strategy
Traffic controls can also work autonomously interacting
with other local traffic controls
Process is continuously repeated
14. CASE STUDY III – DECENTRALIZED SOLUTIONS
Connected robots or drones may collaborate as a swarm
static or ad-hoc connection
Scenario
Swarm receives task such as controlling a pipeline or a plant
Swarm members are coordinating their work to achieve
their joint goal
If necessary, swarm member can ask other members for
assistance
If a member must be recharged, it leaves swarm and moves
to charging station
Mission accomplished => swarm returns
15. CASE STUDY IV: INTERACTIVE MAINTENANCE
For maintenance of large or complex systems,
IoT devices interact with maintenance/service
staff
Maintenance/service staff uses VR solution
System visualized as 3D object which can be
analyzed with respect to its parts, state,
defects
User can interact with system
For each component/area/part a dedicated
IoT device is in charge
16. COMMUNICATION PROTOCOLS
To connect heterogeneous hardware
standardized communication protocols
are necessary
In IoT two widely used standards are
MQTT
CoAP
17. MQTT
MQTT originally meant MQ Telemetry Transport. Today, it
defines an OASIS- resp. ISO Standard (ISO/IEC PRF 20922)
follows the Publisher/Subscriber Pattern
requires a MQTT Broker for storing and and managing
messages and topics
defines Quality of Service: fire‘n forget, at-least-once, exactly-
once
uses different ports depending on security requirements
(unsecured port: 1883)
does not care about message content
Tools: mosquito (free broker), MQTT.fx (test client)
18. RESTFUL WITH COAP
REST is an Architecture Style (used by HTTP)
Principles:
Ressources support verbs such as GET, PUT, POST,
DELETE
Client-Server Interaction using standardized
interfaces
Statelessness
Caching
Layered Architecture
Call-dependent code generation
20. COAP - BENEFITS AND LIABILITIES
CoAP feels more natural than MQTT due
to its close relationsship with REST
CoAP implementations need more
ressources (memory)
=> Does not fit well in small memory
devices such as wearables, Arduino
21. ELECTRONICS
Dealing with IoT/Digitalization involves
dealing with embedded hardware and
electronics
We software engineers hoped to get rid of
these bottom layers by abstraction
Unfortunately, we must go back to the
roots
22. CIRCUIT DIAGRAMS
Typical elements in a circuit diagram
Battery/Cell: produces voltage
Lamp: consumes voltage
Switch: opens or closes circuit
Cable: connects producers and consumers
Current only flows in closed circuits
Base assumption: we only use independent voltage
sources (that produce a constant voltage), but no
independent current sources
CIRCUIT DIAGRAMS
Typical elements in a circuit diagram
Battery/Cell: produces voltage
Lamp: consumes voltage
Switch: opens or closes circuit
Cable: connects producers and consumers
Current only flows in closed circuits
Base assumption: we only use independent voltage
sources (that produce a constant voltage), but no
independent current sources
23. CURRENT FLOW
• In contrast to intuition current flows from
• Cathode (+) to
• Anode (-)
e-
e-
e-
e-
Physical flow of
electrons
- +
Technical flow of current
e-
e-
e-
e-
e-
e-
e- e-
25. RESISTORS
• Problem: consumers are only able to
consume a maximum current
• Solution: Resistors consume energy (by
converting electricity into heat), thus
reducing overall current
• All parts in a circuit have resistance,
even cables (which can mostly be
neglected)
• An open switch has infinite resistance
26. OHM’S LAW
Ohm’s Law: U = R x I
• Serial Resistors: Rserial = R1 + R2 + ….
Hint: it is common practice to combine resistors for better
achieving a specific resistance value
• Parallel Resistors: 1/Rparallel = 1/R1 + 1/R2 + ....
R1 R2
Same Current
Different Voltages
R1
R2
Same Voltage
Different Currents
Voltage = Resistance x Current
27. RESISTOR COLOR CODE
• 3 Bands: Band 1,2 are digits, Band
3 is multiplier, Additional Band is
Tolerance
• 4 Bands: Band 1,2,3 are digits,
Band 4 is multiplier, Additional
Band is tolerance
Color Multiplier Tolerance
Brown x 10 +/- 1%
Red x 100 +/- 2%
Orange x 1 K
Yellow x 10 K
Green x 100 K +/- .5%
Blue x 1 M +/- .25%
Violet x 10 M +/- .1%
Grey +/- .05%
Gold x .1 +/- 5%
Silver X .01 +/- 10% Example 3-Band Resistor: 27 x 100 K = 2.7 M Ohm with Tolerance +/- 1%
28. KIRCHHOFF’S VOLTAGE LAW
The sum of all voltages of any loop within a circuit is always zero
(you may count clockwise or counterclockwise)
U1
U2
U3
U4
U1+U2+U3+U4 = 0
Kirchhoff’s Voltage Law:
the sum of all power
consumers in a closed
loop equals the sum of all
power producers
In direction of current (+ => -)
generators: negative voltage
consumers: positive voltage
In opposite direction
generators: positive voltage
consumers: negative voltage
29. KIRCHHOFF’S CURRENT LAW
The sum of all in-going/out-going currents at a node is
always zero
I1 - I2 - I3 - I4 = 0
I2
I1
I3
I4
Incoming
currents
Outgoing
currents
Kirchhoff’s Current Law:
the sum of all incoming
currents at a node equals
the sum of its outgoing
currents
30. APPLICATION OF OHM’S LAW
Lets connect a voltage source with a resistor and a LED
An Arduino Uno board operates at 5V and allows to
draw 40mA current from an I/O pin and 200mA from
Vcc/Ground
A red LED’s forward voltage is 2V and its current should
be ca. 20 mA
The resistor must “absorb” the remaining 3V
(Kirchhoff’s Voltage Law)
Ohm’s Law: U = R x I => R = U / I = 3V/20mA = 175 Ohm
=> Use next higher resistor with 220 Ohm
(red/red/brown)
Warning: There are no fuses in the I/O pins of an
Arduino!
Use the 3-band color code:
Red/Red/Brown = 220 Ohm
4-band resistor would be
Red/Red/Black/Black
31. MICROCONTROLLERS IN A NUTSHELL
Microcontrollers (aka µC, uC or MCU) are
not CPUs, but complete systems on a
chip (SoC) with
Processor
Buses
Memory
Input/Output Peripherals
More than half of all microcontrollers are
still 8 bit
Typically, embedded systems software is
written in Assembly Language or C/C++
Source: http://www.mikroe.com/chapters/view/16/chapter-3-pic16f887-microcontroller/
Universal Synchronous/Asynchronous Receiver/Transmitter
Serial Peripheral Interface
Inter-Integrated-Bus
Special Function Registers
WDT
PWM
Capture, Compare, and Pulse Width Modulation- PIC18 µC
Reference Voltage
Deciphering the secret language of µC
USART
SPI
I2C
SFR
WDT
PWM
CCP
Vref
32. COMMON CONSTRAINTS
Limited Memory (Arduino Uno has 32k)
Limited Number of I/O Ports (Raspberry Pi got only a
few out-off-the-box)
Limited Energy if not connected to a power line
Limited Connectivity: Only Arduino Yun has
communication on board
33. LET‘S GO ON BOARD
Increasing number of open
source microcontroller boards
Excellent and cheap tools for prototyping
Useful to learn software development
basics for embedded systems
Scope: systems w/o stringent real-
time/dependability requirements
34. ARDUINO BOARD DESIGN
Analog
Reference
Digital I/O Pins
2-13 (9, 10, 11
with PWM =
Pulse Width
Modulation)
Digital Ground
Pins 1 & 2: Digital
I/O. When used
for communication
then Serial In/Out,
TX/RX
Reset Button: on
reset the
bootloader
restarts
In-Circuit Serial
Programmer: if
you need to
upload a
bootloader
Analog In: 0-5
Jumpers:
Toggling
between USB
power and
external power
(jumpers)
Power Connectors
connected with your
board. Not all boards use
5V!
External Power
Supply
USB Used to load
programs
(=sketches) to the
board, to power the
board, and for serial
communicationBoards (i.e., their
pins) have a
maximum current
they can handle.
Most Arduino
boards define a
maximum of 40
mA. Higher values
will cause
damage.
CPU with
16MHz
35. SENSORS & ACTUATORS
Pressure
Sensor
Ultrasonic
Gyro
Hall Sensor
Temperature
Sensor
Developers needs to add
specific code for reading or
writing actuator/sensor values
Usually attached through an
analog port
Specification of
chip/component explains
mapping between sensor
values and physical units
PWM (Pulse Width Modulation)
often used in digital outputs
(actuators) to vary intensity of
speed, volume, brightness, ...
SENSORS
ACTUATORS
SENSORS & ACTUATORS
Pressure
Sensor
Ultrasonic
Gyro
Hall Sensor
Temperature
Sensor
Developers needs to add
specific code for reading or
writing actuator/sensor values
Usually attached through an
analog port
Specification of
chip/component explains
mapping between sensor
values and physical units
PWM (Pulse Width Modulation)
often used in digital outputs
(actuators) to vary intensity of
speed, volume, brightness, ...
SENSORS
ACTUATORS
36. SHIELDS & HATS
Arduino shields (incl. program libraries) add
advanced logic
Built to fit on top of an Arduino board
Typically, provide the same pins like the
Arduino on top (for stacking of boards)
Examples:
Motor Shield (Arduino)
LCD Shield (Sparkfun)
Proto Shield (Seeed Studio)
GPS Shield (Adafruit)
WiFi Shield (AsyncLabs)
See http://shieldlist.org/
Caveat: Some shields or
libraries may not work
together
37. ELEGOO ARDUINO STARTER KIT
5pcs White LED
5pcs Yellow LED
5pcs Blue LED
5pcs Green LED
5pcs Red LED
1pcs RGB LED
5pcs 22pf Ceramic Capacitor
5pcs 104 Ceramic Capacitor
2pcs Photoresistor
1pcs Thermistor
5pcs Diode Rectifier (1N4007)
2pcs Electrolytic Capacitor (10UF 50V)
2pcs Electrolytic Capacitor (100UF 50V)
5pcs NPN Transistor (PN2222)
5pcs NPN Transistor (S8050)
1pcs Tilt Switc
5pcs Button (small)
1pcs 1 digit 7-segment Display
1pcs 4 digit 7-segment Display
1pcs Sound Sensor Module
1pcs LCD1602 Module ( with pin header)
1pcs Active Buzzer
1pcs Passive Buzzer
1pcs RTC Module
1pcs DHT11 Temperature and Humidity
Module
2pcs Potentiometer
1pcs Rotary Encoder Module
1pcs Joystick Module
1pcs Keypad Module
1pcs 5V Relay
1pcs IR Receiver Module
1pcs UNO R3 Controller Board
1pcs Breadboard
1pcs Servo Motor (SG90)
1pcs Stepper Motor
1pcs ULN2003 Stepper Motor Driver Board
1pcs Prototype Expansion
1pcs Power Supply Module
1pcs HC-SR501 PIR Motion Sensor
1pcs Ultrasonic Sensor
1pcs ADXL335 Module
1pcs 3V Servo Motor
1pcs MAX7219 Module
1pcs Remote
1pcs 9V 1A Power Supply
1pcs 65 Jumper Wire
1pcs Water Lever Sensor
1pcs USB Cable
1pcs 9V Battery with DC
1pcs RC522 RFID Module
10pcs Resistor (10R)
10pcs Resistor (100R)
10pcs Resistor (220R)
10pcs Resistor (330R)
10pcs Resistor (1K)
10pcs Resistor (2K)
10pcs Resistor (5K1)
10pcs Resistor (10K)
10pcs Resistor (100K)
10pcs Resistor (1M)
20pcs Female-to-male Dupont Wire
UNO R3 Arduino compatible board plus USB cable
with Transport Box
Component List:
38. I2C* – THE LOW-SPEED BUS
Multi-master serial single-ended computer
bus invented by Philips Semiconductors
Used in most open source hardware boards
for attaching low-speed peripherals (speed 10
Kb/s-100Kb/s; newer versions even up to 3.6
Mb/s)
Two bidirectional open-drain lines: Serial Data
Line (SDA) und Serial Clock (SCL)
Pull-up resistors to prevent floating signals
Wire library available (for accessing I2C)
o Master generates the clock and
initiates communication
o Slave receives clock and
responds when addressed by
master
o Master sends only if it detects
no start or stop bit sent by
another master
o Single Message or Multi
Message
o License free; only slave
addresses must be bought
* I2C = Inter-Integrated Circuit, invented by Philips Semiconductor Division, now NXP
39. SOLDERLESS BREADBOARDS
Connecting the Arduino to a breadboard is very
useful for designing circuits without soldering
When finished you may use a PCB (Printed
Circuit Board) instead
Breadboards consist of pin holes to place
components (terminal strip) as well as bus strips:
Terminal strip: all vertical lines of pin holes
Notch in the middle (where mostly ICs such as DIPs are
placed)
Bus strips for power supply, blue = ground
red = voltage
NOTCH
40. DRAWING CIRCUITS WITH FRITZING
I use the Open Source
Fritzing editor to draw my
own circuits
Download available from
http://fritzing.org (Mac
OSX, Windows, Linux) – it is
free but you may provide a
small donation
41. THE ARDUINO IDE*
Available for MacOS X, Windows, Linux at no cost
Based on Processing, built with Java
Subset of C/C++, (implementation of Wiring)
Uses gcc & avr-gcc libraries in the build process
C/C++ Libraries import
You may use gcc directly or within Eclipse for C++
Other languages such as Java can remotely connect to Arduino
using a wrapper on top of a RxTx native library
* Free guide available at http://www.me.umn.edu/courses/me2011/arduino/arduinoGuide.pdf
42. PROGRAMMING MODEL
When coding a sketch (= program) for microcontroller
boards like Arduino, two steps are necessary:
Initialization and Controlling & Monitoring
1. Initialization phase executed once at start-up time:
definitions and initialization of ports, connections,
...
2. Control Loop: „Endless“ loop in which application
can monitor and control the board
Application may terminate itself on specific events
Initialization
Control Loop
start
final
43. INTERRUPTS IN ARDUINO
Interrupts enable Event-driven Processing
3 Types of Interrupts:
External: mapped to ports 2 and 3 (INT0 and INT1).
Triggered when input signal is RISING, FALLING,
CHANGING, ...
Pin-Change: can be enabled for all Arduino signal pins.
Triggered on all events. You must figure out what
happened on what pin.
Timer Interrupt: Three 16 bit Timers, originally
exclusively dedicated for timing PWM signals. On a 16
MHz machine timer clock period can be configured
from 0.0625 uS to 8388.608mS (more details on
http://playground.arduino.cc/Code/Timer1)
int pin = 2;
volatile int state = LOW;
void setup()
{
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
// there is also detachInterrupt
}
void loop()
{
digitalWrite(pin, state);
}
void blink()
{
state = !state;
}
44. BLINK IS THE NEW „HELLO WORLD“
„Hello, World“...
for Electronics
=>
Blinking LED
// Pin 13 has an LED connected on most boards
int led = 13;
// the setup routine - runs after each reset:
void setup() {
// initialize digital pin as an output pin
pinMode(led, OUTPUT);
Serial.begin(9600); // start serial port
}
// infinite loop; HIGH & LOW are voltage levels!
void loop() {
Serial.println(“Hello, World”); // send string
digitalWrite(led, HIGH); // shine a light
delay(1000); // wait for a second
digitalWrite(led, LOW); // switch off LED
delay(1000); // wait for a second
}
Language based on
C/C++
Serial stream received by
host and displayed on the
IDE‘s Serial Monitor if
available
46. DEBOUNCING– CODE (SETUP)
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
47. DEBOUNCING – CODE (LOOP)
void loop() {
int reading = digitalRead(buttonPin); // read the state of the switch into a local variable
if (reading != lastButtonState) { // If the switch changed, due to noise or pressing
lastDebounceTime = millis(); // first time measure
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState); // set the LED
lastButtonState = reading; // this will be the lastButtonState in the next loop
}
48. ALTERNATIVE SOLUTION
Using the Debounce
Library (DRY)
Available in the
Arduino IDE
Implements the same
functionality in an
elegant way
// This code turns a led on/off through a debounced switch
#include <Debounce.h>
#define SWITCH 5
#define LED 13
// Instantiate a Debounce object with a 20 millisecond debounce time
Debounce debouncer = Debounce( 20 , SWITCH );
void setup() {
pinMode(SWITCH,INPUT);
pinMode(LED,OUTPUT);
}
void loop() {
// Update the debouncer
debouncer.update ( );
// Get the update value
digitalWrite(LED, debouncer.read() );
}
49. YET ANOTHER ALTERNATIVE
Alternatively, you might use hardware for
debouncing.
A capacitor is smoothing the signal
If the button is not pressed, the capacitor will charge
=> LOW signal on Arduino digital input pin
If the button is pressed, capacitor discharges quickly
=> HIGH signal on input pin
Arduino Digital Pin
Using Hardware
50. PULL-UP RESISTORS
Problem: circuits are subject
to electrical fluctuations which
may lead to an undefined state
Solution: use a pull-up resistor
so that when unpressed, 5V
will be on pin 2, and when
pressed will be low due to
connection with ground
Arduino internally provides
Pull-Up resistors for digital pins
51. void setup(){
Serial.begin(9600); // start serial connection
pinMode(2, INPUT_PULLUP); // pin 2 is input and uses the pull-up resistor
pinMode(13, OUTPUT);
}
void loop(){
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal); // send current value via serial communication to host
// Keep in mind the pull-up means the push-button's
// logic is inverted. It goes HIGH when it's open,
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
}
else {
digitalWrite(13, HIGH);
}
}
PULL-UP RESISTORS – CODE
52. USING PWM
Problem: for dimming a led,
..., we need to change the
actual current continuously,
but how?
Solution: Use PWM (Pulse-
Width-Modulation) to
simulate an analog output
with variable current
Done by swítching the signal
on and off for specific time
intervals (duty cycles)
PWM is useful for fading a LED, changing DC Motor Speed, sending different tones to piezo buzzer
But it is not useful where non-discrete analog values are expected
53. PWM – CODE
int ledPin = 9; // LED connected to digital pin 9
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue); // analog write on digital pin!
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
54. LCD LIBRARY
Problem: How can we make
hardware such as the
LiquidChrystal display easily
usable
Solution: we need to provide a
library, e.g., the LiquidChrystal
library
to save wires use a 16x2 LCD Display
combined with an I2C circuit
16x2 LCD Display
Display connected to digital ports
Potentiometer used to control brightness of display
55. USING LIBRARIES – CODE
#include <LiquidCrystal.h> // the library for using LCDs
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's to 16 numbers and 2 rows
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}
56. LCD DISPLAY OVER I2C
For using a standard 16x2 LCD display we had to use 6
pins on our Arduino plus Vcc plus Gnd
A better option is the I2C bus where we need 2(!!!)
pins plus Vcc plus Gnd
Fortunately, we have a I2C connected LCD Display in
our kit
Connect
LCD Vcc to Arduino 5V
LCD Gnd to Arduino Gnd
LCD SDA to Arduino Analog A4
LCD SCL to Arduino Analog A5
Potentiometer on back side of LCD to adjust
brightness
57. ADDING I2C LCD LIBRARY TO YOUR SKETCH
Create a new sketch
Download ZIP-Library from
http://github.com/marcoschwartz/LiquidCrystal_I2C
Add it to the Arduino Library
Create new sketch
Then
Select IDE menu Item Sketch
Select Include Library
Select Add .zip Library
Select downloaded file
58. CODE – PRINTING ON LCD
lcd.init(); // initialization of LCD
lcd.backlight(); // brighten backlight
lcd.setCursor(0,0); // move cursor to first line
lcd.print(”building iot"); // write to display
lcd.setCursor(0,1); // move cursor to second line
lcd.print(”Hackathon"); // write to display
59. CODE - DECLARATIONS
#include <Wire.h> // communication protocol library
#include <LiquidCrystal_I2C.h> // liquid crystal display library
LiquidCrystal_I2C lcd(0x27,16,2); // Define LCD device on I2C address 0x27
// with a 16 x 2 characters display
60. SCANNING FOR I2C DEVICES
#include <Wire.h> // communication library
int count = 0;
void setup() {
Serial.begin (9600);
Wire.begin(); // starting communication
}
void loop(){
count = 0;
for (int i = 1; i < 255; i++) { // scanning through all 256 IDs of I2C devices
Wire.beginTransmission (i); // attempt communication with device ID i
if (Wire.endTransmission () == 0) { // success => device found
Serial.print (”Device found on ");
Serial.print (" 0x");
Serial.println(i, HEX);
count++;
} // end if
delay (5);
} // end loop
Serial.print ("Found "); Serial.print (count); Serial.println (" devices");
}
61. TEMPERATURE SENSOR 18B20
Now, we are going to measure temperature with
the 18B20 chip
We only need one analog pin A2 for this purpose
The sensor supports the OneWire protocol
You’ll need two libraries
OneWire:
https://github.com/PaulStoffregen/OneWire
18B20 also known as Dallas:
https://github.com/milesburton/Arduino-
Temperature-Control-Library
62. SIDE NOTE
1-Wire is a protocol for communicating
with sensors over 1 single line
One Master (microcontroller), multiple
slaves
Only master can initiate communication
Every sensor has unique ID
Similar to I2C but with lower speed.
Benefit: longer range
64. CODE – INITIALIZATION & SETUP
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2 // Data wire => digital pin 2 on the Arduino
OneWire oneWire(ONE_WIRE_BUS); // init 1-Wire bus
DallasTemperature sensors(&oneWire); // passing 1-Wire reference to sensor
void setup(void)
{
// get serial data to PC
Serial.begin(9600);
// start sensor transmissions
sensors.begin();
}
65. CODE – CONTROL LOOP
void loop(void)
{
// start receiving temperatures
Serial.println(" Arduino as master starts retrieving temperatures");
sensors.requestTemperatures();
Serial.print(”Actual temperature: ");
Serial.println(sensors.getTempCByIndex(0));
// …ByIndex(0) => get first temperature sensor
}
66. TEMPERATURE SENSOR TMP36
We could also have used the analog TMP36
temperature sensor instead
This sensor is connected to an analog port
In the circuit A0 is connected with the analog signal
pin of the sensor
Calculating voltage at Pin A0 (5V Arduino):
milliVolts = (reading from ADC) * (5000.0 / 1024)
Temperature in C°:
temperature = (milliVolts – 500.0) / 10
Note: precision is 0.1°
67. STARTER KIT DHT11 TEMPERATURE AND HUMIDITY
SENSOR
DHT11
Ultra low cost
3 to 5V power and I/O
2.5mA max current use during conversion
(while requesting data)
Good for 20-80% humidity readings with
5% accuracy
Good for 0-50°C temperature readings
±2°C accuracy
No more than 1 Hz sampling rate (once
every second)
Body size 15.5mm x 12mm x 5.5mm
4 pins with 0.1" spacing
72. YET ANOTHER CHALLENGE
We want to connect eight LEDs
to our Arduino
Doing this, only a few digital
pins would be left for other
purposes
Moreover, what happens if we
need to connect more LEDs
than we got digital pins on the
Arduino?
73. SOLUTION: USE THE SHIFT REGISTER 74HC595
A Shift Register gets a byte where each bit
controls an output pin Q0.. Q7 (pins 15, 1..7)
Shift registers can combinable (daisy-chain) over
pin 9 (carry-over)
Pin 9 would be connected to Pin 14 of next
74HC595
Pin 14: send data to register
Pin 12: put new data on output pins
Pin 11: clock that triggers all activities
Other Shift Registers may even offer 16 bits and integrated
resistors
The 74HC595 converts an 8-Bit binary number to its bits. It
acts as a multiplexer/demultiplexer.
74. CIRCUIT
DIAGRAM
74HC595 Arduino Color of Wire
14: DS Digital 11 purple
11: SH_CP Digital 12 yellow
12: ST_CP Digital 8 green
08: GND GND
16: Vcc 5V
13: OE GND
10: MR 5V
1 µF Capacitor prevents signal
floating on latch pin ST_CP
75. CODE – CONTROL LOOP
void loop() {
for (int byteVal = 0; byteVal < 256; byteVal++) {
// latch pin ST_CP low => number not visible on the output of the shift register
digitalWrite(pinLatch, LOW);
// store the byte in the register:
shiftOut(pinData, pinClock, MSBFIRST, byteVal);
// latch pin set to high => byte value visible at 74HC595 output pins
digitalWrite(pinLatch, HIGH);
// take a break
delay(200);
}
}
76. CODE – INITIALIZATION & SETUP
int pinLatch = 8; // connection to ST_CP => latch
int pinClock = 12; // connection to SH_CP => clock
int pinData = 11; // connection to DS => data
void setup() {
pinMode(pinLatch, OUTPUT); // all three pins are output pins
pinMode(pinClock, OUTPUT);
pinMode(pinData, OUTPUT);
}
77. NEOPIXEL WS2812
LED built by adafruit - can be
controlled using a single data line
Controller + LED = WS2812
Often sold as LED strips
You may cut the strip in multiple strips
Simple Connection
Arduino Pin Dx -> WS2812 Data
Arduino 5V -> WS2812 5V
Arduino GND-> WS2812 GND
78. USING A WS2812 LIBRARY
adafruit Neopixel library:
https://github.com/adafruit/Adafruit_NeoPixel
Other option FastLED library (supports other
LED types as well):
https://github.com/FastLED/FastLED/releases
Lightweight library:
https://github.com/cpldcpu/light_ws2812
79. PARAMETERS FOR NEOPIXEL LIBRARY USAGE
Parameter 1 = number of pixels in strip
Parameter 2 = Arduino pin number (most are valid)
Parameter 3 = pixel type flags, add together as needed:
NEO_KHZ800 800 KHz bitstream (most NeoPixel
products w/WS2812 LEDs)
NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels,
WS2811 drivers)
NEO_GRB Pixels are wired for GRB bitstream (most
NeoPixel products)
NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA
pixels, not v2)
• NEO_RGBW Pixels are wired for RGBW bitstream
(NeoPixel RGBW products)
• For non-Adafruit products you might need to
download and use proprietary library
80. CODE – SETUP
include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 8 // Arduino pin connected to data-in of LED strip
#define NO_OF_LEDS 16 // length of strip
// for parameters see strandtest in adafruit examples
Adafruit_NeoPixel pixels
= Adafruit_NeoPixel(NO_OF_LEDS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
pixels.begin(); // Initializing library
}
81. CODE – LOOP
void loop() {
// first LED: 0, second: 1, third : 2, ...
for(int i = 0; i < NO_OF_LEDS; i++) {
pixels.setPixelColor(i, pixels.Color(255,0,0)); // set to red
pixels.show(); // Send pixel color to strip
delay(1000); // wait for a second
}
}
82. DC MOTORS
Problem: Connecting a
low current Arduino with
a high current consumer
Solution:
Transistor (npn) to separate
both circuits
Potentiometer to let user
vary the speed
Diode to prevent any
induced current from
damaging the circuit
Source: http://www.dummies.com/how-to/content/how-to-control-the-
speed-of-a-dc-motor-with-the-ar.html
83. DC MOTORS – CODE
int potPin = A0; // potentiometer on analog pin A0
int motorPin = 9; // motor on digital pin 9
int potValue = 0;
int motorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
potValue = analogRead(potPin);
// map maps from [0, 1023] to [0, 255]
motorValue = map(potValue, 0, 1023, 0, 255);
analogWrite(motorPin, motorValue); // set speed
Serial.print("potentiometer = " );
Serial.print(potValue);
Serial.print("t motor = ");
Serial.println(motorValue);
delay(2);
}
84. ALTERNATIVE SOLUTION
Use a motor shield (several available)
Can support multiple motors (brushed dc motor, stepper, servo)
Motor shields leverage the H-bridge L298P
85. ALTERNATIVE – CODE (SETUP)
const int
PWM_A = 3,
DIR_A = 12,
BRAKE_A = 9,
SNS_A = A0;
void setup() {
// Configure the A output
pinMode(BRAKE_A, OUTPUT); // Brake pin on channel A
pinMode(DIR_A, OUTPUT); // Direction pin on channel A
// Open Serial communication
Serial.begin(9600);
Serial.println("Motor shield DC motor Test:n");
}
86. ALTERNATIVE – CODE (LOOP)
void loop() {
// Set the outputs to run the motor forward
digitalWrite(BRAKE_A, LOW); // setting brake LOW disable motor brake
digitalWrite(DIR_A, HIGH); // setting direction to HIGH: motor will spin forward
analogWrite(PWM_A, 255); // Set the speed of the motor, 255 is the max value
delay(5000); // hold the motor at full speed for 5 seconds
Serial.print("current consumption at full speed: ");
Serial.println(analogRead(SNS_A));
// to be continued
87. ALTERNATIVE – LOOP CONT’D
// Brake the motor
Serial.println("Start brakingn");
// raising the brake pin the motor will stop faster than the stop by inertia
digitalWrite(BRAKE_A, HIGH); // raise the brake
delay(5000);
…
// to be continued
88. ALTERNATIVE – LOOP CONT’D
// Set the outputs to run the motor backward
Serial.println("Backward");
digitalWrite(BRAKE_A, LOW); // setting againg the brake LOW to disable motor brake
digitalWrite(DIR_A, LOW); // now change the direction to backw: LOW DIR_A pin
analogWrite(PWM_A, 255); // Set the speed of the motor
delay(5000);
Serial.print("current consumption backward: ");
Serial.println(analogRead(SNS_A));
…
89. ALTERNATIVE - END OF LOOP
// now stop the motor by inertia, motor will stop slower than with brake function
analogWrite(PWM_A, 0); // turn off power to the motor
Serial.print("current brake: ");
Serial.println(analogRead(A0));
Serial.println("End of the motor shield test with DC motors. Thank you!");
while(1);
}
90. SERVO CONTROLLED
BY POTENTIOMETER
Goal:
• Read potentiometer input, map value
to 0..180 degrees, and move servo
to that position
Parts:
• Genuino/Arduino Uno
• Potentiometer
• Servo Motor
• Jumper Wires
91. CODE
#include <Servo.h> // this library is provided in the Arduino IDE library folder
Servo hs53; // create servo object to control a servo
int potpin = 0; // analog pin A0 is connected to potentiometer
int val; // variable to read the value from the potentiometer
void setup() {
hs53.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600); // starts serial data transfer to PC
}
void loop() {
val = analogRead(potpin); // reads value from potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo
//(position between 0 and 180)
hs53.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get to new position
Serial.println(val); // send the new servo position
}
92. EXAMPLE PROJECT TRAFFIC LIGHT
Building a Traffic Light with
LEDs and a Piezo speaker that
signals red or green.
93. CIRCUIT LAYOUT
• Genuino/Arduino Uno
• Red, Green, Yellow LED
• 3 pcs 220 Ohm Resistors
• Piezo Speaker
• Jumper Wires
Goal:
• Get used to controlling LEDs and
piezo speakers
94. CODE - DECLARATIONS
// Simple Arduino sketch for a stand-alone traffic light by M. Stal, (c) 2016
int red = 9; // red LED on Pin 9
int yellow = 10; // yellow LED on Pin 10
int green = 11; // green LED on Pin 11
int loudspeaker = 6; // Loudspeaker on Pin 6
int REDPHASE = 5000; // Duration Red in msecs
int BEFOREGREEN = 2000; // Duration Before Green
int GREENPHASE = 10000; // Duration Green
int BEFORERED = 2000; // Duration Before Red
int IR = 0; // Interrupthandler IR called on CHANGE
int TONE_DELAY = 50; // Delay between tones
95. CODE - INITIALIZATION
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pins as output.
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(loudspeaker, OUTPUT);
Serial.begin(9600); // for talking to PC
}
97. CODE – UTILITY FUNCTIONS II
void redPhase() {
Serial.println("Red Phase");
redHigh();
toneSignalRed();
yellowLow();
greenLow();
delay(REDPHASE);
beforeGreen();
}
void beforeGreen() {
Serial.println("Before Green Phase");
redHigh();
yellowHigh();
greenLow();
delay(BEFOREGREEN);
greenPhase();
}
…
Applying the State pattern with
“functions for states”
Red Phase
Green Phase
Yellow before
Green
Yellow before Red
98. CODE – HANDLING INTERRUPTS
void emergencyHandler() {
for (int i = 0; i < 10; i++) {
tone(loudspeaker, 240);
delay(TONE_DELAY);
tone(loudspeaker, 160);
delay(TONE_DELAY);
tone(loudspeaker, 440);
delay(TONE_DELAY);
}
}
Reminder:
Interrupt 0 is associated with Pin 2
Interrupt 1 is associated with Pin 3
Interrupt handlers called on defined
events at these pins
Example: Interrupt handler is called
when switch is pressed
99. CODE – MAIN LOOP
// the loop routine runs over and over again forever:
void loop() {
noTone(loudspeaker);
attachInterrupt(IR, emergencyHandler, CHANGE);
redPhase(); // state machine starts with red
}
100. ARDUINO + ESP8266
ESP8266:
Chip from Espressif for under
5 € that supports Wifi
With 3.3V logic
Maybe used standalone as an
Arduino compatible MCU
Or as a peer of the Arduino
board for handling
communication
Different versions: we’ll use
the ESP-01
101. CHALLENGE 2: 2 SERIAL PORTS OF ARDUINO
NECESSARY
Arduino communicates with ESP8266 and
host computer
Solution 1 (rich man‘s approach): Use
Arduino Mega
Solution 2: Use software serial
#include <SoftwareSerial.h> // Simulierter serieller Port
#define ESP_RX 2
#define ESP_TX 3
SoftwareSerial Serial1(ESP_RX, ESP_TX);
102. CHALLENGE 1: DEALING WITH DIFFERENT LOGIC
LEVELS
We cannot directly connect the 3.3V
ESP8266 to the 5V-Arduino
Solution 1 (poor man‘s approach): Voltage
divider using resistors
Solution 2: Logic Level Converter
103. CODE
void setup()
{
Serial.begin(9600);
Serial1.begin(115200);
}
void loop()
{ // read messages from ESP-01
while (Serial1.available()) {
Serial.write(Serial1.read());
}
// write messages to ESP-01
while (Serial.available()) {
Serial1.write(Serial.read());
}
}
Use Serial Monitor with 9600 Baud. Select
Both NL & CR.
AT => OK
AT+GMR => Version
AT+RST => Reset
AT+CWLAP => List of WLAN APs
Connect:
AT+CWJAP_DEF=“SSID”,”PASSWORD”
AT+CIFSR => IP/MAC
104. SAMPLE CIRCUIT
Arduino Uno as Bridge + Breadboard Power
Component
Install boardmanager in Arduino IDE:
http://arduino.esp8266.com/stable/package_esp8266com_index.json is
added in Arduino>Preferences >Add Additional
Board Managers URLs
Go to Tools>Board>Boards Manager and select
ESP board: Tools>Board>Generic ESP8266
Module
Restart IDE
Select right port in Tools>Port
To check it use File>Examples>ESP8266/Blink
105. USING ESP8266 AS WIFI SHIELD
On Uno we will use
Pin 2 as RX Port
Pin 3 as TX Port
In Arduino IDE search for
WiFiEsp Library and include it
For example, see articles 23a
and 23b in archive
106. COMMUNICATION BETWEEN TWO ARDUINOS
Connect two Arduinos over serial
line: Tx to Rx and Rx to Tx (yellow
and green wire)
Don’t forget to also connect Gnd to
Gnd (blue wire)
One Arduino is sending numbers to
the second Arduino, …
… second Arduino blinks (LED on
digital pin 8) <received number> + 1
times
107. SERIAL COMMUNICATION
TX
RX
RX
TX
ArduinoOther
System
e.g. USB
of PC or
other
Arduino
2 lines: one for
sending (TX) on pin 1,
one for receiving (RX)
on pin 0
Arduino MEGA has
several serial
communication lines,
UNO and NANO have
only one
10100011 10110100 01111111 11010101 11011011
01100111 00000000 10110101 11001111 00010101
109. CODE – SKETCHES SENDER & RECEIVER
void setup(){ // init. serial communication line
Serial.begin(9600);
}
void loop(){ // send numbers 1 to 10 all the time
for (int count = 1; count <= 10; count++) {
Serial.println(i); //Send to receiver
delay(7000); // let the other board work
}
}
int val;
const int led = 8;
void setup(){
Serial.begin(9600); // init. serial comm.
pinMode(led, OUTPUT); // pin with LED
}
void loop(){ // recv. value n and blink LED n times
int incoming = Serial.available(); // get data
if (incoming > 0) blink(Serial.parseInt());
}
void blink(int howOften) { // blink LED
for (int j = 0; j < howOften; j++) {
digitalWrite(led, HIGH); // LED on
delay(300);
digitalWrite(led, LOW); // LED off
delay(300);
}
delay(1000); // break to better separate events
}
SENDING ARDUINO RECEIVING ARDUINO
110. DESKTOP TO ARDUINO - CODING OPTIONS
• This presentation introduces three choices
for communicating with an Arduino over
serial comm. (USB)
• We could have also used Arduino + WiFi-
shield or Bluetooth-shield
• Or nodemcu which can also be
programmed using the Arduino IDE
• Processing:
• Implemented in Java
• IDE was base for Arduino IDE
• For developers, artists, …
• Java:
• RXTX library
• JavaScript:
• Server-side JS using node.js
• Johnny-five library
111. INTERFACE TO PROCESSING
• Problem: How can we
access Arduino from
Processing?
• Solution: use the
Processing library
• Based on Firmata:
generic protocol for
communicating with
microcontrollers like the
Arduino from software on a
host computer. Arduino IDE based on Processing. Processing language was developed as a
subset of Java to support visual artists, designers, young programmers, .... It
provides stunning Animation, Simulation, Graphics.
112. SERIAL COMMUNICATION BETWEEN ARDUINO AND
PROCESSING
Processing IDE written in Java for artists, electric engineers, SW developers
Arduino IDE is based on processing
Processing IDE Arduino IDE
113. CODE – ARDUINO SKETCH
void setup(){
Serial.begin(9600);
}
void loop(){
// map analog value from (0,1023) to (0,255)
// will be used as a RGB value
int val = map(analogRead(A0), 0, 1023, 0, 255);
// write result to serial line
Serial.println(val);
// time to relax
delay(70);
}
Task:
• Read potentiometer
• send value over serial line
114. CODE – PROCESSING SKETCH
import processing.serial.*; // use serial library
Serial port; // communication port
float potiVal = 0; // variable to hold read values from potentiometer
void setup(){ // used for initialization same as in Arduino
size(150,150); // draw colored rectangle with size 150 x 150
port = new Serial(this, Serial.list()[1], 9600); // access USB for serial communication
port.bufferUntil('n'); // read data from Arduino until NEWLINE
}
void draw(){ // In Processing there is draw() instead of loop()
background(potiVal,0, 0); // draw red rectangle with brightness depending on received value
}
void serialEvent (Serial port){ // called whenever serial data is available
potiVal = float(port.readStringUntil('n')); // read data until NEWLINE; value is in [0, 255]
}
In your case Serial.list()[0] might
be the right port. You may also
directly specify the port such as
“COM3” (Windows) or “/dev/<tty-
usb>” in (Linux, Mac OS)
Task:
• Obtain value from port
• Draw rectangle with Red = value received
115. import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int ledPin = 13; // standard led on board
void setup()
{
println(Arduino.list()); // all detected Arduinos
// we use the first one
arduino = new Arduino(this, Arduino.list()[0], 57600);
arduino.pinMode(ledPin, Arduino.OUTPUT);
}
void draw() // draw instead of loop
{
arduino.digitalWrite(ledPin, Arduino.HIGH);
delay(1000);
arduino.digitalWrite(ledPin, Arduino.LOW);
delay(1000);
}
DIRECT ACCESS TO ARDUINO FROM PROCESSING - CODE
EXAMPLE
Include libraries
Arduino(Firmata) in your
sketch (Menu Item Sketch)
Sketchbook is a subfolder in
in your Documents folder.
The link to the library is in
the download slide of this
presentation.
116. USING JAVASCRIPT
• What we need
• Node.js http://nodejs.org (JavaScript Server
Framework)
• Johnny-Five http://johnny-five.io (JavaScript
Library for accessing Arduinos, BeagleBone,
Raspberry Pi, …)
• Installation:
• Install node.js
• Use the Node Package Manager to install
Johnny-Five: > npm install johnny-
five
• In the Arduino IDE select
File/Examples/Firmata/StandardFirmata and
upload it to your Arduino boards
var five = require("johnny-five");
var board = new five.Board();
board.on("ready", function() {
var led = new five.Led(13);
led.blink(500);
});
+
117. JOHNNY-FIVE EXAMPLE
var five = require("johnny-five");
var board = new five.Board();
board.on("ready", function() {
// Create a standard `led` component
// on a valid pwm pin
var led = new five.Led(11);
led.pulse();
// Stop and turn off the led pulse loop after 10 seconds (shown in ms)
this.wait(10000, function() {
// stop() terminates the interval, off() shuts the led off
led.stop().off();
});
});
118. USING JAVA
• We need the RXTX libraries
• Get RXTX libs from http://rxtx.qbang.org/wiki/index.php/Download
• Install libraries:
• RXTXcomm.jar (for all OS)
• librxtxSerial.{jnilib | dll | so} for your OS
• Make sure, Firmata is installed on your Arduino (see Johnny-Five slides)
• Make sure, that there is no lock (such as /var/lock on Unix). If it is there, unlock using
sudo chmod go+rxw /var/lock)
120. ARDULINK
• To make it even easier, add Ardulink see:
http://www.ardulink.org
121. ONLINE SCENARIOS
• Retrieve e-mail and initiate an action on
Arduino whenever special
subject/header was found in mail
• I have written an example how to
access mail from Java:
https://dl.dropboxusercontent.com/u/2
228034/JavaMailTest.java
• You’ll need to obtain javax.mail
(JavaMail) and include it in your build
path:
https://java.net/projects/javamail/page
s/Home#Download_JavaMail_Release
• You may use Twitter4J to access tweets:
http://twitter4j.org/en/index.html
• You may also provide a Web Server with
JavaScript accessing the Arduino, i.e., a
Dashboard
122. EVEN MORE OPTIONS FOR WRITING ARDUINO
PROGRAMS
• For this list of development tools
including links visit
http://playground.arduino.cc/Main/DevelopmentTools
123. ARDUINO SIMULATORS
• Simulator for
those with
limited tinkering
capabilities or
without interest
• Virtronics not
perfect, but so
far the best
solution I found
for small budget
Running my
Traffic Lighht
example
124. HACKATHON COMPETITION
Invent a cool IoT device in groups of two or three
Use hardware components you got (which is pretty
obvious)
Examples:
Traffic lights on two Arduinos, one is the master, the other
one the slave. Master is configurable via Internet.
Thermometer with temperature being displayed as binary
code on 8 LEDs or as text on LCD display and obtained via
serial communication
Safe locked and unlocked by Arduino when pressing the
right keys. Alarm is send to user when safe is opened
Clock with temperature display: values can be retrieved
over Internet access
125. LAST WORDS: THE PAIN OF ENGINEERING
The major difference between a
thing that might go wrong and a
thing that cannot possibly go
wrong is that when a thing that
cannot possibly go wrong goes
wrong, it usually turns out to be
impossible to get at and repair.
[Douglas Adams]
127. MVP - MOST VALUABLE POWERTOOLS
Multimeters: 20-40€
current, voltage (AC/DC and DC),
resistance, diode testing, capacitance,
inductance
Oscilloscope: ca. 300€
high bandwidth, frequency counter, high
sampling rate, 2 channels plus one
external channel
Variable Power Supply: 50-80€
variable setting of DC output voltage &
current (e.g., 0-30V, 0-5A)
129. BUILDING YOUR OWN ARDUINO
Bill of Material
• 1 x Processor ATMEGA328P DIP
• Optional: 1 x 28 Pin Socket Holder
• 1 x Breadboard (840)
• 1 x Pushbutton
•16 MHZ Oscillator
• 2 x Ceramic Capacitors 22pF
• 1 x Green Led
• 1 x Red Led
• 1 x1N4001 Diode
• 1 x LM8705 Voltage Regulator
• 1 x Electrolyt Capacitor 100yF
• 1 x Electrolyt Capacitor 10yF
• 1 x 10 KOhm Resistor
• 1 x 220 Ohm Resistor
• Wire
• 1 x Battery/Power Supply or
• FTDI breakout board
See also http://www.arduino.cc/en/Main/Standalone
130. USING ARDUINO UNO BOARD AS PROGRAMMER
• You may also buy a programmer or use an
original Arduino Board to program your
atmega and then move the chip to your DiY
board
• But you may also use an Arduino Uno as a
programmer
• Based on SPI (Serial Peripheral Interface):
allows to upload programs to Microcontroller
• Select Uno as board i the tools menu and your
USB port in the Arduino IDE
• Select ArduinoISP (ISP = In-System Program) in
examples menu
• Run it
• If successful, upload Blink example to your DiY
board
Connect Arduino Board 5V, Gnd
to 5V/Gnd terminal of your
breadboard (red and black
wire)
(for larger boards with many
components use separate
power source instead)
Connect digital pin 10 of Uno
board to reset pin of your
atmega (green wire)
Connect digital pins 13, 12, 11
of Arduino Uno to pins 19, 18,
17 of your Arduino on the
breadboard (yellow wires)
131. BURNING A NEW BOOTLOADER
• Bootloader is functionality that communicates over serial line
for uploading your sketches
• Not used when connecting Arduino directly over SPI
• We overwrite boot loader whenever we upload a sketch over
SPI
• However, the original bootloader configures fuses (memory
chunks) to behave as an Arduino Board
• It makes sense to burn the bootloader once whenever you
use a new Arduino Microcontroller
• In Tools menu configure the board
type of your Arduino and the serial
port of your computer
• As programmer choose„Arduino as
ISP“
• Select Burn bootloader in Tools menu
• Select Blink example from IDE
• Hold shift key while pressing the run
button in IDE
• => Will upload sketch via Arduino Uno
board to your Arduino on a
breadboard
133. CAPACITORS, INDUCTORS, AND MORE
• Capacitors store power and smooth signals: available in
different materials (ceramic => poles do not matter ,
electrolyt. => poles do matter). ingredient for High-
Pass/Low-Pass/Band-Pass filters
• Inductors are coils that produce a magnetic field when
current flows, and induce current when moved through a
magnetic field: ingredient of transformators and motors
• Diodes (LEDs are diodes as well) let pass current through
in only one direction)
• Transistors used to build logical gates (like flip-flops) and
switches (to control and separate a high current circuit
from a low power circuit)
Capacitors
and
Inductors
have
dynamic
resistance
(impedance)
134. ICS
Examples
• 555 Timer IC: used as timer, pulse generator, ocsillator
• Half-Bridge (E.g., a SN754410 offers four half bridges) lets you change in
which direction current flows (e.g., motor movement clock- or anti-clock-
wise). It can control high-voltage circuits.
• Operational Amplifiers (e.g., 741, LM 358, LM386) : amplify input100s or
1000s of times => useful as comparators. In feedback mode different
transfer functions can be implemented
• Shift Registers (HC74HC595): take a byte, convert it to a bit-array with
each bit being an output signal. Example application: reduce number of
required pins of a microcontroller
• Opto couplers (e.g., PC817): let a circuit control another circuit without
being wire-connected (light used insteads)
• Darlington transistor (e.g., ULN2003) chains two transistors tofurther
increase the amplification: used to control motors
Visit http://arduino-
info.wikispaces.com/Popular-
ICs to see more details
135. ADDENDUM D: BRIEF DETOUR - IMPLEMENTING
YOUR OWN LIBRARIES
• If you want to provide a library you need to program in C/C++
• Interface defined in header file, implementation in c++ file
/* Header file specifies public contract */
#ifndef Loudspeaker_h
#define Loudspeaker_h
class Loudspeaker {
Loudspeaker();
~Loudspeaker();
public:
void playTone(int freq);
void shutUp();
}
#endif
/* The Implementation File */
#include <Loudspeaker.h>
const byte SPEAKER_PIN = 0x8;
// constructor
Loudspeaker::Loudspeaker() {
pinMode(SPEAKER_PIN, OUTPUT);
}
Loudspeaker::~Loudspeaker() {/* NOP */}
void Loudspeaker::playTone(int freq) {/* ... */}
void Loudspeaker::shutUp() {/* ... */}
Compile with gcc-avr
138. ADDENDUM F: USING ESP-01 WITH ADAPTER
USB to PC: View
from above
CH340G Driver required:
Windows: http://www.wch.cn/download/CH341SER_ZIP.html
Mac: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
Linux:
http://www.wch.cn/download/CH341SER_LINUX_ZIP.html
For Flash Upload: set orange cable to ground, switch pink cable
(RESET) from voltage to ground and back to voltage. You may
just take away ESP-01 from ground and then put it to voltage
again => now ESP-01 is in update mode
139. FLASHING THE FIRMWARE
Example Flasher Tool for Windows:
https://www.espressif.com/sites/default/files
/tools/flash_download_tools_v3.6.3_0.rar
Current AT-Firmware Version:
https://www.espressif.com/sites/default/files
/ap/esp8266_at_bin_v1.5.1.zip
Visit
https://www.espressif.com/en/support/down
load/documents to obtain AT-
Command/Instruction-Set and -Examples
Documentation for ESP8266
Python tools (esptool) are also available
140. INSTALLING ESP8266/ESP-01 IN THE ARDUINO IDE
With special firmware we can use Arduino sketches on our ESP8266/ESP32 board. Our board then
behaves like an Arduino from a coding perspective
Under the hood the Arduino DIE is using other compilers & tools, however
Steps:
• In Preferences>Settings menu specify a new boardsmanager:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
• In menu Tools>ESP8266>Boardsmanager search for „esp8266“ and install component found
• When adapter is connected with the ESP01, choose Generic ESP8266 Module as board and
select the right port
• In serial monitor set mode „Both NL & CR“ and speed 115200 Baud. Type in AT <return> => ESP-
01 should return OK
• Note: If you upload one of the example sketches, its firmware will be overwritten (if we have
previously put GPIO0 to Low legen and then resetted the ESP-01, which brings the ESP-01 in
update mode)
141. AT COMMANDS (USING SERIAL MONITOR)
Eingabe
AT <cr> // Funktion prüfen
OK
AT+CWMODE=3 <cr> // Chip kann als Station oder AP arbeiten
OK
AT+CWJAP=“SSID“,“PASSWORD“ <cr> // Mit WLAN verbinden
WIFI COMPLETED
WIFI GOT IP
AT+UART? <cr> // UART Konfiguration abfragen
<baudrate>,<databits>,<stopbits>,<flowcontrol>
AT+UART_DEF=9600,<databits>,<stopbits>,<flow control> <cr> // UART auf 9600 Baud setzen