Date post: | 04-Apr-2018 |
Category: |
Documents |
Upload: | mohammed-a-isa |
View: | 222 times |
Download: | 0 times |
of 91
7/29/2019 Practical Training on Arduino
1/91
B. amil ZDEN Serkan TARINDepartment of Mechanical Engineering
Middle East Technical University
ME407
Microcontrollers & Arduino
Seminar
Note: This material is adopted from
Dr. Kokus ME 461 Lecture Notes
7/29/2019 Practical Training on Arduino
2/91
2
Outline
Development Procedure
Hardware
Software
Preprocessor Commands
Arduino Example Functions
Serial Port
Digital I/O Ports
Motor Drive (Step, Servo)
ADC
PWM
Misc. functions
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
3/91
3
Hardware Test / Development
Procedure
Build the basic PIC circuit on the breadboard. Keep everything tidy.
Make sure to keep all leads as short as possible.
Pay attention to electrolytic capacitors:
Their polarities are marked on their packages.
Before powering up, double-checkall connectionsand voltage polarities.
Connect your circuit to the serial port of your computer.
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
4/91
4
Hardware Test / Development
Procedure Make sure that the power supply is disconnected
from your circuit and turn the power supply on and
make sure that voltage is set around 7-9 Volts.
Turn the power supply off, connect your circuit on,and turn the supply back on.
Keep your eye on the current indicator, and if yoususpect that the circuit draws too much current,immediately turn the supply off.
Make sure to check the supply voltage of thePICmicro: Vdd = 4.5V to 5.5V (at most).
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
5/91
Programming PIC via
Programmer
BasicCode*.bas PIC Basic
Compiler
compile
Program the PIC
PC
RS232Parallel port
USB
PICPIC Programmer
Hex Code*.hex
download
PIC Programmer
Software
5ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
6/91
6
Programming PIC via
Bootloader
CCode*.c file PIC
Compiler
compile
Download program
to the PIC
PC
RS232PIC with bootloader
previously programmed
Hex Code*.hex
download
PIC ProgrammerSoftware
a. b. koku METU ME
Lectures
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
7/91
Booting the Loader
By default the bootloader
runs at each program start
If the a download attempt is
detected, the program is
read from the PC and loaded
into the PICs program area,and it will be executed
If no download attempt is
detected, last loadedprogram will be executed.
7
Program Memory
Free Memory
User Program
Bootloader code
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
8/91
8
CCS C Compiler
The CCS C compiler, which is developed by
Customer Computer Services (CCS), supports
almost all devices you can find in the market:
PIC12x
PIC16x
PIC18x
Compiler is quite compatible with ANSI C.
Quality of compiled code is very good. The optimizer does a good job in compressing the
code.
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
9/91
Bit / Byte
ME407 Microcontrollers&Arduino
Seminar
9
7/29/2019 Practical Training on Arduino
10/91
7/29/2019 Practical Training on Arduino
11/91
Analog / Digital
ME407 Microcontrollers&Arduino
Seminar
11
7/29/2019 Practical Training on Arduino
12/91
ARDUINO Uno General View
ME407 Microcontrollers&Arduino
Seminar
12
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
Flash Memory32 KB (ATmega328) of which 0.5 KB used
by bootloader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16 MHz
7/29/2019 Practical Training on Arduino
13/91
ARDUINO Uno Power
ME407 Microcontrollers&Arduino
Seminar
13
The Arduino Uno can be powered via the USB connection or with an external power
supply
VIN. The input voltage to the Arduino board when it's using an external powersource (as opposed to 5 volts from the USB connection or other regulated powersource). You can supply voltage through this pin, or, if supplying voltage via the
power jack, access it through this pin.
5V. This pin outputs a regulated 5V from the regulator on the board. The board canbe supplied with power either from the DC power jack (7 - 12V), the USB connector(5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins
bypasses the regulator, and can damage your board. We don't advise it.
3V3. A 3.3 volt supply generated by the on-board regulator. Maximum current drawis 50 mA.
GND. Ground pins.
7/29/2019 Practical Training on Arduino
14/91
ARDUINO Uno I/O
ME407 Microcontrollers&Arduino
Seminar
14
Each of the 14 digital pins on the Uno can be used as an input or output,
using pinMode(), digitalWrite(), and digitalRead()functions. They operate
at 5 volts. Each pin can provide or receive a maximum of 40 mA.
Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data.These pins are connected to the corresponding pins of the ATmega8U2 USB-to-
TTL Serial chip.
External Interrupts: 2 and 3. These pins can be configured to trigger an interrupton a low value, a rising or falling edge, or a change in value. See
the attachInterrupt() function for details.
PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output withthe analogWrite() function.
7/29/2019 Practical Training on Arduino
15/91
ME407 Microcontrollers&Arduino
Seminar
15
ARDUINO Uno I/OThe Uno has 6 analog inputs, labeled A0 through A5, each of which
provide 10 bits of resolution (i.e. 1024 different values). By default they
measure from ground to 5 volts, though is it possible to change the upperend of their range using the AREF pin and the analogReference()
function
7/29/2019 Practical Training on Arduino
16/91
Getting Started with ARDUINO
1 | Get an Arduino board and USB cable
2 | Download the Arduino environment (http://arduino.cc/en/Main/Software)
3 | Connect the board
4 | Install the drivers
5 | Launch the Arduino application
6 | Open your code
7 | Select your board
8 | Select your serial port
9 | Upload the program
ME407 Microcontrollers&Arduino
Seminar
16
7/29/2019 Practical Training on Arduino
17/91
Getting Started with ARDUINO
ME407 Microcontrollers&ArduinoSeminar
17
4 | Install the drivers
Plug in your board and wait for Windows to begin it's driver installation
process. After a few moments, the process will fail, despite its best efforts
Click on the Start Menu, and open up the Control Panel. While in the Control Panel, navigate to System and Security. Next, click on
System. Once the System window is up, open the Device Manager.
Look under Ports (COM & LPT). You should see an open port named
"Arduino UNO (COMxx)"
Right click on the "Arduino UNO (COmxx)" port and choose the "Update
Driver Software" option.
Next, choose the "Browse my computer for Driver software" option.
Finally, navigate to and select the Uno's driver file,
named "ArduinoUNO.inf", located in the "Drivers" folder of the ArduinoSoftware download (not the "FTDI USB Drivers" sub-directory).
Windows will finish up the driver installation from there.
If needed step by step installation link: http://arduino.cc/en/Guide/UnoDriversWindowsXP
7/29/2019 Practical Training on Arduino
18/91
Getting Started with ARDUINO
ME407 Microcontrollers&ArduinoSeminar
18
5 | Launch the Arduino application
6 | Open your code
7/29/2019 Practical Training on Arduino
19/91
Getting Started with ARDUINO
ME407 Microcontrollers&ArduinoSeminar
19
7 | Select your board
7/29/2019 Practical Training on Arduino
20/91
Getting Started with ARDUINO
ME407 Microcontrollers&ArduinoSeminar
20
8 | Select your serial port
7/29/2019 Practical Training on Arduino
21/91
Getting Started with ARDUINO
ME407 Microcontrollers&ArduinoSeminar
21
9 | Upload the program
Simply click the "Upload" button in the environment. Wait a few seconds - you
should see the RX and TX leds on the board flashing. If the upload is
successful, the message "Done uploading." will appear in the status bar.
For more information visit http://arduino.cc/en/Guide/Windows
7/29/2019 Practical Training on Arduino
22/91
Other Arduinos
ME407 Microcontrollers&ArduinoSeminar
22
Arduino Mega 2560
Arduino Motor Shield
Arduino Micro Arduino WiFi Shield
Arduino Proto Shield
7/29/2019 Practical Training on Arduino
23/91
Arduino Libraries
ME407 Microcontrollers&ArduinoSeminar
23
Standard Libraries
EEPROM - reading and writing to "permanent" storage
Ethernet - for connecting to the internet using the Arduino Ethernet Shield
Firmata - for communicating with applications on the computer using a standard
serial protocol.
LiquidCrystal - for controlling liquid crystal displays (LCDs)
SD - for reading and writing SD cards
Servo - for controlling servo motors
SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus
7/29/2019 Practical Training on Arduino
24/91
Arduino Libraries
ME407 Microcontrollers&ArduinoSeminar
24
SoftwareSerial - for serial communication on any digital pins. Version 1.0 and
later of Arduino incorporate Mikal Hart's NewSoftSerial library as SoftwareSerial.
Stepper- for controlling stepper motors
WiFi - for connecting to the internet using the Arduino WiFi shield
Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net ofdevices or sensors.
More info at: http://arduino.cc/en/Reference/Libraries
References: http://arduino.cc/en/Reference/HomePage
7/29/2019 Practical Training on Arduino
25/91
Arduino Code Basics
ME407 Microcontrollers&ArduinoSeminar
25
The setup() function is called when a sketch starts. Use it to initialize variables,
pin modes, start using libraries, etc. The setup function will only run once, after
each powerup or reset of the Arduino board.
loop() function does precisely what its name suggests, and loops consecutively,
allowing your program to change and respond as it runs. Code in
the loop() section of your sketch is used to actively control the Arduino board.
void setup() {// put your setup code here, to run once:
}void loop() {// put your main code here, to run repeatedly:
}
7/29/2019 Practical Training on Arduino
26/91
Arduino Code Basics
ME407 Microcontrollers&ArduinoSeminar
26
const int buttonPin = 3;
// setup initializes serial and the button pin
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
// loop checks the button pin each time,
// and will send serial if it is pressed
void loop() {
if (digitalRead(buttonPin) == HIGH)
Serial.write('H');else
Serial.write('L');
delay(1000);
}
7/29/2019 Practical Training on Arduino
27/91
Arduino Code Examples -1
ME407 Microcontrollers&ArduinoSeminar
27
To build the circuit, attach a 220-ohm resistor to pin 13. Then
attach the long leg of an LED (the positive leg, called the
anode) to the resistor. Attach the short leg (the negative leg,
called the cathode) to ground.
http://fritzing.org/
/ *Bl i nk
Turns on an LED on f or one second, t hen
of f f or one second, r epeat edl y.
Thi s exampl e code i s i n t he publ i cdomai n.*/
/ / Pi n 13 has an LED connect ed on mostAr dui no boar ds. / / gi ve i t a name: i nt l ed = 13;
7/29/2019 Practical Training on Arduino
28/91
Arduino Code Examples -1
ME407 Microcontrollers&ArduinoSeminar
28
/ / t he set up r out i ne r uns once when you pr ess r eset : voi d set up( ) {
/ / i ni t i al i ze t he di gi t al pi n as an out put .
pi nMode( l ed, OUTPUT) ;}
/ / t he l oop r out i ne r uns over and over agai nf or ever : voi d l oop( ) {
di gi t al Wr i t e( l ed, HI GH) ; / / t ur n t he LED on( HI GH i s t he vol t age l evel )
del ay( 1000) ; / / wai t f or a seconddi gi t al Wr i t e( l ed, LOW) ; / / t ur n t he LED of f by
maki ng t he vol t age LOW
del ay( 1000) ; / / wai t f or a second}
7/29/2019 Practical Training on Arduino
29/91
Arduino Code Examples -2
ME407 Microcontrollers&ArduinoSeminar
29
Analog Read Serial
This example shows you how to read analog input
from the physical world using a potentiometer (10k
ohm)
The Arduino has a circuit inside called an analog-to-
digital converterthat reads this changing voltage
and converts it to a number between 0 and 1023.
In between, analogRead() returns a number between
0 and 1023 that is proportional to the amount ofvoltage being applied to the pin.
7/29/2019 Practical Training on Arduino
30/91
7/29/2019 Practical Training on Arduino
31/91
7/29/2019 Practical Training on Arduino
32/91
7/29/2019 Practical Training on Arduino
33/91
Arduino Code Examples - 3
ME407 Microcontrollers&ArduinoSeminar
33
Pulse Width Modulation, or PWM, is a technique for getting analog results
with digital means. Digital control is used to create a square wave, a signal
switched between on and off. This on-off pattern can simulate voltages in
between full on (5 Volts) and off (0 Volts) by changing the portion of the time
the signal spends on versus the time that the signal spends off.
7/29/2019 Practical Training on Arduino
34/91
Arduino Code Examples - 3
ME407 Microcontrollers&ArduinoSeminar
34
Arduino's PWM frequency at about 500Hz,
the green lines would measure
2 milliseconds each.
A call to analogWrite() is on a scale of 0 -
255, such that analogWrite(255) requests
a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on
half the time) for example.
7/29/2019 Practical Training on Arduino
35/91
Arduino Code Examples - 4
ME407 Microcontrollers&ArduinoSeminar
35
Stepper motors, due to their unique design, can be controlled to a high degree
of accuracy without any feedback mechanisms. The shaft of a stepper, mounted
with a series of magnets, is controlled by a series of electromagnetic coils that
are charged positively and negatively in a specific sequence, precisely moving it
forward or backward in small "steps".
7/29/2019 Practical Training on Arduino
36/91
Arduino Code Examples - 4
ME407 Microcontrollers&ArduinoSeminar
36
Unipolar Stepper Circuit
7/29/2019 Practical Training on Arduino
37/91
Arduino Code Examples - 4
ME407 Microcontrollers&ArduinoSeminar
37
Code/ ** Mot or Knob** A st epper mot or f ol l ows t he t ur ns of a pot ent i omet er
* ( or ot her sensor ) on anal og i nput 0.*/
#i ncl ude
/ / change thi s t o the number of st eps on your motor
#def i ne STEPS 100
/ / creat e an i nst ance of t he st epper cl ass, speci f yi ng/ / t he number of st eps of t he mot or and t he pi ns i t ' s/ / at t ached t oSt epper st epper ( STEPS, 8, 9, 10, 11) ;
/ / t he pr evi ous r eadi ng f r om t he anal og i nput i nt pr evi ous = 0;
7/29/2019 Practical Training on Arduino
38/91
Arduino Code Examples - 4
ME407 Microcontrollers&ArduinoSeminar
38
voi d setup( ){
/ / set t he speed of t he mot or t o 30 RPMsst epper . set Speed(30);
}
voi d l oop( ){
/ / get t he sensor val uei nt val = anal ogRead(0) ;
/ / move a number of st eps equal t o t he change i n t he/ / sensor r eadi ngst epper . step( val - pr evi ous) ;
/ / r emember t he pr evi ous val ue of t he sensor
pr evi ous = val ;}
7/29/2019 Practical Training on Arduino
39/91
QUESTIONS
ME407 Microcontrollers&ArduinoSeminar
39
7/29/2019 Practical Training on Arduino
40/91
7/29/2019 Practical Training on Arduino
41/91
7/29/2019 Practical Training on Arduino
42/91
Bit, byte vs kavramlar Alabilecekleri siteler
ME407 Microcontrollers&ArduinoSeminar
42
7/29/2019 Practical Training on Arduino
43/91
43
Generic CCS C Program
A generic C program for PICmicro constitutes
Preprocessor commands / directives:
Hardware Information PICMicro type, clock frequency, etc.
Configuration of PICMicro
Configuration (mode) bits
Parameters of peripheral units Compiler options and other declarations
Optimization option
Program starting address, file register declarations, etc.
Main program Initialization of peripheral units
Calling built-infunctions for the initialized units
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
44/91
P C d (C d)
7/29/2019 Practical Training on Arduino
45/91
45
Preprocessor Commands (Contd)
#f uses opt i ons tells the compiler about the configuration andoperating mode of the device:
HS option defines the oscillator type as high-speed resonator (>> 4MHz).
Other oscillator options are
XT (standard crystal with a typical. freq. of 4MHz)
LP (low power oscillator)
RC (resistor-capacitor oscillator)
NOWDT tells the compiler that no Watch Dog Timer is utilized. A safety measure in case the execution of the your program gets out of hand!
NOPROTECTspecifies that flash memory is NOT protected:
Resident program could be read/decompiled/reviewed without authorization.
NOLVP informs the compiler that no low voltage programming is to beallowed on this device.
ME407 Microcontrollers&ArduinoSeminar
P C d (C td)
7/29/2019 Practical Training on Arduino
46/91
46
Preprocessor Commands (Contd)
#or g st ar t addr , f i nal addr {}
reserves memory in flash memory (ROM). #or g 0x1F00, 0x1FFF{} reserves the last 255-wordof the ROM for the bootloader (a.k.a. operating
system programof your PICmicro).
#opt opt i on tells the compiler optimizationlevel of your code:
0: lowest
9: highest (leads to the most-efficient compiled code)
ME407 Microcontrollers&ArduinoSeminar
CCS C F ti
7/29/2019 Practical Training on Arduino
47/91
47
CCS C Functions
CCS C built-in functions covered: Serial port (RS-232 / UART)
Digital (discrete) I/O ports A/D converter
Pulse width modulator
Counters/timers Interrupts
Timer interrupts
External interrupt
Miscellaneous functions
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
48/91
Di it l O t t F ti
7/29/2019 Practical Training on Arduino
49/91
49
Digital Output Functions
CCS C provides a number of output functions:
out put _hi gh( PI N_X#) applies 5V to PIN_X#: # is a (bit) number between 0 and (usually) 7.
X is the port name (A, B, ..., G).
out put _l ow( PI N_X#) applies 0V to the output pin.
out put _bi t ( PI N_X#, st at e) applies either 5V or
0V to the pin depending on the state specified.
out put _X( val ue) applies a set of voltages to all
pins of port X depending on the given logic states.
ME407 Microcontrollers&ArduinoSeminar
Digital Input Functions
7/29/2019 Practical Training on Arduino
50/91
50
Digital Input Functions
Here are some digital input functions of CCS C:
i nput ( PI N_X#) returns the logic state of PIN_X#:
5V 1 (High LS)
0V 0 (Low LS)
i nput _X( ) returns the entire logic states of port X.
Type of digital I/O can be specified through thefollowing preprocessor commands:
#use st andar d_i o( X) (in effect, if omitted)
#use f i xed_i o( X_out put s = PI N_X#, PI N_X#, . . . )
#use f ast _i o( X) (we shall prefer this one!)
ME407 Microcontrollers&ArduinoSeminar
Digital I/O Functions (Contd)
7/29/2019 Practical Training on Arduino
51/91
51
Digital I/O Functions (Cont d)
When #use f ast _i o( X) is used, the compiler
performs digital I/O without (re)programming the
direction register (TRISX).
User must ensure TRISX is set correctly via
set _t r i s_X( st at e) :
Bits of byte statecorrespond to directions of the pins of port
X.
If bit is 1, that pin is defined as (1)nput.
Otherwise, it is an (0)utput pin.
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
52/91
7/29/2019 Practical Training on Arduino
53/91
Example Digital I/O
7/29/2019 Practical Training on Arduino
54/91
54
Example Digital I/ORB0
470
RB1
10 k
Vdd = 5V
ButtonLED
Write a C program for a
PIC16F877A interfacing with
a push button that toggles the
shownLED as the buttongets to be depressed.
Solution:
In this exercise, the PICmicroturns into a simple toggle flip/flopdriving a LED. LED and the button are connected to thePI N_B0 (output: 0) and PI N_B1 (input: 1) respectively. Assuming that
no other elements are connected to PORTB, port-pin directions
are simply set by set _t r i s_b( 0xFE) (remaining pins are defined as inputs!)
- Note that 0xFE (hex) = 0b11111110 (bin) = 254 (dec)
ME407 Microcontrollers&ArduinoSeminar
Example Digital I/O
7/29/2019 Practical Training on Arduino
55/91
55
Example Digital I/O
#i ncl ude #f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)
#use f ast _i o( B) / * t r i s_b must be set pr oper l y! */#or g 0x1F00, 0x1FFF {}#opt 9
voi d mai n( ) {i nt 1 Q = 0;
set _t r i s_b( 254) ; / * onl y PI N_B0 i s def i ned as out put */pr i nt f ( "Program st ar t s. . . \ n\ r " ) ;
whi l e( TRUE) { / * i nf i ni t e l oop * /i f ( ! i nput ( PI N_B1) ) { / * when swi t ch i s depr essed. . . */
Q = ! Q; / * . . . t oggl e LED st at e */del ay_ms( 200) ; / * . . . wai t f or 0. 2s t o de- bounce */out put _bi t ( PI N_B0, Q) ; }; / * . . . out put LED st at e */
}}
ME407 Microcontrollers&ArduinoSeminar
Accessing RAM Directly
7/29/2019 Practical Training on Arduino
56/91
56
Accessing RAM Directly
CCS C allows direct access to the RAM including the
(file) registers like PORTX:
#byt e t ag = addr ess associates the byte at the specifiedaddress with the given tag.
#bi t t ag = addr ess. n associates the nth bit of byte residing
at the specified address with the given tag.
While accessing PORTX registers, one must set thedirections of each pin correctly via set _t r i s_X( st at e)
function.
Some useful addresses (refer to the datasheet) are
PORTA = 0x05, PORTB = 0x06
PORTC = 0x07, PORTD = 0x08
ME407 Microcontrollers&ArduinoSeminar
Example 2b Digital I/O
7/29/2019 Practical Training on Arduino
57/91
57
Example 2b Digital I/O#i ncl ude #f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)#use f ast _i o( B) / * t r i s_b must be set pr oper l y! */#or g 0x1F00, 0x1FFF {}#opt 9
#byt e PORTB = 0x06 / * cont r ol r egi st er f or Por t B */ #bi t SW = PORTB. 1 / * RB1 i s connect ed t o swi t ch */ #bi t LED = PORTB. 0 / * RB0 dr i ves a LED */
voi d mai n( ) {i nt 1 Q = 0;set _t r i s_b( 254) ; / * onl y RB0 i s def i ned as out put */pr i nt f ( "Program st ar t s. . . \ n\ r " ) ;whi l e( TRUE) { / * i nf i ni t e l oop * /
i f ( ! SW) { / * when swi t ch i s depr essed. . . */
Q = ! Q; / * . . . t oggl e LED st at e */del ay_ms( 200) ; / * . . . wai t f or 0. 2s t o de- bounce */LED = Q; }; / * . . . out put LED st at e */
}}
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
58/91
Example Serial Port
7/29/2019 Practical Training on Arduino
59/91
59
Example Serial Port
#i ncl ude / * PI CMi cr o Model : 16F877A */#f uses HS, NOWDT, NOPROTECT, NOLVP / * Devi ce conf i gur at i on */
#use del ay( cl ock=20000000) / * CLK f r equency: 20MHz * / #use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7) / * RS- 232 par amet er s */#or g 0x1F00, 0x1FFF {} / * Reser ve memor y i n ROM */#opt 9 / * Compi l er opt . l evel ( max) */
voi d mai n( ) {
char c;l ong nc = 0;pr i nt f ( *** PI C Typewr i t er ***\ n\ r " ) ;do{
c = get c( ) ; / * Get a char act er f r om PC */putc(c); / * Send i t back t o PC */nc++; / * Count char s * /i f ( nc == 13) pr i nt f ( " \ n" ) ; / * Li ne f eed */
} whi l e ( c! =0x11) ; / * Echo unt i l ct r l - Q */pr i nt f ( "\ n\ r No. of char act er s: %l d\ n\ r " , nc) ;whi l e( TRUE) ; / * I nf i ni t e l oop * /
}
As an illustration of these functions, let us write a simple C program
which turns the serial port monitor (siow) into a typewriter:
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
60/91
A/D Conversion (Contd)
7/29/2019 Practical Training on Arduino
61/91
61
A/D Conversion (Cont d)
The following functions are utilized to select a
ADC channel and to read the result:
set _adc_channel ( n) selects the pin RAn as theinput channel.
r ead_ADC( ) returns the 10-bit result.
One must wait at least 10 to 20 s beforereading the result.
ADC unit can generate an interrupt when a
conversion is done. A useful feature for time-sensitive apps.
ME407 Microcontrollers&ArduinoSeminar
Example 3 ADC
7/29/2019 Practical Training on Arduino
62/91
62
Example 3 ADC470
a
b
c
d
e
f
g K
470
LS 5015-20
RC4
RC5
RC3
RD0
RD1
RD3
RD2
Vdd = 5V
20 k(pot.)
470 RA0
AN0
a
b
c
d
e
f
g
Consider a PIC16F877A connected to a seven segment display (SSD)
along with a 20k potentiometer as illustrated. Write a C program suchthat the PIC shows the applied voltage at RA0 pin as a hexadecimal
number (0 F) on the SSD. Furthermore, hex. numbers 0 and F mustblink on the display while the PIC is to send the strings lowand high
respectively over the RS-232.
ME407 Microcontrollers&ArduinoSeminar
7/29/2019 Practical Training on Arduino
63/91
Example 3 C Code
7/29/2019 Practical Training on Arduino
64/91
64
Example 3 C Code#i ncl ude #devi ce ADC=10 / * devi ce has 10- bi t ADC */#f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)
#use f ast _ i o( C)#use f ast _i o( D)#or g 0x1F00, 0x1FFF {}#opt 9
voi d ss_di sp( i nt num) { / * seven segment di spl ay r out i ne */
/ // / Due t o t hi s def i ni t i on, di sp_dat a now r esi des i n ROM!/ /
byt e const SSDat a[ 16] = {123, 80, 103, 117, 92, 61, 63, 120,127, 125, 126, 31, 7, 87, 47, 46};
i f( num < 16) {out put _c( ( SSDat a[ num] & 240) >>1) ;out put _d( SSDat a[ num] & 15) ;
}}
ME407 Microcontrollers&ArduinoSeminar
Example 3 C Code (Contd)
7/29/2019 Practical Training on Arduino
65/91
65
a p e 3 C Code (Co t d)voi d mai n( ) {
l ong adval ;set _t r i s_c( 128) ; set _t r i s_d( 0) ; / * def i ne I / O pi ns f i r st * / out put _c( 0) ; out put _d( 0) ; / * cl ear di spl ay */set up_por t _a( ALL_ANALOG) ; / * set up ADC */set up_adc( ADC_CLOCK_I NTERNAL) ;set _adc_channel ( 0) ;pr i nt f ( "Pr ogr am st ar t s. . . \ n\ r " ) ;whi l e( TRUE) {
del ay_us( 200) ; / * make sure ADC i s r eady */ adval = r ead_ADC( ) ; / * r ead 10- bi t r esul t */
ss_di sp( adval >>6) ; / * di spl ay ( adval / 64) */i f ( adval 960) { / * t oo hi gh or t oo l ow? */
i f ( adval 960) pr i nt f ( "Hi gh\ n\ r " ) ;del ay_ms( 200) ; / * bl i nk t he number . . . */ out put _c( 0) ; out put _d( 0) ; / * . . . on t he di spl ay */del ay_ms( 200) ;
}}
}
ME407 Microcontrollers&ArduinoSeminar
Example 4 PWM
7/29/2019 Practical Training on Arduino
66/91
66
p
470 a
b
c
d
e
f
g K
470
LS 5015-20
RC4
RC5
RC3RD0
RD1
RD3
RD2
Vdd
= 5V
20 k(pot.)
470 RA0
RC2
470
CCP1
AN0
Consider a PIC16F877A connected to a SSD along with a 20k pot. Write aC program such that the PICMicro shows the applied voltage at RA0 pin as a
Hex. number (0 F) on the SSD. Furthermore, it is to adjust the brightness of the
LED (connected to the pin of CCP1) via PWM as the the voltage on RA0 varies.
ME407 Microcontrollers&Arduino
Seminar
Example 4 PWM
7/29/2019 Practical Training on Arduino
67/91
67
pvoi d mai n( ) {
l ong adval ;set _t r i s_c( 128) ; set _t r i s_d( 0) ; / * def i ne I / O pi ns f i r st * / out put _c( 0) ; out put _d( 0) ; / * cl r 7- segment di spl ay */
set up_ccp1( CCP_PWM) ; / * conf i gur e CCP1 as PWM */setup_t i mer _2( T2_DI V_BY_1, 255, 1) ; / * PWM f r equency: ~20kHz */
set up_por t _a( AN0) ; / * onl y AN0 i s used her e! */set up_adc( ADC_CLOCK_DI V_2) ; / * T_AD = 2*T_CLK */
set _adc_channel ( 0) ;
pr i nt f ( "Progr am st ar t s. . . \ n\ r " ) ;whi l e( TRUE) {
del ay_us( 200) ;adval = r ead_ADC( ) ; / * r ead 10- bi t r esul t */
set _pwm1_dut y( adval ) ; / * d( %) = 100*adval / 1024 */ ss_di sp( adval >>6) ; / * di spl ay ( adval / 64) */
}}
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
68/91
7/29/2019 Practical Training on Arduino
69/91
7/29/2019 Practical Training on Arduino
70/91
7/29/2019 Practical Training on Arduino
71/91
Timer 1 Model
7/29/2019 Practical Training on Arduino
72/91
72Timer Interrupt
Internal
PICmicroClock
Internal
PICmicro
Clock
External
Frequency
Source
External
Frequency
Source
Frequency
Divider
Frequency
Divider
8-bit
Counter
8-bit
Counter
set _t i mer 1( val ue)
T1_DI V_BY_1T1_DI V_BY_2T1_DI V_BY_4T1_DI V_BY_8
get _t i mer 1( )
a
bRC0/T1CK1
a:T1_I NTERNALb:T1_EXTERNAL or
T1_EXT_SYNCH
(20 MHz / 4)
D
CLK
Q
a:T1_I NTERNAL orT1_EXTERNAL
b:T1_EXT_SYNCH
a
bD-F/F
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
73/91
Example 5a Timer0
7/29/2019 Practical Training on Arduino
74/91
74
#i ncl ude #f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)#use f ast _ i o( B)#or g 0x1F00, 0x1FFF {}
#opt 9#bi t SW = 0x06. 1 / * RB1 i s t he swi t ch i nput */
voi d mai n( ) {i nt count ;
set _t r i s_b( 255) ; / * Al l pi ns ar e i nput s */ set up_count ers( RTCC_EXT_L_TO_H, RTCC_DI V_1) ; / * Set up RTCC */set _t i mer 0( 0) ; / * I . C. = 0 */whi l e( TRUE) {
count = get _t i mer 0( ) ; / * Read ct r 0 */i f( ! SW) { / * When SW i s depr essed. . . */
pr i nt f ( "Count er0 = %u\ n\ r " , count ) ; / * . . . send i t out ! * / del ay_ms( 200) ; }; / * Wai t 200 ms t o debounce */
}}
ME407 Microcontrollers&Arduino
Seminar
Example 5b Timer1
7/29/2019 Practical Training on Arduino
75/91
75
#i ncl ude #f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)#use f ast _ i o( B)#or g 0x1F00, 0x1FFF {}
#opt 9#bi t SW = 0x06. 1 / * RB1 i s t he swi t ch i nput */
voi d mai n( ) {l ong count ;
set _t r i s_b( 255) ; / * Al l pi ns ar e i nput s */ set up_t i mer_1( T1_EXTERNAL| T1_DI V_BY_1) ; / * Set up Ti mer 1 */set _t i mer 1( 0) ; / * I . C. = 0 */whi l e( TRUE) {
count = get _t i mer 1( ) ; / * Read ct r 1 */i f( ! SW) { / * When SW i s depr essed. . . */
pr i nt f ( "Count er 1 = %l u\ n\ r " , count ) ; / * . . . send i t out ! * / del ay_ms( 200) ; }; / * Wai t 200 ms t o debounce */
}}
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
76/91
Interrupt Functions
7/29/2019 Practical Training on Arduino
77/91
77
In CCS C, ISRs (interrupt-handlerfunctions) are marked up via a compilerdirective: #I NT_XXXX where XXXX stands for the type of interrupt.
The interrupt service procedures are embedded inside this function.
Interrupts must be enabled at the beginning of main function:
enabl e_i nt er r upt s( I NT_XXXX) sets the interrupt enable flag at the givenlevel.
enabl e_i nt er r upt s( GLOBAL) enables all interrupts.
Other relevant built-in functions are di sabl e_i nt er r upt s( I NT_XXXX)
di sabl e_i nt er r upt s( GLOBAL) cl ear _i nt er r upt ( I NT_XXXX) clears the interrupt flag at the given level.
Interrupts available in PIC 16F877A are External interrupt (INT_EXT)
Timer interrupts (INT_RTCC, INT_TIMER1)
Change on (Port B) pin interrupt (INT_RB)
A/D conversion complete interrupt (INT_AD) Serial port interrupts (INT_RDA, INT_TBE)
And more... }
of major
interest
ME407 Microcontrollers&Arduino
Seminar
Timer Interrupts
7/29/2019 Practical Training on Arduino
78/91
78
Timer0 (RTCC) and Timer1 are frequently used to generate
(precise) periodic interrupts for timing-sensitive applications like
digital control systems!
When RTCC orTimer1 counter overflows, it generates an interrupt.
Once the timer is set up in the main function, its interrupt is enabled.
Timers are set up such that the internal clock drives their counters.
The functions discussed in previous section are employed for this
purpose:
Timer0 (or RTCC):
set up_count er s( RTCC_I NTERNAL, RTCC_DI V_n)
Prescaler: n {1, 2, 4, 8, ..., 256}
Timer1:
set up_t i mer _1( T1_I NTERNAL| T1_DI V_BY_n) Prescaler: n {1, 2, 4, 8}
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
79/91
Timer Interrupts (Contd)
7/29/2019 Practical Training on Arduino
80/91
80
One can precisely set the desired interrupt frequency (fd)
[Hz] by selecting the initial value (m0) of timerX:
d
X
fnm
6
)1(80
105int2
Hence, at the beginning of ISR, the counter value is set
to m0 using set _t i mer X( m0) . As an illustration, letus calculate the initial counter value for timer0 (withRTCC_DI V_128 option: n = 128) if fd = 750 Hz:
20452256750128
105int26)01(8
0
m
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
81/91
Example 6a - C program
7/29/2019 Practical Training on Arduino
82/91
82
/ // / Pr epr ocessor di r ect i ves ar e same as Exampl e 5a/ /l ong count = 0; / * Gl obal var i abl e */
#I NT_RTCC / * I SR f or t i mer 0- over f l ow i nt er r upt */ voi d i sr ( ) {count ++; }
voi d mai n( ) {set _t r i s_b( 255) ; / * Al l pi ns of Por t B ar e i nput s */ set up_count er s( RTCC_I NTERNAL, RTCC_DI V_256) ; / * Set up RTCC */set _t i mer 0( 0) ; / * I . C. = 0 */enabl e_i nt er r upt s( I NT_RTCC) ; / * Enabl e i nt er r upt s */ enabl e_i nt er r upt s( GLOBAL) ;whi l e( TRUE) {
i f( ! SW) { / * When SW i s depr essed. . . */
pr i nt f ( "Count er = %l u\ n\ r " , count ) ; / * . . . send i t out ! * /del ay_ms( 200) ; }; / * Wai t 200 ms t o debounce */
}}
ME407 Microcontrollers&Arduino
Seminar
External Interrupt
7/29/2019 Practical Training on Arduino
83/91
83
PIC16F877A allows the use of a single external
interrupt (INT_EXT):
External (interrupt) source must be connected toRB0/INT pin.
Before enabling the external interrupt, the type
of clock edge triggering intrerupt should be
specified:
ext _i nt _edge( L_TO_H) denotes the positive edge
of the clock triggers the interrupt.
ext _i nt _edge( H_TO_L) denotes the negative
edge of the clock triggers the interrupt.
ME407 Microcontrollers&Arduino
Seminar
Example 6b External Interrupt
7/29/2019 Practical Training on Arduino
84/91
84
In this example, the external clock is to be coupled to RB0/INT pin. We will
write a C program for the PICmicro such that it will count the pulses ofexternal clock and will send out counter values to the serial port monitor (PC)
whenever the pushbutton is depressed.
+
RB0/INT1
CD40106B
2
20 k
100 FVdd (14) = 5VV
ss(7) = GND
RB1
10 k
Vdd
= 5V
Button
ME407 Microcontrollers&Arduino
Seminar
Example 6b External Interrupt
7/29/2019 Practical Training on Arduino
85/91
85
/ // / Pr epr ocessor di r ect i ves ar e same as Exampl e 5a/ /l ong count = 0; / * Gl obal var i abl e */
#I NT_EXT / * I SR f or ext er nal B0 i nt er r upt */ voi d i sr ( ) {count ++; }
voi d mai n( ) {set _t r i s_b( 255) ; / * Al l pi ns of Por t B ar e i nput s */
ext _i nt _edge( L_TO_H) ; / * I nt er r upt on ( +) edge */enabl e_i nt er r upt s( I NT_EXT) ; / * Enabl e i nt er r upt s */ enabl e_i nt er r upt s( GLOBAL) ;whi l e( TRUE) {
i f( ! SW) { / * When SW i s depr essed. . . */
pr i nt f ( "Count er = %l u\ n\ r " , count ) ; / * . . . send i t out ! * /del ay_ms( 200) ; }; / * Wai t 200 ms t o debounce */
}}
ME407 Microcontrollers&Arduino
Seminar
Pin-change Interrupt
7/29/2019 Practical Training on Arduino
86/91
86
In 16F877A, pin change interrupt (INT_RB) is
used to detect the logic state changes at pin
RB7-RB4. If there is any change in these four inputs,
PICmicro generates an interrupt.
This interrupt is intended forkeyboard wake-up Microchip does not recommend the utilization of this interrupt
for any other applications.
Any read or write to Port B (say RB3-RB0) clears the
mismatch condition.
ME407 Microcontrollers&Arduino
Seminar
Example 6c Pin Change Interrupt
7/29/2019 Practical Training on Arduino
87/91
87
In this exercise, we would like to develop a C program for PICmicro so that the
microcontroller measures the input frequency (Hz) of the external clock at RB7
and transmits that information through the serial port. Note that for testing
purposes,a LED coupled to RB1 pin gets toggled whenever a pin-changeinterrupt is generated.
RB1
470
+
RB71
CD40106B
2
20 k
100 FV
dd
(14) = 5V
Vss (7) = GND
ME407 Microcontrollers&Arduino
Seminar
Example 6c RB Change Interrupt#i l d 16F877A h
7/29/2019 Practical Training on Arduino
88/91
88
#i ncl ude #f uses HS, NOWDT, NOPROTECT, NOLVP#use del ay( cl ock=20000000)#use r s232( baud=19200, xmi t =PI N_C6, r cv=PI N_C7)#or g 0x1F00, 0x1FFF {}
#use f ast _ i o( B)#opt 9#bi t LED = 0x06. 1 / * RB1 dr i ves a LED */
i nt count = 0; / * Gl obal var i abl es */shor t Q = 0;
#I NT_RB / * RB Change I SR */voi d i s r ( ) {
count ++; / * Count changes */Q = ! Q; / * Toggl e LED */
LED = Q; / * must R/ W t o Por t B bef or e cl ear i ng RBI F */cl ear _i nt er r upt ( I NT_RB) ; / * Cl ear RBI F */
}
ME407 Microcontrollers&Arduino
Seminar
7/29/2019 Practical Training on Arduino
89/91
EEPROM Commands
7/29/2019 Practical Training on Arduino
90/91
90
PIC 16F877A incorporate 256-byte non-volatile
memory.
The user can access EEPROM through thefollowing built-in functions of CCS C:
r ead_eepr om( addr ess) reads a byte from the
EEPROM at the specified address (8-bit). The address ranges between 0 and 255 for PIC 16F877A.
wr i t e_eepr om( addr ess, val ue) writes a byte
(value) to EEPROM at the specified address.
This function takes several milliseconds to execute.
ME407 Microcontrollers&Arduino
Seminar
Watch Dog Timer (WDT)
7/29/2019 Practical Training on Arduino
91/91
91
The WDT function is to monitor the computer system whether work
normally.
Otherwise, it will have some measures to fix up the system.
The main reason of the WDT is that software sometimes got lost: Enter infinite loops
Unexpected (conditional) branching puts the routine to go crazy.
The WDT unique intention is to reset the machine if certain
programmable timer expires. Therefore properly operating"software should "reset"WDT before it does!
For instance, if you program the WDT to 1 second, you should reset the
WDT timer before that happens.
If a routine gets lost, the WDT will reset your machine in onesecond, so not much is wasted.
ME407 Microcontrollers&Arduino
Seminar