Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
103 views

Embedded System Microcontroller Interact

Uploaded by

Ahmad Osman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Embedded System Microcontroller Interact

Uploaded by

Ahmad Osman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 258



 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
Appendix Programming Microcontrollers

Open-Source multipurpose interactive embedded systems


Microcontroller kit for laboratory education

WALID BALID
Faculty of EEE, University of Aleppo
Aleppo – Syria
2009

Faculty of Electrical and Electronic Eng. 253 Automatic Control & Automation Dept.
   

Acknowledgment :

I would thanks Mr. Mark ALBERTS the programmer of BASCOM-AVR, this kit has been designed and
tested with BASCOM.

Introduction:

The kit development aimed at designing a universal training board that can cover a wide range of
experiments for the electronics, communication, control, and power departments of the electrical and
electronics engineering.

The kit has followed in the designing process all standards, so it can utilize any AVR MCU or any SPI
protocol compatible one. The MCU programming can be done by all GNU based compilers with both
low-level (ASM) and high-level (Basic, Pascal, C, or C++.) MCUs programming languages.

Many peripherals have been placed on the board to enrich its universality. About 70 different
experiments (on basic, intermediate, and advanced level) have been developed.

There has been 47 peripherals unit selected and the units were placed on the board in a way that saves
a comfortable working space and separates the elements of each unit from the other units.

Since a good planned student-centric approach has proven effectiveness in engaging students, the
experiments manual was designed in a student-centred manner, so that the students can perform
proceed with the experiment and develop the aimed skills without a need of teacher supervision.

A detailed description including schematics, experiments, and How to Build recipe have been made
available for the students as an open source to enable them to build their own board, and give them
even more deeper centric role in this experiential part of engineering.
 254 
Appendix Programming Microcontrollers

It is planned to put these resources on the web making the prototype available to implement for any
practicing engineering student. It is hoped that the open source approach will attract academic staff
and/or students to develop more experiments based on the rich peripheral components of the kit.

The average cost of building our board is about 120$, while any similar commercial kit will cost more
than 700$.

Selection of the designed experiments has been taught in Spring 2008/2009 for about 65 students in the
Electrical Engineering faculty at Aleppo University.

So, here we go. I will put the whole system between your hands.

The Kit Block Diagram:

The MCU ATmega128 is the kit core and it is linked with the kit peripherals such as a Liquid Crystal
Display LCD through I/O ports. It is linked with the kit serial communication units, e.g. CAN, RS232,
USB, RS485, PS2, I2C, and 1-wire through the serial interfaces. It is linked with the analog sensors, e.g.
temperature or pressure, through Analog to Digital (AD) convertors. It utilizes the external interrupts I/O
ports to interface with the switch buttons and the rotary encoder. The serial port I2C is connected with
the data memory EEPROM (AT24C512 chip), and the real time chip RTC (DS1307 chip).

Faculty of Electrical and Electronic Eng. 255 Automatic Control & Automation Dept.
   

The serial port SPI is connected with the programming unit (STK300) of the MCU and the voice chip
APR6016, it is also linked with an MMC card and a data flash memory (AT25xx). The serial port UART0
is connected with USB interface (FT232R chip) and with COM port through RS232 protocol for
facilitating PC connection. The serial port UART2 is connected with a CAN port for facilitating industrial
communication purposes. The Figure below shows the kit block diagram. All peripherals that needs
external communication with the surrounding world are linked to the grey boxes.

Hands-on Experiments that can be done with the kit:

1. Programming the MCU ports for displaying LEDs light movements


2. Interfacing switches with the MCU ports
3. Interfacing 4x4 Hexadecimal Array Keypad (16key) with the MCU
4. Interfacing and programming the MCU with a 20x4 LCD
5. Interfacing and programming the MCU with a 128x4 GLCD
6. Interfacing and scanning Quad seven-segment display
7. IR remote control sender/receiver based on RC5 code
8. Data Transfer using RF Transmitter based on FSK modulation
9. Interfacing and programming the MCU with Real-time clock chip
10. DAC by Interfacing 8-bit ladder network with the MCU
11. Programming the MCU analog comparator unit
12. Digital Frequency counter/meter 1HZ – 4MHz
13. Measuring the luminous intensity (Flux) using LDR
14. Measuring the barometric pressure and altitude using a Barometer
15. Interfacing with the LM35DZ analog temperature sensor
16. Storing Data using MMC/SD card in FAT23 format
17. Programming Smart-Card with high-security software algorithms
18. Interfacing and Programming 32x8pixel LED-Matrix scrolling Display
19. Speed control of DC motor using PWM
20. Interfacing the MCU with PC using RS232 protocol
21. wide area data transfer using the industrial CAN protocol
22. Interfacing with RS485 for wide area data transfer Digital Scientific calculator by Interfacing LCD
(liquid crystal display) and Hexadecimal Keypad with AVR MCU.
23. Adjustable Signal Generator (Sin, Cos, Smooth, Triangular, square) by Interfacing GLCD
(Graphical liquid crystal display), button Keys, and variable resistor with AVR MCU.
24. RC5 code based, IR (Infrared) remote control sender/receiver, by interfacing IR receiver module
unit and IR transmitter diode with AVR MCU.
25. Obstacle detection using IR transmitter.
26. Interfacing Barometer with AVR MCU for measuring barometric pressure and altitude.
27. Interfacing RTC (Real Time Clock) chip (DS1307) for real time application.
28. Speed control of DC motor using PWM (Pulse width modulation)
29. Interfacing 8-bit ladder network with AVR MCU for DAC purpose.
30. Interfacing RS485 converter with UART serial interface for long area data transfer
31. Interfacing AVR MCU with PC using RS232 converter and USART serial interface
32. Digital Frequency counter/meter 1HZ – 4MHz
33. Programming Smart-Card with high-security software algorithms using the AES and DES
symmetric-key algorithm
34. Storing Data using MMC/SD card in FAT23 format
35. Resistance and Capacitance Digital Meter
36. Wireless data transfer using IR 38KHz (Infrared) based on Ir-Data Protocol
37. Wireless data transfer using RF 433MHz (Radio Frequency) based on FSK modulation
38. wide area data transfer using the industrial CAN protocol for

 256 


Appendix Programming Microcontrollers

39. Digital to Analog conversion using 8-bit Ladder network


40. Programming 32x8pixel LED-Matrix scrolling Display
41. Interfacing with LM35 analog temperature sensor (-45ºC ~ +125ºC)

Also, some of the experiments were provided with Simulation using Proteus.

Faculty of Electrical and Electronic Eng. 257 Automatic Control & Automation Dept.
‫ﺎﻣﻌﺔ ﻠﺐ‬
‫ﳇﻴﺔ اﻟﻬﻨﺪﺳﺔ ا ﻜﻬﺮ ﺋﻴﺔ واﻹ ﻜﱰوﻧﻴﺔ‬
‫ﻗﺴﻢ ﻫﻨﺪﺳﺔ اﻟﺘﺤﲂ اﻵﱄ واﻷﲤﺘﺔ‬
 

 

‫ﺩﺭﺍﺳﺔ ﻭﺗﺼﻤﻴﻢ ﻧﻈﺎﻡ ﺗﻌﻠﻴﻤﻲ ﻣﺘﻜﺎﻣﻞ ﻳﻌﺘﻤﺪ ﺍﳌﻨﻬﺠﻴﺎﺕ ﺍﻟﻌﻤﻠﻴﺔ ﺍﻟﺘﻔﺎﻋﻠﻴﺔ‬

‫ﻭﻳﺘﻀﻤﻦ ﺗﺼﻤﻴﻢ ﻟﻮﺣﺔ ﺗﻄﻮﻳﺮ ﺫﺍﺗﻲ ﺗﻔﺎﻋﻠﻴﺔ ﻭﺇﻋﺪﺍﺩ ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ ﻟﺘﻌﻠﻴﻢ‬

‫ﻃﻼﺏ ﺍﻟﻜﻠﻴﺎﺕ ﺍﳍﻨﺪﺳﻴﺔ ﺑﺮﳎﺔ ﻧﻈﻢ ﺍﳌﺘﺤﻜﻤﺎﺕ ﺍﳌﺼﻐﺮﺓ‬

Designing A Novel Interactive Microcontroller Training Kit for Teaching Undergraduates


Programming Embedded System Microcontroller Using Interaction Methodologies




WALID BALID, 2009
walidbalid81@gmail.com


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


Tuesday, December 15, 2009
 

General Introduction about this course  

              


 

Assembly               
              
 

AVR
 Bascom-AVRBasic

      Proteus       
 

   Development Board         

 50

  

 2 
Practical Class 1 Programming Microcontrollers

Bascom-AVR Compiler  Bascom-AVR

   Bascom-AVR


 

 ·

 

_ ·

 

Faculty of Electrical and Electronic Eng. 3 Automatic Control & Automation Dept.
 

Compile ·

              ·


 
 Bascom-AVR

  LCD Designer   


         


  Graphic Converter   


       
*.bgfGLCD

 4 
Practical Class 1 Programming Microcontrollers

 Plugin Manager   


/

 Patch Compiler    




TCP/IP
 

  LIB Manager   


\

Stack Analyzer


   PDF Update    


   ATMEL    
 AVR

Faculty of Electrical and Electronic Eng. 5 Automatic Control & Automation Dept.
 

WORDExport to RTF ifle 


.Export to HTML
 Bascom-AVR
. .1
 2

1- Directives
Directives are special instructions for the compiler. They can override a setting from the IDE.

2- Configuration
Configuration commands initialize the hardware to the desired state.

3- Variables
Dimension all required variables.

4- Main Program
Contains all executive instructions such as: Mathematical Instruction.

5- Sub Routines
They are sub programs or sub procedures, call from the main program
 
ProgramSyntax Check 3
 4

،LOOP ‫ﻳﺘﻮﻗﻊ ﻭﺟﻮﺩ ﺗﻌﻠﻴﻤﺔ‬


.DO‫ﻫﺬﺍ ﺻﺤﻴﺢ ﻷﻧﻪ ﻳﻮﺟﺪ‬

 6 
Practical Class 1 Programming Microcontrollers

 Program   Compile         5

ProgramSend to programmer 6
 Bascom-AVR
‫لﻮ ﻮ ﺗوﺮ‬
‫اﻟﴩﻃﻴﺔ‬ ‫ا ﳤﻴﺌﺔ‬ ‫اﻟﺘﺤﻮﯾﻼت‬ ‫اﻟﺘﻮﻗ ﺖ واﻟﺘﺎرﱗ‬ ‫اﻟﺘﺄ ﲑ اﻟﺰﻣﲏ‬
1-WIRE
‫اﻟﺘﻌﺎﻣﻞ ﻣﻊ‬
‫ ﺎ دﻹ ا‬I2C
‫ج اﺮﺧﻹ او ل‬ ‫لﻮ ﻮ ﺗوﺮ‬ ‫ﺗﺼﻨﻴﻒ اﻟﺘﻌﻠ ت‬ ‫ت ﺎﻔﻠﳌا‬
‫اﻟﺘﻮﺟﳱﺎ ت‬
‫اﻟﱪﳎﻴﺔ ﰲ ﺑ ﺔ اﻟﱪ ﻣﺞ‬
‫لﻮ ﻮ ﺗوﺮ‬ ‫اﻟﺘﻌﺎﻣﻞ ﻣﻊ‬
RS232
‫اﻟﺘﺤﲂ ﻋﻦ ﺑﻌﺪ‬ Bascom-AVR ‫ةﺮ ا ا‬
‫اﻟﺘﺤﲂ ﳌﻌﺎﰿ‬
‫ﺪد اﻟﺘﻌﻠ ت ﺰﯾﺪ ﻋﻦ‬
‫اﳊ ﺴﺎﺑﻴﺔ‬ ‫لﻮ ﻮ ﺗوﺮ‬ ‫لﻮ ﻮ ﺗوﺮ‬
‫واﳌﺜﻠﺜﺎ ت‬ TCP/IP ‫ ﺗﻌﻠﳰﺔ‬350 ‫اﻟ ﺴﻼﺳﻞ اﶈﺮﻓ ﺔ‬
SPI
‫لﻮ ﻮ ﺗوﺮ‬ ‫ر ﺎﻬﻇﻹ ا ﺔﺷ ﺎﺷ‬ ‫ر ﺎﻬﻇﻹ ا ﺔﺷ ﺎﺷ‬
‫ت ﺎﻌﻃ ﺎﻘﳌا‬ ‫ﴍ ﺆ ﳌا ﺰ ﻔﻘ ﻟاوت ﺎﻘﻠﳊ ا‬
‫ت ا‬
PS2 ‫ا ﻟﻜ ﺮ ﺴ ﺘ ﺎ ﻟﻴ ﺔ‬ ‫ﺔ ﻣﻮﺳﺮ ﻟا‬
 
 
ISIS Proteus Simulation  ISIS Proteus

 
Faculty of Electrical and Electronic Eng. 7 Automatic Control & Automation Dept.
 

Proteus
 
 
 
Comparison between most famous µC families  

 AVR, PIC, 8051


 

AVR PIC 8051


 16MHZ 20MHZ 24MHZ

 1Cycle 4Cycle 12Cycle

 16/1 = 16MIPS 20/4 = 5MIPS 24/12 = 2MIPS

 100% 70% 50%

 132 35 215

 >256KBytes <64KBytes <32KBytes

 Liner banked Liner


CISC/Von
 RISC/Harvard RISC/Harvard
Neumann
 16 Bit 12 Bit 8 Bit

 
AVR Microcontrollers Family  AVR® 8-Bit
 AVR
 

   
Automotive AVR  
AVR Z-Link  IEEE 802.15.4 / ZigBee
Battery Ma nageme nt AVR  1.8~25
CAN AVR  CANopen, DeviceNet, OSEKCAN
LCD AVR LCD
Lighting AVR  
USB AVR USB
Tiny AVR  
MEGA AVR 20MIPS
XMEGA AVR  32MIPS
AT90Sxxxx   MEGA

 8 
Practical Class 1 Programming Microcontrollers

BatteryM AVR Lighting AVR USB AVR megaAVR tinyAVR


18 ~ 48 Pin 24 ~ 32 Pin 32 ~ 64 Pin 28 ~ 100 Pin 8 ~ 32 Pin
MAX I/O 4~18 MAX I/O 19~27 MAX I/O 22~48 MAX I/O 23~86 MAX I/O 6~28
4KB~40KB Flash 8KB~16KB Flash 8KB~128KB Flash 4KB~256KB Flash 1KB~8KB Flash
256B~1KB EPROM 512B EPROM 512B~4KB EPROM 512B~4KB EPROM 64B~512B EPROM
512B~2KB SRAM 512B~1KB SRAM 512B~8KB SRAM 512B~16KB SRAM 32B~512B SRAM
Up To 8MIPS Up To 16MIPS Up To 16MIPS Up To 20MIPS Up To 20MIPS
1.8V – 25V 2.7V – 5.5V 2.7V – 5.5V 1.8V – 5.5V 1.8V – 5.5V

AVR® 8-Bit    


Automotive AVR CAN AVR LCD AVR AVR Z-Link xmegaAVR
14 ~ 64 Pin 64 ~ 100 Pin 44 ~ 100 Pin
MAX I/O 6~54 64 Pin MAX I/O 54~69 MCU Wireless MAX I/O 36~78
2KB~128KB Flash 32KB~128KB Flash 16KB~64KB Flash chipset for: 16KB~384KB Flash
128B~4KB EPROM 1KB~4KB EPROM 512B~2KB EPROM IEEE 802.15.4 1KB~4KB EPROM
128B~4KB SRAM 1K~4KB SRAM 1KB~4KB SRAM and 2KB~32KB SRAM
Up To 16MIPS Up To 16MIPS Up To 20MIPS ZigBee Up To 32MIPS
2.7V – 5.5V 2.7V – 5.5V 1.8V – 5.5V applications. 1.8V – 3.6V
 
Reading AVR Package information  AVR

 
 ––AVR

 

 

Faculty of Electrical and Electronic Eng. 9 Automatic Control & Automation Dept.
 

 
 

.ATMEL :AT
  :Mega
8,16,32,64,128,256, etc…8
2.7V~5.5V L :L
 4.5V~5.5V––
 2016 :8
                 :P
 SOIC, TQFP, LQFP…PDIP

 
IC :I
 M

 10 
Practical Class 1 Programming Microcontrollers

Reading Datasheet of ICs  


 – Datasheet –

 Bascom-AVR
 Assembly

 ––

 
 
Reading Datasheet of ATmega128  ATmega128

Features ·
High-performance, Low-power AVR® 8-bit Microcontroller    8-bit 
· Advanced RISC Architecture.    RISC ·
– 133 Powerful Instructions Most Single Clock Cycle.   133 –
– 32 x 8 General Purpose Working Registers + Peripheral
 + 32 x 8 –
Control Registers
– Fully Static Operation   –
– Up to 16 MIPS Throughput at 16 MHz 16 MHz 16 –
– On-chip 2-cycle Multiplier    –
· Nonvolatile Program and Data Memories    ·
– 128K Bytes of In-System Reprogrammable Flash         128KB  –
Endurance: 10,000 Write/Erase Cycles
  10,000 
– Optional Boot Code Section with Independent Lock Bits
In-System Programming by On-chip Boot Program - True  –
Read-While-Write Operation    EEPROM    4KB –
– 4K Bytes EEPROM   100,000
Endurance: 100,000 Write/Erase Cycles
 SRAM 4KB–
– 4K Bytes Internal SRAM
– Up to 64K Bytes Optional External Memory Space
 64KB–
– Programming Lock for Software Security  –
– SPI Interface for In-System Programming  SPI–
· JTAG (IEEE std. 1149.1 Compliant) Interface   JTAG  ·
– Boundary-scan Capabilities According to the JTAG Standard
 –
– Extensive On-chip Debug Support
–Programming of Flash, EEPROM, Fuses and Lock Bits  Debug–
through the JTAG Interface  –

Faculty of Electrical and Electronic Eng. 11 Automatic Control & Automation Dept.
 

   ·
· Peripheral Features
–Two 8-bit Timer/Counters with Separate Prescalers and  8-bit/–
Compare Modes  16-bit/–
–Two Expanded 16-bit Timer/Counters with Separate  
Prescaler, Compare Mode and Capture Mode
 –
– Real Time Counter with Separate Oscillator
– Two 8-bit PWM Channels   8-bit PWM–
– 6 PWM Channels with Programmable Resolution from 2 to  16-bit PWM–
16 Bits  162
– Output Compare Modulator
 10-bit/–
– 8-channel, 10-bit ADC
– Byte-oriented Two-wire Serial Interface
 I2C–
– Dual Programmable Serial USARTs  USARTs–
– Master/Slave SPI Serial Interface  /SPI–
– Programmable Watchdog Timer with On-chip Oscillator
 –
– On-chip Analog Comparator
 –
· Special Microcontroller Features    ·
– Power-on Reset and Programmable Brown-out Detection  –
– Internal Calibrated RC Oscillator  –
– External and Internal Interrupt Sources
 –
– Six Sleep Modes: Idle, ADC Noise Reduction, Power-save,
Power-down, Standby, and Extended Standby  –
– Software Selectable Clock Frequency  –
– ATmega103 Compatibility Mode Selected by a Fuse   ATmega103 –
– Global Pull-up Disable
 –
· I/O and Packages   / ·
– 53 Programmable I/O Lines-PDIP  PDIP/53–
– 64-lead TQFP and 64-pad MLF  TQFP/64–
· Operating Voltages    ·
– 2.7 - 5.5V for ATmega128L  ATmega128L 2.7 - 5.5V –
– 4.5 - 5.5V for ATmega128  ATmega128 4.5 - 5.5V –
· Speed Grades    ·
– 0 - 8 MHz for ATmega128L  ATmega128L 8-MHz –
– 0 - 16 MHz for ATmega128  ATmega128 16-MHz –


 

 ATmega128  


. ATmegaxxx 

 12 
Practical Class 1 Programming Microcontrollers

Pin Configur ations  ·

 
PE0(RXD/PDI) 2
    PE0   /          
    JTAG       UART   
 

 
Faculty of Electrical and Electronic Eng. 13 Automatic Control & Automation Dept.
 

Block Diagram ·

 
 
 
 
   RISC  Harvard     AVR     


 14 
Practical Class 1 Programming Microcontrollers

Standard Systems Design  

 
 Von NeumannHarvard

 Von-Neumann

 
 
  ·
  ·
  ·
  ·
 
 Harvard
      
     
     


 
 
Methods Architecture Systems Design  

 
.(150 ~ 1500 Instruction) Complex Instruction Set Computer : CISC
.(30 ~ 130 Instruction) Reduced Instruction Set Computer : RISC
.(15 ~ 30 Instruction) Minimum Instruction Set Computer :MISC
      CISC         
              
Faculty of Electrical and Electronic Eng. 15 Automatic Control & Automation Dept.
 

             
             
AMD& INTEL

   RISC


                 
            
RISC
 DSPsMicrocontrollers


µA
 MISC

 

 16 
Practical Class 1 Programming Microcontrollers

AVR Development Board  AVR 

AVR
  50
 --
 Human-Computer Interaction Methods

 
 
 .1
 .2
/ .3
 .4
 .5
.LCD 20x4 .6
GLCD 128x64 .7

Faculty of Electrical and Electronic Eng. 17 Automatic Control & Automation Dept.
 

 .8
DTMF .9
 .10
 .11
.RC5, RC5-Extended .12
.RC5, RC5-Extended  .13
0 – 9 .14
.0 – 9999 .15
RS232UART1 .16
UART2 .17
RS485 .18
 .19
 .20
 .21
.LM35DZ-45⁰C ~ +100⁰C .22
ADCNTC .23
 .24
.ADC .25
 .26
 .27
 .28
PWM .29
 .30
 .31
 .32
DACLadder .33
DAC .34

 18 
Practical Class 1 Programming Microcontrollers

 .35
RTC .36
.EEPROM .37
 .38
Overflow, Compare & Capture modes .39
MMC .40
Smart Card .41
PS2 .42
PS2 .43
DS18211-Wire .44
LED-Matrix Displays .45
USARTRS232 .46
EEPROM .47
 .48
 .49
 .50
 .51
.JTAG .52
 .53
ESD, EMC & EMIPCBs .54
RTSMultitasking .55
 .56
SPI .57

 

 

 

Faculty of Electrical and Electronic Eng. 19 Automatic Control & Automation Dept.
 

AVR Development Board Designing schedule  

AVR -1
             -2

 -3

              -4
Embedded EMC,EMR,ESD
Systems
Proteus -5
 

 

       compilers      -1
 AVR
In System Programming -2
 -3
10060 -4
                -5
            Embedded Systems Design

self learners  -6

 -7
 ،USD120
 
.USD700 
 20 
Practical Class 1 Programming Microcontrollers

              -8
 Lab-Center Proteus-7.2

Bascom-AVR
       Debugger       -9
RS232 Interface
 -10
48 I/O

AVR -11
SPI
 -12

 -13
5% : a
85% b
             c
90%
96% d
.98% e
 f
1507045%
 -14
 -15

        Open Source   

 LabVIEW, VB6, Matlab, etc… -16
Faculty of Electrical and Electronic Eng. 21 Automatic Control & Automation Dept.
 

Development Board Layout Diagram  

 

 
 22 
Practical Class 1 Programming Microcontrollers

Development Board Schematic & Board Design  

 

 
 

 

Faculty of Electrical and Electronic Eng. 23 Automatic Control & Automation Dept.
 



 
 


 
 

 24 
Practical Class 1 Programming Microcontrollers

 
 

 
 
 

 
 

Faculty of Electrical and Electronic Eng. 25 Automatic Control & Automation Dept.
 

 

 
 
 

 

 26 
Practical Class 1 Programming Microcontrollers

 USART

 
 
 

 

Faculty of Electrical and Electronic Eng. 27 Automatic Control & Automation Dept.
 

 

 
 
 EEPROM & RTC I2C

 
 

 28 
Practical Class 1 Programming Microcontrollers

 RS485

 
 
 

 

Faculty of Electrical and Electronic Eng. 29 Automatic Control & Automation Dept.
 

 

 
 
 

 

 30 
Practical Class 1 Programming Microcontrollers

 MMC/SD

 
 
 

 
 
 PWM

 

Faculty of Electrical and Electronic Eng. 31 Automatic Control & Automation Dept.
 

 PS2

 
 
 

 
 
 

 
 32 
Practical Class 1 Programming Microcontrollers

 

 
 
 

 
 
 1-Wire

Faculty of Electrical and Electronic Eng. 33 Automatic Control & Automation Dept.
 

 

 
 
 

 
 
 34 
Practical Class 1 Programming Microcontrollers



   
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Faculty of Electrical and Electronic Eng. 35 Automatic Control & Automation Dept.
 

 

 
 36 
Practical Class 1 Programming Microcontrollers

 

 

Faculty of Electrical and Electronic Eng. 37 Automatic Control & Automation Dept.
 

 

 
 38 
Practical Class 1 Programming Microcontrollers

 

 
Faculty of Electrical and Electronic Eng. 39 Automatic Control & Automation Dept.
 

 
Px.0 Px.1 Px.2 Px.3 Px.4 Px.5 Px.6 Px.7
RS485 Interface PWM>DAC Four Buttons/Leds1
INT4~7
UART1 UART1 with Hand-checking and LEDs Indicators
Port E

AIN
OC3A,B,C
T3
8-bit DAC Interface
ICP3
External Port Connector for further connecting and can be set to Pull Up/Down Resistor

Programmer
SPI
MMC/SD Card SPI Interface Speaker IR Sender PWM IR Receiver
Port B

OC1A,B
OC0,2
OC1C
Hexadecimal Keypad

External Port Connector for further connecting and can be set to Pull Up/Down Resistor

Four Buttons/Leds2 ICP1 Relay1 T1 Relay2


INT0~3
Port D

UART2 PS2 SCK UART2


TWI
T1~2 RTC & EEPROM
ICP1
External Port Connector for further connecting and can be set to Pull Up/Down Resistor

DS1820 GLCD Control Bus

LCD
Port C

Ex.MI-H Quad Seven Segment Control Lines

Dual Led-Matrix Display Data Bus

External Port Connector for further connecting and can be set to Pull Up/Down Resistor

GLCD Data Bus

UART2 Hand-checking Basic Card


Port A

Ex.MI-L
Quad Seven Segment Data Bus

External Port Connector for further connecting and can be set to Pull Up/Down Resistor
LDR NTC Pressure Variable Variable 4 Switches Temperature
Port F

ADC0~7 Resistor Resistor sensor Resistor Resistor On a line Sensor


JTAG
JTAG Interface
Dual Led-Matrix Display
RC Circuit 23KHZ Crystal x x x
Port G

TOSC Control Lines


WR/RD
ASK TR ASK RE PS2 Data x x x x x

 

1
Buttons for Interrupt 4~7 can be set to VCC or GND by Jumper, connected with led indicators.
2
Buttons for Interrupt 0~3 can be set to VCC or GND by Jumper, connected with led indicators.
 40 


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
 

Essential Instructions in Bascom-AVR Bascom-AVR

  ·
   
$regfile = "m128def.dat"  ATmega128
$crystal = 1000000  
$baud = 9600  

  ·
   
Wait value  Value
Waitms value  Value
Waitus value  Value

 / ·
   
Config Portc = Output  C
Config Portc.5 = Output C5
Config Portc = Input  C
Config Pinc.5 = Input C5
Portc = 255 C
Pinc.5 = 1 C5
Pinc.5 = 0 C5
Portc = &B11110000 C
/
Config Portc = &B11110000
 10
Leds Alias Portd  LedsD
Leds Alias Portd.5  Led5

     





 42 
Practical Class 2 Programming Microcontrollers

 Set/Reset ·
   
Set bit  /
Reset bit  /
Toggle bit  /
 
  ·
   
If Expression1 Then
Statements1           
...
Elseif Expression2 Then  
Statements2
 11
...
Else 22
Statements3
...  3
End If
SELECT CASE var
          
Case Test1 : Statements1  
Case Test2 : Statements2  1 var = Test1
Case Else : Statements3  2 var = Test2
 3
END SELECT

  ·
   
Do
        
Statements
 
Loop [until Expression]
While Condition

Statements   
Wend
For Var = Start To End [step Value]          
Statements End  Start
Next Var  .step
Exit For For
Exit Do Do
Exit While  While

Faculty of Electrical and Electronic Eng. 43 Automatic Control & Automation Dept.
 

 SRAM ·
   
Dim Var1 As Bit  0 or 1
Dim Var2 As Byte 0 to 255
Dim Var3 As Integer -32,768 to +32,767
Dim Var4 As Word 0 to 65535
Dim Var5 As Long -2147483648 to 2147483647
Dim Var6 As Single 1.5 x 10^–45 to 3.4 x 10^38
Dim Var7 As Double 
Dim Var8 As String * 1  * chr_num

Dim Array(8) As Byte  


Const Symbol = Numconst
Ex. Const Pi = 3.14159265358979
 
Const Symbol = Stringconst
Ex. Const S = "TEST"  
Const Symbol = Expression
Ex. Const E =(b1 * 3) + 2
 
Local Var As Type  

  ·
   
    Px.y     
Debounce Px.y , state , label , Sub
Ex. Debounce Key1 , 0 , Sw1 , Sub
state
 label
Debounce 
Config Debounce = time
  
Bitwait x , Set/reset          
Ex. Bitwait Pinb.7 , reset  

 44 
Practical Class 2 Programming Microcontrollers

Exp.1: Scrolling LEDs  

 
 
 

 
 
 JP9, JP10
 
 
.LEDs7 -1
 -2
 -3
Faculty of Electrical and Electronic Eng. 45 Automatic Control & Automation Dept.
 

  -4
 
$regfile = "m128def.dat"
$crystal = 1000000  
'-----------------------
Config Portd.0 = Output
Config Portd.1 = Output
Config Portd.2 = Output
Config Portd.3 = Output
 
Config Porte.4 = Output
Config Porte.5 = Output
Config Porte.6 = Output
Config Porte.7 = Output
'-----------------------
Leds1 Alias Portd 
Leds2 Alias Porte 
'-----------------------
Dim I As Byte , J As Byte  
'-----------------------
Do
For I = 0 To 3
J = I + 4 
Set Leds1.i
Set Leds2.j  
Wait 1
Next I

For I = 3 To 0 Step -1
J = I + 4
Reset Leds1.i 
Reset Leds2.j
Wait 1  
Next I
Loop
End
 

 46 
Practical Class 2 Programming Microcontrollers

Exp.2: Tact Switches  

 
 
 

 
 
 JP6, JP8
 
Faculty of Electrical and Electronic Eng. 47 Automatic Control & Automation Dept.
 

 
 
GNDJP6, JP8 -1
VCC JP6, GNDJP8 -2

 GNDJP6, JP8
$regfile = "m128def.dat"
$crystal = 1000000  
$baud = 4800
'-----------------------
Config Debounce = 150  
Config Pind.0 = Input
Config Pind.1 = Input
Config Pind.2 = Input
Config Pind.3 = Input
 
Config Pine.4 = Input
Config Pine.5 = Input
Config Pine.6 = Input
Config Pine.7 = Input

Portd.0 = 1 : Portd.1 = 1
Portd.2 = 1 : Portd.3 = 1
Porte.4 = 1 : Porte.5 = 1
 
Porte.6 = 1 : Porte.7 = 1
'-----------------------
Key1 Alias Pind.0
Key2 Alias Pind.1
Key3 Alias Pind.2
Key4 Alias Pind.3 
Key5 Alias Pine.4
 
Key6 Alias Pine.5
Key7 Alias Pine.6
Key8 Alias Pine.7
'-----------------------

Do
Debounce Key1 , 0 , Sw1 , Sub
Debounce Key2 , 0 , Sw2 , Sub
Debounce Key3 , 0 , Sw3 , Sub
Debounce Key4 , 0 , Sw4 , Sub  
Debounce Key5 , 0 , Sw5 , Sub
Debounce Key6 , 0 , Sw6 , Sub  
Debounce Key7 , 0 , Sw7 , Sub
Debounce Key8 , 0 , Sw8 , Sub

Waitms 200

Loop
End
'-----------------------

 48 
Practical Class 2 Programming Microcontrollers

Sw1:  
Print "Switch(1) is pressed!"
Return  
'/------------
Sw2:  
Print "Switch(2) is pressed!"
Return
'/------------
Sw3:
Print "Switch(3) is pressed!"
Return
'/------------
Sw4:
Print "Switch(4) is pressed!"
Return
'/------------
Sw5:
Print "Switch(5) is pressed!"
Return
'/------------
Sw6:
Print "Switch(6) is pressed!"
Return
'/------------
Sw7:
Print "Switch(7) is pressed!"
Return
'/------------
Sw8:
Print "Switch(8) is pressed!"
Return

Faculty of Electrical and Electronic Eng. 49 Automatic Control & Automation Dept.
 

 VCC JP8‫ و‬GNDJP6,


 PortD
 S6

 
 
$regfile = "m128def.dat"
$crystal = 1000000  
$baud = 4800
'-----------------------
Config Debounce = 150  
Config Pind.0 = Input
Config Pind.1 = Input
Config Pind.2 = Input
Config Pind.3 = Input
 
Config Pine.4 = Input
Config Pine.5 = Input
Config Pine.6 = Input
Config Pine.7 = Input

 50 
Practical Class 2 Programming Microcontrollers

Portd.0 = 0 : Portd.1 = 0
Portd.2 = 0 : Portd.3 = 0 Portd
Porte.4 = 1 : Porte.5 = 1
Porte.6 = 1 : Porte.7 = 1  PortE
'-----------------------
Key1 Alias Pind.0
Key2 Alias Pind.1
Key3 Alias Pind.2
Key4 Alias Pind.3 
Key5 Alias Pine.4
Key6 Alias Pine.5  
Key7 Alias Pine.6
Key8 Alias Pine.7
'-----------------------
Do
Debounce Key1 , 0 , Sw1 , Sub
Debounce Key2 , 0 , Sw2 , Sub
Debounce Key3 , 0 , Sw3 , Sub
Debounce Key4 , 0 , Sw4 , Sub
Debounce Key5 , 0 , Sw5 , Sub  
Debounce Key6 , 0 , Sw6 , Sub  
Debounce Key7 , 0 , Sw7 , Sub
Debounce Key8 , 0 , Sw8 , Sub
Waitms 200
Loop
End
'-----------------------
Sw1:
Print "Switch(1) is pressed!"
Return
'/------------
Sw2:
Print "Switch(2) is pressed!"
Return
'/------------
Sw3:
Print "Switch(3) is pressed!"
Return
'/------------
Sw4:
Print "Switch(4) is pressed!"
Return
'/------------  
Sw5:
Print "Switch(5) is pressed!"  
Return  
'/------------
Sw6:
Print "Switch(6) is pressed!"
Return
'/------------
Sw7:
Print "Switch(7) is pressed!"
Return
'/------------
Sw8:
Print "Switch(8) is pressed!"
Return

Faculty of Electrical and Electronic Eng. 51 Automatic Control & Automation Dept.
 

Exp.3: Expansion Connectors  /

 
 /–
 

 
 
 –JP1~ JP6
 

 S
VCC -1
 GND -2

 
 
 

 52 
Practical Class 2 Programming Microcontrollers

 :GND  ·
$regfile = "m128def.dat"
$crystal = 1000000  
$baud = 4800
'-----------------------
Config Porte = Input
Config Portb = Input
Config Portd = Input  
Config Portc = Input
Config Porta = Input
'-----------------------
Porta = 255
Portb = 255
Portc = 255  
Portd = 255
Porte = 255
'-----------------------
Pa_value Alias Pina
Pb_value Alias Pinb 
Pc_value Alias Pinc
Pd_value Alias Pind  
Pe_value Alias Pine
'-----------------------
Do
Print "PA= " ; Pa_value
Print "PB= " ; Pb_value
Print "PC= " ; Pc_value
Print "PD= " ; Pd_value  
Print "PE= " ; Pe_value  
Print "------------"
Wait 1
Loop
End
'-----------------------  

Faculty of Electrical and Electronic Eng. 53 Automatic Control & Automation Dept.
 

 :VCC ·
$regfile = "m128def.dat"
$crystal = 1000000  
$baud1 = 4800
'-----------------------
Config Porte = Input
Config Portb = Input
Config Portd = Input  
Config Portc = Input
Config Porta = Input
'-----------------------
Porta = 0
Portb = 0
Portc = 0  
Portd = 0
Porte = 0
'-----------------------
Pa_value Alias Pina
Pb_value Alias Pinb 
Pc_value Alias Pinc
Pd_value Alias Pind  
Pe_value Alias Pine
'-----------------------
Open "com2:" For Binary As #1

Do
Print #1 , "PA= " ; Pa_value
Print #1 , "PB= " ; Pb_value
Print #1 , "PC= " ; Pc_value
Print #1 , "PD= " ; Pd_value  
Print #1 , "PE= " ; Pe_value
Print #1 , "-----------"
 
Wait 1
Loop

Close #1
End
'-----------------------

 54 
Practical Class 2 Programming Microcontrollers

Exp.4: Controlling Relay (On/Off)  

 
 
 

 
 
 JP22~ JP21
 
Faculty of Electrical and Electronic Eng. 55 Automatic Control & Automation Dept.
 

 
     Portd.7  Portd.5       
 K2K1
 
$regfile = "m128def.dat"
$crystal = 1000000  
'-----------------------
Config Portd.5 = Output  
Config Portd.7 = Output
'-----------------------
Relay1 Alias Portd.5 
Relay2 Alias Portd.7  
'-----------------------
Dim I As Byte  
'-----------------------
For I = 0 To 9
Set Relay1
Wait 2
Set Relay2

Wait 2
 
Reset Relay1
Wait 2
Reset Relay2
Next I
End
'-----------------------

 56 


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.5: Hexadecimal Array Keypad  

 
 
 

 
 

 
 
 
     
 
 Config Kbd = Portb , Delay = 150
 
 
   Var = 16      1
 Var = Getkbd() 
    2
  

 58 
Practical Class 3 Programming Microcontrollers

S1 = 0
S2 = 1
S3 = 2
S4 = 4
S5 = 5
S6 = 6
S7 = 8
S8 = 9
S9 = 10
S* = 12
S0 = 13
S# = 14
A=3
B=7
C = 11
D = 15
 
$regfile = "m128def.dat"
$crystal = 1000000  
$baud = 4800
'-----------------------
Config Kbd = Portb , Delay = 150  
'-----------------------
Dim Var As Byte  
'-----------------------
Do
Var = Getkbd()
If Var < 16 Then
Gosub Check_number  
End If
 
Loop

End
'-----------------------
Check_number:
Select Case Var
Case 0 : Print "Key Pressed is (1)"
Case 1 : Print "Key Pressed is (2)"
Case 2 : Print "Key Pressed is (3)"
Case 3 : Print "Key Pressed is (A)"
Case 4 : Print "Key Pressed is (4)"
Case 5 : Print "Key Pressed is (5)"
Case 6 : Print "Key Pressed is (6)"
Case 7 : Print "Key Pressed is (B)" 
Case 8 : Print "Key Pressed is (7)"
Case 9 : Print "Key Pressed is (8)"  
Case 10 : Print "Key Pressed is (9)"
Case 11 : Print "Key Pressed is (C)"
Case 12 : Print "Key Pressed is (*)"
Case 13 : Print "Key Pressed is (0)"
Case 14 : Print "Key Pressed is (#)"
Case 15 : Print "Key Pressed is (D)"
End Select
Return
'-----------------------

Faculty of Electrical and Electronic Eng. 59 Automatic Control & Automation Dept.
   

Exp.6: Programming LCD  

 
 20x4
 

 
 
 SW2
 
             
 
 
     
Config Lcdpin = Pin ,
Db4 = Portc.4 , Db5 = Portc.5 , Db6 = Portc.6  
Db7 = Portc.7 ,E = Portc.2 , Rs = Portc.3
Config Lcd = 20 * 4  
Deflcdchar 0 , 14 , 17 , 14 , 17 , 17 , 14 , 17 , 14 LCD Designer

Cls  

 60 
Practical Class 3 Programming Microcontrollers

Lcd var  /


Lowerline  
Shiftlcd Right  
Shiftlcd Left  
Locate X , Y  /
Shiftcursor Right  
Shiftcursor Left  
Home Upper  /
Cursor Off Noblink  
Cursor On Blink  
Display Off  
Display On  
Thirdline  
Fourthline  
Home Third  
Home Fourth  
Lcd Chr(x)  

 
$regfile = "m128def.dat"  
$crystal = 8000000
'----------------------- 
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 = Portc.5 ,
Db6 = Portc.6 , Db7 = Portc.7 , E = Portc.2 , Rs = Portc.3  
 
Config Lcd = 20 * 4

Deflcdchar 0 , 14 , 17 , 14 , 17 , 17 , 14 , 17 , 14
Deflcdchar 1 , 17 , 14 , 17 , 14 , 14 , 17 , 14 , 17 LCD Designer
'-----------------------
 
Dim A As Byte
'-----------------------
Do
Cls
Lcd "hello world!"
Wait 1  
 
Lowerline
Wait 1  
 
Lcd "LCD Test"
Wait 1

For A = 1 To 8
Shiftlcd Right

Faculty of Electrical and Electronic Eng. 61 Automatic Control & Automation Dept.
   

Waitms 500
Next A

For A = 1 To 8
Shiftlcd Left
Waitms 500
Next A

Locate 2 , 9
Lcd "-L2,C9"
Wait 1

Shiftcursor Right
Lcd "-*-"
Wait 1

Shiftcursor Left
Lcd "*-*"
Wait 1

Home Upper
Lcd "HELLO WORLD"
Wait 1

Cursor Off Noblink


Wait 1

Cursor On Blink
Wait 1

Display Off
Wait 1

Display On
Wait 1

Thirdline
Lcd " /Line 3"
Wait 1

Fourthline
Lcd " /Line 4"
Wait 1

Home Third
Lcd ":)"
Wait 1

Home Fourth
Lcd ":("
Wait 1

Cls
Locate 1 , 9 : Lcd Chr(0)
Wait 1
Locate 1 , 11 : Lcd Chr(1)
Loop

End
 62 
Practical Class 3 Programming Microcontrollers

Exp.7: Programming Graphic LCD  

 
 128x64
 

 
 
 SW3
 

 
 
     
Config Graphlcd = 128 * 64sed ,
Dataport= Porta, Controlport= Portc ,
Ce = 2 , Ce2 = 4 , Cd = 7 , Rd = 6 ,
 
 Reset = 3 , Enable = 5
 $lib "glcdKS108.lib"  
Faculty of Electrical and Electronic Eng. 63 Automatic Control & Automation Dept.
   

Setfont Font  


Cls  
Cls Text  
Cls Graph  
Lcdat y , x , var [, inv]  
Line(X0 , Y0) - (X1 , Y1) , Color  
Pset X , Y , Color  SET/RST Pixel
Circle(X , Y) , r , Color r
Showpic X , Y , label  
$include "Font5x8.font"  
$bgf "Smiley1.bgf"  bgf
 
$regfile = "m128def.dat"
$crystal = 8000000  
$lib "glcdKS108.lib"
'-------------------------
Config Graphlcd = 128 * 64sed , Dataport
= Porta , Controlport = Portc , Ce = 2 ,
Ce2 = 4 , Cd = 7 , Rd = 6 , Reset = 3 ,  
Enable = 5
'-------------------------
Dim X As Byte , Y As Byte  
'-------------------------
Cls : Cls Text : Cls Graph  
'-------------------------
Setfont Font8x8
Lcdat 3 , 11 , "Font 5x8 Test"
Lcdat 4 , 11 , "Font 6x8 Test" 8x8
Lcdat 5 , 11 , "Font 8x8 Test"
Wait 2

Cls
Setfont Font5x8  5x8
Lcdat 1 , 1 , "LINE1" : Wait 1
Lcdat 2 , 1 , "LINE2" : Wait 1
Lcdat 3 , 1 , "LINE3" : Wait 1

Setfont Font6x8
Lcdat 4 , 1 , "LINE4" : Wait 1  6x8
Lcdat 5 , 1 , "LINE5" : Wait 1
Lcdat 6 , 1 , "LINE6" : Wait 1

Setfont Font8x8
Lcdat 7 , 1 , "LINE7" : Wait 1  8x8
Lcdat 8 , 1 , "LINE8" : Wait 1
'/------------/
Cls
Setfont Font16x16  16x16

 64 
Practical Class 3 Programming Microcontrollers

Lcdat 4 , 23 , "16x16" : Wait 2


Cls
Lcdat 1 , 1 , "LINE1" : Wait 1
Lcdat 3 , 1 , "LINE2" : Wait 1
Lcdat 5 , 1 , "LINE3" : Wait 1
Lcdat 7 , 1 , "LINE4" : Wait 1
'/------------/
Setfont Font8x8
Lcdat 4 , 11 , "Drawing Lines" :
Wait 2
Cls Text 
Line(0 , 0) -(127 , 0) , 255 Y
63,31
Wait 1 127,0
Line(0 , 63) -(127 , 63) , 255 0,0

Wait 1
Line(0 , 0) -(0 , 63) , 255
Wait 1
Line(127 , 0) -(127 , 63) , 255
Wait 1 127,63
0,63
Line(0 , 0) -(127 , 63) , 255
 
X
Wait 1
Cls Graph  
'/------------/
Lcdat 4 , 11 , "SET/RST Pixel" :
Wait 2
Cls Text
For X = 0 To 127
Pset X , 20 , 255
Pset X , 43 , 255
Waitms 200
Next X

For Y = 0 To 63
Pset 42 , Y , 255
Pset 86 , Y , 255
Waitms 200
Next Y

For X = 127 To 0 Step -1


Pset X , 20 , 0
Pset X , 43 , 0
Waitms 200
Next X  
 
For Y = 63 To 0 Step -1
Pset 42 , Y , 0
Pset 86 , Y , 0
Waitms 200
Next X
Cls Graph
'/------------/
Lcdat 4 , 11 , "Drawing Circle" :
Wait 2
Cls Graph
For X = 1 To 31 
Circle(63 , 31) , X , 255
Waitms 200
Circle(63 , 31) , X , 0
Next X  

Faculty of Electrical and Electronic Eng. 65 Automatic Control & Automation Dept.
   

Cls Graph
 
'/------------/
Showpic 0 , 0 , Smiley1
Wait 2
Cls : Cls Text : Cls Graph

Showpic 0 , 0 , Smiley2
Wait 2
Cls Graph
 
Showpic 0 , 0 , Smiley3
Wait 2
Cls Graph

Showpic 0 , 0 , Smiley4
Wait 2
'/------------/
Glcdcmd &H3E , 1 : Glcdcmd &H3E , 2   
Wait 1
Glcdcmd &H3F , 1 : Glcdcmd &H3F , 2   
'/------------/
End
'-------------------
$include "Font5x8.font"
$include "Font6x8.font"  
$include "Font8x8.font"
$include "Font16x16.font"
'-------------------
Smiley1:
$bgf "Smiley1.bgf"

Smiley2:
$bgf "Smiley2.bgf"
 
Smiley3:
$bgf "Smiley3.bgf"

Smiley4:
$bgf "Smiley4.bgf"
 

 66 
Practical Class 3 Programming Microcontrollers

Exp.8: Generating Tones  

 
 
 

 
 
.Jumper JP16
 PB4,PB5
 


 sound
 Speaker

Faculty of Electrical and Electronic Eng. 67 Automatic Control & Automation Dept.
   

 
     
   Speaker    
 Sound Speaker , Pulses , Periods
 PeriodsPulses
 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Portb.4 = Output
Speaker Alias Portb.4  
'---------------------
Dim Pulses As Word , Periods As Word
Dim I As Byte
 
Pulses = 50 : Periods = 100
'---------------------
Sound Speaker , 100 , 200 : Wait 1

Do
Sound Speaker , Pulses , Periods
Waitms 1
Periods = Periods + 5 
Loop Until Periods = 1000
 
For I = 0 To 6  
Sound Speaker , 150 , 800
Waitms 1000
Next I

Sound Speaker , 100 , 200


End
 

 

 68 
Practical Class 3 Programming Microcontrollers

Exp.9: Generating DTMF Tones  DTMF

 
  DTMF (Dual Tone Multi Frequency) 
 

 
 
.Jumper JP16
 PB4,PB5
 
 DTMF       
OC1A

Faculty of Electrical and Electronic Eng. 69 Automatic Control & Automation Dept.
   

 
     
 OC1A
Dtmfout Number , Duration   :Number
 Dtmfout String , Duration  Duration
 String
 
$regfile = "m128def.dat"
$crystal = 8000000  
'-------------------
Enable Interrupts DTMF
 1
'-------------------
Dim Var As Byte
Dim Btmp As Byte , Sdtmf As String * 10  
Sdtmf = "1234567890"
'-------------------
Do
Dtmfout Sdtmf , 50
Waitms 1000

For Btmp = 0 To 15
Dtmfout Btmp , 100
 
Waitms 500  
Next Btmp
Loop

1Dtmfout1
 OC1A

.4MHZ ~ 8MHZ2

    Atmel application note (AN314)     3
  

 70 


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.10: Shift & Rotate Instructions  

 
 Rotate Shift
 

 
 
Shift Right S6
 Shift LeftS7
 S14 Rotate Right  S13
 Rotate Right
 
 .Jumper JP9 JP6
 

 72 
Practical Class 4 Programming Microcontrollers

 
     
        
Shift var , Right/Left [, shift]
 [, shift]
        
Rotate var , Right/Left [, rotate]
 [, shift]
 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Pine.4 = Input
Config Pine.5 = Input
Config Pine.6 = Input
Config Pine.7 = Input

Pine.4 = 1 : Pine.5 = 1
Pine.6 = 1 : Pine.7 = 1

Shift_r Alias Pine.4  
Shift_l Alias Pine.5
Rotat_r Alias Pine.6
Rotat_l Alias Pine.7

Config Portd = Output


Leds Alias Portd
Portd = &B00000001
'---------------------
Do
Debounce Shift_r , 0 , Sr , Sub
Debounce Shift_l , 0 , Sl , Sub
Debounce Rotat_r , 0 , Rr , Sub  
Debounce Rotat_l , 0 , Rl , Sub
Loop
End
'---------------------
Sr:
If Leds > 1 Then Shift Leds , Right , 1
Return
'---------------------
Sl:
If Leds < 128 Then Shift Leds , Left , 1
Return
'---------------------  
Rr:
Rotate Leds , Right , 1
Return
'---------------------
Rl:
Rotate Leds , Left , 1
Return
'---------------------

Faculty of Electrical and Electronic Eng. 73 Automatic Control & Automation Dept.
   

Exp.11: Get RC Value  

 
 
 

 

 
               
 Getrc
 
 
 SW2.Jumper JP14

 

 74 
Practical Class 4 Programming Microcontrollers

 
     

     pinx   y
 var = Getrc(pinx , y)

 
 
 
$regfile = "m128def.dat"
$crystal = 8000000  
'----------------------
Config Lcdpin = Pin , Db4 = Portc.4 ,
Db5 = Portc.5 , Db6 = Portc.6 , Db7 = 
Portc.7 , E = Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4
'----------------------
Dim Rc_var As Word  
'----------------------
Cls : Cursor Off
Lcd "RC Val= "
Do
Rc_var = Getrc(ping , 2)
Locate 1 , 9  
Lcd Rc_var
 
Waitms 1000
Locate 1 , 8 : Lcd Spc(7)
Loop

End

 

Faculty of Electrical and Electronic Eng. 75 Automatic Control & Automation Dept.
   

Exp.12: IR receiver, RC5-code  RC5IR 

 
.RC5, RC5-ExtendedCLRM-2038S

 

 
 
               
.RC5
 
 SW2.Jumper JP18
 

 76 
Practical Class 4 Programming Microcontrollers

     
 Config Rc5 = Pinb.7 IR
Getrc5(address , Command)  
 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Lcdpin = Pin , Db4 = Portc.4 ,
Db5 = Portc.5 , Db6 = Portc.6 , Db7 = 
Portc.7 , E = Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4
'---------------------
Config Rc5 = Pinb.7  
'---------------------
 
Dim Address As Byte , Command As Byte
Enable Interrupts  
'---------------------
Cls
Do 
Gosub Remote_control  
Loop
'---------------------

Remote_control:
Getrc5(address , Command)
If Address = 0 Then  
Command = Command And &B01111111  TV
Cls
Lcd "Command is: " ; Command 
Waitms 50  
End If
Return
'---------------------

 

Faculty of Electrical and Electronic Eng. 77 Automatic Control & Automation Dept.
   

Exp.13: IR transmi er, RC5-code  RC5IR 

 
 RC5
 

 
 
RC5,              
 RC5-Extended
 
SW2.Jumper JP17
 
 
     
       
 Rc5send Togbit , Address , Command
RC5OC1A
 78 
Practical Class 4 Programming Microcontrollers

 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Debounce = 200
 
Config Pine.4 = Input
Porte.4 = 1
'---------------------
Dim Togbit As Byte , Command As Byte ,
Address As Byte
 
Command = 12  
Togbit = 0
Address = 0
'---------------------
Do

Debounce Pine.4 , 0 , Pwr_cmd , Sub
Loop   OC1A pin 
 
End
'---------------------

Pwr_cmd:
Rc5send Togbit , Address , Command 
Waitms 200
Return  
'\-------------\

 
 

Faculty of Electrical and Electronic Eng. 79 Automatic Control & Automation Dept.
   

Appendix: Exp.12 and Exp.13  

RC5-code
Detailed Article about Remote Control and IR Module

What is infrared?  



 950nm
 

 
               

               
               
 

              

 Address
36KHZ 30KHZ – 60KHZ
36KHZ, 38KHZ38KHZ
 36~38
 
          36KHZ, 38KHZ    

              

 80 
Practical Class 4 Programming Microcontrollers

              
  27uS     36KHZ         
 21

   
 1  2
 

What is IR Transmitting pr ot ocol s?   


RC5 SIRCS NEC          
          Sony SAMSUNG JAPAN
 Waveforms

RC5 Transmi ing protocols? RC5


14       RC5      
1.728mS
 130mS
 
Address Length -
Command Length -
Carrier Frequency  -
Start Bit -
High-Bit-Time"1" -
Low-Bit-Time"0" -



Faculty of Electrical and Electronic Eng. 81 Automatic Control & Automation Dept.
   


 

 


 
 27µs
demodulator
6432
32 "0"
 32 x 27µs of silence27µs
 32 32 x 27µs of silence "1"
 27µs

 
| +---| |---+ |
| | | | | |
| | | | | |
|---+ | | +---|
<-----> <----->
1.7778ms 1.7778ms
Logic 1 Logic 0
 

 
 RC5

 82 
Practical Class 4 Programming Microcontrollers

 14BitsRC5
  Bit1   Bit2 Bit3 Bit4 Bit5 Bit6 Bit7 Bit8 Bit9 Bit10 Bit11 Bit12 Bit13 Bit14
  start bits   control   Address   Command
Start Bits or AGC "Automatic Gain Control Bits1-2 -
"1"
Control Bit or Toggle Bit CHECK bitBit3 -

–
11

Bits4-8 -
2^5=3232
SYSTEM ADDRESS EQUIPMENT
0 TV SET 1
1 TV SET 2
2 VIDEOTEXT
3 EXPANSION FOR TV 1 AND 2
4 LASER VIDEO PLAYER
5 VIDEO RECORDER 1 (VCR 1)
6 VIDEO RECORDER 2 (VCR 2)
7 RESERVED
8 SAT 1
9 EXPANSION FOR VCR 1 OR 2
10 SAT 2
11 RESERVED
12 CD VIDEO
13 RESERVED
14 CD PHOTO
15 RESERVED
16 AUDIO PREAMPLIFIER 1
17 RECEIVER / TUNER
18 TAPE / CASSETE RECORDER
19 AUDIO PREAMPLIFIER 2
20 CD
21 AUDIO RACK
22 AUDIO SAT RECEIVER
23 DCC RECORDER
24 RESERVED
25 RESERVED
26 WRITABLE CD
26-31 RESERVED

Faculty of Electrical and Electronic Eng. 83 Automatic Control & Automation Dept.
   

 Bits9-14 -
 2^6=64  64


COMMAND (in decimal) DESCRIPTION of FUNCTION


0-9 NUMERIC KEYS 0 - 9
12 STANDBY
13 MUTE
14 PRESETS
16 VOLUME UP
17 VOLUME DOWN
18 BRIGHTNESS +
19 BRIGHTNESS -
20 COLOR SATURATION +
21 COLOR SATURATION -
22 BASS UP
23 BASS DOWN
24 TREBLE +
25 TREBLE -
26 BALANCE RIGHT
27 BALANCE LEFT
48 PAUSE
50 FAST REVERSE
52 FAST FORWARD-
53 PLAY
54 STOP
55 RECORD
63 SYSTEM SELECT
71 DIM LOCAL DISPLAY
77 LINEAR FUNCTION (+)
78 LINEAR FUNCTION (-)
80 STEP UP
81 STEP DOWN
82 MENU ON
83 MENU OFF
84 DISPLAY A/V SYS STATUS
85 STEP LEFT
86 STEP RIGHT
87 ACKNOWLEDGE
88 PIP ON/OFF
89 PIP SHIFT
90 PIP MAIN SWAP
91 STROBE ON/OFF
92 MULTI STROBE
93 MAIN FROZEN
94 3/9 MULTI SCAN
95 PIP SELECT
96 MOSAIC MULTI PIP
97 PICTURE DNR
98 MAIN STORED
99 PIP STROBE
100 RECALL MAIN PICTURE
101 PIP FREEZE
102 PIP STEP UP
103 PIP STEP DOWN
118 SUB MODE
119 OPTIONS BUS MODE
123 CONNECT
124 DISCONNECT

 84 
Practical Class 4 Programming Microcontrollers

Interfacing IR Receiver to uC. IR 


 uPuC
"0"=On | "1" = off–  1
"1"inactivity  2
  3
              
14
  4

4.752mS
1.728mS


 
CLRM-2038S IR Module CLRM-2038S
 CLRM-2038S
  1
PCM  2
  3
  4
2.7V~5.5V  5
TTL, CMOS  6
NEC code,RC5 code  7
38KHZ  8
Faculty of Electrical and Electronic Eng. 85 Automatic Control & Automation Dept.
   

12m  9
  10
Optical switch ·
Audio, TV, VCR, CD, MD, DVD, etc ·
Air-conditioner, Fan, CATV, etc ·

Pins Config. & Int ernal Di agram   CLRM-2038S


CLRM-2038S

 
 
 CLRM-2038S

    
 
 86 
Practical Class 4 Programming Microcontrollers

Rc5 receiver interface 


4.7uF

 
 

 
 
IRSAT Remote Control   IRSAT

 IRSAT RC5 TV Remote Control with 33 Keys ·
  China (mainland)  ·
AA x 2 ·
10 meters ·
3μ AStandby current ·
17x4.7x2.5cm ·
 
IRSAT Remote Control Key Commands   IRSAT
 


Faculty of Electrical and Electronic Eng. 87 Automatic Control & Automation Dept.
   

COMMAND (in Hex) DESCRIPTION of FUNCTION


0-9 NUMERIC KEYS 0 - 9
12
13
14
16 VOLUME UP
17 VOLUME DOWN
18

19
20

21

22 BASS UP
23 BASS DOWN
24

25

26

27

48

50
52 F1
53 F2
54 F3
55 F4
63
71

RC5 Sender   RC5


 OC1(A)

 

 88 
Practical Class 4 Programming Microcontrollers

 Bascom-AVR
        RC5      
 
  Timer1     RC5SEND     
 
$regfile = "m8def.dat" ' specify the used micro
$crystal = 4000000 ' used crystal frequency

Dim Togbit As Byte , Command As Byte , Address As Byte

Command = 12 ' power on off


Togbit = 0 ' make it 0 or 32 to set the toggle bit
Address = 0

Do
Waitms 200
Rc5send Togbit , Address , Command
Loop

End

RC5 Receiver   RC5


 
 

 
 
 Bascom-AVR
        RC5      
 
 Timer0 getrc5
 
 
Faculty of Electrical and Electronic Eng. 89 Automatic Control & Automation Dept.
   

$regfile = "m8def.dat" ' specify the used micro


$crystal = 4000000 ' used crystal frequency
$baud = 19200 ' use baud rate
$lib "mcsbyte.lbx"

Config Rc5 = Pind.2 ' pin we want to use for the receiver input

Enable Interrupts ' enable the interrupts


Dim Address As Byte , Command As Byte 'reserve space for variables

Print "Waiting for RC5..."

Do
Getrc5(address , Command) ' check if a key on the remote is pressed

If Address = 0 Then 'we check for the TV address and that is


Command = Command And &B01111111 'clear the toggle bit (bit7)
Print Address ; " " ; Command
End If
Loop
End

Red: AGC pulses (ON)


Blue: Check bit (flipping)
White: Address (00)
Green: Command

 90 


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.14: 7-Segment Single Display  

 
  7-Segment
 

 
 
 
0 – 9 1
0 – 99 2
0 – 9999 3


 
 
 92 
Practical Class 5 Programming Microcontrollers


 
 CCCA
 

 A,…..,H

  
 
B,C1
 

 
 
PortC
 PortD
Faculty of Electrical and Electronic Eng. 93 Automatic Control & Automation Dept.
   

 

 
PortC 
  :‫ اﻟﻘﻄﻊ اﻟﱵ ﱔ ﰲ ﺎ ﲻﻞ‬7-H 6-G 5-F 4-E 3-D 2-C 1-B 0-A   

A.B.C.D.E.F 1 1 0 0 0 0 0 0 0
B.C 1 1 1 1 1 0 0 1 1
A.B.D.E.G 1 0 1 0 0 1 0 0 2
A.B.C.D.G 1 0 1 1 0 0 0 0 3
B.C.F.G 1 0 0 1 1 0 0 1 4
A.C.D.F.G 1 0 0 1 0 0 1 0 5
A.C.D.E.F.G 1 0 0 0 0 0 1 0 6
A.B.C 1 1 1 1 1 0 0 0 7
A.B.C.D.E.F.G 1 0 0 0 0 0 0 0 8
A.B.C.D.F.G 1 0 0 1 0 0 0 0 9
 94 
Practical Class 5 Programming Microcontrollers

 

 
&HC0 &HF9 &HA4 &HB0 &H99 &H92 &H82 &HF8 &H80 &H90


 

  :‫اﻟﻘﻄﻊ اﻟﱵ ﱔ ﰲ ﺎ ﲻﻞ‬ PortC 


7-H 6-G 5-F 4-E 3-D 2-C 1-B 0-A   

A.B.C.D.E.F 0 0 1 1 1 1 1 1 0
B.C 0 0 0 0 0 1 1 0 1
A.B.D.E.G 0 1 0 1 1 0 1 1 2
A.B.C.D.G 0 1 0 0 1 1 1 1 3
B.C.F.G 0 1 1 0 0 1 1 0 4
A.C.D.F.G 0 1 1 0 1 1 0 1 5
A.C.D.E.F.G 0 1 1 1 1 1 0 1 6
A.B.C 0 0 0 0 0 1 1 1 7
A.B.C.D.E.F.G 0 1 1 1 1 1 1 1 8
A.B.C.D.F.G 0 1 1 0 1 1 1 1 9
 
 

 
&H3F &H06 &H5B &H4F &H66 &H6D &H7D &H07 &H7F &H6F


 255 DEC&HFF

Faculty of Electrical and Electronic Eng. 95 Automatic Control & Automation Dept.
   

 
 LUT: Look-Up Table            
 
     

Data var1 , … , varn
 .0
label Data LUT
var = Lookup(Index , label)
 Index
  Data   LUT   
Var = Lookupstr(Index , Label)
 Indexlabel
  value  Index   
Var = Lookdown(value,Label,Entries)  label Data
 Entries
         
Restore Label  label Data LUT
Read Var
  Data   LUT     
Read Var   Restore    
 Var
 
 
 
 
 
 
 
 
 
 
 
 
 96 
Practical Class 5 Programming Microcontrollers

 0-9
 SW344 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
 
Config Porta = Output
Segment Alias Porta &H81
Porta = &H81  
Config Portc.4 = Output  
Ctr1 Alias Portc.4
Reset Ctr1  
'---------------------
Dim I As Byte  
'---------------------
Do
For I = 0 To 9
Segment = Lookup(i , Seg)  
Waitms 1000
Next I
SegData
Loop  Lookup
End
'---------------------

Seg:  
Data &H81 , &HF3 , &H49 , &H61 , &H33 ,
&H25 , &H05 , &HF1 , &H01 , &H21

Faculty of Electrical and Electronic Eng. 97 Automatic Control & Automation Dept.
   

 0 – 99
 SW344,5 
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Porta = Output 
Segment Alias Porta
Porta = &H81  
Config Portc.4 = Output &H81
Display1 Alias Portc.4  
Config Portc.5 = Output 
Display2 Alias Portc.5
 
Set Display1 : Set Display2  
'---------------------
Dim I As Byte , J As Byte  
'---------------------

Do
For I = 0 To 9
For J = 0 To 9  
Segment = Lookup(i , Seg)
Reset Display1 : Waitms 20 SegData
Set Display1
 Lookup
Segment = Lookup(j , Seg)  
Reset Display2 : Waitms 20
Set Display2  
Next J
Next I
 
Loop

End
'---------------------
Seg:
Data &H81 , &HF3 , &H49 , &H61 , &H33 ,  
&H25 , &H05 , &HF1 , &H01 , &H21

 98 
Practical Class 5 Programming Microcontrollers

 0 – 9999
$regfile = "m128def.dat"
$crystal = 8000000  
'---------------------
Config Porta = Output
Segment Alias Porta 
Porta = &H81
 
Config Portc = &B11110000 &H81
Display1 Alias Portc.4
Display2 Alias Portc.5  
Display3 Alias Portc.6 
Display4 Alias Portc.7
 
Set Display1 : Set Display2
Set Display3 : Set Display4
 
'---------------------
Dim I As Byte , J As Byte
Dim K As Byte , L As Byte  
'---------------------
Do
For I = 0 To 9
For J = 0 To 9
For K = 0 To 9
For L = 0 To 9
Segment = Lookup(i , Seg)
Reset Display1 : Waitms 7
Set Display1
 
Segment = Lookup(j , Seg)
Reset Display2 : Waitms 7 SegData
Set Display2  Lookup
Segment = Lookup(k , Seg)  
Reset Display3 : Waitms 7
Set Display3  
 
Segment = Lookup(l , Seg)
Reset Display4 : Waitms 7  
Set Display4
Next L
Next K
Next J
Next I
Loop

End
'---------------------
Seg:
Data &H81 , &HF3 , &H49 , &H61 , &H33 ,  
&H25 , &H05 , &HF1 , &H01 , &H21





Faculty of Electrical and Electronic Eng. 99 Automatic Control & Automation Dept.
   

Exp.15: Real Time Clock  

 
 
 

 
 
 SW2
 
 

 
  RTC         
  32.786 KHZ       
 TOSC1,2

 100 


Practical Class 5 Programming Microcontrollers

 
 
     
Config Clock = Soft | User  |
Config Date = Dmy , Separator = Char  
Time$ = "hh:mm:ss"  
Date$ = "mm/dd/yy"  
Var = Time$  
Var = Date$  

 
$regfile = "m128def.dat"
$crystal = 8000000 Directives
'----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E
= Portc.2 , Rs = Portc.3  Configure the LCD display
Config Lcd = 20 * 4
'----------------------
Config Clock = Soft  
Config Date = Dmy , Separator = /
Enable Interrupts  //
 
Time$ = "16:59:00"
Date$ = "14/04/08"  
----------------------
Do
Print Time$  
Print Date$
 
Lcd Time$ : Locate 2 , 1 : Lcd Date$

Wait 1  
Cls
Loop

Faculty of Electrical and Electronic Eng. 101 Automatic Control & Automation Dept.
   

Exp.16: DAC using Ladder R-2R  

 
 R-2R
 

 
 102 
Practical Class 5 Programming Microcontrollers

 
 SW37
SW2
 
 
 
      0 or 1         
 
0-255         8-bit       
 0-5VDC00000000>>11111111
V OUT = V REF x VAL / 2N
Digital Input
0 ~ 255

Analog Output
0 ~ 5V

 
 
 ،8-bit
Vstep = VM / 2N = 5 / 255 = 0.019 Volt

 
Vout = Digval x V step
  1000 0001=129
129 x 0.019 = 2.451V
Faculty of Electrical and Electronic Eng. 103 Automatic Control & Automation Dept.
   

 
 

 
 
V2V1

        
 
          1
        
0-to-Vcc      
 4.5VVcc - 0.5V
  2
       
3.9V
 
 5V6.5V
D7
  0 to 2.5V 

 104 


Practical Class 5 Programming Microcontrollers

5.5V ~ 12V

 
 
 
     
 x
Var = Round(x) Round(2.3) = 2 , Round(2.8) = 3
 Round(-2.3) = -2 , Round(-2.8) = -3
Var = Int(source) Ex: Int(134.567)=134  
Var = Frac(source) Ex: Frac(134.567)=567  
Var = Fix(x) EX: Fix(12.98)=12  x
Var=-1  x<0x
Var = Sgn(x)
Var=1  x>0

 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E  
= Portc.2 , Rs = Portc.3
Config Lcd = 20 * 4
 
'----------------------
Config Porte = Output  
Digital Alias Porte
'-----------------------  
Dim I As Byte , V_out As Single
Const Vlot_step = 5 / 255  
'-----------------------
Cls
Do
 
For I = 0 To 255
Digital = I 
V_out = I * Vlot_step
Lcd "DAC OUT= " ; V_out  
Wait 1 : Cls 
Next I
Loop  
End

Faculty of Electrical and Electronic Eng. 105 Automatic Control & Automation Dept.
   

Exp.17: Analog Comparator  

 
 
 

 
 
 SW2
 JP11, JP12Jumpers
 
 

 106 


Practical Class 5 Programming Microcontrollers

 ANI0
High   AIN1
 LowAIN0ANI1
 
 
  1/
 
 
 
 
     
    | Aci=On|off
 
  1     Compare=On|off
 
 Trigger
Config Aci= On|off ,
Compare= On|off ,    (Ain0 > Ain1) :Rising
Trigger = TOGGLE|RISING|FALLING Ain0
Ain1
 (Ain0 < Ain1) :Falling
Ain0
Ain1
 (Ain0 > Ain1 and Ain0 < Ain1) :Toggle
Enable Aci  
        
On Aci label
 label
Start Ac  
Stop Ac  
         
Enable Interrupts
 
Assembly
nop
 

Faculty of Electrical and Electronic Eng. 107 Automatic Control & Automation Dept.
   

 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 ,  
E = Portc.2 , Rs = Portc.3
Config Lcd = 20 * 4
 

Config Aci = On , Compare = Off , Trigger = 


Rising
On Aci Isr_aci  
Enable Aci 
Start Ac
Enable Interrupts  
'-----------------------  
Dim I As Byte
'-----------------------
Cls 
Do
nop  
Loop  
End
'-----------------------

Isr_aci:  
Cls
I = I + 1 
Lcd "change: " ; I  
Waitms 100
Return
 

 

 

 108 




 


‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬


 

Interfacing with Microcontrollers






P rogramming E mbedded S
ystems M
icrocontroller

You Can Practice Microcontroller Programming Easily Now!

WALID BALID, Tuesday, December 15, 2009


   

Powering Microcontroller  

––  


 



 

 
 4.5VAVR
8MHZ3V
 

 


        
       Vcc to Gnd 
      \  
20~40mA
         
    200mA   
 AVR


 

 110 


Practical Class 6 Programming Microcontrollers

 

 

 
Itotal = Ioperating_current + (8 x ILED)
2V
 150Ω
ILED = V / R = (5 - 2) / 150 = 20mA
 2.4mA
Itotal = 2.5mA + 8 x ILED = 8 x 20mA = 162.5mA
 AVR
 90mAPIC200mA

 

 
    
 
    
Source
    
Sink
 

Faculty of Electrical and Electronic Eng. 111 Automatic Control & Automation Dept.
   

Calculating Current Resistor Value  


 LED
 

IF VF VF VR Luminous Viewing
Type Colour Wavelength
max. typ. max. max. intensity angle
Standard Red 20mA 2.0V 2.3V 5V 5mcd @ 10mA 60° 660nm
Super bright Bright red 25mA 3.0V 3.4V 5V 80mcd @ 10mA 60° 625nm
Standard Yellow 20mA 2.1V 2.3V 5V 32mcd @ 10mA 60° 590nm
Standard Green 20mA 3.2V 3.5V 5V 32mcd @ 10mA 60° 565nm
High intensity Blue 20mA 3.4V 3.6V 5V 60mcd @ 20mA 50° 430nm
Super bright White 20mA 3.4V 3.6V 5V 500mcd @ 20mA 60° 660nm

 IF max
 VF typ
 VF max
 VR max
 Luminous intensity
 Viewing angle
  Wavelength
 
2V/20mA
 

 =

5− 2 3
= = = 150Ω
20 20

= × =( − ) ×

= (5 − 2) × 20 = 60
 

  1/4Watt  150Ω

 112 


Practical Class 6 Programming Microcontrollers

Using Transistors as Control Switches  

20mA––
 On/Off 

 

BJT  
FET  
         
 
FET/MOSFET BJT  
 
  
  VBE=0.6V  1 – 10mA
 nS10  (uS) 200MHZ   
      
      
      
12
 (10 )     
  100V   
      
      

             
 On/Off 
 
 
 
 
 IB=0Off state  ·
     IC = IB x hFE     On active state    ·
 
  :(On saturate state ·

Faculty of Electrical and Electronic Eng. 113 Automatic Control & Automation Dept.
   

 

 

 

 BC337
IC_max=800mA, V BE_saturate =0.65V, VCE_saturate=0.2V,
hFE = 100, VCE_max=50V

 IC
 VLED=2VILED= 20mA
IC = 5 x 20mA = 100mA

− 5−2
= = = 150Ω
20

=( − )×
= (5 − 2) × 100 = 300

100
= × → = = =1
100

= × = 0.2 × 100 = 20

     


 
− 5 − 0.7
= = = 4.3 Ω
1

=( − )×

= (5 − 0.7) × 1 = 4.3
 114 
Practical Class 6 Programming Microcontrollers

Practical Circuits of Transistors as Control Switches  

 BJT
 

(1) ‫اﻟﺸﲁ‬ “1”         
     
  GND   /
NPN
 
  (2) ‫اﻟﺸﲁ‬
“0”   
     
   VCC   /
 PNP
 
 

VCC /NPN
 GND/PNP

 NPN    


 VCC/
   
 VBE=0.7V 
 VE= VCC-VCE = 5 – 0.2 = 4.8V  (E
 VB = VPIN = 5V
 VBE= VB – VE = 5 – 4.8 = 0.2V
           
 IC



   
Faculty of Electrical and Electronic Eng. 115 Automatic Control & Automation Dept.
   

 5V21
   0.7V             


(3) ‫اﻟﺸﲁ‬  0.7~1V

(4) ‫اﻟﺸﲁ‬

=
+
1
=5 = 0.87
4.7 + 1
   


 Relay

 
3V, 5V, 6V, 9V, 12V, 15V, 24V, 36V, 48V, 60V

30mA ~ 300mA 


 


                


  

 Relay

 116 


Practical Class 6 Programming Microcontrollers

(6) ‫اﻟﺸﲁ‬
(5) ‫اﻟﺸﲁ‬

 
 
 24V12V65
 Q8 “1”6
P, SK1
 
Electromotive Force
D1, D2
 

 

“0” or “1”
 
Q
(7) ‫اﻟﺸﲁ‬  NPN7
Q
Pull-Up      
 .(5V, 12V, ..
 “1” 
   “0”

 PNP8 (8) ‫اﻟﺸﲁ‬


Q
 
 “0” 
 “1” Q
 

Faculty of Electrical and Electronic Eng. 117 Automatic Control & Automation Dept.
   

 MOSFET & FET


          
 
 
“N”
 G
“P”
 G

MOSFETL
 “N”
VDS_max =200V, IDS_max = 160mA, RDS = 0.16Ω, VG =5V

 
VLoad = 15V, ILoad=100mA
 

       VG =5V     
 


EMF


5V ~ 25V
               

 

 “P”    MOSFET    L        
 
VDS_max =100V, IDS_max = 12A, RDS = 0.3Ω, VG =15V

 118 


Practical Class 6 Programming Microcontrollers

. VLoad = 15V, ILoad=10

      


 “0”     BC337 
“0” Q10
 Q11
 “1”       
   
Q10  
 Q1115V
 
 

 

 

 
 

 

 

 

 

 

 

 
Faculty of Electrical and Electronic Eng. 119 Automatic Control & Automation Dept.
   

Practical Circuits of Optocouplers  

  


TTL

   

 

  


 OPTO-ISOLATORS or PHOTO-COUPLERS
        
        
 
       
 


 
    
 

 4Pin, 6Pin, 8Pin

 
 
 120 
Practical Class 6 Programming Microcontrollers

 2V                 
 15mA
–– ––
 –

 
 
 
 P
 “1”
      
    “0”  
 P Q13
 “0”
      
Q13 15V
 
 
 

  


 

 “1”
      
       “0” 
        
 “0”
        
 
 

Faculty of Electrical and Electronic Eng. 121 Automatic Control & Automation Dept.
   

                 
 

 

 
“0”
BT138220V/50HZ IN1 
“1”OUT1,2
C12 R51
 

 

 

 

 122 


Practical Class 6 Programming Microcontrollers

Designing a Liner DC Power Supply  

 

 

  

  
95%
90V~265V / 45HZ~55HZ

 

 

220V AC

Transformer Rectifier Smoothing Regulating


220V / 12V AC / DC Capacitors 5VDC
 

5V DC  
 
          220V      
 
220V
 
 
 5V, 6V, 9V, 12V, 15V, 28V, 24V, 36V, 48V
 
 200mA, 300mA, 400mA, 500mA, 1000mA, 1500mA
6x2, 8x2, 9x2, 12x2, 15x2, etc…    
   

Faculty of Electrical and Electronic Eng. 123 Automatic Control & Automation Dept.
   

 
          
  
 + , - , ~

          ~   
 + , -




 

 
  1A, 2A, 4A, 6A, 10A, 14A, 25A, 40A      
 

14A / 400V 6 Amp 4 Amp 1 Amp


 

 
 

 

 

 
 124 
Practical Class 6 Programming Microcontrollers


 
 


 
 
               
 

 

      

Vdc =
2Vm
Vdc =
2Vm Vdc = Vm
π π π

Vm Vm Vm
V = V = V =
rms 2 rms 2
rms 2

2 2V 2 2V 2V
Vdc = rms
Vdc = rms
Vdc = rms
p
p p
VDiod = Vm VDiod = 2Vm VDiod = Vm

I Diod = 0.5IL I Diod = 0.5IL I Diod = IL

 
Faculty of Electrical and Electronic Eng. 125 Automatic Control & Automation Dept.
   

 

 

 

×
=
×

 fpeak value of unsmoothed DCVsIL


 
 

 

78XX78XX, 79XX
 79XX

 
 
 5V, 6V, 8V, 9V, 10V, 12V, 15V, 18V, 24V

 

 126 


Practical Class 6 Programming Microcontrollers


 
1A 78XX or 79XX
 
 1A

 
Transformer + Rectifier

Transformer + Rectifier + Smo ot hi ng

Transformer + Rectifier + Smo ot hi ng + Re gul ator

 
Faculty of Electrical and Electronic Eng. 127 Automatic Control & Automation Dept.
   

Designing a Liner DC Power Supply Project  

 800mA5V

 7.3V 5V 


 220V/9V

VRectifier_Bridge = VPPTrans – VDiod_Drop

VRectifier_Bridge = 9 – 1.4 = 7.6V

800mA
 20%

IDevice = ILoad x 20%

IDevice = 0.8A x 20% = 1A

 1000mA

 1000uF ~ 2200uF



 

              
  100uF ~ 220uF

100nF

        
 

          

 100nF

 128 


Practical Class 6 Programming Microcontrollers

                

Diode
 

 

 

 5V, 12V 


 5V, 12V

 

 

 

Faculty of Electrical and Electronic Eng. 129 Automatic Control & Automation Dept.
   

LM317  


 1.25V ~ 33V

 

= . × + +

 

 

 

Written by: Walid Balid, Embedded Systems Engineer,


Aleppo, on Sunday, 22th March, 2009

 130 




 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.18: Interfacing n-Switch to a Single PIN  

 
  
 

 
 SW2S426 
 
 

 

 132 


Practical Class 7 Programming Microcontrollers

 
 
     
 
ADSC Start ADC  Single
Config Adc= Single/Free, .Getadc 

Prescaler = Auto, Start ADCFree


ADCH          
Reference = off|Avcc|internal
 and ADCL
Prescaler
 Reference
Start Adc  
Stop Adc  
var = Getadc(channel) channel

     Prescaler   



50 ~200 KHz

200KHz
 

 2.56VInternal Reference


AVCC

 Vref
 off 

 AVR
 AVRmega
 10-bit §
 0 - VCC §
 ±2 LSB §

Faculty of Electrical and Electronic Eng. 133 Automatic Control & Automation Dept.
   

0.5 LSB §
13 – 260 Micro Sec §

 
 15KSPS §
 2.56V §
 Single, Free §
  §
  §
 50 ~1000 KHz §
  §
  §
 x10 – x200 §

 AVR

                

 R=100Ω, C=100nFRCL=100uH, C=100nFLC
           
 ± 0.3V
         
        
 
         
 

 134 


Practical Class 7 Programming Microcontrollers

        Idle mode      
 
 “Single” ü
 “Enable ADC ” ü
 “Start ADC ” ü
 “Idle ” ü
 ü

 
 “Stop ADC ” ü

ADC 

Faculty of Electrical and Electronic Eng. 135 Automatic Control & Automation Dept.
   

 
   210=1024  10-bit   AVR       
 0 – VCC 0 – 1023

 
×
=
 
 Vin
 Vref
 

×
=
 
 ADC

( )× ×
=
 
 V Pos
 VNeg
 1X, 10X, 200XGAIN

 ADC val

0 → 511 ≫
512 → 1023 ≫

 
 
 
 136 
Practical Class 7 Programming Microcontrollers

 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 = 
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E
= Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4
 
Config Adc = Single , Prescaler = Auto ,  
Reference = Avcc
Start Adc
'----------------------  
Dim W1 As Word , Voltage As Single
Dim Sw As String * 1
Const V_ref = 5
'----------------------  
Do  
Gosub Get_var  
Gosub Check_sw
Gosub Show_temp
Wait 1
Loop
'---------------------- 
 
Get_var:
W1 = Getadc(5)
Voltage = W1 * V_ref
Voltage = Voltage / 1024
Return
'----------------------

Check_sw:
 
Select Case W1
Case 150 To 250 : Sw = "1"
Case 300 To 400 : Sw = "2"
Case 550 To 700 : Sw = "3"
Case 750 To 850 : Sw = "4"

Case Else : Sw = "-"


End Select
Return
'----------------------  
Show_temp:  
Cls
Locate 1 , 1 : Lcd "VAR1= " ; W1
Locate 2 , 1 : Lcd "VOLT= " ; Voltage
Locate 3 , 1 : Lcd "Switch NO. " ; Sw
Return


 

Faculty of Electrical and Electronic Eng. 137 Automatic Control & Automation Dept.
   

Exp.19: Reading Analog Liner Voltage  

 
 
 

 
  
 SW2S424,5
 
               
 R107, R100
 138 
Practical Class 7 Programming Microcontrollers

 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 = 
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E
= Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4  
 
Config Adc = Single , Prescaler = Auto ,
Reference = Avcc  
Start Adc
'----------------------
Dim W1 As Integer , W2 As Integer ,  
Temperature As Integer
Dim Voltage1 As Single , Voltage2 As Single
Const V_ref = 5
'----------------------  
 
Do
Gosub Get_var  
Gosub Show_var
Wait 1
Loop
'----------------------

Get_var: 
W1 = Getadc(3)
W2 = Getadc(4)
 

Voltage1 = W1 * V_ref
Voltage1 = Voltage1 / 1024

Voltage2 = W2 * V_ref
Voltage2 = Voltage2 / 1024
Return
'----------------------

Show_var:
 
Cls  
Locate 1 , 1 : Lcd "VAR1= " ; W1
Locate 2 , 1 : Lcd "VAR2= " ; W2
Locate 3 , 1 : Lcd "VOLT1= " ; Voltage1
Locate 3 , 1 : Lcd "VOLT2= " ; Voltage2
Return













Faculty of Electrical and Electronic Eng. 139 Automatic Control & Automation Dept.
   



Exp.20: Interfacing LDR  

 
  
 

 
  
 SW2S421

 
 
    CDS
100Ω
 350nm ~ 800nm2MΩ

 LDRillumination
.
= ×
 
 140 
Practical Class 7 Programming Microcontrollers

 LUXL 340x103A
 
LDR Technical Specifications
Dark Resistance 1MΩ
Resistance @ 10 Lux 10 – 20 KΩ
Resistance @ 100 Lux 2 – 4 KΩ
Peak Spectral response 540nm
Maximum Voltage 150V peak AC or DC
Power Dissipation 100mW
Operating Temperature -30°C to + 70°C
 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =

Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E  
= Portc.2 , Rs = Portc.3
Config Lcd = 20 * 4  
 
Config Adc = Single , Prescaler = Auto ,
Reference = Avcc  
Start Adc
'----------------------
Dim Ldr_r As Single, W1 As Word  
Dim Vin As Single
Dim Var1 As Single , Var2 As Single
Const V_ref = 5 : Const Vcc = 5
Const R_serial = 10000  
'----------------------
 
Do  
Gosub Get_adc
Gosub Calc_r  
Gosub Show_val
Wait 1
Loop  
'----------------------

Get_adc:
W1 = Getadc(0)
Return
'---------------------- 

Calc_r:
Vin = W1 * V_ref
 'LDR R=(Vin.10K)/(Vcc-Vin)
Vin = Vin / 1024

Var1 = Vcc - Vin


Var2 = Vin * R_serial
Ldr_r = Var2 / Var1  
Return
'----------------------  

Show_val:

Faculty of Electrical and Electronic Eng. 141 Automatic Control & Automation Dept.
   

Cls
Locate 1 , 1 : Lcd "ADC= " ; W1
Locate 2 , 1 : Lcd "Vin= " ; Vin
Locate 3 , 1 : Lcd "LDR= " ; Ldr_r
Return

Exp.21: Interfacing NTC Resistor  NTC

 
 NTC
 

  
 SW2S422

 
Negative Temperature ) NTC    
      (Coefficient


 142 


Practical Class 7 Programming Microcontrollers

 

                
10K 25°C


 

= ×
 25°C
3450
 
 

° = −

 
 
 
 273°K
 273°K + 25°C = 298°K
 

° = −

 
 

 
 

Faculty of Electrical and Electronic Eng. 143 Automatic Control & Automation Dept.
   

 
 
 
 

 
$regfile = "m128def.dat"
$crystal = 8000000  
'----------------------- 
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =
Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E  
= Portc.2 , Rs = Portc.3
Config Lcd = 20 * 4  
 
Config Adc = Single , Prescaler = Auto ,
Reference = Avcc  
Start Adc
'----------------------
Dim W1 As Word , Voltage As Single  
Dim Temp As Single
Dim F1 As Single, Ntc_volt As Single
Const V_ref = 5  
'----------------------
Do  
Gosub Get_temp  
Gosub Show_temp
Wait 1
Loop
'----------------------
Get_temp:
W1 = Getadc(1) 
Ntc_volt = W1 * V_ref  
Ntc_volt = Ntc_volt / 1024  'Beta/Tamp = 4250/298 = 14.2167
F1 = 1024 - W1
F1 = W1 / F1
F1 = Log(f1)
F1 = F1 + 14.2617
F1 = 4250 / F1
Temp = F1 - 273
Return
'----------------------  
Show_temp:
Cls  
Locate 1 , 1 : Lcd "VAR1= " ; W1
Locate 2 , 1 : Lcd "VOLT= " ; Ntc_volt
Locate 3 , 1 : Lcd "TEMP= " ; Temp
Return
 

 144 


Practical Class 7 Programming Microcontrollers

Exp.22: Interfacing LM35  LM35

 
   LM35DZ
  -45°C ~ +145°C
 

 

  
 SW2S427,8

 
        LM35     
 12 V
 

Faculty of Electrical and Electronic Eng. 145 Automatic Control & Automation Dept.
   

 
℃ →
 
 10mV
× . ×
= = =4
.
 4
 
 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =

Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E
= Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4
 
Config Adc = Single , Prescaler = Auto ,  
Reference = Internal
Start Adc
'----------------------  
Dim W1 As Integer , W2 As Integer ,
Temperature As Integer
'----------------------  

Do
 
Gosub Get_temp  
Gosub Show_temp
Wait 1
Loop
'---------------------- 
Get_temp:  
W1 = Getadc(6)  ' 4 steps = 1 degree
W2 = Getadc(7)
Temperature = W1 - W2
Temperature = Temperature / 4
Return
'----------------------
 
Show_temp:  
Cls
Lcd "Temp= " ; Temperature ; " C"
Return
 

  

 146 


Practical Class 7 Programming Microcontrollers

Exp.23: Interfacing Pressure Sensor  

 
 
 

 

  
 SW2S423

 
 “Freescale”     MPXAZ6115A      
 

Faculty of Electrical and Electronic Eng. 147 Automatic Control & Automation Dept.
   

15 ~ 115 kPa(kilopascals)


 101.325-kPa 1-atm(atmosphere)
Atmosphere = 101,325 * Pascal
Atmosphere = 1.013 * bar

 15 ~ 115 kPa0.2V ~ 4.8V

 

= × ( . × − . ) ∓ ( × × 0.009 × )
= . ∓ .

 


 1.5kPa
= × ( . × − . )

 

.
= +
. × .

  100m    7mbar      
310mbar8848m
           
 Pressure-to-altitudeAltimeters

 148 


Practical Class 7 Programming Microcontrollers

. . / ∙
ℎ= ∙ 1−
. /

Zero altitude pressure = 101325Pa = 1’013.25mbar; (100Pa = 1mbar)


Zero altitude temperature = 288.15K
Temperature gradient = 6.5K/1000m

R is the specific gas cons tant : = = 287.052
.

12km 

  +/-100m

 
$regfile = "m128def.dat"
$crystal = 8000000  
'-----------------------
Config Lcdpin = Pin , Db4 = Portc.4 , Db5 =

Portc.5 , Db6 = Portc.6 , Db7 = Portc.7 , E
= Portc.2 , Rs = Portc.3  
Config Lcd = 20 * 4
 
Config Adc = Single , Prescaler = Auto ,  
Reference = Avcc
Start Adc
'----------------------  
Dim W1 As Word , Voltage As Single ,
Pressure As Single
Const V_ref = 5
'----------------------  
 
Do
Gosub Get_temp  
Gosub Show_temp
Wait 1
Loop
'----------------------

Get_temp: 
W1 = Getadc(2)
Voltage = W1 * V_ref  
Voltage = Voltage / 1024

Pressure = Voltage / 0.045


Pressure = Pressure + 10.55
Return  
'----------------------
 
Show_temp:
Cls

Faculty of Electrical and Electronic Eng. 149 Automatic Control & Automation Dept.
   

Locate 1 , 1 : Lcd "VAR1= " ; W1


Locate 2 , 1 : Lcd "VOLT= " ; Voltage
Locate 3 , 1 : Lcd "PRES= " ; Pressure
Return

 
 LM317

 
1.3V~5VP62R118
 LM385LM317
 LM385
 1.3V:LM385-1.3
 2.5V:LM385-2.5
1.1V~5VLM385

 

 
 150 


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.24:External Interrupts  

 
  INT0 ~ INT7
 

 
  
 JP5, JP6, JP8
 
 

 
 

 152 


Practical Class 8 Programming Microcontrollers

 

Do  
If Key1 = 0 Then
...
...
 Debounce
End If

Debounce Key1 , 0 , Sw1 , Sub

Bitwait Key1, reset  Bitwait


Loop

                 
 
 
     
 x=0,1,~,7
 State
 Falling
Config Intx = State
 Rising
 “0”Low Level
 Change
           
On Intx label
 label
Enable Intx  
Disable Intx 
Enable Interrupts  

 

 
 
 
 Int0
   Disable Int0 

 Enable Int0

Faculty of Electrical and Electronic Eng. 153 Automatic Control & Automation Dept.
   


 


 Enable Interrupts



 
 154 
Practical Class 8 Programming Microcontrollers

 
$regfile = "m128def.dat"
$crystal = 1000000  
$baud = 9600
'-----------------------
Config Int0 = Rising
Config Int1 = Rising     
Config Int2 = Change
Config Int3 = Change ATmega128x=0,1,~,7
Config Int4 = Falling
Config Int5 = Falling  
Config Int6 = Change
Config Int7 = Low Level

On Int0 Int0_isr
On Int1 Int1_isr
On Int2 Int2_isr        
On Int3 Int3_isr
On Int4 Int4_isr  label
On Int5 Int5_isr
On Int6 Int6_isr
On Int7 Int7_isr Nosave
     
Porte = &B11110000 : Portd = &B00000000
       
Enable Int0 : Enable Int1
Enable Int2 : Enable Int3  
Enable Int4 : Enable Int5
Enable Int6 : Enable Int7  
Enable Interrupts
'-----------------------
Do
nop  
Loop Until Inkey() = 27
End
'-----------------------
Int0_isr:
Disable Interrupts    INT0    
Print "Int0 Occurred at Falling Edge!"
Enable Interrupts  
Return
'-----------------------
Int1_isr:    INT1    
Print "Int1 Occurred at Falling Edge!"
Return  
'-----------------------
Int2_isr:    INT2    
Print "Int2 Occurred at Low Level!"
Return  
   INT3    
'-----------------------
Int3_isr:
Print "Int3 Occurred at Low Level!"
Return  
   INT4    
'-----------------------
Int4_isr:
Print "Int4 Occurred at
Return
Rising Edge!"
 
'-----------------------    INT5    
Int5_isr:
Print "Int5 Occurred at Rising Edge!"  
Return
'-----------------------
Int6_isr:
   INT6    
Disable Int6  
Print "Int6 Occurred at Change of Edge!"
Return
   INT7    
'-----------------------
Int7_isr:
Disable Int7
Print "Int7 Occurred at Change of Edge!"  low
Return

Faculty of Electrical and Electronic Eng. 155 Automatic Control & Automation Dept.
   

Exp.25: Dealing with Timers  

 
  Timer1  Timer0

 /
        /  AVR   
           AVR   /
 

 /
  /
 16bit 8bit

 16bit /0 – 255 8bit /


 0 – 65536

          Clock   / 
Prescaler             
 

 
Value
Clock Timer Register [8/16 bit]  
Inc/Dec

 

 / /


 /

 /Overflow
       /  255>8bit | 65535>16bit 
 

 156 


Practical Class 8 Programming Microcontrollers

 Prescaler
10bit
/ Clock/
 

     
Prescaler = 1 TIMERClock = FCPU
Prescaler = 8 TIMERClock = FCPU / 8
Prescaler = 64 TIMERClock = FCPU / 64
Prescaler = 256 TIMERClock = FCPU / 256
Prescaler = 1024 TIMERClock = FCPU / 1024

 
               
 T0, T1/Clock

 
   
 

=
 
 T
 NTIMER1=16NTIMER0=8 N
 [1, 8, 64, 256 or 1024]Prescaler
 fOSC

 
  
Clock

=
Faculty of Electrical and Electronic Eng. 157 Automatic Control & Automation Dept.
   

Prescaler=64fOSC=2MHZ
 Clock

= = = 31250

 

= = = 0.000032 = 32µ

 23uS

 
 Timer0, Timer1

Timing of Timer0 at fOSC = 1MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.001 0.008 0.064 0.256 1.024
Maximum Timer Period (mSec) 0.256 2.048 16.384 65.536 262.144

Timing of Timer0 at fOSC = 2MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.0005 0.004 0.032 0.128 0.512
Maximum Timer Period (mSec) 0.128 1.024 8.192 32.768 131.072

Timing of Timer0 at fOSC = 4MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.00025 0.002 0.016 0.064 0.256
Maximum Timer Period (mSec) 0.064 0.512 4.096 16.384 65.536

Timing of Timer0 at fOSC = 8MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.000125 0.001 0.008 0.032 0.128
Maximum Timer Period (mSec) 0.032 0.256 2.048 8.192 32.768

Timing of Timer1 at fOSC = 1MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.001 0.008 0.064 0.256 1.024
Maximum Timer Period (Sec) 0.0655 0.5243 4.1943 16.777 67.1088

 158 


Practical Class 8 Programming Microcontrollers

Timing of Timer1 at fOSC = 2MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.0005 0.004 0.032 0.128 0.512
Maximum Timer Period (Sec) 0.0328 0.262 2.097 8.3886 33.554

Timing of Timer1 at fOSC = 4MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.00025 0.002 0.016 0.064 0.256
Maximum Timer Period (Sec) 0.016 0.131 1.049 4.194 16.777

Timing of Timer1 at fOSC = 8MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (mSec) 0.000125 0.001 0.008 0.032 0.128
Maximum Timer Period (mSec) 0.0082 0.0655 0.5243 2.097 8.3886

Timing of Timer1 at fOSC = 12MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (uSec) 0.0833 0.666 5.333 21.333 85.333
Maximum Timer Period (mSec) 0.0055 0.0437 0.3495 1.3981 5.5924

Timing of Timer1 at fOSC = 16MHZ


Prescaler 1 8 64 256 1024
Timer Resolution in (uSec) 0.0625 0.5 4 16 64
Maximum Timer Period (mSec) 0.0041 0.0328 0.262 1.0486 4.1943

 

Faculty of Electrical and Electronic Eng. 159 Automatic Control & Automation Dept.
   

 
     
Config Timer0 = Timer ,  8bitTimer0
Prescale = 1|8|64|256|1024  Prescaler
Config Timer0 = Counter ,  8bitTimer0
Prescale = 1|8|64|256|1024 ,
 Edge
Edge = Rising / Falling ,
Clear Timer = 1|0  Clear
Start Timer0
 |Timer0|
Stop Timer0
Enable Ovf0 / Enable Timer0
Timer0|
Disable Ovf0 / Disable Timer0
On Ovf0 T0_isr   T0_isr
Timer0 = Value
Value = Timer0   Timer0|
Config Timer1 = Counter|Timer, Edge = Rising|Falling, Prescale = 1|8|64|256|1024,
Noise Cancel = 0|1 , Capture Edge = Rising|Falling , Clear Timer = 1|0,
Compare A = Clear|Set|Toggle|Disconnect, Compare B = Clear|Set|Toggle|Disconnect

 16bit|Timer1
|Edge
Prescaler
 Timer1|Noise Cancel
 Timer1Capture Edge
 Timer1|Clear Timer
 OCR1A OC1ACompare A
 OC1A"Inv""0""1"TCNT1Timer1
OCR1BOC1BCompare B
  OC1B"Inv""0""1"TCNT1Timer1

Stop Timer1
  |Timer1|
Start Timer1
Enable Ovf1 / Enable Timer0
Disable Ovf1 / Disable Timer0
Timer1|
On Ovf1 T1_isr T1_isr
Enable Capture1
Disable Capture1
Timer1|
On Capture1 Cpa1_isr Cap1_isr
Enable Compare1a
Enable Compare1b
Timer1|
On Compare1a Oc1a
OC1a/b
On Compare1b Oc1b
Compare1a = Value
Timer1
Compare1b = Value
Value = Compare1a
  Timer1
Value = Compare1b
 160 
Practical Class 8 Programming Microcontrollers

 AVR

 Normal Mode
 1MHZ
 1uSecClock1uS

        50mSec       
 

× .
= = = = 50000
×

Timer0                
 Timer1255

 50mS

$regfile = "m8def.dat"
$crystal = 1000000
$baud = 4800
'-----------------------
Config Timer1 = Timer , Prescale = 1
Start Timer1

Config Portb.0 = Output


Led Alias Portb.0
'-----------------------
Do
If Timer1 >= 50000 Then
Stop Timer1
Toggle Led
Timer1 = 0
Start Timer1
End If
Loop
End
 


  5x10ms=50ms

Faculty of Electrical and Electronic Eng. 161 Automatic Control & Automation Dept.
   

 Overflow
    
 fOSC, Prescaler, N

      “ 1 OVF1 or 2 OVF0”      
 CPU“TIFR”
 Tifr.x3 = 1“1”

“1”
 [Tifr.x = 1]

=2 − 1

                
 Maximum Timer Period

=2
 N=8, 16 ·
 fOSC ·
Prescaler ·

Timer = Max
T0_Max= 255, T1_Max= 65536
Tifr.x=1
Timer
Timer = 0

Timer=0

Start Timer
 
1
OVF1: Timer/Counter1 Overflow Flag located in TIFR/bit 2, to check or reset this bit: TIFR.2=1
2
OVF0: Timer/Counter0 Overflow Flag located in TIFR/bit 0, to check or reset this bit: TIFR.0=1
3
X = 0 for Timer0, X = 2 for Timer1
 162 
Practical Class 8 Programming Microcontrollers

$regfile = "m8def.dat"
$crystal = 1000000

$baud = 4800
'-----------------------         
Config Timer1 = Timer,
Prescale = 1      65536µSec   
Start Timer1
       65536  Timer1
Config Portb.0 = Output
Led Alias Portb.0 1MHZ
'-----------------------
Do
If Tifr.2 = 1 Then
Tifr.2 = 1
Stop Timer1
Toggle Led
Start Timer1 65536us
End If
Loop  
End

 

 Overflow INT
Hardware 
 TIFR

 
$regfile = "m8def.dat"
$crystal = 1000000          
'-----------------------
Config Timer1 = Timer , 
Prescale = 1
Enable Ovf1
On Ovf1 T1_isr
 65536µSec
 65536 Timer1
Enable Interrupts

Config Portb.0 = Output


Led Alias Portb.0 1MHZ
Dim Flag As Bit
Start Timer1
'-----------------------
Do
If Flag = 1 Then
Reset Flag
Toggle Led 65536us
Start Timer1
End If
Loop  
End
'-----------------------
T1_isr:
Stop Timer1 : Set Flag
Return

Faculty of Electrical and Electronic Eng. 163 Automatic Control & Automation Dept.
   

Overflow
Interrupt
Max 0

CTCOCR Mode
   Timer1    OCR0     Timer0  
 OCR2Timer2OCR1A, OCR1B

               
TCNT=OCRnx TCNTn
 OCFnx

 TCCR1B WGM12=1“1”

 

×
=
 
 OCR1AL, OCR1AH
 
$regfile = "m8def.dat"
$crystal = 1000000  Timer1 
'-----------------------
Config Timer1 = Timer ,  641MHZ1Sec
Prescale = 64
Compare1a = 15625
×
Set Tccr1b.3 = =
Config Portb.0 = Output
Led Alias Portb.0

Start Timer1
'----------------------- 1Sec15620
Do
If Tifr.4 = 1 Then
Stop Timer1
Timer1 = 0
Toggle Led
Tifr.4 = 1
Start Timer1
End If
Loop 1Sec
End  
'-----------------------

 164 


Practical Class 8 Programming Microcontrollers

Timer1Max
65536

TCNT1 OCR1A

TCNT1
= OCR1A=
OCR1A 15620

Tifr.4=1 Start Timer


Timer=0
 

CTC Mode using Interrupt



 Tifr.4
Tifr.4       OCIEnx        
 OCF1A
$regfile = "m8def.dat"
 Timer1 
$crystal = 1000000
'-----------------------
Config Timer1 = Timer ,
Prescale=64,Clear Timer=1  641MHZ1Sec
On Compare1a Timer1_isr
Compare1a = 15625
Enable Compare1a ×
= =
Config Portb.0 = Output
Led Alias Portb.0
          
Dim Flag As Bit
Start Timer1   1Sec      15620  
Enable Interrupts
'-----------------------
Do 1Sec
If Flag = 1 Then
Reset Flag
Toggle Led
Start Timer1
End If
Loop
'-----------------------
Timer1_isr:
1Sec
 
Stop Timer1 : Set Flag
Return

Faculty of Electrical and Electronic Eng. 165 Automatic Control & Automation Dept.
   

 OCR1B OCR1A


 
$regfile = "m8def.dat"
$crystal = 1000000  Timer1      
'-----------------------
Config Timer1 = Timer ,  OC1A   1Sec    
Compare A= Toggle, Compare B= Toggle
, Prescale = 64
Compare1a = 15625
   OC1B   2Sec  
 Pinb.0 
Compare1b = 31250
On Compare1a Oc1a
On Compare1b Oc1b
Enable Compare1a  641MHZ
Enable Compare1b

×
Config Portb.0 = Output
Led Alias Portb.0
= =

Dim Flag1 As Bit , Flag2 As Bit


×
Start Timer1 = =
Enable Interrupts
'-----------------------
Do
If Flag1 = 1 Then
Reset Flag1 : Toggle Led
End If
If Flag2 = 1 Then
Reset Flag2 : Toggle Led
Timer1 = 0 : Start Timer1
End If
Loop
End
'-----------------------
Oc1a:
Set Flag1
Return
'-----------------------
Oc1b:
Set Flag2 : Stop Timer1
Return
 

OC1B

OC1A

LED

 

 166 


Practical Class 8 Programming Microcontrollers

CTC Overflow Mode


  

 TimerxMAX



 
               
 
×
_ = −
  

 

= − _

$regfile = "m8def.dat"
$crystal = 1000000  Timer1
'-----------------------
Config Timer1 = Timer , 641MHZ1Sec
Prescale=64
On Timer1 Timer1_isr
×
Timer1 = 49911 = − =
Enable Timer1

Config Portb.0 = Output


Led Alias Portb.0

Dim Flag As Bit


Start Timer1
Enable Interrupts
'-----------------------
Do
If Flag = 1 Then 1Sec
Reset Flag
Toggle Led
Start Timer1
End If
Max Start
Loop
End
'-----------------------
49911
Timer1_isr: Overflow
Stop Timer1
Set Flag Interrupt
Timer1 = 49911
Return

Faculty of Electrical and Electronic Eng. 167 Automatic Control & Automation Dept.
   

Timer1Max
65536
Tifr.2=1

Start Timer

TCNT = 49911

TCNT1

 
 Capture Mode
ICP Timer1 
Capture
 ICR1Capture1TCCR1Timer1
$regfile = "m8def.dat"
$crystal = 1000000   0   1  
$baud = 4800
'----------------------         Max
Config Timer1 = Timer, Capture Edge = Rising
, Noise Cancel = 1 , Prescale = 1024
Start Timer1
 
Config Pinb.0 = Input
Portb.0 = 1
'----------------------
Do
Print "Timer: " ; Timer1
Print "Icr1l: " ; Icr1l
Print "Icr1H: " ; Icr1h
Print "Capture: " ; Capture1
Print "--------------"
Loop
End
 
 Capture Mode Interrupt
Timer1 ICP
       (ICR1) Capture1      TCCR1
 

 168 


Practical Class 8 Programming Microcontrollers

$regfile = "m8def.dat"
$crystal = 1000000   0   1  
$baud = 4800
'----------------------         Max
Config Timer1 = Timer , Capture Edge =
Rising , Noise Cancel = 1 , Prescale = 1024
Enable Interrupts
 
      
Enable Capture1
Start Timer1
On Icp1 Timer1_cpa_isr

Config Pinb.0 = Input
Portb.0 = 1
'----------------------
      
Do
nop  
Loop
End
'----------------------
Timer1_cpa_isr:
Stop Timer1
Disable Capture1

Print "Timer: " ; Timer1


Print "Captr: " ; Capture1

Capture1 = 0 : Timer1 = 0
Enable Capture1
Start Timer1
Return

 Counters

     To, T1        
 

T0, T1
                  
 TCNTx

        Timer0      T0 
 255

Timer1T1
 65535

 

Faculty of Electrical and Electronic Eng. 169 Automatic Control & Automation Dept.
   


 

 
 

 Conter0 Normal ModeCounter1 


    T0         (1)
 255
$regfile = "m8def.dat"
$crystal = 1000000
$baud = 4800
'----------------------
Config Timer0 = Counter , Edge = Falling
Start Timer0
Tcnt0 = 0
'----------------------
Do
nop
Print Counter0
Loop Until Tcnt0 >= 255
End  

 

 

 

 

 

 170 


Practical Class 8 Programming Microcontrollers

 1Sec T0(2)


              
 255HZ
$regfile = "m8def.dat"
$crystal = 1000000
$baud = 4800
'----------------------
Config Timer0 = Counter , Edge = Falling
, Prescale = 1
Stop Timer0
Config Pind.4 = Input
'----------------------
Do
Counter0 = 0
Start Counter0
Waitms 1000
Stop Counter0  
Print "Counter0: " ; Counter0 ; "HZ"
Loop

 Overflow Counter0 Interrupt Counter1


$regfile = "m8def.dat"
$crystal = 1000000     (3)
  T0    
$baud = 4800
'----------------------
1Sec
Config Timer0 = Counter , Edge = Falling ,
On Timer0 Counter0_isr
Enable Timer0
Enable Interrupts       
>255      
'----------------------
Dim Count As Word , Fereq As Long

Do      


Start Timer0
Waitms 1000  
Stop Timer0
Fereq = Count * 255
Fereq = Fereq + Timer0
Print "Fereq= " ; Fereq
Timer0 = 0 : Count = 0
Loop
End
'----------------------
Counter0_isr:
Incr Count
Return

Faculty of Electrical and Electronic Eng. 171 Automatic Control & Automation Dept.
   

 Overflow Counter0 Interrupt  Counter1


$regfile = "m8def.dat"
$crystal = 1000000      (4)
      
$baud = 4800
'----------------------

Config Timer0 = Counter , Edge = Falling ,
Prescaler = 1
Timer0 = 255 - 10
Enable Timer0       
Enable Interrupts
On Timer0 Counter0_isr “155”“100”
'----------------------
Dim Count As Byte  
Do
nop
Loop Counter0     
End
'----------------------  10
Counter0_isr:
Load Timer0 , 10
Incr Count
Print "Count=" ; Count
Return
 Capture ModeCounter1
 Counter0Counter1
 §
 §
  §
 
$regfile = "m8def.dat"
$crystal = 1000000  0 1(5)
  Max
$baud = 4800
'----------------------
 
Config Timer1 = Counter , Prescale = 1024 ,
Edge = Rising , Capture Edge = Falling ,
Noise Cancel = 1
Start Timer1
Config Pinb.0 = Input
Portb.0 = 1
'----------------------
Do
Print "Timer: " ; Counter1
Print "Icr1l: " ; Icr1l
Print "Icr1H: " ; Icr1h
Print "Capture: " ; Capture1
Loop
End
 

 

 

 172 


Practical Class 8 Programming Microcontrollers

 Capture Mode InterruptCounter1


$regfile = "m8def.dat"
$crystal = 1000000    Counter1  (6)
T1
$baud = 4800
'----------------------
       
Config Timer1 = Counter , Edge = Falling ,
Capture Edge = Falling , Noise Cancel = 1 ,
Prescale = 1
Enable Timer1       
Enable Capture1
On Capture1 Ctr1_cpa_isr 
Enable Interrupts
      
Config Pinb.0 = Input
Portb.0 = 1  
'----------------------
Do
nop
Loop
End
'----------------------
Ctr1_cpa_isr:
Stop Counter1
Disable Capture1

Print "Counter1: " ; Counter1


Print "Capture1: " ; Capture1  
Enable Capture1
Start Counter1
Return

 Counter1 OC ModeCounter1
$regfile = "m8def.dat"
$crystal = 8000000  Counter1 :(7)
     
'----------------------
Config Timer1 = Counter , Edge = Rising ,
     Prescaler
Prescale = 8 , Compare A = Toggle
Compare1a = 102

Config Portb.1 = Output      


OC1A     Compare1a
'----------------------
Do
nop
Loop  38Khz~13uS

 
Faculty of Electrical and Electronic Eng. 173 Automatic Control & Automation Dept.
   

 Timer1 & Timer0


 20uSTimer0

=2 = 256 = 20
.

1Sec

= = = 500000

 Cnt=0Cnt = 49999Timer050000

T1 Timer1
 1Sec

65536 Timer1
 

$regfile = "m8def.dat"
$crystal = 12800000 ' External 12.8MHZ
$baud = 4800
'----------------------
Config Timer1 = Counter , Edge = Rising , Noise Cancel = 1
Config Timer0 = Timer , Prescale = 1 '20uS
On Timer0 Timer0_isr
On Timer1 Timer1_isr
Stop Timer0
Stop Counter1

Config Pind.5 = Input


'----------------------
Dim Frequency As Long , Flag As Bit , Overflow As Byte , Cnt As Word
'----------------------
Enable Timer0
Enable Timer1
Enable Interrupts

 174 


Practical Class 8 Programming Microcontrollers

Print "Frequency Counter"


Main:
Counter1 = 0 : Overflow = 0 : Cnt = 49999
'----------------------
Start Timer0
Start Counter1
'----------------------
Do
If Flag = 1 Then
Reset Flag

Frequency = Overflow * 65536


Frequency = Frequency + Counter1

Print "Frequency= " ; Frequency ; " HZ"


Goto Main
End If
Loop
'----------------------

Timer1_isr:
Incr Overflow
Return
'----------------------
Timer0_isr:
If Cnt <> 0 Then
Decr Cnt
Else
Stop Counter1
Stop Timer0
Set Flag
End If
Return
'----------------------
 
  

Faculty of Electrical and Electronic Eng. 175 Automatic Control & Automation Dept.
   

 1nF~100uF

                 “0”
 50KΩ

2.7V              
 
$regfile = "m8def.dat"
$crystal = 8000000
$baud = 4800
'----------------------
Dim T As Long , C As Single
'----------------------
Do
T = 0
Config Pinb.0 = Output
Portb.0 = 0 'Low Z, 0V

Waitms 1000 ~2.7V


Config Pinb.0 = Input
Portb.0 = 1

Do
T = T + 1
Loop Until Pinb.0 = 1

C = T * 0.0866  
C = Round(c)
Print C ; " nF"
Loop
End


 2.7V


 

 176 




 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
   

Exp.26:Serial Communications RS232 

 
  RS232

 
 
  ·
 ·


              
 


 
  Serial Communications Parallel
Asynchronous Synchronous   Communications
· Morse code telegraphy o I2C § LPT
· RS-232 (COM Port) o SPI § ISA
· RS-423 o PS2 § EISA
· RS-485 § VESA
§ ATA
· Universal Serial Bus (USB)
§ SCSI
· FireWire
§ PCI
· Ethernet § PCMCIA
· Fiber Channel1 § IEEE-1284
· InfiniBand2 § IEEE-488
· MIDI3
· DMX5124
· Serial ATA5
· SpaceWire6
· PCI Express
· SONET and SDH7
· T-1, E-18

1
High-speed, for connecting computers to mass storage devices
2
Very high speed, broadly comparable in scope to PCI
3
Control of electronic musical instruments
4
Control of theatrical lighting
5
New replacement for parallel IDE
6
Spacecraft communication network
7
High speed telecommunication over optical fibers
8
High speed telecommunication over copper pairs
 178 
Practical Class 9 Programming Microcontrollers

 RS232
DTE9
 DCE10

 
 

 
 TTL
 +3V ~ +25V"Space"“0” Ø
 .-3V ~ -25V"Mark"“1” Ø
 .-3V ~ +3V“x” Ø

“GND”±25V
 500mA

 
9
Data Terminal Equipment (computer)
10
Data Circuit-terminating Equipment (modem)
Faculty of Electrical and Electronic Eng. 179 Automatic Control & Automation Dept.
   

 RS232
 Advantages  Disadvantages
       ü System-to-System       ×
   Chip-2-Chip
 50 ü .Chip-2-Sensor 
         ×
   
±25 ü RS232<>TTL ×
 “0” , “1”  Single Master/Single Slave ×
 ü  ×

 

 RS232
Serial Port “COM” RS232
 
Port Address
COM1 0x3F8
COM2 0x2F8
COM3 0x3E8
COM4 0x2E8

 DB-9PinCOMx

 

 180 


Practical Class 9 Programming Microcontrollers

 
 1, 2, 3, …., 9

Pin Name Direction Function Description


1 CD In Control Carrier Detect
2 RXD In Data Receive Data
3 TXD Out Data Transmit Data
4 DTR Out Control Data Terminal Ready
5 GND --- Ground System Ground
6 DSR In Control Data Set Ready
7 RTS Out Control Request to Send
8 CTS In Control Clear to Send
9 RI In Control Ring Indicator
  : C D – C a r r i e r D e t e c t ( C o n t r o l s e n t fr o m D C E t o D T E )
 

:RxD – Receive Data (Data sent from DCE to DTE)


 DTEDCE
Idle State, “1 or Negative”(Mark state, “0 or Positive”
 

:TxD – Transmit Data (Data sent from DTE to DCE)


 DCEDTE
Idle State, “1 or Negative”Mark state, “0 or Positive”
 

Faculty of Electrical and Electronic Eng. 181 Automatic Control & Automation Dept.
   

: D T R – D a t a T e r m i n a l R e a d y ( C o n t r o l s e n t fr o m D T E t o D C E )
  DTE 
 DCE

: D S R – D a t a S e t R e a d y ( C o n t r o l s e n t fr o m D C E t o D T E )
 DTEDCE
 “1”“0”

: R T S – R e q u e s t T o S e n d ( C o n t r o l s e n t fr o m D T E t o D C E )
DTE  DCE
 
“1” “0”
 

: C T S – C l e a r T o S e n d ( C o n t r o l s e n t fr o m D C E t o D T E )
 DTE  
DCE
 
 “1”           “0” 


: R I – R i n g I n d i c a t o r ( C o n t r o l s e n t fr o m D C E t o D T E )
   DTE
 

“TxD ”              
 “RxD ”

 

 182 


Practical Class 9 Programming Microcontrollers

       Hardware handshaking     
 TxD, RxDRTS, CTS

 CTS Ø

 RTS Ø
RTS
 Ø
 ·
       RTS        ·


 RS232
SPECIFICATIONS RS232 RS423
Mode of Operation SINGLE-ENDED SINGLE-ENDED
Total Number of Drivers and Receivers on One Line 1DRIVER/1RECVR 1DRIVER/10RECVR
Maximum Cable Length 50 FT 4000 FT
Maximum Data Rate 20kb/s 100kb/s
Maximum Driver Output Voltage ±25V ±6V
Driver Output Signal Level (Loaded Min.) Loaded ±5V to ±15V ±3.6V
Driver Output Signal Level (Unloaded Max) Unloaded ±25V ±6V
Driver Load Impedance (Ohms) 3k to 7k >=450
Max. Driver Current in High Z State Power On N/A N/A
Max. Driver Current in High Z State Power Off ±6mA @ ±2v ±100uA
Slew Rate (Max.) 30V/µS Adjustable
Receiver Input Voltage Range ±15V ±12V
Receiver Input Sensitivity ±3V ±200mV
Receiver Input Resistance (Ohms) 3k to 7k 4k min


Shield24AWG
100Ω16PF/FT

Faculty of Electrical and Electronic Eng. 183 Automatic Control & Automation Dept.
   

 AsynchronizeSynchronize

 clock or strobe
 

 
\
 


Start Bit
Stop Bit


 

 

 
 184 
Practical Class 9 Programming Microcontrollers




 

Full-DuplexHalf-Duplex ü
6, 7 or 8bit  ü
Baud Rate ü
    Parity Bit         ü
Even or Odd
 1, 1.5 or 2 ü

      Half-Duplex   
             
 
Full-Duplex
 

Parity Bit
 

 
“0” “Even”
“1”
10110010 > Parity Bit = 0 | 10110110 > Parity Bit = 1
“0”“Odd”
 .“1”
10110010 > Parity Bit = 1 | 10110110 > Parity Bit = 0
Faculty of Electrical and Electronic Eng. 185 Automatic Control & Automation Dept.
   

N
 ASCII=127 N=7bit5, 6, 7 or 8bit

 

1, 1.5 or 2 Stop Bit

 

        Baud Rate 
 

300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, etc…
 

 

/ =
 

 

 186 


Practical Class 9 Programming Microcontrollers

 RS232

 
Faculty of Electrical and Electronic Eng. 187 Automatic Control & Automation Dept.
   

 RS232
8250-UART
 
IOR, Input/Output Register/
COM1: 0x3F8 | COM2: 0x2F8
 TxDRxD

 
LCR, Line Control Register
COM1: 0x3FB | COM2: 0x2FB
 

LSR, Line Status Register


COM1: 0x3FD | COM2: 0x2FD
 

MCR, Modem Control Register


COM1: 0x3FC | COM2: 0x2FC
 8250

 188 


Practical Class 9 Programming Microcontrollers

MSR, Modem Status Register


COM1: 0x3FE | COM2: 0x2FE
 “dxxx=1”  
 

 

 IER, Interrupt Enable Register


COM1: 0x3F9 | COM2: 0x2F9
       “1” Active    COM   
 COM2IRQ3COM1IRQ4

 

IIR, Interrupt Identification Re gi ster 


COM1: 0x3FA | COM2: 0x2FA


 

 
Faculty of Electrical and Electronic Eng. 189 Automatic Control & Automation Dept.
   

 COM3 


 

 

 
 8250  
 "Divisor"1.8432MHZ
1.8432 × 10
=
16 ×

 Divisor9600bps

1.8432 × 10 1.8432 × 10
= = = 12
16 × 16 × 9600

 UART8250D=12
 LCRBit7=1 ·
 0x3F8LSB ·
 0x3F9MSB ·
 LCRBit7=0 ·

 190 


Practical Class 9 Programming Microcontrollers

 VB, MVS2008.netCOM 



          ActiveX & OCX Components
Bios
 

 

MSCOMM32.ocx“OCX”“MSComm”VB6
 COM

 System32
 VB6SP6

 “Standard EXE”


 VB6
 “Enterprice Edition”
 

Faculty of Electrical and Electronic Eng. 191 Automatic Control & Automation Dept.
   

 VB6 “Microsoft Visual Studio 2008”


SerialPort
 .(VB.net, C#.net or C++.net.net

 
        SerialPort     
 VB6

 VB6
              
 (COM
    
 Test1/ProjRS232.vbp

OutGoing
Send Data
    
    
 InComing
 192 
Practical Class 9 Programming Microcontrollers

  
Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,N,8,1"
MSComm1.RThreshold = 1
MSComm1.InputLen = 0
MSComm1.InBufferCount = 0
End Sub

Private Sub cmdClear_Click()


txtOutput.Text = ""
txtInput.Text = ""
End Sub

Private Sub optCOM1_Click()


MSComm1.CommPort = 1
End Sub

Private Sub optCOM2_Click()


MSComm1.CommPort = 2
End Sub

Private Sub optOpen_Click()


MSComm1.PortOpen = True
End Sub

Private Sub optClose_Click()


MSComm1.PortOpen = Flase
End Sub

Private Sub optTXT_Click()


MSComm1.InputMode = comInputModeText
End Sub

Private Sub optBIN_Click()


MSComm1.InputMode = comInputModeBinary
End Sub

Private Sub cmdSendData_Click()


MSComm1.Output = txtOutput.Text & Chr(13)
End Sub

Private Sub cmdExit_Click()


If MSComm1.PortOpen = True Then MSComm1.PortOpen = Flase
End
End Sub
Private Sub MSComm1_OnComm()
Static sBuff As String
If MSComm1.CommEvent = comEvReceive Then
If optBIN.Value = True Then
sBuff = sBuff & StrConv(MSComm1.Input, vbUnicode)
txtInput.Text = sBuff
Else
txtInput.Text = txtInput.Text & MSComm1.Input
End If
End If
End Sub
Faculty of Electrical and Electronic Eng. 193 Automatic Control & Automation Dept.
   

 :“MSComm”
MSComm1.CommPort = N
 N
MSComm1.Settings = "Baud,Parity,Bits,Stop"

MSComm1.RThreshold = n
comEvReceive

 n=0
MSComm1.InputLen = n
   n=0      
 
MSComm1.InBufferSize = n
1~1024
MSComm1.OutBufferSize = n
1~1024
MSComm1.InBufferCount = n

MSComm1.OutBufferCount = n

MSComm1.PortOpen = True | Flase
|
MSComm1.InputMode = comInputModeText | comInputModeBinary
Input|
var = MSComm1.InPut

MSComm1.OutPut = var

MSComm1.CommEvent = Value
 
Value  
comEvCD CD
comEvCTS   CTS
comEvDSR   DSR
comEvRing RI
comEvReceive   RThreshold
comEvSend   SThreshold
comEvEOF   vbCrLf

MSComm1.DTREnable = True | Flase


 “0” “1”TrueDTR  |  | 
“0”Flase
MSComm1.Handshaking = comNone|comRTS|comXOnXoff|comRTSXOnXOff
 194 
Practical Class 9 Programming Microcontrollers

 
MSComm1.RTSEnable = True | Flase
 “1”TrueHardwareRTS | |
 “0”Flase“0”
 
 
 
  Poling the Port  ü
              

 
Footer ByteHeader Byte
      OnComm() event    ü
  OnComm




 
Faculty of Electrical and Electronic Eng. 195 Automatic Control & Automation Dept.
   

 Matlab
           Matlab   
 
 
obj = serial('Port','PropertyName',PropertyValue,...)
Ser = serial('COM1','BaudRate',9600,'DataBits',8, 'Parity','non');
 
fopen(obj)
fopen(Ser);
 
fclose(obj)
fclose(Ser);
 
delete(obj)
delete(Ser);
 
fprintf(fid, format, A, ...)
fprintf(Ser,'This is Test');
TXT
fwrite(fid, format, A, ...)
fwrite(Ser,4);
BIN
A = fscanf(fid, format)
A = fscanf(Ser);
TXT
A = fread(fid)
A = fread(Ser);
BIN
 
ser = serial('COM1','BaudRate',9600,'DataBits',8);
fopen(ser)

fprintf(ser,'This is Test')
A = fscanf(ser);
fprintf(ser,A)

for i=1:5
fwrite(ser,i);
end
A = fread(ser);
fwrite(ser,A);

fclose(ser)
delete(ser)
clear ser
 196 
Practical Class 9 Programming Microcontrollers

 TTL <> RS232


  RS232    
     
    TTL    
 Adapter

   Max232   


 TTL<>RS232

 

 

 

 

RS232 TTL<>RS232  


 Max232UART
 

 
 
 
 

Faculty of Electrical and Electronic Eng. 197 Automatic Control & Automation Dept.
   

RS232 TTL<>RS232
 UART

 

 198 


Practical Class 9 Programming Microcontrollers

Exp.27: UART Interface UART


 
  UART
 

 

  
 TxD, RxDS312,4
 
RS232
.UART

Faculty of Electrical and Electronic Eng. 199 Automatic Control & Automation Dept.
   

 Universal Asynchronous Receiver and Transmitter Int erface  UART


              
TTL RS232
 UART RS232

 MCU-MCU           
 MCU-PC

 
  AVR

TXD, RXDUART ü
 TXD, RXDUSART ü
 XCK

 UART Frame Format


RS232      UART        
 

 
St: Start bit, always low.
Data bits: (0 to 8).
P : Parity bit (Can be odd or even)
Sp: Stop bit, always high.
IDLE: No transfers on the communication line (RxD or TxD), IDLE line is high.
 200 
Practical Class 9 Programming Microcontrollers

Baud Rate Register

 0 – 4095 UBRRH and UBRR UBRR

 9600bps 1Mhz UBRR


 
1000000
, = − = − 1 = 5.510416 ≈ 6
× 16 × 9600

9600
                
 


0.5%
 5%

 

[%] = − × %

 

9600
[%] = − 1 × 100% = 7.52%
8928.571

               
 

Faculty of Electrical and Electronic Eng. 201 Automatic Control & Automation Dept.
   

 
     
$baud = Var .UART0 (Hardware)
Baud = Var  UART0 (Hardware)
$BAUD1 = var .UART1 (Hardware)
Baud1 = Var  UART1 (Hardware)
Baud #x , BaudRate x UART0 (Software)

Baud1 #x , BaudRate x UART1 (Software) 

Print Var ; "const"  .UART0


Print [#channel,] Var; "const" .channel  UARTx
.UARTx
Printbin Var [; Varn]
 [; Varn]
.channel  UARTx
Printbin #channel, Var [;Varn]
 [; Varn]
 UART0RS232
 ["prompt"]
Input ["prompt"] , Var [,Varn]
 Var
 n=1,2…[,Varn]

Input #ch, Var [,Varn ]  .ch UART0RS232


 UART0RS232
Inputbin Var1 [,Var2]
 [,Var2]
Inputbin #channel, Var1[,Var2]  .ch UARTxRS232

Inputhex ["prompt"],Var[,Varn]  HEXUART0RS232

var = INKEY()  .UART0buffer Ascii


UARTx   buffer      Ascii   
Var = Inkey(#channel)
.“0”  .channel 
 UART0   buffer       
var = WAITKEY()
  Ascii
 UARTx buffer 
Var = Waitkey(#channel)
  Asciichannel 
 “1”   UART0    buffer   
Var = Ischarwaiting() “0“
 

 202 


Practical Class 9 Programming Microcontrollers

 “1”   UARTx   buffer   
Var = Ischarwaiting(#channel)
 .“0”
   UART1,2      
$Timeout = value ‫ و‬Waitkey() Input  ،Input
  buffer 
Echo On|off  Input|
compiler
Config Input = Term,
 CR, LF, CRLF or LFCR 
Echo = Echo | Noecho
 Input

$serialinput2lcd
 .Terminal 

Config Serialin|Serialin1|Serialin2|Serialin3 = Buffered, Size = Size


[, Bytematch = All|byte|none]
[, Cts = Pin, Rts = Pin, Threshold_full = Num, Threshold_empty = Num]

 SRAM  Serialin Input Buffer 


SizeMAX= 255
§ SERIALIN : 1st UART Hardware Interface > UART0
§ SERIALIN1 : 2nd UART Hardware Interface > UART1
§ SERIALIN2 : 3rd UART Hardware Interface > UART2
§ SERIALIN3 : 4th UART Hardware Interface > UART3
 “ASCII” “Bytematch=byte”
 
§ Serial0CharMatch (for SERIALIN or the 1st UART/UART0)
§ Serial1CharMatch (for SERIALIN1 or the 2nd UART/UART1)
§ Serial2CharMatch (for SERIALIN2 or the 3rd UART/UART2)
§ Serial3CharMatch (for SERIALIN3 or the 4th UART/UART3)
 “Bytematch=all”
§ Serial0ByteReceived (for SERIALIN or the 1st UART/UART0)
§ Serial1ByteReceived (for SERIALIN1 or the 2nd UART/UART1)
§ Serial2ByteReceived (for SERIALIN2 or the 3rd UART/UART2)
§ Serial3ByteReceived (for SERIALIN3 or the 4th UART/UART3)
 “Bytematch=none”
 “CTS”Cts = Pin
“RTS”Rts = Pin
       “RTS=1”        Threshold_full = Num

                Threshold_empty = Num
 “CTS=0”
“CTS-RTS”

Faculty of Electrical and Electronic Eng. 203 Automatic Control & Automation Dept.
   

Config Serialout|Serialout1|Serialout2|Serialout3 = Buffered, Size = Size


  SRAM  Serialout Output Buffer 
SizeMAX= 255
SERIALOUT : 1st UART Hardware Interface > UART0
SERIALOUT1 : 2nd UART Hardware Interface > UART1
SERIALOUT2 : 3rd UART Hardware Interface > UART2
 SERIALOUT3 : 4th UART Hardware Interface > UART3

Config Comx = Baud , Synchrone = 0|1 , Parity = None|disabled|even|odd ,


Stopbits = 1|2 , Databits = 4|6|7|8|9 , Clockpol = 0|1

 “x”UART
.$Baud'dummy'Baud
 |Synchrone = 0|1
 |||Parity = None|disabled|even|odd
 Stopbits = 1|2
 Databits = 4|6|7|8|9
 Clockpol = 0|1
Serin Var , Bts , Port , Pin , Baud , Parity , Dbits , Sbits
Serout Var , Bts , Port , Pin , Baud , Parity , Dbits , Sbits

   | 


 Serout
 Serin

 |Var
 |Bts
 Port
 Pin
 Baud
 NONE=0, EVEN=1, ODD=2Parity
 7,8Dbits
 1,2Sbits

 

 


 Data Bus

.Bts=0
 n
Var = Bufspace(n) n=0 : output buffer 1st UART | n=1 : input buffer 1st UART
n=2 : output buffer 2nd UART | n=3 : input buffer 2nd UART
 204 
Practical Class 9 Programming Microcontrollers

Clear Serialin
Clear Serialout
 |
 UART
 "device"
 "COM1:" Comx "Hardware"
 "Software"
Open "device" For Mode As #channel "COMpin:Speed,N,Parity,Stopbits[,Inverted]"
  
Examples:  |COMpin
'open hardware UART   BaudSpeed
Open "com1:" For Binary As #1
  6,7,8 or 9N
'open a Transmit channel for output
(software UART)  (||) N|O|E <Parity
Open "comd.1:9600,8,n,1" For Output As #2
 1|2Stopbits
'open a Receive channel for input
(software UART)
Open "comd.0:9600,8,n,1" For Input As #3
 [,Inverted]
 Mode
 Com1, Com2  Binary or Random"Hardware"
. OutputInput"Software"
 #channel
Close #channel  software UART
Get #channel, Var  HW or SW
Put #channel , Var   HW or SW
Enable | Disable Urxc .UART|
On Urxc Rx_isr 
Enable | Disable Utxc .UART|
On Utxc Tx_isr   
Enable | Disable Udre .UART|
On Udre Empty_isr   
Enable | Disable Serial UART|
$dbg
 Debugging
Dbg

 (;)Print

 .Print Chr (var); Printbin 

          Printbin     
 Arr
Printbin Arr(1) ; 10

 Inputbin 


 Arr

Faculty of Electrical and Electronic Eng. 205 Automatic Control & Automation Dept.
   

Inputbin Arr(1) , 10

 Inputbin

Print #channel 


OPEN & CLOSEInput #channel


       COM1 Open "device"    

 OPEN & CLOSE

       value   $Timeout = value   

 

$Timeout = value
fOSC Value = 100 Value = 1000 Value = 10000 Value = 100000
1MHZ 1.6ms 16ms 160ms 1600ms
2MHZ 0.8ms 8ms 80ms 800ms
4MHZ 0.4ms 4ms 40ms 400ms
8MHZ 0.2ms 2ms 20ms 200ms
16MHZ 0.1ms 1ms 10ms 100ms
 ASCII

 206 


Practical Class 9 Programming Microcontrollers

 Input
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Dim Num1 As Integer
Dim Num2 As Integer
Dim Sum As Integer
'----------------------
Do
Num1 = 0 : Num2 = 0
Input "Enter 1st Number: " , Num1
Input "Enter 2nd Number: " , Num2

Sum = Num1 + Num2


Print "Sum: " ; Sum
Loop
 
End

 InputHex
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Dim Num1 As Byte, Num2 As Byte, Sum As Word
'----------------------
Do
Num1 = 0 : Num2 = 0
Inputhex "Enter 1st Number as two-character hex-code: " , Num1
Inputhex "Enter 2nd Number as two-character hex-code: " , Num2

Sum = Num1 + Num2


Print "Sum Dec:" ; Sum
Print "Sum Hex:" ; Hex(sum)
Print "-------------"
Loop
End

 

 

 

 

 
Faculty of Electrical and Electronic Eng. 207 Automatic Control & Automation Dept.
   

 Waitkey()
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Dim Inchar As Byte
'----------------------
Do
Inchar = Waitkey()
Print Inchar
Loop Until Inchar = " " Pressed keys is:
Print "END..."
End 1,2,3,4,5,6,A,B,C,Esc,

 
 Input, Inputhex
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Dim Num1 As Byte, Num2 As Byte
Dim Sum As Integer, Arr(2) As Byte
'----------------------
Do
Num1 = 0 : Num2 = 0
Input "Enter DEC: " , Num1 , Num2
Sum = Num1 + Num2
Print "Sum: " ; Sum
Print "-----------"

Inputhex "Enter HEX: ", Num1, Num2


Sum = Num1 + Num2
Print "Sum: " ; Sum ;  
Print "-----------"
Loop
End

 UART0
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 19200
'----------------------
Config Serialin = Buffered , Size = 10
Config Serialout = Buffered , Size =10
Enable Interrupts
'----------------------
Dim Arr(10) As Byte
'----------------------
Baud = 9600
Do
If Ischarwaiting() = 1 Then
Inputbin Arr(1) , 10
Printbin Arr(1) , 10
Waitms 10
Clear Serialin  
Clear Serialout
End If
Loop
End

 208 


Practical Class 9 Programming Microcontrollers

 
$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Enable Urxc
On Urxc Getchar
Enable Interrupts
'----------------------
Dim Inchar As String * 1
'----------------------
Do
nop
Loop Until Inchar = " "
'----------------------

Getchar:  
Inchar = Inkey() : Print Inchar
Return

 Urxc, Utxc, Udre


$regfile = "m8def.dat"
$crystal = 4000000
$baud = 9600
'----------------------
Enable Urxc
Disable Utxc
Disable Udre

On Urxc Getchar
On Utxc Finish
On Udre Empty

Enable Interrupts
'----------------------
Dim Inchar(10) As Byte
Dim Flag As Bit
'----------------------
Do
nop
Loop Until Flag = 1
End
'----------------------
Getchar:
Disable Urxc
Enable Udre
Enable Utxc

Inputbin Inchar(1) , 10
Printbin Inchar(1) ; 10
Return  
'----------------------
Finish:
Disable Utxc : Set Flag
Print "Serial TX complete interrupt!"
Return
'----------------------
Empty:
Disable Udre : Print ""
Print "UART Register is Empty!"
Return

Faculty of Electrical and Electronic Eng. 209 Automatic Control & Automation Dept.
   

 UART0, UART1
$regfile = "m128def.dat"
$crystal = 4000000
$baud = 9600
$baud1 = 9600
'-------------------------
Config Com1=Dummy, Synchrone =0, Parity = None, Stopbits =1, Databits =8, Clockpol=0
Config Com2=Dummy, Synchrone =0, Parity = None, Stopbits =1, Databits =8, Clockpol=0

Open "com1:" For Binary As #1


Open "com2:" For Binary As #2

Config Serialin = Buffered , Size = 20 , Bytematch = 27


Config Serialin1 = Buffered , Size = 20 , Bytematch = All

Config Serialout = Buffered , Size = 20


Config Serialout1 = Buffered , Size = 20

Enable Interrupts
'-------------------------
Dim Msg As String * 10
'------------------------
Do
If Ischarwaiting() = 1 Then
Input Msg : Print Msg
End If

If Ischarwaiting(#2) = 1 Then
Input #2 , Msg : Print #2 , Msg
End If
Loop
End
'------------------------
Serial0charmatch:
Print "Esc Char!"
Return
'------------------------
Serial1bytereceived:
Print #2 , " "
Print #2 , "We got a Char!"
Return
'------------------------
Close #1
Close #2

 210 


Practical Class 9 Programming Microcontrollers

 
$regfile = "m8def.dat"
$crystal = 4000000
'------------------------
Ucsrb = 0 : Wait 1
Dim Value As Byte
'------------------------
Open "comb.0:9600,8,n,1" For Output As #1
Open "comb.1:9600,8,n,1" For Input As #2

Open "comc.0:9600,8,n,1" For Output As #3


Open "comc.1:9600,8,n,1" For Input As #4

Open "comd.6:9600,8,n,1" For Output As #5


Open "comd.7:9600,8,n,1" For Input As #6
'------------------------
Print #1 , "SW UART1, " ; "Enter a value"
Input #2 , Value
Print #1 , "value is: " ; Value
Print #3 , "SW UART2, " ; "Enter a value"
Input #4 , Value
Print #3 , "value is: " ; Value
Print #5 , "SW UART3, " ; "Enter a value"
Input #6 , Value
Print #5 , "value is: " ; Value
'------------------------
Get # 2 , A : Put # 1 , A
Do
Value = Inkey(#2)
If Value > 0 Then Print #1 , "SW UART1:" ; Chr(value)

Value = Inkey(#4)
If Value > 0 Then Print #3 , "SW UART2:" ; Chr(value)

Value = Inkey(#6)
If Value > 0 Then Print #5 , "SW UART3:" ; Chr(value)

Loop Until Inkey(#2) = 1 Or Inkey(#4) = 1 Or Inkey(#6) = 1


'------------------------
Close #6 : Close #5 : Close #4
Close #3 : Close #2 : Close #1
End

 
Faculty of Electrical and Electronic Eng. 211 Automatic Control & Automation Dept.


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
Practical Class 10 Programming Microcontrollers

Exp.28:Serial Communications RS485 RS485

 
  RS485

 RS485
          RS485  
 
A,B 
 VA>VB “1” VA<VB
 “1”“0”

 
 RS485
B A
                 
 

 RS485
RS485
ST TI MAXIM LTC
ST485 SN75176 MAX485 LTC485
:RS485
Faculty of Electrical and Electronic Eng. 213 Automatic Control & Automation Dept.
    

 RS485
SPECIFICATIONS RS232 RS423 RS422 RS485

Mode of Operation SINGLE-ENDED SINGLE-ENDED Differential Differential


Total Number of Drivers and 1DRIVER 1DRIVER 1DRIVER 32DRIVER
Receivers on One Line 1RECVR 10RECVR 10RECVR 32RECVR
Maximum Cable Length 50 FT 4000 FT 4000 FT 4000 FT
10Mb/s 10Mb/s
Maximum Data Rate 20kb/s 100kb/s
100Kb/s 100Kb/s
Maximum Driver Output Voltage ±25V ±6V -0.25V to +6V -7V to +12V
Driver Output Signal
Loaded ±5V to ±15V ±3.6V ±2.0V ±1.5V
Level (Loaded Min.)
Driver Output Signal
Unloaded ±25V ±6V ±6V ±6V
Level (Unloaded Max)
Driver Load Impedance (Ohms) 3k to 7k >=450 100 54
Max. Driver Current in
Power On N/A N/A N/A ±100uA
High Z State
Max. Driver Current in
Power Off ±6mA @ ±2v ±100uA ±100uA ±100uA
High Z State
Slew Rate (Max.) 30V/µS Adjustable N/A N/A
Receiver Input Voltage Range ±15V ±12V -10V to +10V -7V to +12V
Receiver Input Sensitivity ±3V ±200mV ±200mV ±200mV
Receiver Input Resistance (Ohms) 3k to 7k 4k min 4k min >=12k

 
 
            
 RS485

   

              
 
 
 214 
Practical Class 10 Programming Microcontrollers

 RS485
B  A  
 

 

15Meter 
 Backbone with StubsDaisy Chain

 
 RS485

 

Faculty of Electrical and Electronic Eng. 215 Automatic Control & Automation Dept.
    

 

 RS485
 
PASSIVE DUPLEX CONTROL (AUTOMATIC ) ü
ACTIVE DUPLEX CONTROL (RTS Pin ) ü
RS485    RO, DI      Passive Duplex   ü
 DE/RE Driver
  
 
No data to send  §
             “1”
Idle

Master sends a request  §


     Start Bit       
Stop Bit
             Check sum 
Idle

 216 


Practical Class 10 Programming Microcontrollers

Slave sends a response  §


          add = 07   



 

RS485 Driver Active Duplex ü


  RTS Control
 
         No data to send     §
RTS
         “1”   


Master sends a request  §


     Start Bit       
Stop Bit
Check sum

Idle

Faculty of Electrical and Electronic Eng. 217 Automatic Control & Automation Dept.
    

Slave sends a response 


 add = 07



 

 RS232
 Advantages  Disadvantages
       ü System-to-System       ×
   Chip-2-Chip
 1200 ü .Chip-2-Sensor 
 100kb/s RS485<>TTL ×
  ü       
 ü 

:RS485MODBUS
         MODEBUS  
Multi Master/Slave
               
 
Master Device   MODEBUS        
 Slave Device

 Slave DeviceMaster DeviceQueryMODEBUS

Slave Function Start Start


Byte Count Data CRC
Address Code Address Hi Address Lo

 218 


Practical Class 10 Programming Microcontrollers

Slave Function Byte Start Data CRC


Address Code Count Address Stream CRC Low CRC Hi
1 byte 1 byte 1 byte 2 byte 0 ~ 252 byte 1~2 byte

1~252Slave Address •
Function code •
Byte Count •
Start Address •
255 byte maxData Stream •
 Cyclic Redundancy CheckCRC •
 Inter-frame-time             
t3.5

 

 
Data
 t1.5

 

 
Inter-character time-out (t1.5) = 750μs
Inter-frame delay (t3.5) = 1.750ms

Faculty of Electrical and Electronic Eng. 219 Automatic Control & Automation Dept.
    

70Byte9600bps

 Slave address

 

70 ×8 = 560

× 1000 = .

   58ms             

 .t3.5= 1.75ms

 

Start Master

Set Control Pin

Waitms 10

Send Data Frame

Reset Control Pin

Waitms 100

End
 220 
Practical Class 10 Programming Microcontrollers

 
Start Slave

NO

UART INT

Yes

Byte1 is Disable UART


Slave ADD Wait 90ms

NO
Yes

Get the data at the 90ms


Passed?
UART Interface
(MSB First, LSB Last ) Yes

Enable UART

NO
Check Count
Check CRC

Programming
YES
OK
Ignore Data
Set Data Value

End

 MasterSlaveResponceMODEBUS
    Slave           
                
 

Slave Function Byte CRC


Address Code Count CRC Low CRC Hi
1 byte 1 byte 1 byte 1~2 byte

Slave
 CRC

Faculty of Electrical and Electronic Eng. 221 Automatic Control & Automation Dept.
    

 RS485|

Full-DuplexHalf-DuplexRS485
 

 

 

 

 

  RS485


  

 222 


Practical Class 10 Programming Microcontrollers

 UART<>RS458
Max485

 

 
     
Config Print0 = Porte.2 , Mode = Set .RS485

“DE”“1”Config Print0

 “0”“DE”

“DE”
 

Faculty of Electrical and Electronic Eng. 223 Automatic Control & Automation Dept.
    

 Microcontroller is Master, PC is Slave


$regfile = "m128def.dat"
$crystal = 8000000  
$baud = 9600
'------------------
Config Print0 = Porte.2 , Mode = Set 
Config Pine.2 = Output
 DE
Config Pine.4 = Input  
Key1 Alias Pine.4
Porte.4 = 1
'------------------  
Dim Msg As String * 100
'------------------
Do
Debounce Key1 , 0 , Sendall , Sub
Loop
End
'------------------
Sendall:
Print "This is RS485 Test Program"
Print "RS458 Protocol Done Based-on MAX485"
Print "University of Aleppo - Syria"
Print "Faculty of Alectrical & Electronic Engineering"  
Print "Control Department"
Print "Fourth Year Students"
Print "Computer Aided Design Session"
Print "Unfutunality This Was The Last Session Lab"
Print "2nd Semester"
Print "See You Next Semester Guys ;)"
Print "Kindest Regards"
Print "Walid BALID"
Print ":) :) :) :) :) :) :) :) :) :) :) :)"
Wait 1
Return

 

 

 

 

 

 

 

 224 


Practical Class 10 Programming Microcontrollers

 Microcontroller is Slave, PC is Master


$regfile = "m128def.dat"
$crystal = 8000000  
$baud = 9600
'-------------------------  DE
Config Porte.2 = Output
Config Print = Porte.2 , Mode = Reset  
Open "comd.3:9600,8,n,1" For Output As #1  UART
Open "comd.2:9600,8,n,1" For Input As #2  
Config Serialin = Buffered , Size = 250  
Enable Interrupts
'-------------------------  
Dim Msg As String * 250
'------------------------
Do  
If Ischarwaiting() = 1 Then
Input Msg
UART
Print #1 , Msg 
End If
Loop  UART
End

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Faculty of Electrical and Electronic Eng. 225 Automatic Control & Automation Dept.
    

 RS232<>RS458
RS232<>RS458

RS232<>RS458

 

 

 

 

 226 


Practical Class 10 Programming Microcontrollers

 RS232<>UART<>RS458
      RS232<>UART<>RS458      
 Max232 UART Max485
UART

 
 RS232<>UART<>RS458

Faculty of Electrical and Electronic Eng. 227 Automatic Control & Automation Dept.
    

Exp.29:Serial Communications USB USB

 
  USB

  
        USB   
 USB

 USB
 480Mb/s ü
 . Plug & Play  ü
  ü
 127 ü

  :USB

 USB 1.0 & USB 1.1 & USB 2.0& USB 3.0USB

 USB 1.01.5 Mbits/s Low Speed §


USB 1.112 Mbits/s Full Speed §
.USB 2.0480 Mbits/s High Speed §
 .USB 3.04800 Mbits/s  §

     

 USB
 ”Host Controlled”  USB
       )   
          
 USB

 228 


Practical Class 10 Programming Microcontrollers

”On-The-Go”
 

 USB
  ü
 ü

 HUB USB




 
 
 Plug& Play
 Plug & Play USB
  USB

 

 VID, PID 

 USB
 

Faculty of Electrical and Electronic Eng. 229 Automatic Control & Automation Dept.
    

 USB 
 USB
 A §
 B §


 

 D- & D++5v & GNDUSB

 VCC1
  D-2
  D+3
 
  GND4

  '1'       D+&D-  USB  
 D-  '0' D+ '1'
 

 :(Non Return to Zero Invert) NRZI


NRZIUSB
 

'0' '1''0'
 '1'

 

 '1'
 

 230 


Practical Class 10 Programming Microcontrollers

 
 
  USB
 D- D+
D- .1
D+ .2
 .3

   
 USB
 USB
 USB

                USB Device USB 
USB Function Host Controller IC USB
 USB

 USBUSB Function

         USB Function  Endpoint  
EndpointUSB Function
 InOut
Faculty of Electrical and Electronic Eng. 231 Automatic Control & Automation Dept.
    

 USB  


 EP2 In

 USB Function  


 

 
 USB1  EP1 In
 USB1
[Addr : 2] [Endpoint : EP1] [In]

PipePipe

EP0 In & EP0 Out  Pipe0  Pipe  
 

 
 Pipe
 
Control Transfers §

 232 


Practical Class 10 Programming Microcontrollers

Interrupt Transfers §
Isochronous Transfers §
Bulk Transfers §

 USB
         Frame     USB  
 1ms  USB1.1, USB2.0
 125µs

Transaction 
 

 
              Token Packet


 In Token
 Synchronization .1
 
 Packet Identity PID .2
 
 128Address .3
 Endpoint .4
 5Cyclic Redundancy CheckCRC .5

 Out Token


 In Token

Control Transfer : Setup Token


 In Token

Faculty of Electrical and Electronic Eng. 233 Automatic Control & Automation Dept.
    

1ms±500ns: Start of frame Token


11Frame number

 Data Packet


Data0 .1
Data1 .2
16bitCRC1024bit

 

Handshake Packet
Acknowledge

Not acknowledge


Stall
 

 

 

 

 

 234 


Practical Class 10 Programming Microcontrollers

 USB
 USB  USB 
 
 USBHardware .1
 . .2
              

 USB

 USB
UARTUSB

 USB

      FT232         
 FTDIUSB<>UART

HardwareUSB

USB
 

 D2XX driver & VCP driver

 
  .COM

 
Faculty of Electrical and Electronic Eng. 235 Automatic Control & Automation Dept.
    

 D2XX driver & VCP driver

D2XX.DLL Driver VCP Driver  


     
3MB 300 KB/s  
     

 Com USB :(Virtual Com Port) VCP


 ComUSB

   :D2XX.DLL


 DLL

 

 FT232BM
 ü
VCP& D2XX.DLLFTDI ü
USB1.1, USB2.0 ü
 ü
300kb~2Mb ü
384FIFO  ü

128FIFO  ü
VID, PID ü
 ü

USBUSB
  USB            
 USB

 236 


Practical Class 10 Programming Microcontrollers

 

 

 
  11 
 

                
PWREN#
 
Faculty of Electrical and Electronic Eng. 237 Automatic Control & Automation Dept.
    

 3ms Sleep mode  


Sleep=”1”
 

Wake up

 

 USB
 Serial Interface EngineSIE
USBUSB §
CRC §
Start Of Packet, End Of Packet, Resume, Reset  §
NRZI §
PID §

USB1.1USB Transceiver
  D+              USB2.0,
 

 FT232BM 
 6MHz48MHz
  EEPROM PID, VID 
 

 
 
 
 

 238 


Practical Class 10 Programming Microcontrollers

 RS232<>UART<>USB

 

 

 RS232<>UART<>USB

 
 
 
 
 

Faculty of Electrical and Electronic Eng. 239 Automatic Control & Automation Dept.


 

‫ﺍﻟﺘﺠﺎﺭﺏ ﺍﻟﻌﻤﻠﻴﺔ‬

 





Programming
Embedded Systems Microcontroller

You Can Practice Microcontroller Programming Easily Now!


WALID BALID, Tuesday, December 15, 2009
Practical Class 11 Programming Microcontrollers

Exp.30: Programming Internal EEPROM EEPROM

 
  EEPROM

 

 

Faculty of Electrical and Electronic Eng. 241 Automatic Control & Automation Dept.
   

 
 UART1
             RS232
.EEPROM

 
     
  | |     
Dim Var As [xram|Sram|Eram]
Type [at Location][overlay]  

Examples: overlay
Dim Sram_var As Sram Byte At &H10

Dim Eprm_var As Eram Byte At &H80
Writeeeprom Var , Address AddressEEPROMVar
Writeeeprom Var , Label LabelEEPROMVar
Readeeprom Var , Address AddressEEPROMVar
Readeeprom Var , Label LabelEEPROMVar
 DATA
$eeprom
 EPPEEPROM
$data  
 Intel HEXEPP
$eepromhex
$eeprom
$eepleave  EEPROMEPP

$default Sram | Xram | Eram

Examples:
$default Sram  $default
Dim A As Byte , B As Byte

$default Eram
Dim C As Byte , D As Byte

$end $default  


$noramclear  SRAM
$romstart = address  

 EEPROM AVR


 

 242 


Practical Class 11 Programming Microcontrollers

 (1)

$regfile = "m128def.dat"
 
$crystal = 4000000
$baud = 9600
'------------------
Dim B As Byte , I As Byte SRAM
Dim W As Word , S As String * 5

Dim Eb As Eram Byte At 13


Dim Ei As Eram Integer At 14 EEPROM
Dim El As Eram Long At 16
Dim Es As Eram String * 5 At 20
'------------------
Do
S = "ABCDE" : Es = S
S = ""
S = Es : Print S
SRAM     
.EEPROM
B = 10 : Eb = B
B = 0
B = Eb : Print B
'/------

For I = 0 To 4   


Readeeprom B , I SRAMEPROM
Print B
Next I
'/------  
S = "abcde" : W = 10000 SRAM     
Writeeeprom S , 5
EEPROM
Writeeeprom W , 11

S = "" : W = 0  


Readeeprom S , 5 : Print S
Readeeprom W , 11 : Print W SRAMEPROM
'/------

Restore Lbl
Read B : Print B SRAM
Read B : Print B ROM
Loop
End
'------------------ ROM
Lbl:
Data 10 , 12
'------------------ EEPROM
$eeprom
Data 1 , 2 , 3 , 4 , 5
$data

 

 
Faculty of Electrical and Electronic Eng. 243 Automatic Control & Automation Dept.
   

 (2)

$regfile = "m128def.dat"
$crystal = 4000000
$baud = 9600  
$eepromhex
$eepleave
'------------------
Dim Var As Sram Byte At &H200
'------------------  EEPROM    
$eeprom
Label1: 
Data 1 , 2 , 3 , 4 , 5

Label2:
Data 10 , 20 , 30 , 40 , 50
$data
'------------------   
Readeeprom Var , Label1 SRAMEPROM
Print Var
Readeeprom Var
Print Var
'/------
  
SRAMEPROM
Readeeprom Var , Label2
Print Var
Readeeprom Var
Print Var  
'/------

SRAM     


Var = 100
Writeeeprom Var , Label1 EEPROM
Var = 101
Writeeeprom Var

Readeeprom Var , Label1


Print Var
Readeeprom Var
Print Var
'/------

Var = 0
Writeeeprom Var , 3
Readeeprom Var , 3
Print Var
End

 
  

 244 


Practical Class 11 Programming Microcontrollers

Exp.31: Interfacing with I2C I2C

 
   EEPROM       I2C    
  .RTC 

 

 

Faculty of Electrical and Electronic Eng. 245 Automatic Control & Automation Dept.
   

I2C
 Philips 1980Inter-Integrated Circuit I2C 
TV
 Two Wire InterfaceTWI
 
SDA, SCK          I2C  
 SDA
    One-Master<>Multi-Slaves         SCK
Multi-Master<>Multi-Slaves

 Chip-to-Chip
Multi-SlaveMaster    Multi-Drop Bus
 Master<>Slave 
 Multi-Slave Multi-Master

SDA, SCKOpen collector I2C


 “1”

112 nodes 7-BitUnique Address I²C


  1008 nodes 10-bit
 


 10pF400pF

 

 

 246 


Practical Class 11 Programming Microcontrollers

 
 

 I2C
 Advantages  Disadvantages
Slave ü .(3meter) ×
 ü 400Khz ×
 ü  ×
 ü


Faculty of Electrical and Electronic Eng. 247 Automatic Control & Automation Dept.
   

Interfacing I2C EEPROM


Description:

I²C is an abbreviation of Inter Integrated Circuit and is a protocol for serial communication between
Integrated Circuits, it is also called Two Wire Interface (TWI). The bus is used for communication
between microcontrollers and peripheral devices like memories, temperature sensors and I/O
expanders. An EEPROM is a Electrically Erasable and Programmable Read Only Memory.

EEPROM Model Size Internally Organized Address (hex)


AT24C01 128 Bytes 128 x 8 = 1024 bits 00000 >> 0007F
AT24C02 256 Bytes 256 x 8 = 2048 bits 00000 >> 000FF
AT24C04 512 Bytes 512 x 8 = 4096 bits 00000 >> 001FF
AT24C08 1 Kbyte 1024 x 8 = 8192 bits 00000 >> 003FF
AT24C16 2 Kbyte 2048 x 8 = 16384 bits 00000 >> 007FF
AT24C32 4 Kbyte 4096 x 8 = 32768 bits 00000 >> 00FFF
AT24C64 8 Kbyte 8192 x 8 = 65536 bits 00000 >> 01FFF
AT24C128 16 Kbyte 16384 x 8 = 131072 bits 00000 >> 03FFF
AT24C256 32 Kbyte 32768 x 8 = 262144 bits 00000 >> 07FFF
AT24C512 64 Kbyte 65536 x 8 = 524288 bits 00000 >> 0FFFF
AT24C1024 128 Kbyte 131072 x 8 = 1048576 bits 00000 >> 1FFFF

The communication of the bus goes along two lines: SDA (Serial Data) and SCL (Serial Clock). Each I²C
device has a unique 7-bit address (Device Select Code). The most significant bits are fixed and
assigned to a specific device category (e.g. b1010 is assigned to serial EEPROMS). The three less
significant bits (A2,A1 and A0) are programmable and used to address the device. The three bits
allows eight different I2C address combinations and therefore allowing up to eight different devices of
that type to operate on the same I2C-bus. The I2C address is send in the 1st byte, the lest signi icant bit
of the first byte is used to indicate if the master is going to write(0) or read(1) from the slave.

The device that sends data along the bus is called master, a device that receives the data is called
slave. The master starts the transmission with a start signal and stops the transmission with a stop
signal on the SDA line. During the start and stop signals the SCL line has to be high. After the master
has started the data-transmission with a start signal, the master writes a device address byte to the

 248 


Practical Class 11 Programming Microcontrollers

slave. Each data byte has to have a length of 8 bits. The slave has to acknowledge the reception of the
data byte with a acknowledge-bit (ACK).

A write operation requires a device address bytes, two address bytes and the data-byte. Upon receive
of the address the EEPROM sends an ACK and then clocks in the data-byte. The EEPROM sends again
an ACK and the microcontrollers sends a stop-signal to terminate the write sequence.

All devices from 32K – 512K will require no system changes and can be interchanged with only the
page size differences to consider.

Low Density Random Read:

Faculty of Electrical and Electronic Eng. 249 Automatic Control & Automation Dept.
   

Medium and High Density Random Read:

AT24C32 (4 Kbyte)
4096 * 8 = 32768 bits 0000 >> 0FFF 32 byte page

&H0000 Saturday [128 Set]


128 x 4 = 215 Bytes

512Bytes &H01FF
&H0200 Sunday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H03FF
&H0400 Monday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H05FF
&H0600 Tuesday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H07FF
&H0800 Wednesday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H09FF
&H0A00 Thursday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H0BFF
&H0C00 Friday [128 Set]
128 x 4 = 215 Bytes

512Bytes &H0DFF
&H0E00 NON USED AREA

512Bytes &H0FFF
[

 250 


Practical Class 11 Programming Microcontrollers

Software:

The BASCOM-AVR compiler is used to make a program that writes and reads one byte from the EEPROM. BASCOM has
several embedded commands to control the I2C bus.

In BASCOM-AVR you irst have to con igure the ports you use for the SDA and SCL lines of the I2C bus. Then you send the
device address to select the EEPROM that is connected to the I2C bus. After that you send two bytes to the EEPROM to select
the address in the EEPROM to which you want to write the data. The last byte to send in a write sequence is the data byte.

$regfile = "m16def.dat"
$crystal = 2000000
$lib "I2C_TWI.LBX"
$baud = 9600
'---------------------------
Config Scl = Portc.0
Config Sda = Portc.1
Config Twi = 100000 '100KHZ
'---------------------------
Const Addressw = 160 '&B10100000 slave write address
Const Addressr = 161 '&B10100001 slave read address
'---------------------------
Dim Adres_h As Byte , Adres_l As Byte
Dim Rd_value As Byte , Wr_value As Byte
'---------------------------
Do
Input "Wr_value:" , Wr_value
Input "Adres_l:" , Adres_l
Input "Adres_h:" , Adres_h

Gosub Write_eeprom
Gosub Read_eeprom

Print "Error W: " ; Err


print "Wr_value: " ; Wr_value

Print "Error R: " ; Err


Print "Rd_value: " ; Rd_value
Loop
End
'---------------------------
Write_eeprom:
I2cstart 'Start condition
I2cwbyte Addressw 'Slave address
I2cwbyte Adres_h 'H address of EEPROM
I2cwbyte Adres_l 'L address of EEPROM
I2cwbyte Wr_value 'Value to write
I2cstop 'Stop condition
Waitms 10 'Wait for 10 milliseconds
Return
'---------------------------
Read_eeprom:
I2cstart 'Generate start
I2cwbyte Addressw 'Slave adsress
I2cwbyte Adres_h 'H address of EEPROM
I2cwbyte Adres_l 'L address of EEPROM
I2cstart 'Repeated start
I2cwbyte Addressr 'Slave address (read)
I2crbyte Rd_value , Nack 'Read byte
I2cstop 'Generate stop
Return
'---------------------------

 
Faculty of Electrical and Electronic Eng. 251 Automatic Control & Automation Dept.

You might also like