MIKRO2 - Teori MK Mikrokontroller
MIKRO2 - Teori MK Mikrokontroller
MIKRO2 - Teori MK Mikrokontroller
Triwiyanto
Expertise on embedded system,
biomedical signal processing,
rehabilitation engineering
WA: 081-5512-6883
Email: [email protected]
Introduction to...
Arduino
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., compar., logical, cond., loop)
3. Analog read
4. Analog write
5. Motor (DC/ Servo/ Stepper)
6. Mid Test (UTS)
7. SPI/ I2C
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Micro-Controller:
It is a micro-computer.
As any computer it has
internal CPU, RAM, IOs
interface.
It is used for control
purposes, and for data
analysis.
• A printed circuit
board designed to
facilitate work with a
particular
microcontroller.
• Typical components include:
• power circuit
• programming interface
• basic input; usually buttons and LEDs
• I/O pins
What is Arduino Not?
todbot.com/blog/bionicarduino
What is Arduino?
A microcontroller board, contains on-board
power supply, USB port to communicate with PC,
and an Atmel microcontroller chip.
It simplify the process of creating any control
system by providing the standard board that can
be programmed and connected to the system
without the need to any sophisticated PCB design
and implementation.
Arduino.
Atmel
MicroController
USB port
Power input
Analog input.
Power Supply
Arduino Program Development
• Based on C++ without 80% of the instructions.
• A handful of new commands.
• Programs are called 'sketches'.
• Sketches need two functions:
– void setup( )
– void loop( )
• setup( ) runs first and once.
• loop( ) runs over and over, until power is lost or a
new sketch is loaded.
Terminology
Arduino C
• Arduino sketches are centered around the
pins on an Arduino board.
• Arduino sketches always loop.
– void loop( ) {} is equivalent to while(1) { }
• The pins can be thought of as global variables.
Digital I/0
pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Arduino Timing
• delay(ms)
– Pauses for a few milliseconds
• delayMicroseconds(us)
– Pauses for a few microseconds
• More commands:
arduino.cc/en/Reference/HomePage
Compiler Features
• Numerous sample
sketches are included in
the compiler
• Located under File,
Examples
• Once a sketch is
written, it is uploaded
by clicking on File,
Upload, or by pressing
<Ctrl> U
Arduino C is Derived from C++
◼ These programs blink an LED on pin 13
• avr-libc • Arduino C
#include <avr/io.h> void setup( ) {
#include <util/delay.h> pinMode(13, OUTPUT);
}
int main(void) {
while (1) { void loop( ) {
PORTB = 0x20; digitalWrite(13, HIGH);
_delay_ms(1000); delay(1000);
PORTB = 0x00; digitalWrite(13, LOW);
_delay_ms(1000); delay(1000);
} }
return 1;
}
Basic Electric Circuit
• Every circuit (electric or electronic) must have
at least a power source and a load.
• The simplest circuit is a light.
• Plug in the light, and it lights up.
• Unplug it, the light goes out.
• Electricity flows from the power source,
through the load (the light) and then back to
the power source.
Void setup ()
Putting It Together {
pinMode (13, OUTPUT)
}
Long: Long variables are extended size variables for number storage,
and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.
Ex. long u=199203;
var = 0;
while(var < 200)
while
{
// do something repetitive 200 times
var++;
}
do...while Syntax:
do
{
// statement block
} while (condition);
Example Code:
do
{
delay(50); // wait for sensors to stabilize
x = readSensors(); // check the sensors
} while (x < 100);
Syntax
if...else VCC
if (condition)
Buat program agar pada saat {
SW ditekan maka LED nyala //statement(s)
Demikian sebaliknya
PIN0 }
VCC
Example:
if (digitalRead(0) == HIGH)
{
digitalWrite(13, HIGH); PIN13
}
digitalWrite(13, LOW)
Example: VCC
digitalWrite(14,LOW) ;0
digitalWrite(11,LOW); pulse
digitalWrite(11,HIGH)
digitalWrite(11,LOW)
x 7x
digitalWrite(12, LOW);
if(condition)
if...else {
statements-1;
…
statement-N;
}
else if(condition2)
{
Statements;
}
Else{statements;}
Syntax
for for (condition)
For (int j=0; j<100; j++) {
{
x = readSensors();
//statement(s)
delay(1000); }
}
v=analogRead(pin);
analogWrite(pin);//PWM.
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
Analog input
0 00 0000 0000 = 0
0.002 00 0000 0001 = 1
:
00 0000 1000 = 8
00 0000 1001 = 9
:
5
11 1111 1111 =1023
0-2V 0-1023
Ax Void setup()
5V {
Aref analogReference(EXTERNAL)
2V
AREF= Eksternal
}
= 0-5V
Void setup()
Ax
0-1,1V 0-1023 {
Aref=1.1 analogReference(INTERNAL)
}
AREF= INTERNAL
= 1,1V Void setup()
{
Ax
0-5V 0-1023 analogReference(DEFAULT)
Aref=5V }
AREF= INTERNAL
Void loop()
= 5V {
Voltage=analogRead(A0)
}
0-2V 0-1023
5V
Ax VRESOLUSI= Vmax/1023
Aref
2V
AREF= Eksternal
= 2V
~ 2 mV/bit
Vresolusi = 2/1023 = 0,001955 V/bit atau ~ 0,002 V/bit
Input (V) Output (bit)
0,000 00 0000 0000
0,002 00 0000 0001
0,004 00 0000 0010
0,006 00 0000 0011
:
2,000 11 1111 1111
Ax
0-1,1V 0-1023
Aref=1.1
AREF= INTERNAL
= 1,1V
Vresolusi = 1,1/1023 = 0,001075 V/bit
Input (V) Output (bit)
0,000000 00 0000 0000
0,001075 00 0000 0001
0,002150 00 0000 0010
0,003225 00 0000 0011
:
1,100000 11 1111 1111
Ax
0-5V 0-1023
Aref=5V
AREF= INTERNAL
= 5V
Gambar 1 Gambar 2
AREF= Eksternal
Fungsi transfer =10mV/ oC
= ?V
ADC tersebut akan digunakan untuk mengukur suhu
0-100 oC. Berapakah tegangan referensi yang harus
diberikan.
0-100 oC = 0 – 1000 mV atau 0 – 1 V
Tugas:
a. Bandingkan resolusi ADC untuk konfigurasi gambar 1
dan gambar 2
b. Listing program sederhana
0-1023 2V
Ax
5V
Aref
?V
Summing
Amp.
1V
-1V
Aside: Potentiometers
(variable resistors, rheostats)
Activity 5 – Volume Knob
• Connect the potentiometer from 5V to GND
• Use analogRead(A0) to measure the voltage on the center pin
• Set the LED blink rate depending on the reading
Activity 6 – Arduino
Thermometer
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
Example: analogRead() display to 0.0 - 5.0
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
Description
1. Writes an analog value (PWM wave) to a pin.
2. An analog value ranges from 0 to 255.
3. In Arduino Uno/Nano microcontroller, Only pins 3, 5,
6, 9, 10, 11 can be used as analog output pins as
they have the ~ sign printed beside their pin
number.
4. The ~ sign means that the pin is PWM-enabled
PWM pin on NANO
PWM pin on MEGA16
Analog Output?
• PWM, also
known as Pulse
Width
Modulation, is a
technique for
getting analog
results with
digital means.
PWM Duty Cycle
output voltage = (on_time / cycle_time) * 5V
• Command:
analogWrite(pin,value)
• Examples:
analogWrite(9, 128)
for a 50% duty cycle
analogWrite(11, 64)
for a 25% duty cycle
Image from Theory and Practice of Tangible User Interfaces at UC Berkley
PulseWidth Modulation (PWM)
PWM available on pins 3, 5, 6, 9, 10, 11
• analogWrite(pin,val)
set the PWM fraction:
– val = 0: always off
– val = 255: always on
• Remember to designate pin
for digital output:
pinMode(pin,OUTPUT);
(usually in setup)
• Default PWM frequency:
– 16 MHz / 215 = 488.28125 Hz
Note: the PWM frequency and
resolution can be changed by
re-configuring the timers
PWM LED Dimmer
• Use PWM to control the brightness of an LED
– connect LED to pin 3, 5, 6, 9, 10 or 11
– remember to use 220 Ω current-limiting resistor
• Set the brightness from the serial port, or
potentiometer ADC 0-255 PWM
0-1023
Useful:
• newValue = map(oldValue, a, b, c, d)
Converts/maps a number in the range (a:b) to a new number in
the range (c:d)
Example:
– newValue = map(oldValue,0,1023,0,255);
analogWrite(pin,value)
//value-→ 0 sd 255 → DC = 0- 100
0-255
3 PWM
Duty Cycle = 0-100
• Standard servo:
– PWM duty cycle controls direction:
– 0% duty cycle → 0 degrees
– 100% duty cycle → 180 degrees
• Continuous-rotation servo:
– duty cycle sets speed and/or direction
Servo Motor Basic Concept (mechanical)
Servo Motor Basic Concept (electrical)
Activity 9 – Servomotor Control
#define servoPin 3
void setup() {
pinMode(servoPin, OUTPUT);
}
void loop() {
// A pulse each 20ms
digitalWrite(servoPin, HIGH);
delayMicroseconds(1500); // ON TIME
digitalWrite(servoPin, LOW);
delayMicroseconds(18500); // OFF TIME
}
A listing program using SERVO Library
#include <Servo.h>
int servoPin = 3;
Servo Servo1;
void setup() {
Servo1.attach(servoPin);
}
void loop(){
Servo1.write(0); // Make servo go to 0 degrees
delay(1000);
Servo1.write(90); // Make servo go to 90 degrees
delay(1000);
Servo1.write(180); // Make servo go to 180 degrees
delay(1000);
}
Driving a servo using ANALOG (ADC)
ADC 10 bit
00 0000 0000 biner
11 1111 1111 biner
0000 desimal
1023 desimal
Loop ()
{
tegangan=readAnalog(A0)
data=map(tegangan, 0,1023, 0,180)
Servo1.write(data);
}
#include <Stepper.h>
const int stepsPerRevolution = 200;
// / change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
void setup() {
// nothing to do inside the setup
}
void loop() {
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}
This semester: 12 meeting & 2 exam
1. Introduction Arduino (a demonstration video)
2. Instruction (arith., comp., logical, cond., loop)
3. Analog input
4. Analog output
5. Motor (DC/ Servo/ Stepper)
6. SPI/ I2C
7. Mid Test (UTS)
8. DHT11 temp./humidity
@meeting:
9. TCS32000 color sensor
1. Lecturing: 30 minute
10.RTC DS1307
2. Exercise: 20 minute
11.MPU 6050 Acc/Gyro
3. Assignment: 5 minute
12.Student presentation
4. Closing: 5 minute
13.Student presentation
14.Final test
SPI/ I2C
Communication: I2C, SPI
• I2C (Inter-Integrated Circuit)
– Developed by Phillips
– Speed = 100 kHz, 400 kHz, and 3.4 MHz (not
supported by Arduino)
– Two bi-directional lines: SDA, SCL
– Multiple slaves can share same bus
• SPI (Serial Peripheral Interface Bus)
– Speed = 1-100 MHz (clock/device limited)
– Four-wire bus: SCLK, MOSI, MISO, SS
– Multiple slaves can share same bus
(but each needs a dedicated SS, slave select)
SPI and I2C on the Arduino
SPI pins:
• SCK = serial clock
• MISO = master in, slave out
• MOSI = master out slave in
• SS = slave select
I2C pins:
• SDA = data line
• SCL = clock line
SDA (A4) SCL (A5)
Connecting Multiple Devices
(I2C and SPI)
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(100);
}
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
delay(500);
}
Basic Arduino I2C Commands
COMMAND EXPLANATION
Wire.begin() Join the I2C bus as master (usually
invoked in setup)
Wire.beginTransmission(address) Begin communicating to a slave
device
Wire.write(byte) Write one byte to I2C bus (after
request)
Wire.endTransmission(address) End transmission to slave device
Note: you must include the Wire library: Note: pinMode() not needed
#include <Wire.h> for I2C on pins A4 and A5
Example: MCP4725 12-bit DAC
MCP4725 write command (taken from data sheet)
7-bit I2C address command power down mode data bits (MSB → LSB)
(1100000) (010) (00)
Note: binary numbers are preceded by B:
B1100000 = 96
Arduino program segment: data >> 4: shift bits left by four positions
Note: you must include the Wire library: Note: pinMode() not needed
#include <Wire.h> for I2C on pins A4 and A5
Activity 12: Sawtooth Wave
• Program the MCP4725 DAC to produce a
sawtooth (ramp) wave:
– What is the frequency of the sawtooth wave?
– Can you make f = 100 Hz?
MCP4725
Note: the I2C bus requires pull-
breakout
up resistors on SCL and SDA
board: (provided on the board)
http://www.sparkfun.com/
Basic Arduino SPI Commands
COMMAND EXPLANATION
SPI.begin() Initializes the SPI bus, setting SCK,
MOSI, and SS to outputs, pulling
SCK and MOSI low and SS high.
byteIn = SPI.transfer(byteOut) Transfer one byte (both send and
receive) returns the received byte
Note: you must include the SPI library: Note: pinMode() not needed
#include <SPI.h>
Example: AD5206 Digital
Potentiometer
Functional block diagram:
Features:
• six independent, 3-
wiper potentiometers
• 8-bit precision
(256 possible levels)
• Available in 10kΩ,
50kΩ and 100kΩ
• Programmed
through SPI interface
AD5206 Write Sequence
Note: same as MOSI
(master out slave in)
Note: same as SS
(slave select)
CLOCK
116
KOMUNIKASI ASINKRON
1. Asinkron berarti tanpa sinkronisasi, sehingga tidak diperlukan
pengiriman sinyal clock.
2. Akan tetapi, pada setiap awalan dan akhiran harus ditandai dengan bit
start dan bit stop.
3. Start bit menunjukkan, bahwa data akan segera dikirim atau diterima,
dan bit stop menyatakan akhiran dari sinyal.
4. Keperluan penambahan pengiriman dua bit ini akan menyebabkan
komunikasi asinkron akan lebih lambat bila dibandingkan dengan
komunikasi sinkron.
5. Pada jalur asinkron, kondisi idle dinyatakan sebagai nilai ‘1’ ( yang juga
disebut sebagai keadaan mark )
117
Asynchronous Transmission Format
• Bit Types
–Start bit
–Data bits
–Parity bit
–Stop bits
118
Definitions
• Start Bit
– Signals the beginning of a word
– Is normally a ‚0‘ and is detected as a transition from high
to low
• Data Bits
– The actual data, which should be transmitted
– Sender and receiver have to agree on the number of data
bits (usually 8)
– Always the least significant bit will be send first
119
Definitions cont
• Parity Bit
– An error check
– Odd or even parity
• Odd parity means the sum of the 1‘s will be odd
• Even parity means the sum of the 1‘s will be even
• You count all bits including the parity bit
– Disadvantage: If two bytes altered by noise, an error
will not be detected by the parity check
120
Definitions cont
• Stop Bits
– These bits mark the end of a data word
– Is usually high (1)
121
Asynchronous Data Transmission
• Example 1:
– Hex# 4A16 is to be sent with one start bit, even parity, 8-
bit data length and two stop bits
– 4A16 = 0100 10102
Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit
0 0 1 0 1 0 0 1 0 1 1 1
122
Asynchronous Data Transmission
• Example 2:
– Hex# B416 is to be sent with one start bit, even parity, 8-
bit data length and two stop bits
– B416 = 1011 01002
Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit
0 0 0 1 0 1 1 0 1 0 1 1
123
Asynchronous Data Transmission
• Example 3:
– Hex# B416 is to be sent with one start bit, odd parity, 8-
bit data length and two stop bits
– B416 = 1011
Start Bit Data Bit 0 Data Bit 1 Data Bit 2 Data Bit 3 Data Bit 4 Data Bit 5 Data Bit 6 Data Bit 7 Parity Bit Stop Bit Stop Bit
0 0 0 1 0 1 1 0 1 1 1 1
124
Baud Rate vs. Bit Rate
125
Baud Rate Calculations
• Example:
– Consider baud rate: 4800 baud
– 12 bits/word = 1 start bit + 8 data bits + 1 parity bit + 2
stop bits
126