Claus Kuhnel
BASCOM
Programming of
Microcontrollers with Ease
An Introduction
by Program ExamplesBASCOM Programming of Microcontrollers with Ease:
An Introduction by Program Examples
Copyright © 2001 Claus Kuhnel
All rights reserved. No part of this work may be reproduced in any
form except by written permission of the author.
All rights of translation reserved.
Publisher and author assume no responsibility for any errors that
may arise from the use of devices and software described in this
book.
Universal Publishers/uPUBLISH.com
USA + 2001
ISBN: 1-58112-671-9
www.upublish.com/books/kuhnel.htmPreface
The microcontroller market knows some well introduced 8-bit micro-
controller families like Intel's 8051 with its many derivatives from
different manufacturers, Motorola's 6805 and 68HC11, Microchip's
PiCmicros and Atmel's AVR.
The 8051 microcontroller family has been well-known over many
years. The development of new derivatives is not finished yet. From
time to time new powerful derivatives are announced.
You will find derivatives from Philips, Dallas, Analog Devices and
Cygnal and others with the known 8051 core but enhanced clock and
peripherals. For example, complete analog-to-digital and digital-to-
analog subsystems were integrated in some chips.
Atmel developed the AVR microcontroller family which is well suited
for high-level language programming and in-system programming.
For all those microcontrollers there is development software ranging
from simple assemblers for DOS to integrated development envi-
ronments for Windows95/98/NT on the market.
Apart from programming environments as they are offered, for ex-
ample, by KEIL, IAR or E-LAB Computer for professional applica-
tions, also the more economical and nonetheless sufficiently
equipped development environments can maintain ground.
BASCOM-8051 and BASCOM-AVR are development environments
built around a powerful BASIC compiler which is suited for project
handling and program development for the 8051 family and its de-
rivatives as well as for the AVR microcontrollers from Atmel.
The programming of microcontrollers using BASCOM-8051 (version
2.0.4.0) and BASCOM-AVR (version 1.11.3.0) will be described in
this book.
Some applications help understand the usage of BASCOM-8051 and
BASCOM-AVR.Acknowledgement
| should like to thank the following:
in the first place, Mark Alberts of MCS Electronics, who developed
the BASCOM programming environment at an outstanding price-
performance ratio,
Atmel for the development of the AVR RISC microcontrollers
which introduced new capabilities into the microcontroller families,
Christer Johansson of High Tech Horizon, who supports safe
communication of microcontrollers and PC by the development
and free distribution of the S.N.A.P. protocol and the necessary
tools effectively and
Lars Wictorsson of LAWICEL for the development of the
CANDIPs, microcontroller modules with CAN interface.Contents
1 Supported Microcontrollers
1.1 8051 Family
1.2 AVR Family.
2 BASCOM
2.1 BASCOM Demos....
2.2 BASCOM Commercial Versions.....
2.3 Update of BASCOM Commercial Versions ............:0ceeenes 25
2.4 BASCOM Projects
2.4.1 Working ON Projects ........ccccesessseseseerestesesesteensseeteeetseens 20
2.4.2 BASCOM Options
2.5 BASCOM Tools
2.5.1 Simulation
2.5.2 Terminal Emulator
2.5.3 LCD Designer ..
2.5.4 Library Manager
2.5.5 Programming Devices .. aoe sesteesesertestsestseeeeeseeess OO.
2.6 Hardware for AVR RISC Microcontroller .............csseeeeees OD
2.6.1 DTO06 AVR Development Board...
2.6.2 AVR-ALPHA with AT90S2313
2.7 Instead Of "Hello World" ..........ceceseeseeeesesteseeteeteeeeseeneeee
2.7.1 AVR..
2.7.2 8051.
2.7.3 Things in Commo
2.7.4 Simulation
2.8 BASCOM Help System
3 Some BASCOM Internals
3.1 Building new instructions3.2 Parameters for Subroutines in BASCOM-AVR
3.3 BASIC & Assembler.
3.3.2 8051 .eeeeecseseceesesseeeseseeeeees
4 Applications ...........
4.1 Programmable Logic..
4.2 Timer and Counter.
4.2.1 AVR...
4.2.2 8051 ooeeeccsceseceesesseeeeeseseeeee
4.3 LED Control ........cceceeceeseeeeeteenes
4.3.1 Single LED ..
4.3.2 Seven-Segment Displays....
4.3.3 Dot-Matrix Displays .............
4.4 LCD ComtiOl ........cceeeceeseeteeeeseeees
4.4.1 Direct Control
4.4.2 LCD with Serial Interface ....
4.5 Connecting Keys and Keyboard:
4.5.1 Single Keys ....
4.5.2 Matrix Keypad ..... +132
4.5.3 PC-AT Keyboard .............00 -- 136
4.6 Data Input by IR Remote Control...... 140
4.7 Asynchronous Serial Communication..... 2 143
4.8 1-WIRE Interface 151
4.9 SPI Interface -- 161
4.10 °C Bus..
4.11 Scalable Network Protocol S.N.A.P
4.11.1 S.N.A-P. Features
167
173
4.11.2 Description of S.N.A.P. Protocol .... 2175
4.11.3 S.N.A.P. Monitor............0.. 179
4.11.4 Digital VO... «1834.12 CANDIP - Interface to CAN
4.13 Random NUMDETS ..........ccceeeceeeseeseeseeteseeteeteeteneeneeee
4.14 Moving Average .......... cece seseeeteeseeeeseseteeereeseeneees
5 Appendix ... Saesendonsraush
5.1 Decimal-Hex-ASCII Converter.
5.2 DT006 Circuit Diagram.....
5.3 Characters in Seven-Segment Display...............ceeeee 222
5.4 BASIC Stamp II
5.5 Literature eee cece cence eeseeseeteeneseesesteeeeseenseneaees1 Supported Microcontrollers
BASCOM is an Integrated Development Environment (IDE) that sup-
ports the 8051 family of microcontrollers and some derivatives as
well as Atmel's AVR microcontrollers. Two products are available for
the various microcontrollers - BASCOM-8051 and BASCOM-AVR.
In a microcontroller project one needs to know the hardware base,
i.e. the microcontroller with internal and connected peripherals, and
the software used, i.e. IDE handling, programming and debugging.
In this first chapter, let's have a look at the supported microcontrol-
lers. A general overview will be given only; the various parts are
documented by the manufacturers in more detail. You may also
search the web for more information and documentation on all the
microcontrollers dealt with here.
1.1 8051 Family
The 8051 is an accumulator-based microcontroller featuring 255
instructions. A basic instruction cycle takes 12 clocks; however,
some manufacturers redesigned the instruction-execution circuitry to
reduce the instruction cycle.
The CPU has four banks of eight 8-bit registers in on-chip RAM for
context switching. These registers reside within the 8051's lower 128
bytes of RAM along with a bit-operation area and scratchpad RAM.
These lower bytes can be addressed directly or indirectly by using an
8-bit value. The upper 128 bytes of on-chip data RAM encompass
two overlapping address spaces. One space is for directly addressed
special-function registers (SFRs); the other space is for indirectly
addressed RAM or stack. The SFRs define peripheral operations and
configurations. The 8051 also has 16 bit-addressable bytes of on-
chip RAM for flags or variables.
Without external circuitry, the maximum address range of all 8051
processors is 64 Kbytes of program memory and 64 Kbytes of data
memory. External means can be made use of to increase this ad-
dress space.
Register indirection uses an 8-bit register for an on-chip RAM ad-
dress; an off-chip address requires an 8- or 16-bit data-pointer reg-
ister (DPTR). The original 8051 has only one DPTR. Derivatives from
Atmel, Dallas, and Philips have two DPTRs. Siemens microcontrol-
9lers have eight DPTRs. The 8051 microcontroller has bidirectional
and individually addressable I/O lines.
The 8051 performs extensive bit manipulation via instructions, such
as set, clear, complement, and jump on bit set or jump on bit clear,
only for a 16-byte area of RAM and some SFRs. It can also handle
AND or OR bits with a carry bit. The Dallas versions have variable-
length move-external-data instructions. Math functions include add,
subtract, increment, decrement, multiply, divide, complement, rotate,
and swap nibbles. Some of the Siemens devices have a hardware
multiplier/divider for 16-bit multiply and 32-bit divide. Figure 1 shows
the block diagram of an 8051 [1].
Figure 1 Block diagram 8051
10To elucidate the differences in the derivatives, Figure 2 shows the
block diagram of the C8051F0000 microcontroller from Cygnal [2].
Figure 2 Block diagram C8051F0000
This is not the place to discuss the hardware aspects of the different
derivatives of the 8051 family. The examples are meant to show that
not all parts named 8051 are alike; the core is the same but the in-
ternal peripherals differ significantly.
Once you know the used hardware, you can organize the access to
the resources of the chosen microcontroller.
1.2 AVR Family
Since Atmel's AVR microcontrollers were introduced to the market
only a few years ago, they are not so well known as the 8051 con-
trollers. Therefore, this interesting microcontroller family should be
described in more detail.
11Atmel's AVR microcontrollers use a new RISC architecture which has
been developed to take advantage of the semiconductor integration
and software capabilities of the 1990's. The resulting microcontrollers
offer the highest MIPS/mW capability available in the 8-bit microcon-
trollers market today.
The architecture of the AVR microcontrollers was designed together
with C-language experts to ensure that the hardware and software
work hand-in-hand to develop a highly efficient, high-performance
code.
To optimize the code size, performance and power consumption,
AVR microcontrollers have big register files and fast one-cycle in-
structions.
The family of AVR microcontrollers includes differently equipped
controllers - from a simple 8-pin microcontroller up to a high-end
microcontroller with a large internal memory. The Harvard architec-
ture addresses memories up to 8 MB directly. The register file is
"dual mapped" and can be addressed as part of the on-chip SRAM,
whereby fast context switches are possible.
All AVR microcontrollers are based on Atmel's low-power nonvolatile
CMOS technology. The on-chip in-system programmable (ISP),
downloadable flash memory permits devices on the user's circuit
board to be reprogrammed via SPI or with the help of a conventional
programming device.
By combining the efficient architecture with the downloadable flash
memory on the same chip, the AVR microcontrollers represent an
efficient approach to applications in the "Embedded Controller" mar-
ket.
Table 1 shows an overview of the devices available today, including
the configuration of the internal memory and I/O. Further information
can be found on Atmel's web site [http://www.atmel.com] and in the
literature [3].
12Device Flash [KB] EEPROM SRAM | //O Pins
ATtiny11 1 0 0 6
ATtiny12 1 64 0 6
ATtiny22 2 128 90 5
AT90S1200 1 64 0 15
AT90S2313 2 128 128 15
AT90S2323 2 128 128 3
AT90S2343 2 128 128 5
AT90S2333 2 128 128 20
AT90S4414 4 256 256 32
AT90S4433 4 256 128 20
AT90S4434 4 256 256 32
AT90S8515 8 512 512 32
AT90S8534 8 512 256 15
AT90S8535 8 512 512 32
ATmega603 64 2K 4k 48
ATmega103 128 4k 4k 48
Table 1 AVR microcontrollers and their resources
The internal resources of the AVR microcontrollers will be considered
with AT90S8515 used as an example. Figure 3 shows the block dia-
gram of an AT90S8515.
13PAD-PAT Pooper
7
ce fT HHfTE
ti yy yy :
TET TET «TREE TET:
S 7 > 7
ae ‘OSCILLATOR
1 I
i 1 ni
Proce | PT cram feo} feof POUCONTROL > Ae
"se ] Lae jodie K=
EF] FES [ae —
tt
contro. au lof ccpnon
EE
2s 4
¥
Procrumancte sor Jeol feof arr
—— = »
| aT t Fy t
AN Passe”) (2s. me") [Boe
Ra(7..4) 1
BSET s Flag Set SREG(s) <1 1
BCLR s Flag Clear SREG(s) <0 1
SBIP,b Set bit in /O Register VO(P, b) — 4 2
CBIP, b Clear bit in /O Register VO(P, b) — 0 2
BST Rr, b bit Store from Register toT | T — Rr(b) 1
BLD Rd, b bit load from T to Register. | Rd(b) — T 1
SEC Set Carry cet 1
cLC Clear Carry ceo 1
SEN Set Negative Flag Ne1 1
CLN Clear Negative Flag Neo 1
20SEZ Set Zero Flag Ze1 1
cLz Clear Zero Flag Zoo 1
SEI Global Interrupt Enable 1e4 1
CLI Global Interrupt Disable 10 1
SES Set Signed Test Flag Sei 1
cLS Clear Signed Test Flag seo 1
SEV Set Two's Complement vel 1
Overflow
cLv Clear Two's Complement |v —0 1
Overflow
SET Set T in SREG Te1 1
CLT Clear T in SREG TEO 1
SEH Set Half Carry Flag in SREG |H <1 1
CLH Clear Half Carry Flag in Heo 1
SREG
NOP No Operation None 1
SLEEP Sleep 1
WOR Watchdog Reset 1
Table 2 Instruction Set of AVR microcontrollers
These introducing remarks on the AVR microcontrollers cannot of
course replace a detailed study of the technical documentation of the
manufacturer. Descriptions of the individual microcontrollers as well
as application notes and program examples can be found on Atmel's
web site [http:/www.atmel.com]. The manufacturer's documentation
is complemented by further publications [3][4].
21222 BASCOM
BASCOM-AVR is not only a BASIC Compiler, but also a comfortable
Integrated Development Environment (IDE) running under Windows
95 and Windows NT.
Such a development environment supports the whole process from
coding and testing a program to programming the used micro-
controller.
In this book the term BASCOM is used when no distinction must be
made between BASCOM-8051 and BASCOM-AVR. In all cases
where a distinction is necessary, a few changes only are required to
make the program work with the other family of microcontrollers. This
is one important advantage of high-level languages.
So as to prevent that work with BASCOM and the program examples
in this book are mere dry homework, a demo of BASCOM-8051 or
BASCOM-AVR can be used for first tests. These BASCOM demos
can be downloaded free of charge from different URLs.
For proper installation of the required BASCOM IDE, make sure a
printer is installed - the printer need not necessarily be used or con-
nected.
The licence agreement must be accepted before one of the
BASCOM IDEs is installed
2.1 BASCOM Demos
Over a link to the download area of the BASCOM developer MCS
Electronics [http://www.mcselec.com] some files are available for
download.
For download the BASCOM-8051 demo use this URL
http://www.mcselec.com/download_8051.htm
and for downloading the BASCOM-AVR demo use
http://www.mcselec.com/download_avr.htm .
On these download sites you will find the manuals as PDF and all
information required for an upgrade to the commercial versions.
After extracting all downloaded files to a separate directory, there is a
setup program for installation.
23Installation starts as usual under Windows when this setup program
is called.
After completion of the installation, the following files need to be in-
stalled on the PC. Figure 6 shows the files installed for BASCOM-
AVR as an example. Inspecting the directory with the Explorer will
show some more files there. These files will be explained later.
Datei Bearbeiten Ancicht 2
e @
BASCOM av BASCOM-AVR Help LICENSE README
DEMO,
fe) 133KB
Figure 6 BASCOM-AVR Demo Files
As is common for most demo programs, some restrictions must be
expected. The only restriction of both BASCOM demos is a reduced
code size of 2 KB.
If the code size exceeds this limit after compilation, the compiler will
generate error messages as shown in Figure 7.
24LSE: CEs
Fie Edt Progam Tools Options Window Hel
_Dlelielsia) sellers al visio) sale | a
Dslelk Alias Porth 6 c onnect ty
41 | of
ferro’ 10000 Line 235 DEMO/BETA only supports 1024 bytes of code . m File E \BASCOMAVA DEMO\PHOGRAM\SAMPLE
Err: 10000 Line: 235 DEMO/BETA only supports 1024 bytes of code . in Fie : E|\BASCOM-AVA DEMO\PROGRAM\SAMPLE
Eric: 10000 Line: 235 DEMO/BETA only supports 1024 bytes of code . in File E:\BASCOM-AVR DEMO\PROGRAM\SAMPLE
a4 Insert
Figure 7 Error messages due to exceeding the restricted code size
2.2 BASCOM Commercial Versions
If you decide to buy the commercial version of the used BASCOM
IDE, you may order it from http:/Awww.mcselec.com or one of the
local distributors. Downloading the files and ordering the license is
done in next to no time. The license will be sent immediately by e-
mail.
The installation of the commercial version does not differ from the
procedure for the BASCOM demo. Start SetUp and follow the in-
structions of the SetUp program.
2.3 Update of BASCOM Commercial Versions
When a commercial version of BASCOM is installed, it can be up-
dated when a new version is ready for downloading from MCS Elec-
tronic's web site. In the download area you will find a link to an Aut-
oUpdate program.
Install this AutoUpdate program in your BASCOM-8051 or BASCOM-
AVR subdirectory as you installed BASCOM-8051 or BASCOM-AVR
before.
25Figure 8 shows the downloading and extracting of updated files in an
existing installation of BASCOM-AVR.
A eee
Extiacting LIBDEMO.BAS ~
Extiacting SINCOS.B:
Extiacting BASMON.BAS
Extacting FORMAT BAS
Extracting MAGCARD BAS
Extacting BINZBD~1 BAS
Extiacting MEGACL™1.BAS
Downloading avride.zip
_ Auto Update Setup
Number of files
Oe Exit
Bytes
Figure 8 Update of BASCOM-AVR
If your installation is up-to-date then there is no need for an update.
The AutoUpdate program detects this state automatically (Figure 9).
26Cvrk
Log messages
Downloading info
Received info
4 ~ No newer version available
New or open an existing file by selecting File>Open.
In the next step, check such BASCOM Options like device selection,
baud rate, clock frequency and other relating options. A detailed ex-
planation of these options will be given in the next chapter.
Now you may edit the BASIC source and compile it afterwards. As a
rule, the compiler detects here the first errors and the program must
be debugged.
The BASIC source must be edited as long as the compilation is with-
out any errors. Normally, the process of editing, compiling and de-
bugging needs to be repeated several times. It makes no sense to
debug all errors in one step. Editing several typing errors in one step
is no problem. But for more difficult errors, a separate compiler run
checks the validity of the changes carried out. It is always easier to
debug a localized error.
27With the help of the internal BASCOM Simulator the program opera-
tion can be checked without any hardware.
The probably last task in a project is programming the device that is
used in the application hardware, followed by an excessive test of the
program on the target.
The project proves to be successful if these tests document a proper
function in the target hardware. Otherwise, some steps must be re-
peated.
Before working with the BASCOM-AVR, the development environ-
ment will be described by means of a small program example; the
next chapter describes the BASCOM options important to the
BASCOM environment used and the target hardware.
2.4.2 BASCOM Options
Each BASCOM offers a lot of options that must be defined by selec-
tion in the Option menu. The options should be selected at the be-
ginning of a project and saved. Later changes of this setup will then
only be required for details.
The following description applies to BASCOM-AVR. In BASCOM-
8051, selecting the various options is quite similar.
In the first step, the used microcontroller is defined by selecting Op-
tions>Compiler>Chip. Let us use here an AT90S8515 without ex-
ternal RAM. Figure 10 shows the parameters. On the right side you
can see the available memory of the selected microcontroller.
Each parameter in a function needs two bytes of stack. the stack size
shows the number of reserved bytes for the stack. The value 32 is
default and remains unchanged here.
Local variables are saved in a frame. The default value is 50 and
remains unchanged, too.
28CRSeIP Nk eced
Compiler | Communication| Environment | Simulator | Programmes | Monitor | Printer |
Chip | Output] Communication | 12c.SPLIWIRE | LCD |
Chip S0S8515 a FlashAOM = (6 KB
xRaM [None z= SRAM 52
Stacksize |S2 EEPROM = 4512S
Framesize |50
T SRAM waitstate
Jf Ok % Cancel
Figure 10 Selection of a device and external memory
The compiler generates many files selectable by Options> Com-
piler>Output. Figure 11 shows the possibilities for selection.
In dependence of the used programmer, Bin files and/or Hex files will
be generated. The compiler itself needs the debug file. The report file
reports all parameters and memory allocations. The error file docu-
ments all errors occurring during compilation.
29Peek [x]
Compiler | Communication | Enviorment | Simulater | Programmer | Monitor Printer |
Chip Output | Communication | 120, SPI, 1WIRE | LOD. |
IM Binary file ¥ AVR Studio Object file
¥ Debug File
I HEX file 1 Swap words
Report tile
IM Enor file
Lancel
Figure 11 Selection of files to be generated
To simplify matters, all files on the left side should be selected.
For simulations with AVR Studio (AVR only), the related object file is
required. Activating Size warning reports an exceeding of the avail-
able program memory. The last option can be very helpful.
Some programmers require Bin or Hex files with swapped LSB and
MSB. In this case, activate the Swap Words option.
The baud rate of serial communication (RS232) depends on the
clock frequency of the microcontroller. The clock frequency and de-
sired baud rate can be selected from menu Options> Com-
piler>Communication. Figure 12 shows the parameter input. The
error field shows the deviation of the generated baud rate.
It is very important to keep this deviation within defined limits as oth-
erwise communication errors may occur.
30EE =]
Compiler | Communication| Environment | Simulator | Programmes | Monitor | Printer |
Chip | Output Communication ]i2c. SPL 1wiRE | LCD |
Baudrate = °° °° «+d
Frequency 4000000 =| He
Enor O16
Sf Ok | % Cancel
Figure 12 Selection of baud rate and oscillator frequency
In addition to serial communication according to RS232, BASCOM
supports | C, SPI and 1-Wire data transfer. As Figure 13 shows, the
menu Options>Compiler>I2C, SPI, 1WIRE allows the allocation of
pins to the respective lines. At this time at the latest, a wiring diagram
or schematic of the target hardware is required.
31tas Leak LM Oe
Compile: | Communication | Environment | Simulator | Programmer | Moritor | Printer |
Chip | Output] Communication 120. SPL 1WIRE |LcD |
plac SPI
SCL port PORTA O x Clock PORTB.5 xz
SDA pot Tan IAT =] mos! fPORTB6 =]
1
ae miso. [PORTR? =|
wire [ronts.o Hi 88 PORTBS x
T™ Use Hardware SPI
X cored
Figure 13 Selection of pins for serial communication
From menu Options>Compiler>LCD an LCD can be connected to
the selected pins. Figure 14 shows the input of the required pa-
rameters.
For BASCOM-AVR there are different methods for controlling an
LCD. If the microcontroller has an external RAM, then the LCD can
be connected to the data bus. The address bus controls lines E and
RS. The following connections are required in the bus mode.
AT90Sxxxx] A15 A14] D7 D6 D5 D4 D3 D2 D1 BO
8-bit Mode} E RS | db7 db6 dbS5 db4 db3 db2 db1 dbO
4-bit Mode] E RS | db7 db6 = db5 db4 - - -
For BASCOM-8051 and BASCOM-AVR it is possible to assign any
pin of the microcontroller to the LCD pins. Usually, the 4-bit mode will
be used (four data lines).
When defining user-specific characters, bit-maps are assigned to
printable characters. This process is very simple and is supported by
the LCD designer. Using the option "Make upper 3 bit 1 in LCD De-
signer" the bit-maps can be influenced as shown.
32ox
Rd
Compiler | Commurication | Environment | Simulator | Programmer | Monitor | Pinter |
Chip | Ouiput] Commuricalion | 120, SPL 1wIRE LCD |
LCD type [18°12 2 Enable =
BUS mode Data mode RS ad
& Abt bin z
C Bhi | DB7 J
DBE 4
LCD-addess [000 DBS a
RS-addiess fapgg De4 a4
I Make upper 3 bits 1 in LCD designer
% Cancel
Figure 14 BASCOM-AVR LCD SetUp
When communicating from the PC with the target hardware, the pa-
rameters of the terminal emulator must be coordinated with the in-
terface parameters of the target hardware. As is shown in Figure 15,
these parameters can be input via the menu Options> Communica-
tion.
33LJ ta Opti
Compiler Communicetion | Ervionment | Simulator | Programmer | Moritor | Printer |
COM port Handshake [None =
Baudate —[ap00 | Emulation [agg aNsI =
Paity None =] Font Font
Databits [fg = Backco [EE New a
Stopbits 7 z
X cored
Figure 15 Parameter selection for terminal emulator
The editor features can be adapted as preferred. Figure 16 shows
the setup options; they are selectable via menu Options> Environ-
ment.
As experience shows, the setup can be used as default for the first
time. Any changes can be made later when you are more familiar
with the editing of source text.
34CRSEIPN ik eced
Compiler | Communication Environment | Simulator | Progtammet | Monitor | Printer |
I Butoindent
~ Dont change case EditorFont Font
I¥ Reformat BAS fies ee
17 Reformat code Comment positon (O49 TAB-size [¢
1 Smart TAB ow,
ground cok White 7
1 suntan raeaget Background color [__]
1 Show margin Keymapping [Default =
1¥ Tooltips =
1¥ Shows Toolbar File location
I Save file ac. for new files
Size of new editor window:
® Normal
© Mavimized DAT
Sf Ok | % Cancel
Figure 16 Selection of editor options
No reformat extension
In BASCOM-AVR you can choose the internal simulator or AVR Stu-
dio for simulation. In menu Options>Simulator the AVR Studio can
be linked to BASCOM-AVR. Figure 17 shows the link to AVRStu-
dio.exe in path D:\Programme\AVRSTUD\, which is specific to
the author's system.
35Erevan)
Compiler | Communication | Environment [ Simulator] Programmer | Monitor | Printer |
I¥ Use integrated Simulator
[~ Run Simulator af compilation
Program —[D.\Programme\AVASTUDVAVAStudinene a.
Parameter [[FILE).OB)
Jf ok % Cancet
Figure 17 Selection of a simulator
The last important step is the selection of a programmer via menu
Options>Programmer . Figure 18 shows this selection.
In this case, the AVR ISP Programmer was selected because most
BASCOM-AVR program examples described here used the
MCU00100 evaluation board as a hardware platform. Basically, the
use of an external programmer is possible.
36EE =]
Compiler | Communication| Environment | Simulator Programme: | Monitor | Printer |
Programmer
[~ Erase waming [~ AutoFlash [~ AulcVerly f¥ Upload Code and Dato
Parallel Setial | Other |
COMpat fF]
Sf Ok | % Cancel
Figure 18 Selection of a programmer
2.5 BASCOM Tools
BASCOM IDE includes some important tools. The simulator and
programmer have already been mentioned.
Further tools are
* a Terminal Emulator for communication with the serial interface of
the target hardware,
e an LCD Designer supporting the design of customer-specific
characters for a connected character LCD
e a library manager supporting the management of libraries and
* for BASCOM-805,1, a Graphic BMP Converter intended to con-
vert BMP files into BASCOM Graphic Files (BGF) for display by a
Graphic LCD.
2.5.1 Simulation
BASCOM-8051 and BASCOM-AVR have their own internal simula-
tor. A simple program example describes the use of the simulator in
both BASCOM IDEs.
37The program to be simulated controls an alphanumeric LCD of two
lines of 16 characters each. Listing 1 shows the source text.
$sim ' for simulation only otherwise comment
Dim A As Byte
Mi:
A = Waitkey()
If A = 27 Then Goto M2
cls
Upperline
Iced A
Lowerline
Lcd Hex(a)
Print Chr(a)
Goto ML
M2:
End
Listing 1 LCD Test (LCD.BAS)
Clicking Program>Simulate or F2 starts the Simulator and the
simulation window opens up.
Figure 19 shows the simulation window of BASCOM-8051 and
Figure 20 that of BASCOM-AVR.
38POSE
fr ifm 5
[a |
delelols
—
“nto [ints [to | 11 sen wend cro | cri | cre | cra | ape] cwo| om
Variables | Break |
Variable [Value PY |
a LCD
oa Ports Digit
Pal CG
vw CG
Ey ¥ CG
py i CG
pal i CG
Del CG |
OP A= Vaitkey a] 8 val [-|
° If & = 27 Then Goto M2 fhe
° Upper line a 00
° Led A iE oo
5 Fomprtae HE. foo
° Print Chr(a) [a 09
9 Goto Mi xi foo
‘ 21 [Po ‘00 x
Flunring — 29828(32.3654513888889n Max stacie3C
Figure 19 BASCOM-8051 Simulator
HAVAVA Simulal Lob)
[> nfm] ealcz |m%| [ro Bl r sintinns |
Variables | Locals | 42" watch | % uP] irvempts|
Vainis [Vdue [Hex (Bm |
2 UL eee
ico
file's 4.3/2 10) __f. 5.143.121 19
PA 19 O98 0008@ | 1606606066
Pp |@@6CC066 Bp 1000000080
Pc |@@@O@e@8@ Cc 99900906
. po |@@4e864966@ p 08000086
[> [6 A= Waitke
7
a 8 If A= 27 Then Goto MZ ~
2 9 cis
o 10 Upperline :
Gi | a
Po=0 Cycles =0 “Running j
Figure 20 BASCOM-AVR Simulator
39The program instructions can be seen at the bottom of the window. A
terminal window is placed in the middle, and a watch window pre-
senting the contents of the variables on top.
In the example, the control of an LCD is simulated. For the purpose,
the LCD windows were opened. As can be seen, the LCD windows
differ.
After program start the program runs until instruction a = Wait-
key (), and waits for a character to be received on the serial input.
Key in a character from the terminal window and this character will
be read by the program.
If the received character is not ESC, its ASCII code will be displayed
in the upper row of the LCD and its hex value in the lower row of the
simulated LCD.
In the example, the received character was "a". The ASCII code dis-
played in the upper line is 92. The hex value displayed in the lower
line is 61.
During the simulation there is the possibility for a single-step chang-
ing of the contents of the variables and the simulation of interrupts.
2.5.2 Terminal Emulator
The Terminal Emulator is used for communication with the serial
interfaces of the target hardware.
Listing 2 shows a simple test program. The program waits until it
receives one character, echoes this character, and adds some char-
acters for commentary purposes.
40Dim A As Byte
Do A = Inkey() 'get value from serial port
If A > 0 Then "we got. something
Print "Received fron serial port:"
Print "ASCII Code"; A;
Print " = Character " ; Chr(a)
End If
Loop Until A = 27
End
Listing 2 Test of serial communication (SERIAL.BAS)
To start the Terminal Emulator, click Tools>Terminal emulator or
press Ctrl+T. Figure 21 shows the open terminal window. The pa-
rameters for communication can be selected via menu Op-
tions>Communications; they are shown in the status line.
ig BASCOM-AVR Terminal emulal
File Terminal
Received from serial port:
ASCII Code 43 = Character +
Received from serial port:
SCIl Code 97 = Character a
fcoM:9600.N 2.1
Figure 21 BASCOM-AVR Terminal Emulator
If a character is sent to the target hardware by typing this character in
the PC's keyboard, then the program checks the received character
(A = inkey()) and sends back a comment and the results of some
operations (Print ... ) until the ESC key is pressed and the pro-
gram stops.
“1The Terminal Emulator can be used for testing all communication
tasks of the serial interface of the used microcontroller.
2.5.3 LCD Designer
The LCD Designer is useful for defining customer-specific characters
displayed on an alphanumeric LCD. All alphanumeric LCDs, working
with Hitachi's LCD controller HD 44780 or a compatible, allow cus-
tom-specific characters to be defined.
Figure 22 shows three characters which are defined as custom-
specific characters and tested.
Figure 22
The first character is used to demonstrate custom-specific character
definition with the help of the LCD Designer.
By Tools>LCD Designer or Ctrl+L, the LCD designer is started
(Figure 23).
Cee
Clear all
Setall
¥ Ok
% Cancel
Figure 23
Custom-specific character definition in LCD Designer
42The pixels in the 8x5 matrix can be set or cleared. The lowest pixel
line, though reserved for the display of the LCD cursor, can be used.
By pressing OK the character is defined and the respective instruc-
tion is written in the source text window.
For the time being, the designation of the character is provided with a
question mark which must be replaced by a character (or a variable)
within the range from 0 to 7.
Figure 24 shows the entry in the source text completed by a constant
of 1 as the name for this first user-specific character.
Fie Edit Program Tools Options Window Help
‘Dlelelraigic
Si loll
Peficdchar 1 238 255. 252 249 252 255 4]
id
ae
1
1 Modified — Insert
Figure 24 Instruction generated by the LCD designer
A small program (Listing 3) supports the test of these user-specific
character indications.
43Deflodchar 1, 238 , 255 , 252 , 248 , 252 , 255 , 238 , 224
Deflodchar 2 , 238 , 255 , 255 , 248 , 255, 255 , 238 , 224
Deflodchar 3, 238 , 255 , 255, 255 , 255, 255, 238 , 224
Cls
Config Led = 16 * 1
Lcd "Hello "
Home
Led Chr (1)
Home
led" " ; Chr(2)
Home
Led " "> Chr(3)
Listing 3 Customer-specific characters (LCD1.BAS)
At the beginning of the program there are three character definitions
created by using LCD Designer as described. It is important that the
defined instructions are followed by instruction CLS which activates
the data memory of the LCD.
The first thing displayed on the LCD is the word "Hello". The charac-
ters of the word "Hello" will later be eaten by the customer-specific
characters.
Figure 25 shows the LCD output as it appears during a single-step
simulation one after another. Several hardcopies of the Simulator's
LCD window were cascaded one below the other so that the various
steps taken can be seen very clearly.
44(alert (are eRe
simulation
(anon psi
Figure 25 LCD output in Simulator
452.5.4 Library Manager
A library contains assembler routines which can be accessed from a
program. The Library Manager supports the administration and
modification of such a library.
Figure 26 shows routines of the library MCS.LIB for BASCOM-8051.
Pra Ez]
‘Libraries Routines
ADJUSTBIT_ADDRESS
LICIOST.UE giT_2c
BIT_2 BYTE
GETADCADUCS12
TIME_OUT
READ _MAGCARD
SHOWPICTURE
Figure 26 BASCOM-8051 LIB Manager
Figure 27 shows routines of the library MCS.LIB for BASCOM-AVR.
46os
Libraries Routines
|-ADJUST_PIN
ADJUST_BIT_ADDRESS
PULSE_OUT
BIT_STR
COUNT_ONES
CHECKSUM
Add
FORMAT_STR
WIRE Delete |
READ_MAGCARD
PULSE_IN
RAMPZ
BYTE2STR
STR2BYTE
MAKE_DT
SET_DATE
SET_TIME —
SOFT_CLOCK =
MYLIB LIB
Compile
Figure 27 BASCOM-8051 LIB Manager
The libraries will be searched when a used routine is declared with
the directive $EXTERNAL. The library search order is the same as the
order of the names of the libraries. Library MCS.LIB included in both
BASCOM IDEs is always the last library searched. There is no need
to specify MCS.LIB by the directive $LIB.
Since MCS.LIB is always the last library searched, routines with the
same name but a different function can be included in private librar-
ies. Because of the search order, that routine is found first and thus
redefines the definition in MCS.LIB.
To change the predefined routines in MCS.LIB, copy and rename
MCS.LIB and edit the routines to be changed. It is als possible to
create private libraries. Listing 4 shows a BlockMove routine for
BASCOM-AVR in library CK.LIB.
47Copyright = Claus Kuehnel
WWW = http: //www.ckuehnel .ch
Email = avr@ckuehnel.ch
Conment. = Avr Compiler Library
Libversion = 1.00
Date = 19.01.2000
Statement = No Source Code From The Library May Be Distributed In
Any Form
Statement = Of Course This Does Not Applie For The Compiled Code
When You Have A Bascom - Avr License
History = No Known Bugs.
History
[_blockmove]
_Blockmove:
1d _templ,Z+ iget data from BLOCKL
st X+,_templ ;store data to BLOCK2
dec _temp2 ;
bre _blockmove ;if not done, loop more
ret jretum
[end]
Listing 4 Library CK.LIB
A library is a simple text file. Each editor can be used for making
changes. By means of the BASCOM internal editor, a library can be
edited in the same way as a BASIC source file.
The header contains some useful information.
Each routine begins with its name in angular brackets and end with
an end tag. In this example it begins with [_blockmove]. The end
is always [END] .
Listing 5 shows the access to a library function in a sample program.
Const Bl = 40 ' Defines a block length
Dim Blocklength As Byte
Blocklength = Bl
Dim Blocki(bl) As Byte ' ‘Two blocks of 40 bytes each
Dim Block2 (bl) As Byte
Dim I As Byte ' Index variable
$lib "CK.LIB" ' Use _blockmove from CK.LIB
$external _blockmove
48Declare Sub Blockmove (source As Byte , Dest As Byte , Byval Length
As Byte)
For I = 1 To BL ' Initialize Block
Blockl(i) =I * 2
Next
' Call Blockmove subroutine
Call Blockmove (block1(1) , Block2(1) , Blocklength)
For I = 1 To 40 " clear Block1
Blockl (i) = 0
Next
' copy Block2 to Blockl back
' Blockmove is the entry for blockmove assembler routine
Sub Blockmove (source As byte , Dest As byte , Length As Byte)
Sasm
loadadr Length , Z
1d _temp2, Z
Loadadr Source , Z
Loadadr Dest , X
xeall _blockmove ' copy from source to dest
' length bytes
$end Asm
Returm
Listing 5 Copying a memory area (TEST_LIB.BAS)
At the beginning of the program two memory blocks of a length of 40
bytes each are declared. Block’ is (arbitrariy) initialized before the
assembler routine _blockmove copies block1 to block2.
The BASIC subroutine handles the parameter for the assembler
routine only. The copying process takes place exclusively at assem-
bler level.
To compare the runtime of such an assembler routine with a com-
mon BASIC subroutine, block1 is cleared for the purpose of copying
block2 back to block1 at BASIC level (thereafter).
A runtime measurement is possible in AVR Studio and delivers the
following results for the 4 MHz clock frequency:
49For I = 1 To 40
Routine |Blockmove (...) Block1(i) = Block2(i)
Next
Runtime 89,6 us 474,0 us
2.5.5 Programming Devices
2.5.5.1 AVR
As AVR microcontrollers are in-system programmable (ISP), pro-
gramming equipment is not required. Rather, the evaluation boards
can be used to program and test the first AVR programs.
If evaluation board MCU00100 is used, the AVR ICP910 Program-
mer needs to be activated. Figure 28 shows the user interface in-
cluding memory dumps for Flash memory and EEPROM.
EGET eed [jo]
File Butter Chip
4|e|A| S| olSls) wl B) Crefsosesis a
Manufactor Atmel Size 8KB rist
Chip 9058515 r ip2
FlashROM | EEPROM |
00 [or [o2 [os [o* [os Jos [07 [os Tos [oa [oe [oc [oo Tor [or ~
‘9000 OC 95 18 95 18 95 19 95 18 95 19 95 18 CO 20 ALLLLA al
0010 [95 16 95 18 95 18 95 18 95 18 £1 OF BD Bl El GF qeeeépeap
0020 [BD 81 E5 8F BF 8D E4 CO EO ED 26 4E EO 82 BF SE Malas Nak!
0030 |E0 D2 EO F2 26 SF 2? 88 2E 68 EF SF BB G7 EF OF 20a0_‘hiblil
0040 [BB 88 EO 65 BF 83 B7 89 60 62 BF 89 94 76 CF FF oper Telli
0050 |92 OF 92 1F $2 2F 92 GF 92 4F 92 SF 92 17001
92
aq
2
8
2
S
3
=
0050 92 OF 92 9F 93 2F 93 3F TELL? bs
»
(9) MCS Electronics
262 bytes read
Figure 28 Programming with AVR ICP910
If there is no evaluation board or programmer available, one of the
proposals published in the Web are a good choice to consider.
50Figure 29 shows the circuit diagram of Jerry Meng's FBPRG Pro-
grammer driven from the parallel port of the PC
[http:/www.qsl.net/fatfb/]. A lot of people use Jerry's design with
success.
Heed
T ex te 2] |
Figure 29 FBPRG Programmer
Figure 30 shows the user interface of the programmer software in a
DOS window.
51Load HEX file to Flash buffer
Load HEX file to EEPROM buffer
Display Flash butter
Display EEPROM buffer
Program
Read Device code
Read Flash ¢ EEPROM to buffer
Save Flash buffer to HEX file
Save EEPROM buffer to HEX £ile
Generate AVR Studio DEBUG. OBJ
Show schematic
Toggle Reset to high(Current low)
Figure 30 FBPRG in a DOS window
Programmer software and circuit diagram of Jerry Meng's FBPRG
Programmer are available for downloading from the author's web site
assigned to this book [www.ckuehnel.ch/bascom_buch.htm].
BASCOM-AVR does not support this programmer directly. The pro-
grammer software FBPRG.EXE must be linked in menu Op-
tions>Programmer>Other to BASCOM-AVR.
This is the way to include unknown programmers in both BASCOM
IDEs.
2.5.5.2 8051
BASCOM-8051 supports the whole 8051 family of microcontrollers
with many memory types and programming needs. It is becessary to
choose the right programmer for the microcontroller in use.
The Micro-Pro 51 from Equinox Technologies was used for pro-
gramming the 8051 derivatives (mostly the AT89C2051)
[http://www.equinox-tech.com].
52After installing the link to the external programmer, the latter can be
run directly from BASCOM-8051. Figure 31 shows the installation of
an external programmer.
BASCOM-8051 Opi
Comper | Communication | Environment | Hardware simulator Programmer | Monitor | Printer |
Programmer Extemal programmer x pone
wutoVerify
WAM file jE ce
Paralle!| Serial Other |
Program = [D:\MicroProWMicropioeve
Paametes ["st=~=—“C~SstsSsSSS:S:.. Us HEX le
Mode Run from current directory |
wv Ok x Cance! |
Figure 31 Link to external programmer
This programmer has no special features. Figure 32 shows a loaded
hex file in the internal buffer. After programming the result should be
comparable with Figure 33.
53[Spal] at || 2 |
Pee 2051 ES
Figure 32 Buffer view
Checking Signature = Pass
Code Program = Done (1.2 Sec}
Programming Done
Programming Done
Figure 33 Programming result
After programming the device, the microcontroller must be placed in
the target board. For the small AT89C2051 | used the X051 Demo
Module from the same manufacturer.There are many other programming and evaluation devices on the
market. Frequently, the manufacturers of microcontrollers offer such
devices for first tests or prototyping.
2.6 Hardware for AVR RISC Microcontroller
2.6.1 DT006 AVR Development Board
Dontronics [http://www.dontronics.com] is the producer of the so
called SimmSticks. This is a standard that makes use of the well
know Simm connectors. There are motherboards and application
boards.
For BASCOM-AVR Dontronics designed the DT006. This is a moth-
erboard with integrated Sample Electronics programmer, LEDs,
switches and RS-232 serial interface.
So with this PCB you can create a programmer and you can use it as
a development board too.
The DTO006 board will program the 8, 20, and 28 pin DIP chips on
board, and will also program the DT107 (8515 and 4433 footprint),
DT104 (2313 footprint) and SIMM100 (8535 footprint) AVR
SimmSticks, as well as any AVR target board that has a Kanda type
header.
Current burning software is achieved with the programmer software
built into Bascom-AVR.
This means, after you have this programmer unit up and running as a
development platform, all you need to duplicate the procedure with a
stand alone micro, is a single AT90S2313-10-PC micro, and a
DT104 PCB and a handful of simple components. Or you can use
your own circuit design on a proto board, vero board, your own art-
work, whatever.
Figure 34 shows the DT006 AVR Development Board with two Simm
expansions slots on the right side (J2, J3). Chapter 5.2 shows the
DTO006 circuit diagram.
55|
q
|
|
oO RI eCaz
=
°
°
ol
°
°
°
2
2
°
°
2
6
es
°
°
o
°
°
°
2
s
2
°
°
2
=
°
Figure 34 DTO06 Board
2.6.2 AVR-ALPHA with AT90S2313
We [http:/Awww.ckuehnel.ch/ask.htm] support starting with the 2313
by the small AVR-ALPHA mini module. Figure 35 shows this module.
All I/O lines are connected to the pins of that module. Prototyping
without soldering is possible using a simple breadboard.
All AVR micros are in-circuit programmable and a simple program-
ming adapter fulfills all needs for programming the AVR-ALPHA. This
programming adapter can be linked to BASCOM-AVR as an external
programmer.
56Figure 35 AVR-ALPHA Mini Module
2.7 Instead of "Hello World"
After the introduction of the basic programming procedure as well as
the BASCOM Options and Tools, a first and very simple program
example will describe the working with BASCOM.
Usually, programs of the "Hello World" class fulfill this exercise. But,
the example here is a program controlled by a timer interrupt which |
think is a more typical microcontroller program than "Hello World".
Due to the different hardware base of the 8051 and AVR family, the
timer example will be explained for both microcontroller families
separately.
2.7.1 AVR
Timer0 is an 8-bit timer with a 10-bit prescaler. The timer period can
be calculated using the following expression:
prescaler
T =256-
OSC
For a clock frequency of 4 MHz and a prescaler of 1024 a timer pe-
riod of 0.065536 s is obtained. That means the timer overflows each
0.065536 s and generates an interrupt.
57In our program example the assigned interrupt service routine (ISR)
increments a byte variable and toggles an I/O pin. Listing 6 shows
the source text of program SIM_TIMER.BAS.
' SIM TIMER.BAS for AVR
Dim A As Byte ' ‘Temporary Variable
Ddrb = 255 ' PortB is output
Porth = 255 ' All outputs Hi
' Configure the timer to use the clock divided by 1024
Config TimerO = Timer , Prescale = 1024
Qn Timer0 TimerO_isr dump to Timer0 ISR
Enable Timer0
Enable Interrupts
Enable the timer interrupt
Enable Global Interrupt
Do
' Do nothing
Loop
Timer0_isr: Interrupt Service Routine
Incr A ' Increment Variable A
Portb.0 = Not Portb.0 ' Toggle Portb.0
Retum
Listing 6 Timer program for AVR (SIM_TIMER.BAS)
2.7.2 8051
TimerO operates in Mode 2 as a 16-bit timer. The timer period can be
calculated using the following expression:
12
T = 65536:——
OSC
For a clock frequency of 11.059 MHz and a fixed prescaler of 12, a
timer period of 0.07111 s is obtained. That means the timer over-
flows each 71 ms and generates an interrupt.
In our program example the assigned interrupt service routine (ISR)
increments a byte variable and toggles an I/O pin. Listing 7 shows
the source text of program SIM_TIMER.BAS.
58' SIM TIMER.BAS for AT89C2051
Dim A As Byte ' ‘Temporary Variable
Pl = 255 ' All outputs Hi
' Configure timerd as 16-bit timer
Config Timer0 = Timer , Mode = 1
Start Timerd
Qn TimerO TimerO_isr dump to Timer0 ISR
Enable Timerd
Enable Interrupts
Enable the timer interrupt
Enable Global Interrupt
Do
"Do nothing
Loop
TimerO_isr: ' Interrupt Service Routine
Incr A ' Increment Variable A
P1.0 = Not P1.0 ' Toggle P1.0
Returm
Listing 7 Timer program for 8051 (SIM_TIMER.BAS)
2.7.3. Things in Common
When comparing Listing 6 with Listing 7, only a few differences can
be seen to exist; the major part does not differ from eachother.
At first, a variable A is declared as byte. The format (here byte) de-
fines the memory allocation to the variable.
The timer overflow interrupt toggles an I/O pin. For AVR we use PinO
of PortB (PortB.0) and for 8051 PinO of Port1 (P1.0).
For the AVR, a data direction register initializes a pin as input or out-
put. Therefore, at least the pin toggled must be an output. To simplify
matters all pins of PortB are declared as outputs (DDRB = 255) and
set to Hi afterwards (PORTB = 255). For 8051, all Pins of Port1 are
set to Hi(P1 = 255) only.
The timer configurations of the microcontroller family differ from each
other; see the description in the previous two chapters.
Finally, the interrupts must be enabled. Enable Timer0O enables
the timer interrupt and Enable Interrupts enables the global
interrupts in the last initialization step.
59Following this initialization the program enters its main loop
(Do. . Loop) where nothing is to be done in this example.
The declaration of an interrupt service (ISR) routine in BASCOM is
performed in the same way as the declaration of a normal sub-
routine. The compiler replaces Return by the required Ret i (Return
from Interrupt) and supports the Push and Pop of all registers.
Inside the ISR Timer0_isr variable A is incremented (Incr A) and
PinO of PortB (AVR) and Port1 (8051), respectively, will be toggled
afterwards. That means reading Pin0, inverting the value and writing
back (Portb.0 = Not Portb.0 and P1.0 = Not P1.0, re-
spectively).
Next, input this program or open it after downloading from our web
site. Compiling and debugging is explained for BASCOM-AVR only
but do not differ for BASCOM-8051.
Figure 36 shows the source text of program SIM_TIMER.BAS
opened in the BASCOM-AVR Editor.
60File Edit Progiam Toole Options Window Help
| oleltaleslalal slel<| al isle) siele| | al
ESE L- [os]
|
[od
a 0: \D okumente\M ani
Dim A as Byte
Ddrb = 255 PortB is ou
Porth = 255 All output:
Config TimerO = Timer Prescale - 1024 gure
lock @
On Timer0 Tiner_isr to Tine
Enable Tiaer0
Enable Interrupts
Do
' Do nothing
Loop
TinerO_isr
Incr & a
Portb 0 = Wot Porth 0
Return .
Le
“8:40 | “Insert
Ir
Figure 36 Source text in BASCOM-AVR Editor
Before the first compilation the options must be set. The parameters
for the serial interfaces (I°C, SPI and 1-wire) and LCD are not rele-
vant here and can be set as desired.
Before a complete compilation, it may help to check the syntax. Start
the syntax check from menu Program>Syntax Check or Ctrl+F7.
61Figure 37 shows a syntax check with errors. By double-clicking the
error line the last "e" is seen to be missing in instruction Enable.
Ps [ord
file Edt Program Tools Options Window Help
KAPRLSI| & [Ma|t[2= [<=] ga) [4 [cS] Aw
Dim a As Byte
Ddrb = 255
Porth = 255
Config Timer0 « Timer . Prescale « 1024
On TimerO TinerO_isr
Enabl Timerd
Enable Interrupts
431 Insert Double click to jump to enor fine
Figure 37 Result of syntax check
When the missing character is entered, the syntax check will show
no error anymore, and the compilation will be faultless as well. Start
the compilation from menu Program>Compile or F7.
As expected there is no error after compilation. Look for the result by
clicking Program>Show Result or Ctrl+W. Listing 8 shows the re-
port file SIM_TIMER.RPT generated for BASCOM-AVR.
62Date
Time
compiler
Processor
SRAM
EEPROM
ROMSIZE
ROMIMAGE,
BAUD
XTAL
BAUD error
Stackstart
S-Stacksize
S-Stackstart :
: 32 hex
: 20D hex
Framesize
Framestart
LCD DB7
LCD DBE
LCD DBS
LcD DB4
LOE
LCD RS
LCD mode
: SIM_TIMER
: 10-31-1999
: 19:07:06
: BASCOM-AVR LIBRARY V 1.05, Standard Edition
: 9088515
: 200 hex
: 200 hex
: 2000 hex
: FA hex -> Will fit into RM
: 9600 Baud
: 4000000 Hz
0.16%
: 25F hex
: 20 hex
240 hex
: PORTB.7
: PORTB.6
: PORTB.5S
Listing 8 Report file for BASCOM-AVR (SIM_TIMER.RPT)
63Listing 9 shows the report file generated for BASCOM-8051.
Compiler : BASCOM 8051 LIBRARY V 2.04
Processor : AT89C2051
Report : SIM_TIMER
Date : 12-27-2000
Time : 15:20:03
Baud Timer : 1
Baudrate : 0
Frequency : 11059200
ROM start : sHO
RAM start : SHO
LD mode =: 4-bit
StackStart : 22
Used ROM =: SHAD —-173 (dec) > Ok
Listing 9 Report file SIM_TIMER.RPT for BASCOM-8051
2.7.4 Simulation
In the next step, the simulator can be started from menu
Program>Simulate or by pressing F2.
The simulator of the BASCOM IDE has been referred to already. So
let's use here the simulator of the AVR Studio for the BASCOM-AVR
example.
Caution: If you have to go deep into the compiled code, using the
AVR Studio has some advantages. When a functional simulation is
sufficient, using the internal simulator will be simpler.
Load the generated Obj-File from menu File>Open or press Ctri+O.
Figure 38 shows the simulator with three open windows.
64SEE ee ier)
File Edt Debug Breakpoinls Watch Oplione View Window Help
S| 2) 2) B=Sja/0) ele) allele -[8) 8]
Aa To
[SiOcumeaeitenaicae=]) fi a
ee—_—rss :t—|
76543210
Pot [FE Vil
VVRVWI
ore
On TimerO TimerO_isr ms
a
peeshe eileen bor [FO WR
Eneble Interrupts [/) Ce
be [bas =] raJ[a ae]
' Do nothing ‘Address Data
Loop ‘900020 00 00 00 00 G0 00 00 00 00 00 00 G0 00 00 00 00
00030 «00 00 G0 00 00 00 FE FF FE 00 00 00 00 00 00 00
00040 ©0017 GO 40 G0 00 O0 00 OD 00 90 an OO 00 00 OO
—- 00050 00 00 O0 O5 00 00 00 00 00 O2 OO 00 OO SD O2 00
Porth. = Not) goons A 00 00 00 00 00 OD CO GO oO OO 00 OO OO OO oO
4 =
For Help, press F1 Simulator
Figure 38 Simulation von SIM_TIMER.BAS in AVR Studio
The source text can be seen on the left side. We placed a break
point to the ISR. The top right window shows all bits of PortB. The
bottom right window shows a memory dump of data memory. These
windows can be opened from menu View>Peripheral>Port>PortB
or View>New Memory View.
Simulation can start when the AT90S8515 is selected in the simula-
tion option (Options>Simulation Options).
Start the simulation from menu Debug>Go or F5. The simulation
stops at the break point. All changes at PinO of PortB and in memory
location 60, are visible. The timer period in simulation depends on
the fastness of the PC used. With the author's PC a timer period of
about five seconds was achieved.
However, a simulation is not all in life. Therefore the program is burnt
into the microcontroller and the program checked in the target hard-
ware.
65Evaluation board MCU00100 must be connected to COM1 of the PC
before starting the programmer from menu Program>Send to Chip
or F4. Figure 39 shows the user interface of the programmer.
The AT90S8515 used in evaluation board MCU00100 has already
Baa
File Buffer Chip
2\elH| 2/2) olSle| a] B) — “efsosests “le
Manufactor Atmel Sie 8KB Ex
Chip 9058515 r
~FlashROM | EEPROM
100 | 01 [02 [03 [04 |05 [05 |O7 |08 [09 |G |OB |OC }0D [OE |OF eS
‘000 OC 95 18 95 18 95 18 95 18 95 18 95 18 CO 20 AILLILIA
0010 |95 18 95 18 95 18 95 18 35 18 E1 SF BD 81 El 87 IiutLapadl
O20 [BD & ES 8F BF 8D E4 CO ED ED 2E 4E EO 82 BF BE
0030 |EO D2 0 F2 26 5F 27 88 2E 6B EF GF BB GF EF SF abad_Thilolil
0040 _|BB 88 EO 85 BF 63 B7 89 60 B2 BF 89 94 a
0050 |92 OF 92 1F 92 2F 92 3F 92 4F 92 5F 92 a
0060 [92 8 92 9F 92 BF 93 OF 93 1F 93 2F 99 3F ‘WW “ULLIMI? x
Lt 2A
() MCS Electronics
zx
252 bytes read
Figure 39 BASCOM-AVR ICP910 Programmer
been identified already. The generated code is visible in FlashROM.
Load the program into the flash memory of AT90S8515 from menu
Chip>Autoprogram.
Immediately after Verify, the program starts and the LED connected
to PinO of PortB blinks at the programmed rate.
This first example should explain the fundamental project work with
BASCOM. It should be clear that planning the resources like the allo-
cation of I/O pins and so on is independent of the used programming
language or environment. This step must be finished before coding.
Later, any resulting collisions can be repaired at greater expenses
only.
662.8 BASCOM Help System
If you need help for any BASCOM instruction, place the cursor to the
respective key word and press function key F1. Figure 40 shows the
opening help window with explanations.
Eero Sc
Fle Est Progam Tcok Oplons Window Helo lax)
_Dieimleslelal + {al
gaivetian Lecszechen Qptionen 2?
Todor [Zune [Dpken I
Dimension a variable.
Syntax
Do. DIM var AS [XRAMARAM] type [AT location]
Remarks i
Figure 40 Press F1 for Help
Just as important as the explaining text are additional program ex-
amples which describe the use of instructions and/or functions.
Furthermore, the help system has a very comfortable index and
search system. Figure 41 shows a search for "interrupt" information
and resulting hints.
67lfethemen: BASCOM-AVR
linden Suchen |
1. Geben Sie die geniinschten Suchbegrife ein
interupt Lischen
2, Maikioren Sie einige Wortenteprechungen ale Serer
inschrankende Suchkiterien ene
ey
Aktualsieren..
2. Klicken Sie auf ein Thema und dann aut “Anzeigen”.
a
‘AVE intemal Hardware Port D
AVR Intemal Hardware TIMERO
AVR Intemal Hardware TIMER
Changes compared to BASCOM-G051
CONFIG INTs
CONFIG TIMERO as
25 Themen gefunden Alle Wiiter, Anfang, Auto, Pause
arecigen | & Abbiechen
Figure 41 Search Function in the BASCOM Help System
683 Some BASCOM Internals
This chapter describes some BASCOM details which caused some
responses and queries in the past.
Caution: Since BASCOM has a very powerful help system, there is
no list of compiler directives and instructions in this book.
Please use the Help System first. A lot of newsgroup queries can be
answered this way.
3.1 Building new instructions
BASCOM's subroutine construct is a powerful means for generating
new instructions. A simple example will demonstrate it.
In the example we generate an instruction that toggles some pins of
port P1 of an 8051 microcontroller. The instruction shall have one
parameter - the toggle mask.
We define subroutine Toggle_p1(x) that reads, masks and writes
back port P1(P1 = Pl Xor X). If this subroutine is declared at the
beginning of the program, there are two ways for calling it at a later
time.
Call Toggle_p1(mask) and Toggle_p1 mask are two equiva-
lent subroutine calls. The second kind of call is marked bold in the
program example. It looks like a new instruction.
Dim Mask As Byte , X As Byte
Mask = §B11000011 ' Toggle mask
' Declaration of instruction toggle _pl
Declare Sub Toggle _pl(x As Byte)
Do
Call Toggle pl (mask) ' Subroutine call
Toggle pl Mask ' Usage of new instruction
Loop
End
' Defintion of subroutine
Sub Toggle pl (x As Byte)
1 = Pl Xor X
End Sub
69We can go into the simulator and see the equality again.
In the single-step mode, we set port P1 to &HAS, for example, and
see P1 toggling from &HAS5 to &H66 and vice versa.
Pl &HAS 1010 0101
Mask 1100 0011
Pl &HE6 0110 0110
Figure 42 shows the simulator window with port P1 toggled.
(PES Lox]
ofr a| sls | Sls] alelmlolS —
_into| int: |_to_| 1 | sen
Vaiables | Break |
Variable [Value |Hex Bin
102 opo006s © go00000001100110
Declare Sub Tosgle_pl(= As Byte} [Ace 66
Do a ca
° Call Toggle_pi (mask) + Wie 00
3 Toggle_pi Hask Wie. 0
i? 2
O End P3 FF
Sub Toggle_pi(x As Byte) fl
ub Toggle _pi(x As Byte Tee
Om Pi = Fi vor ¥ ao
O End Sub et oo
~l/sp 25
a toe 00 al
Pauzed — 468[0.5078125ms] [Max stack 25
Figure 42 Subroutine call in simulator of BASCOM-8051
There are minor differences between BASCOM-8051 and BASCOM-
AVR as regards the declaration of subroutines. The next chapter
70describes in detail the parameter passing by reference or by value in
BASCOM-AVR only.
3.2 Parameters for Subroutines in BASCOM-AVR
A wrong parameter handling BYREF or BYVAL is a frequent reason
for errors in application programs. A simple example will give more
clarity.
In the next example, a mask function cutting the high nibble of a
value multiplied by four is defined.
Value A and mask B are parameters of a function to be defined. The
result is saved in variable Z. The binary representation of this task is
as follows:
A 10101010 for example
Shift A, Left , 2 10101000 2*A
B 00001111 mask
Zz 00001000 result
The program reads as follows:
* Subroutine in BASCOM-AVR
Dim X As Byte , Y As Byte , Z As Byte
X = 6810101010
Y = 6800001111
Declare Function Mask (byval a As Byte , B As Byte) As Byte
Z = Mask(x , Y)
End
Function Mask (byval A As Byte , B As Byte) As Byte
Shift A, Left , 2
Mask = A And B
End Function
71Running the program in the single-step mode reveals that variable x
is unchanged after access to the function. Figure 43 shows the un-
changed variable x after access to function mask ().
Sa a SEE
ofa «| alt as ffm] Bi] 7 sin Tiers aj
Vatiables | Locals | du* watch | @ uP | intemupts |
Variable Valve Hex
170 AA To1oT010
y 15 F oot 111
2 0 0 ooono000
a
11 4
12 Function Mask (byval A As Byte , B As Byte) As Byte
2 18 gnitt A, Left , 2
© 14 ask = A And B
> 15 End Function ¥]
< | oe ei
PC=0062 | Cyol = 002 Pause
Figure 43 Parameter passing BYVAL
When cutting keyword BYVAL, the default parameter passing BYREF
is active. In this case the variable changes from &HAA to &HAS after
access to the function mask (Shift A , Left , 2); see Figure
44.
72A —T= T=]
rum] caica| Ss] | o[m| GQ] Pr sintines |
Vatiables | Locals | 6° Watch | % uP | Irtenupis |
Variable Value Hew Bin
168 48 voror000
y 5 F oogt111
2 8 8 00001000
Tr
12 Function Mask (A As Byte , B As Byte) As Byte
° 13 Shift A, Left , 2
° 14 Mask = A& And B
> 15 End Function
Lf
PC = 0040, Cyel = 3160 Pause:
Figure 44 Parameter passing BYREF (default)
3.3 BASIC & Assembler
In some cases a direct effect on the code is needed. If a desired
function is not in the instruction set, it can be defined as a BASIC or
Assembler subroutine.
Of importance is that BASCOM supports the mixing of BASIC and
Assembler.
The compiler recognizes most assembler mnemonics automatically.
Exceptions are SWAP and, additionally, SUB and ouT for BASCOM-
AVR. These mnemonics are reserved words of BASIC and therefore
have a higher priority as the assembler mnemonics.
However, using prefix ! makes the compiler recognize that word as
assembler mnemonics, too.
Short examples for both microcontroller families demonstrate the use
of the assembler in a BASIC source file.
733.3.1 AVR
The assembler is based on the standard AVR mnemonics.
In the following program examples, the assembler instructions are
marked in bold.
Dim A As Byte ' Bytevariable
A = GHSA ' Initialize Variable
Lloadadr A, X ' Load Address of A into X
Id R1, X ' Load R1 with contents where
' X is pointing to
ISWAP RL ' Swap nibbles
Byte variable A holds the value &H5A. Instruction Loadadr A , X
places the address of this variable into register X.
Register R1 is then loaded with the value of variable A and, finally,
the content of register R1 is swapped.
Without prefix ! before swap, the compiler would have recognized
swap as a BASIC instruction.
Another possibility is the use of the compiler directives $asm and
$Sasm end. Normal assembler mnemonics can be placed between
these two directives.
Dim A As Byte ' Bytevariable
A= GHA ' Initialize Variable
loadadr A, X ' Load Address of A into X
Sasm
Id Rl, X ' Load R1 with contents where
' X is pointing to
Swap RL ' Swap nibbles
Send Asm
Run these examples in the simulator to see how such includes work.
It is a matter of taste what kind of notation one prefers. Functionally,
both examples are equivalent.
Take care when manipulating registers directly! BASCOM-AVR uses
some registers. R4/R5 serve as a pointer to the stack frame. R8/RO
74serve as data pointer for the READ instruction. R6 contains a few bit
variables:
R6.0 Flag for integer-word conversion
R6.1 Temporary bit for bit swap
R6.2 — Error bit (ERR)
R6.3. Show/Noshow bit of INPUT instruction
Caution: Do not change these registers in any assembler included.
Other registers will be used independence of the BASIC instruction
referred to.
3.3.2 8051
The assembler is based on the standard Intel mnemonics.
In the following program examples, the assembler instructions are
marked in bold.
Bytevariable
Initialize Variable
Dim A As Byte
A= &5A
Load RO with address
from variable A
Placeadres A , RO
‘MOV A,@RO ' Load ACC with contents
of variable A
ISWAP A Swap nibbles
Byte variable A holds the value &H5A. Instruction Placeadres A
, RO places the address of this variable into register RO.
The accumulator is then loaded indirectly with the value of variable A
and, finally, the content of the accumulator is swapped.
Without prefix ! before swap, the compiler would have recognized
swap as a BASIC instruction.
Another possibility is the use of compiler directives $asm and $asm
end. Normal assembler mnemonics can be placed between these
two directives.
75Dim A As Byte ' Bytevariable
A= GSA Initialize Variable
Load RO with address
from variable A
Placeadres A , RO
Sasm
MOV A,@RO ' Load ACC with contents
' of variable A
Swap A ' Swap nibbles
Send Asm
A third way simplifies access to the variable by a different notation.
Dim A As Byte ' Bytevariable
A= GHSA ' Initialize Variable
Sasm
wv A, {a} ' Load ACC with contents
' of variable A
Swap A ' Swap nibbles
$end Asm
Run these examples in the simulator to see how such assembler
includes work.
It is a matter of taste what kind of notation one prefers. Functionally,
all three examples are equivalent.
Caution: Take care when directly manipulating registers! BASCOM-
8051 uses the registers ACC, B and SP. Do not change these regis-
ters in any assembler included.
764 Applications
This chapter describes the applications both microcontroller families
can be used for. It is the underlying hardware of the microcontroller
concerned that is responsible for any differences in the programs.
The program examples were first set up with BASCOM-AVR. Hints
for porting the AVR examples to 8051 are included. In some cases
we discuss the solutions which are dependent on the microcontroller
used. In other cases the differences are insignificant.
4.1 Programmable Logic
Logical devices query input lines (input pattern) and assign a defined
bit pattern to the output lines. The logical relations can be expressed
by way of a table. In the example the following relations are intended
to be implemented:
AT A6 AS A4 AZ A2 AT AD|Q7 Q6 QS Q4 Q3 Q2 QI QO
1 1 4 4 4 4 4 Off 1 4 4 4 0 0 0 0
1 1°14 4 1 4 0 4170 0 0 04 4 4 «4
x x x x x x 4 T4171 1 41 1 1 «4 «14 «2
The logical devices should have eight inputs A7..A0 and eight out-
puts Q7..Q0. Each bit pattern at an input has a corresponding bit
pattern at an output.
For eight input lines we obtain 256 different bit patterns, and the table
would be very long.
In the table we use, there are only three different bit patterns at the
output. Therefore, the table poses no problem.
Interpreting the table, we find the following results:
¢ IfA=&B11111110 then set Q = &B11110000.
e IfA=&B11111101 then set Q = &B00001111.
¢ Inall other cases set Q=&B11111111.
Shown in Fig. 43 is the whole circuit including clock generation and
reset circuitry for an application using an AVR microcontroller.
77/RESET
AT
AG
AS
Ad
A3
AQ
Al
AO
ld er
6
5
O4
€ O03
Q2
<1
Qo
CLK >—
PRESET
XTAL2
XTALI
PO7 GRO)
PDB GWR)
PDS (OC1A)
PD
D3 (NTI)
D2 (INTO)
PDI (TxD)
POO (RXD)
P87 (SCK)
P86 (MISO)
PBS (MOS!)
P84 USS)
PBS (AINT)
PB2 (AINO)
Pat (Tt)
BO (TO)
(ADT) PAT
(AD8) PAB
(ADS) PAS
(D4) Pag
(D3) PAB
(D2) PAD
(AD1) PAT
(AD0) PAD
(15) PCT
(ata) PCO
(A13) PCS
(12) PCS
(att) Pcs
(Ato) PC2
(ag) Pct
(a8) PCO
Figure 45 AT90S8515 as a logical device
The clock and reset components are always the same and will be
omitted in the next circuit diagrams. Supply voltage and ground are
normally not drawn, either.
The eight input lines A7..A0 go to PortD. PortB drives the eight output
lines. Keys on the evaluation board used are connected to PortD.
PortB is connected to LEDs with resistors in series.
Program LOGIC.BAS waits for a pulse (rising edge followed by a
falling edge) at input CLK and, thereafter reads the input lines at
78PortD. In a case structure the bit pattern is evaluated and the result
forces the pins on PortB.
The BITWAIT instructions query PinO of PortA and block the pro-
gram until the mentioned pulse is detected.
The bit pattern of the input is saved in variable A. Variable Q contains
the bit pattern of the output.
The pins have an internal pull-up resistor, which is activated by set-
ting the port line. PORTD.x = 1 activates the pull-up resistor on the
respective I/O line. In this program example, the whole port will be
set (Listing 10).
' Logic with AT90S8515
Dim A As Byte , Q As Byte
Config Porta = Input
Porta = 255 ' pull-up active
Config Portb = Output
Config Portd = Input
Portd = 255 * pull-up active
Do
bitwait Pina.0 , Set
bitwait Pina.0 , Reset
A = Pind
Select Case A
Case &B11111110 : &B11110000
Case &B11111101 : = &B00001111
Case Else Q = &B11111111
End Select
Portb = Q
Loop
End
Listing 10 Logical device with AT90S8515 (LOGIC.BAS)
Input CLK triggers the data input of the input lines at PortD. So as to
get periodic queries of the input lines, a timer can be used for trig-
gering. The circuit remains unchanged. Input CLK has no function
now.
Timer applications will be discussed in the next chapter.
79Listing 11 shows the timer controlled logic device. The complete I/O.
handling is here accommodated in the interrupt handler.
' Logic with AT90S8515
Dim A As Byte , Q As Byte
Config Portb = Output
Portb = 255 ' All outputs Hi
Config Portd = Input
' Configure the timer to use the clock divided by 1024
Config TimerO = Timer , Prescale = 1024
On Timer0 Timer0_isr ' Jump to Timer0 ISR
Enable Timer0 ' Enable the timer interrupt
Enable Internpts ' Enable Global Interrupt
Do
Nop
Loop
End
Timer0_isr:
A = Pind
Select Case A
Case &B11111110 : Q = 6B11110000
Case §B11111101 : Q = &B00001111
Case Else Q = 8811111111
End Select
Porth = Q
Retum
Listing 11 Timer controlled logic devices (LOGIC1.BAS)
When deciding to use an 8051 microcontroller a device with enough
V/O lines is required. The next program examples are based on the
AT89S8252. Listing 12 shows the slightly modified program. A com-
parison with Listing 10 shows modifications only for port I/O.
P1 is the input and P3 the output for the logical signals. P2.0 serves
as clock input here.
80' Logic with AT89S8252
Dim A As Byte , Q As Byte
Pl = 255 ' pull-up active
P2 = 255 ' P2.0 is CLK input
Do
Bitwait P2.0 , Set
Bitwait P2.0 , Reset
A=PL ' Read Pl
Case &B11111110 : Q = 6B11110000
Case 6B11111101 : Q = 8800001111
Case Else Q = sB11111111
End Select
P3=Q ' Write B3
Loop
End
Listing 12 Logical device with AT89S8252 (LOGIC.BAS)
4.2 Timer and Counter
As the timers/counters of the 8051 and AVR microcontrollers differ
from each other, the timers will be described separately.
Timer and counter denote different modes of the same hardware. To
simplify description, the term timer will be used in all general expla-
nations.
Caution: Please read the documentation of the manufacturer very
carefully. The correct setup of some registers is the key to a correct
implementation of the required functions. In case of a wrong setup
debugging can be very difficult.
4.2.1 AVR
The AVR microcontrollers have different internal timers. The 8-bit
timer has already been used for simple timer functions.
Since the 16-bit timer offers far more flexibility than the 8-bit timer, it
will be primarily dealt with here.
Caution: The pinout for the alternative functions such as clock in-
puts TO and 11, differs for the various types of the AVR family.
All timer program examples given below refer to the AT90S8515.
814.2.1.1 Timer
Timer0 is an 8-bit timer and Timer1 a 16-bit timer. Each timer has a
10-bit prescaler. The maximum timer period can be calculated using
the following equation:
par’. prescaler
Sos
N = 8 for TimerO and N = 16 for Timer1. The prescaler may have a
value of 1, 8, 64, 256 or 1024. The next tables show the resolution
and maximum timer period for TimerO and Timer1 for a clock fre-
quency of 4 MHz.
Timing for Timer0 at 4 MHz
Prescaler 1 8 64 256 1024
max. Timer Period in ms 0,064 0,512 4,096 16,384 65,536
Resolution in ms 0,00025, 0,002 0,016 0,064 0,256
Timing for Timer at 4 MHz
Prescaler 1 8 64 256 1024
max. Timer Period in s 0,016 0,131 1,049 4,194 16,777
Resolution ins 0,00025, 0,002 0,016 0,064 0,256
The next example is a clock generator blinking an LED once per
second.
The maximum period for Timer1 with a prescaler of 64 is 1.049 sec-
onds. To get the period of one second exactly we have to shorten
this time by 49 ms. The Output Compare Mode of Timer1 can reduce
the timer period.
Derived from the equation above we find the following formula
fox
OutputCompare =
prescaler
Soll
and with the known parameters we get an output compare value of
62500. This value must be saved in the Output Compare Register.
Listing 13 shows the configuration of Timer1 as timer with a pres-
caler of 64.
82Dim New time As Byte
Dim Temp As Byte
Dim Seconds As Byte
Dim Minutes As Byte
Dim Hours As Byte
Dim Key As Byte
Const True = 1
Const Reload = 62500
Config Timerl = Timer , Prescale = 64
Ocrlah
Ocrlal.
Tecrla = 0
Set Tecrlb.3
High (reload)
Low (reload) Reload Timerl for
Period of 1 sec
Disconnect OC1A from T/CL
Reset T/Cl after Compare
Config Portb = Output
Portb = 255 ' All outputs Hi
On Comparela Timerl_isr
Enable Comparela
Enable Interrupts
Do
Jump to Timerl ISR
Enable the timer interrupt
Enable Global Interrupt
Key = Pind
If Key = SH7F Then
Seconds = 0
Minutes = 0
Hours = 0
End If
While New time = True
I£ Seconds = 60 Then
Seconds = 0 : Incr Mimites
End If
If Minutes = 60 Then
Minutes = 0 : Incr Hours
End If
If Hours = 24 Then Hours = 0
‘Temp = Makebcd (seconds)
Tf Key = &HFE Then Temp = Makebcd (minutes)
If Key = &HFD Then Temp = Makebcd (hours)
Porth = Not Temp
New time = Not True
Wend
83Timerl_isr:
New_time = True
Incr Seconds
Retum
Listing 13 Second-Timer with Timer1 (TIMER3.BAS)
Timer1 operates as an up-counter. When the timer count is equal to
the content of Output Compare RegisterA, a compare interrupt oc-
curs. To start a new timer period, bit CTC1 of control register
TCCR1B must be set.
To avoid unintentional changes in timer control registers TCCR1A
and/or TCCR1B, instruction CONFIG TIMER1... should be used at
program start before any other timer configurations.
From instruction
Config Timerl = Timer , Prescale = 64
BASCOM-AVR generates the following assembler code:
LDI R24, 0x00 ; 0x00 = 0b00000000 = 0
our Ox2F, R24
IDI R24, 0x03 ; 0x03 = Ob00000011 = 3
our Ox2E, R24
Register TCCR1A is reset to &HOO. Outputs OC1A and OC1B are
disconnected from Timer1. PWM is deactivated. Register TCC1B is
set to &HO3 switching the prescaler 64.
The CTC1 bit in register TCCR1B must be set separately. Instruction
Set Tccrlb.3 can do the job without exerting any influence on
other bits in TCCR1B.
From instruction
Set Tecrlb.3
BASCOM-AVR generates the following assembler code:
IN R24, 0x2E
ORT R24, 0x08 ; 0x08 = 0b00001000 = 8
our Ox2E, R24
After enabling the compare interrupt, the program enters an endless
loop showing the time in the BCD format. Seconds, minutes or hours
can be displayed by striking the respective keys.
84The Output Compare Function of Timer1 generates a compare inter-
rupt when the timer is equal to the compare value. The interrupt han-
dler sets flag New_time and increments variable Seconds. A reload
of Timer1 is not required because Timer1 is reset on compare event.
Timer0 is less comfortably equipped, and reloading must be imple-
mented in the software. The procedure is demonstrated with a 50 ms
timer.
At a clock of 4 MHz and a prescaler of 1024, it will take 195 cycles to
get a timer period of 50 ms.
TimerO has the overflow interrupt available only. TimerO must be
loaded with a value of 256 - 195 to get an overflow after 195 cycles.
Listing 14 shows the initialization of TimerO and PortB and an end-
less loop as the main program.
On TimerO overflow the instruction Load TimerO , Reload re-
loads the timer. Calculation 256 - Reload is performed internally.
Const Reload = 195 ' Reload value for Period of 50 ms
Config TimerO = Timer , Prescale = 1024
Qn TimerO Timer0_isr ' Jump to Timerl ISR
Config Portb = Output
Enable Timer0 ' Enable the timer interrupt
Enable Interrupts ' Enable Global Interrupt
Do
Nop
Loop
End
Timer0_isr:
" Reload TimerO for Period of 50 ms
Load Timer0 , Reload
Portb.0 = Not Pinb.0 ' Toggle Portb.Pin0
Return
Listing 14 Clock generation using Timer0 (TIMERO.BAS)
Especially when manipulating the internal registers it is recom-
mended to inspect the initialized registers or the generated code with
the simulator.
85As shown in the following assembler list, all internal registers and the
status register are saved on stack at the beginning of every interrupt
service routine (ISR). Only after this pushing will the activities of the
ISR start.
In the example, the first activity (marked gray) is loading register
TCNTO with the value of 256-195 = &H3D.
Instruction Cycles | TCNTO (Prescaler=1)
PUSH RO 2 &HOG
PUSH R1 2 &HO8
PUSH R2 2 &HOA
PUSH R3 2 &HOC
PUSH R4 2 &HOE
PUSH RS 2 &H10
PUSH R6 2 &H12
PUSH R7 2 &H14
PUSH R8 2 &H16
PUSH RO 2 &H18
PUSH R10 2 SHIA
PUSH R11 2 &HIC
PUSH R16 2 &HIE
PUSH R17 2 &H20
PUSH R18 2 &H22
PUSH R19 2 &H24
PUSH R20 2 &H26
PUSH R21 2 &H28
PUSH R22 2 &H2A
PUSH R23 2 &H2C
PUSH R24 2 &H2E
PUSH R25 2 &H30
PUSH R26 2 &H32
PUSH R27 2 &H34
PUSH R28 2 &H36
PUSH R29 2 &H38
PUSH R30 2 &H3A
PUSH R31 2 &H3C
IN R24,0x3F 1 &H3E
PUSH R24 2 &H3F
LDI R24, 0x3D 1 &H41
our 0x32,R24 1 &H42
1 &H3D
IN R24,0x16
The interrupt occurs after 195 cycles of Timer0. The first activity in
the ISR is carried out 66 cycles (&H42) later. Such deviations may be
unacceptable in some cases.
86Caution: |n case of low prescaler values, take into account the time
needed for register saving.
Listing 15 shows a simple way (marked in bold) of taking the addi-
tional cycles into consideration.
Const Reload = 195 ' Reload value for Period of 50 ms
Dim Counter As Byte
Config Timer0 = Timer , Prescale = 1
On TimerO Timer0_isr ' dump to Timerl ISR
Config Portb = Output
Enable Timer ' Enable the timer interrupt
Enable Interrupts ' Enable Global Interrupt
Do
Nop
Loop
End
Timer0_isr:
" Reload TimerO for Period of 50 ms
Counter = Tent ' Read Timerd
Tont0 = Counter - Reload ' Reload Timerd
Portb.0 = Not Pinb.0 ' Toggle Portb.0
Retum
Listing 15 Modified clock generation by Timer0 (TIMERO_1.BAS)
Before reloading Timer0, its content is read and the reload value can
be corrected before reloading Timer0. The assembler list shows the
changes following this program modification.
87Instruction Cycles TCNTO ( Prescaler=1)
PUSH RO 2 &HOT
PUSH RL 2 &HOO
PUSH R2 2 &HOB
PUSH R3 2 &HOD
PUSH R4 2 &HOF
PUSH RS 2 &H11
PUSH R6 2 &H13
PUSH R7 2 &H15
PUSH RS 2 &H17
PUSH RQ 2 &H19
PUSH R10 2 &H1B
PUSH R11 2 &HID
PUSH R16 2 &HIF
PUSH R17 2 &H21
PUSH R18 2 &H23
PUSH R19 2 &H25
PUSH R20 2 &H27
PUSH R21 2 &H29
PUSH R22 2 &H2B
PUSH R23 2 &H2D
PUSH R24 2 &H2F
PUSH R25 2 &H31
PUSH R26 2 &H33
PUSH R27 2 &H35
PUSH R28 2 &H37
PUSH R29 2 &H39
PUSH R30 2 &H3B
PUSH R31 2 &H3D
IN R24, 0x3F 1 &H3F
PUSH R24 2 &H40
LDI R26, 0x60 1 &H42
LDI R27, 0x00 1 &H43
IN R24, 0x32 2 &H44
ST X,R24 2 &H45
LDI R26, 0x60 1 &H47
LDI R27, 0x00 1 &H48
LD R16,X 2 &H49
LDI R20, 0xC3 1 &H4B
SUB R16,R20 1 &H4AC
OUT 0x32,R16 1 &H4D
IN R24, 0x16 a &H81
The timer period should be 195 cycles of TimerO again. After 77 cy-
cles (= &H4D) the calculated value of 129 (= &H81) is reloaded. With
a prescaler of 1, Timer0O will overflow after 256 - 129 + 77 = 204
cycles.
88The remaining difference to the expected value of 195 results from
the difference between reading and writing TCNTO (&H4D-&H44). It
is nine cycles here and can be considered when necessary.
4.2.1.2 Counter
In the counter mode the timers/counters of the AVR microcontrollers
are able to count (external) events. For Timer0, PinO of PortB serves
as counter input TO. The leading or falling edge of the input signal
can trigger the counter. Register TCNTO contains the number of
counted pulses.
A simple example demonstrates the counter mode of Timer0. What
is to be counted are pulse packages of 10 pulses each. The number
of received packages will be saved in a variable. Listing 16 shows the
resulting source.
Const Ticks = 10 ' Number of pulses in a package
Dim Count As Byte * Counter
Config Timer0 = Counter , Edge = Falling
Load Timer0 , Ticks ‘Overflow Interrupt after 10 cycles
On TimerO Timer0_isr ' gump to TimerO ISR
Config Portb = Output ' PortB Output
Reset. Darb.0 ' PortbO Input for pulse counter
Enable Timer0 ' Enable the timer interrupt
Enable Interrupts ' Enable Global Interrupt
Do
Porth = Count * 2 ' Shift one bit left for display
Loop
End
Timer0_isr:
Load Timer0 , Ticks
Iner Count
Returm
Listing 16 Pulse Counter with Timer0 (COUNTERO.BAS)
At the beginning of this program example, TimerO is configured as
counting falling edges of the input signal. Register TCNTO is loaded
so that an overflow interrupt occurs after 10 counted pulses.
89The ISR manages reloading and increments variable Count.
In the endless loop, the variable counter is displayed by the LEDs
connected to PortB. As PinO serves as counter input TO, it is not
available for display. The result needs to be shifted one bit to the left,
and the rest of PortB is used for display only.
Compared with Timer0, Timer’ offers a lot more features in counter
mode as well.
Timer1 can count pulses from Pin1 of PortB (T1). If a capture pulse
is detected at Pin4 of PortD (ICP), then the register will be moved to
the Capture Register. Pulse edges and noise cancellation can be set
by means of instruction Config Timerl = Counter ....
Listing 17 shows a simple program example intended to run in the
simulator. For printing reasons the first line is broken. The whole
instruction Config Timer1 = ... must be keyed in in one line.
Config Timerl = Camter , Edge = Falling , Noice Cancel = 1,
Capture Edge = Rising
' Count Input is Tl (PB1)
Capture Input is ICP (PD4)
Config Portb = Output
Config Pinb.1 = Input
Portbo Output
PinB.1 Input for pulse counter
Portb = 255
Do
Porth = Icrll * 4 ' Shift two bits left for display
Loop
End
Listing 17 Timer/Counter1 Input Capture (CAPTURE1.BAS)
Since Pin1 of PortB serves as counter input T1, it is not available for
display. We have to shift The result must be shifted two bits to the
left, and the rest of PortB is used for display only.
It is very important to know the exact result of a configuration like
Config Timerl = Counter , Edge = Falling , Noise
Cancel = 1 , Capture Edge = Rising. Take the simulator
and inspect the phase of initialization in the single-step mode. Figure
46 shows the content of the Timer1 Register after initialization.
90no) Lo]
Name Value Location
“ AT90S8515
= & cpu
#) & External Interrupts
*! © Timer/Counter)
Cee
© Timer/Courter High 0x00 OxaD
© Timer/CourterLow 0x00 0x20
“1 F® Intenupt Mask Register ITT 0439, bit 7,6,5,3
1 Intenupt Flag Register ITT 0x38, bit 7,6,5,3
2178 ContolRegteA PTT orm
278 ConiolRege® WR TR RT
© Compare A High ox00
© Compare A Low ox00
© Compare B High x00
© Compare B Low 0x00
® Input Capture High ox00
® Input Capture Low ox00
42 Watchdog
29 SPI Interface
29 UART Interface
D Analog Comparator
ett
g
a
Figure 46 Initial State of TCCR1B in CAPTURE1.BAS
Instruction Config Timerl = Counter , Edge = Falling ,
Noice Cancel = 1 , Capture Edge = Rising sets the fol-
lowing bits in register TCCR1B:
ICNC1 | ICES1 cTc1 | Csi2 | Csi1_| CSIO
1 41 0 1 1 0} TCCR1B
The Input Capture Noise Canceller samples pin ICP four times. De-
pending on the chosen capture edge, all four samples must be Hi or
Lo. Bit ICNC1 must be set (Noise Cancel = 1) to activate the
noise canceller. If bit ICNC1 is reset (Noise Cancel = 0), the
noise canceller is deactivated and a single edge will trigger.
The edge for triggering at pin ICP is defined by bit ICES1. If IECS1 is
set, the leading edge will trigger (Capture Edge = Rising). If
91ICES1 is reset, the falling edge will trigger (Capture Edge = Fal-
ling).
Bit CTC1 defines the content of TCNT1 after Output Compare and
has already been mentioned.
The Clock Select1 bits CS1x define the prescaling source of Timer1.
CS12 CS11 CS10_ Description
0 0 0 Stop Timer/Counter1
0 0 1 CK
0 1 0 CK/8
0 1 1 CK/64
1 0 0 CK/256
1 0 1 CK/1024
1 1 0 External Pin T1, falling edge
1 1 1 External Pin T1, leading edge
Parameter Edge = Falling is responsible for the setting of bits
CS1x in Figure 46.
4.2.1.3 Pulse Width Modulation
A pulse series can be controlled by pulse width modulation (PWM).
Figure 47 shows two pulse series of different pulse width or duty.
218
5/8
Figure 47 Pulse series of different duties
The upper pulse series has a duty of 2/8 which means that, in a pe-
riod of eight cycles, two cycles are Hi and the rest of the period is Lo.
The lower pulse series has a duty of 5/8.
If such a pulse series is used for driving an LED, the brightness of
this LED can be controlled by way of the duty.
Listing 18 shows an example with Timer0 as pulse width modulator.
The whole timer period is divided into a Hi and a Lo phase. The ISR
has two paths that will be passed through alternatively.
92Const True = 1
Const False = 0
Dim Hi As Byte
Dim Lo As Byte
Dim A As Byte
Dim Phase As bit
Dim Pattem As Byte ' pit pattem for display
Pwm Alias Portb.0 ' Modulated Pin
' Rate 244 Hz at 4 MHz Clock
Config TimerO = Timer , Prescale = 64
Qn TimerO Timer0_isr ' Jump to Timer0 ISR
Config Portb = Output
Enable Timer ' Enable the timer interrupt
Enable Interrupts ' Enable Global Interrupt
lo = 128 ' Initial value for PM
Phase = True
Do
A = Pind ' Ask for Key
Select Case A
Case &B11111110 :
Case &B11111101 :
Case &B11111011 :
Case &B11110111 :
Case &B11101111 :
Case &B11011111 :
Case &B10111111 :
Case &B01111111 :
End Select
Bi = 255 - Io
Incr Pattem " Change bit Pattern
Waitms 100 " Wait 100 ms
Loop
End
=0 ' Lo Time short
u
w
8
64
96
128
160
192
= 255 | Lo Time long
BBEBBBBBDS
Timer0_isr:
If Phase = True Then
Portb = GFF ' LED off
Timerd = Lo ' Reload Timer
Phase = False
Else
Portb = Not Patten ' LED on
93TimerOd = Hi ' Reload Timer0
Phase = True
End If
Retum
Listing 18 Brightness Control for LED by PWM (PWM0.BAS)
The following tasks are included in the endless loop of the program:
1. Query the key connected to PortD
2. Set Lo time according to the pressed key to reload TimerO
3. Calculate the corresponding Hi time for reloading TimerO
4. Manipulate the bit pattern for display on PortB
5. Include a waiting time
It is very easy to test this program with the evaluation board. After the
start of the program the Lo time is initialized to 128. The LEDs con-
nected to PortB display the changing bit patterns at a mean bright-
ness.
After pressing one of the keys connected to PortD the CASE con-
struct determines a new Lo time, and the brightness of the LED
changes. The blinking rate does not change because the Hi time will
always be adapted to the changed Lo time.
For PWM, Timer1 offers some more features. Timer1 should be
used if a certain precision is expected. In the PWM mode, Timer1
operates as up/down counter comparing TCNT1 with the Output
Compare registers OCR1A and OCR1B permanently. If TCNT1 is
equal to one of the registers OCR1A or OCR1B, then the actions
described next will start.
Digital-to-analog conversion based on PWM is here exemplified by
PWM with Timer1. See the register contents for a better under-
standing. Use the simulator to inspect the initialization process.
Listing 19 is a program example.
Pwma Alias Portd.5 ' Modulated Pins
Pwmb Alias Oclb
Dim Templ As Word ' Used Variables
Dim Temp2 As Word
Config Portb = Output ' PortB is Output
Portb = 255 ' Switch LEDs off
94Config Timerl = Pwm , Pwm = 10 , Compare A Pwm = Clear Down ,
Compare B Pwm = Clear Up
Templ = &H0000 ' Configure Timerl for PWM
Pwnla = Templ
Pwmlb = Templ
Tecrlb = Tecrlb Or sHO2 ' Prescaler = 8
Config Pind.o = Input Configure PortD
Config Pind.5 = Output
Do
bitwait Pind.0 , Reset
bitwait Pind. , Set
Wait for key pressed
Wait for key unpressed
Templ = Templ + 6H10 Increment Variable
Pwmla = Templ Set PWM Registers
Pwmlb = Templ
Temp2 = Templ / sH10 ' Reset 4 LSB and shift right
Temp2 = Not Temp2
Porth = Low(temp2)
Loop
End
Listing 19 Digital-to-Analog Conversion by PWM (PWM1.BAS)
Invert bit pattem
Output bit pattem
Instruction Config Timerl = Pwm , Pwm = 10 , Compare A
Pwm = Clear Down , Compare B Pwm = Clear Up manages
the setup of register TCCR1A completely. Figure 48 shows the con-
tents of register TCCR1A after configuration.
95Value Location *
‘Ye AT90S8515
=-B cpu
= G External Interrupts
+ © Timer/Counterd
® Timer/Counter High 0x00 0x20
© Timer/Counter Low 0x00 0x20
=) 8# Interrupt Mask Register IT 0439, bit 7,6,5,3
4) P Interrupt Flag Register TT
# WwlRegieA = WTR
2-58 ContolRegte BT Pr
® Compare 4 High x00
® Compare A Low ox00
® Compare B High ox00
© Compare B Low 0x00
® Input Capture High x00
® Input Capture Low x00
Figure 48 Initialization of TCCR1A
The bits in register TCCR1A are set as follows:
COM1A1 | COM1A1
COM1B1
COM1B1 | PWM11 | PWM10.
1 0
1 1 | 1 1 TCCRIA
Bits COM1A1 and COM1A0 define the response of output pin OC1A.
Bits COM1B1 and COM1B0 define it for OC1B. The x in the next
table is to be replaced by A or B.
COM1x1 COM1x0 Description
0 0 not connected
0 1 not connected
1 0 Cleared on compare match, up-counting
Set on compare match, down-counting
1 1 Cleared on compare match, down-counting
Seton compare match, up-counting
Bits PWM11 and PWM10 define the resolution of PWM to 8 bit, 9 bit
or 10 bit.
96PWM11 PWM10 Description
0 0 PWM not activated
0 1 8-bit PWM
1 0 9-bit PWM
1 1 10-bit PWM
The resolution defines the counting range of the up/down-counter.
The counting range is always from 0 to TOP (see table). The fre-
quency depends on the counting range, too.
Resolution TOP PWM Frequency
8 bit &HOOFF Ffric (510
9 bit BHOIFF fy, /1022
10 bit &HOSFF f,,-, (2046
The following equation is used for calculating the PWM frequency:
tt cl
QN_ 9
The clock frequency for Timer fric1 is defined by the prescaler and
will be set in register TCCR1B.
Figure 49 shows the content of register TCCR1B after running in-
struction Tccrlb = Tccrlb Or &H02 at the beginning of this pro-
gram example.
Fou =
97ae rr [-[obJ
Name Value Location *
‘Ye AT90S8515
=-B cpu
= G External Interrupts
+ © Timer/Counterd
® Timer/Counter High 0x00 0x20
© Timer/Counter Low 0x00 0x20
#8 Interrupt Mask Register MIMI TT 0439, bit 7,6,5,3
Interrupt Flag Register IT 0438, bit 7,6,5,3
#8 ContiolRegsieA WIR IR OF, bit7.8!
Ce EE Pi G28. bit 7.6.3.2"
ox00 0.28
® Compare A Low ox00 Ox2a,
® Compare B High ox00 0x29
© Compare B Low oxo0 0428
® Input Capture High x00 (025
® Input Capture Low x00 O24
ls
Figure 49 Initialization of TCCR1B
At a clock frequency of 4 MHz a prescaler of eight generates a PWM
frequency of about 245 Hz. Connecting a resistor and a capacitor as
low pass filter to output OC1A or OC1B is all that is needed to get a
simple digital-to-analog converter.
In practice, the low pass can be designed according to this formula:
C= (10..1000)
Foun
If time constant t is too high, the response time will also be high. On
the other hand, if time constant t is too low, the filtering effect will be
poor.
=R
Table 3 shows the output voltages measured across pins OC1A/
OC1B and ground for program example PWM1.BAS.
To simplify matters, no low pass filter was connected. Due to the
integrating measuring principle, the digital multimeter used for meas-
uring had s sufficient filtering capacity.
By pressing the key connected to PinO of PortD, the duty of the PWM
output can be changed. As there is no debouncing, the change is
sometimes greater than expected. The actual duty is displayed by
LEDs connected to PortB.
98Word
PortB
OC1A
OC1B
Word
PortB
OC1A
OC1B
Word
PortB
OCIA
OC1B
Word
PortB
OC1A
OC1B
Word
PortB
OCIA
OC1B
Word
PortB
OC1A
OC1B
Word
PortB
OCIA
OC1B
Word
PortB
OC1A
OC1B
&HO00
&HOO
001
4.93
&H080
&HO8
622
4.32
&H100
&H10
1.23
3.70
&H180
&H18
1.85
3.08
&H200
&H20
247
2.46
&H280
&H28
3.08
1.85
&H300
&H30
3.70
1.23
&H380
&H38
4.32
618
&HO10
&HO1
078
4.86
&HO90
&HO9
.700
4.24
&H110
&H11
1.31
3.62
&H190
&H19
1.93
3.00
&H210
&H21
2.54
2.39
&H290
&H29
3.16
1.77
&H310
&H31
3.78
1.15
&H390.
&H39
4.40
541
&H020
&HO2
156
4.78
&HOAO
&HOA
T77
4.16
&H120
&H12
1.39
3.54
&H1A0
&H1IA
2.00
2.93
&H220
&H22
2.62
2.31
&H2A0
&H2A
3.24
1.69
&H320
&H32
3.86
1.07
&H3A0
&H3A
447
463
&HO30
&HO3
234
4.70
&HOBO
&HOB
855
4.08
&H130
&H13
1.46
3.47
&H1B0
&H1B
2.08
2.85
&H230
&H23
2.70
2.23
&H2B0
&H2B
3.32
1.61
&H330
&H33
3.93
1.007
&H3B0
&H3B
4.55
385,
&HO040
&HO4
311
462
&HOCO
&HOC
932
4.01
&H140
&H14
1.54
3.39
&H1CO
&HIC
2.16
277
&H240
&H24
2.78
2.15
&H2CO
&H2C
3.39
1.54
&H340
&H34
4.01
929
&H3CO
&H3C
4.63
-308
&HO050
&HOS
-389
4.55
&HODO
&HOD
1.01
3.93
&H150
&H15
1.62
3.31
&H1D0
&H1D
2.24
2.69
&H250
&H25
2.85
2.08
&H2D0
&H2D
3.47
1.46
&H350
&H35
4.09
851
&H3D0
&H3D
471
.230
&HO60
&HO6
467
447
&HOEO
&HOE
1.08
3.85
&H160
&H16
1.69
3.23
&H1E0
&HIE
2.31
2.61
&H260
&H26
2.93
2.00
&H2E0
&H2E
3.55
1.38
&H360
&H36
4.17
774
&H3E0,
&H3E
4.78
152
&HO70
&HO7
544
4.39
&HOFO
&HOF
1.15
3.77
&H170
&H17
1.77
3.16
&H1FO
&H1F
2.39
2.54
&H270
&H27
3.01
1.92
&H2FO
&H2F
3.63
1.30
&H370
&H37
4.24
696
&H3FO
&H3F
4.86
075
Table 3 Digital-to-Analog Conversion by PWM
Figure 50 shows the values of Table 3 in a clearly arranged graphic.
995,000
4500
4,000
3,500 |
3,000
—eocriA
—*—OcR1B
Voltage
2,000
1,500 |
1,000 |
0.500
0.000
SESESESESESS ISTE SEES EE
Word
Figure 50 Digital-to-Analog Conversion by PWM
4.2.1.4 Pulse Length Capture
The timers can also be used for capturing the length of a pulse.
Figure 51 shows a pulse series with two different Lo phases, tp; and
ty2.
Figure 51 Pulse series
In the simplest case, the timer is started with a falling edge and
stopped upon detection of the rising edge. The result in the timer
register reflects the measured time. Listing 20 shows program ex-
ample PULSIN.BAS which uses Timer0 for the time measurement.
Declare Fimction Lopulse() As Byte
Dim Value As Byte
Inputpin Alias Pind.o
Config Portb = Output ' PortB Output
Portb = GFF ' all LEDs off
Config Timerd = Timer , Prescale = 1
100On Timer0 Overflow _isr Nosave
Enable Timer
Enable Interrupts
Do
Value
Portb
Loop
End
Lopulse ()
Value
Function Lopulse() As Byte
While Inputpin <> 0 : Wend ' wait for Hi-Lo on inputpin
Tonto = 0 ' veset TimerO
Start TimerO
While Inputpin = 0 : Wend
Stop Timer0 ' stop Timer0 after 26 cycles minimm
Lopulse = Tent
End Sub
' overflow isr stops timer0 and set tcnt0 to zero
Overflow_isr:
tpush R24
Stop Timerd
Tonto = 0
!pop R24
Return
Listing 20 Capturing a pulse length (PULSIN.BAS)
The key for capturing the pulse length is function Lopulse (). After
calling Lopulse() the program waits for a falling edge on Input -
pin. Inputpin is an alias for PinO of PortD (defined in the third
line).
After the detection of a falling edge register TCNTO is reset and
TimerO starts. Timer0 internally counts clock signals (prescaler = 1)
until it is stopped by a rising edge detected on Inputpin.
If the pulse is longer than the TimerO period, a Timer0 Overflow Inter-
rupt occurs. The ISR stops Timer0 and returns to 0.
At a clock frequency of 4 MHz the resolution is (theoretically) 0.25 ps.
The run time from detecting the falling edge to detecting the rising
edge is 26 cycles, or minimum 6.5 us. Therefore the capture range is
between 6.5 us and 64 ps.
101Using the assembler for edge detection will reduce the runtime.
Listing 21 shows the required changes. The changes are marked in
bold.
Declare Fimction Lopulse() As Byte
Dim Value As Byte
Const Inputpin = $10 , 0 ' Inputpin Alias Pind.o
Config Portb = Output ' PortB Output
Porth = SIF ' all LEDs off
Config TimerO = Timer , Prescale = 1
Qn Timerd Overflow_isr Nosave
Enable Timer
Enable Internpts
Do
Value = Lopulse()
Portb = Value
Loop
End
Function Lopulse() As Byte
Sasm
Hilo:
Sbic Inputpin ' wait for Hi-Lo on inputpin
Rjmp Hilo
$end Asm
TontO = 0 ' reset Timerd
Start Timerd
Sasm
Lohi:
Sbis Inputpin ‘ wait for Hi-Lo on inputpin
Rjmp Lohi
Send Asm
Stop TimerO ' stop Timer after 10 cycles minimm
Lopulse = Tonto
End Sub
102' overflow isr stops timer0 and set tcnt0 to zero
Overflow_isr:
tpush R24
Stop Timero
Tonto = 0
!pop R24
Return
Listing 21 Capturing a pulse length (PULSIN1.BAS)
The changed function needs ten cycles to detect a rising edge. The
minimum pulse length that can be captured is now 2.5 us.
Capturing a pulse length without an internal timer is demonstrated in
Listing 22.
Declare Function Lopulse() As Word
Dim Value As Word
Dim Time As Word
Inputpin Alias Pind.o
Config Portb = Output
Porth = &HFF
Do
Value = Lopulse()
Portb = Low(value)
Loop
End
Function Lopulse() As Word
While Inputpin <> 0 : Wend
Time = 0 ‘ reset Time
While Inputpin = 0
Incr Time
Wend
Lopulse = Time
End Sub
Listing 22 Capturing a pulse length (PULSIN2.BAS)
The value of variable Time is proportional to the pulse length. For an
exact time specification the cycles of the second while-wend loop are
responsible.
103At a clock frequency of 4 MHz Inputpin is queried every 7.7 us.
The longer sampling time is due to the data formats used for the
calculations (word for value and time). An overflow check was not
made here.
4.2.2 8051
Most 8051 derivatives have at least two 16-bit timers. These timers
are fairly complex circuits. Registers TMOD, TCON and IE control
the functionality of these timers.
The timer counts the internal clock divided by 12. The timer period
can be calculated according to the following equation:
12
Sosc
The timer can operate in four modes:
e Mode 0: 13-bit timer (8-bit timer with 5-bit prescaler)
¢ Mode 1 : 16-bit timer.
T=2".
¢ Mode 2: 8-bit timer with auto-reload
e Mode 3: 8-bit timer (see datasheet for details)
Typically working at a clock frequency of 12 MHz, the timer clock is 1
MHz. For Mode 1 and Mode 2 the following data are obtained:
Timer at 12 MHz clock frequency
Mode 2 1
Maximum Timer Period 256 us 65.536 ms
Resolution tus tus
Figure 52 shows a block diagram of TimerO / Timer1. For timer con-
figuration BASCOM-8051 has special instructions that set the re-
spective special function registers (SFR).
104RDATE:
frHo,TLo
10.
THoD
[ Fo
Figure 52 Block diagram of 8051 timer
To configure TimerO, the following bits have to be set/reset in the
TMOD and TCON SFRs. At the beginning it is good practice to verify
this setup in the simulator.
Config TimerO = Counter 1 -> C/T
Config TimerO = Timer 0 -> C/T
Config Gate = External 1 -> Gate
Config Gate = Internal 0 -> Gate
Config Mode = 0-3 00-11 -> M1, MO
Start Timero 1 -> TRO
Stop TimerO 0 -> TRO
In Listing 23, Timer is initialized as timer in mode 2. The timer oper-
ates as a reloadable 8-bit timer with a period of 250 —s. When 250 us
are exceeded, the timer overflows and interrupts the program.
Interrupt handler timer0_isr increments a counter variable. After
4000 timer interrupts, P3.5 is toggled and the same procedure starts
again.
If an INTO interrupt occurs, the reload value for TimerO is manipu-
lated, and the blinking rate changes.
105In the main loop of the program, P1.7 is toggled every 100 ms to
demonstrate some activity of the main program.
This program can be run in the simulator. Reducing the value of
Ms_delay has a favorable effect in the simulation.
' TimerO for 8051
Dim Ms_cntr As Integer
Dim Ms delay As Integer
Dim RI_value As Byte ' Reload value for Timerd
' Timer0 is a reloadable 8-bit Timer
Config Timero = Timer , Mode = 2
On Timer0 Timer0_isr
Qn Into Into_isr
Main:
Rl_value = 250'Timer0 Overflow after 250us at 12 MHz
Ms_cntr = 0 ‘Init Ms_cntr
Ms_delay = 4000 "Delay of 4000 x 250us = 1000 ms
Gosub Init_io
Gosub Init_timerd
Enable Interrupts ‘Global Interrupt Enable
Do
P1.7 = Not P1.7 "Do Anything Forever
Waitms 100
Loop
End
' Interrupt Handler
TimerO_isr: ‘Handler for Timer0 Overflow
Incr Ms_cntr
If Ms cntr = Ms delay Then
Ms cntr = 0
P3.5 = Not P3.5 "Toggle P3.5
End If
Retum,
Int0_isr:
Rl _value = Rl_value / 2 ‘Change R1_value Value
Stop Timero
Load Timer0 , Rl_value ‘SetUp Timer0 with changed RI_value
Start TimerOd
P3.7 = Not P3.7 "Toggle P3.7
RetumInit_io:
7 a
5 a
Set Toon.0 ‘Falling edge triggers INTO
Enable Into ‘Enables INTO
Return
Init_timero
Load Timerd , R1_value "Store Rl_value in Timerd
Enable Timerd ‘Enable Timer0 Overflow Interrupt
Start TimerOd ‘Start Timerd
Returm
Listing 23 Timer example (TIMER.BAS)
4.3 LED Control
LEDs or displays based on LEDs are widely used for simple display
functions. Their advantage is the excellent visibility. In most cases,
however, this advantage must be paid for with a high power con-
sumption.
4.3.1 Single LED
LEDs can be directly driven from the pins of AVR microcontrollers.
Due to the electrical specifications it is advantageous to connect the
LEDs as is shown in Figure 53.
The following equation is used to calculate the series resistances:
V
R=—< =,
in Ve
I,
OL,
LED
According to the datasheet of the AT90S8515, the output voltage VoL
is 0.6 V maximum at a current of 20 mA.
If an LED is intended to be driven at a current of 10 mA, the series
resistance can be determined using the parameters Voc = 5V, Vie =
4,5 Vand Vo. = 0.3V(R= 320Q).
However, if the resistors shown in Figure 53 are used the current
flowing through the LEDs will be lower.
107— meser
>was of
— | roocxo) (avo) Pan
7 —J xa ALE
x ras ip |
— | Po7qr) aor) par L—
Poe CWA) cade) PAD |-—
PDS(OCtA) (ADs) PAS | —
—] Poa) (napa | —
SS TSS POSGNTI) (ADS) RAs
* ii | ~ POZ(INTO) —(AD2) PAZ
— rote) otras PL
PET(SCK) (AIS) PCT
tape
PBICTt) (aa) Pct
PBO(TO) (ss) pco f—
Figure 53 Connecting LEDs to PortB
4.3.2 Seven-Segment Displays
Seven-segment displays can display the figures of our numbering
system and a couple of special characters.
There are many types of seven-segment displays from different
manufacturers. Basically, this type of display consists of a number of
LEDs with connected anodes or cathodes.
In our application example, the type SA03-11 display made by King-
bright is used. Figure 54 depicts such a display.
Gg
Figure 54 Seven-Segment Display SA03-11
Caution: To connect an LED display to the port of any micro-
controller, adhere to the connecting diagram of the display used.
108Figure 55 shows the segment assignment and pin configuration of an
SA03-11 display.
a} by) ¢| 4) e] ft! 9) DPQ
1 913 108 7 2 119
PIN 4 , 5, 12 NO PIN
PIN 6 NO CONNECTOR
Figure 55 Segment Assignment and Pin Configuration of SA03-11
To display alphanumeric data with such a seven-segment display, it
is necessary to define the control scheme.
As can be seen in Figure 55, the anodes of the individual LEDs are
interconnected. If a cathode resistor is connected to a microcontroller
pin, the LED can be switched on and off. Lo at the controlling pin
switches the LED on, and Hi switches it off.
Table 4 shows the segment control for characters 0 to 9 and A to F
as is required for displaying hexadecimal numbers.
109Character Segments Output
&H40
&H79
&H24
&H30
&H19
&H12
&HO2
&H78
&HOO
&H10
&HO08
&H03
&H46
&H21
&HO6
&HOE
TAMIDQNODPFOCHNADAWNAD
CSCOA20CCO200CCO=R34
SCO2DDDDCOA0 COBH Ols
CODDDO202 0222 0+0]o
ACDDO2002=00-00-0]0
BA2O20CCOCOOCOCOA0—0]o
BBOB BDDC OBA CCC COls
CO202=00CC COCO <0]p
Table 4 Segment Control
Chapter 0 lists the complete character set of a seven-segment dis-
play. This table permits a lot more characters to be defined. No more
than seven bits of the control byte are required for the complete
character set. The MSB can control the decimal point.
Listing 24 shows a program example that displays the characters 0 to
F on a seven-segment display continuously.
Config Porta = Output ' PortA Output
Porta = 255 ' all segments off
Dim I As Byte
Dim X(16) As Byte ' Array for controlling bit patterns
Restore Value_table
For I= 10 16 ' Read data in array
Read X(i)
Next
Do
For I= 10 16
Porta = X(i) ' Display character
Waitms 250 ' Wait .5 seconds
Waitms 250
Next
110Loop
End
value _table:
Data &H40 , SH79 , SH24 , SH30 , SHI9 , SHI2 , SHO2 , SH78
Data 6&HOO , &H1O , &HO8 , SHO3 , SH46 , 6H21 , SHOG , SHOE
Listing 24 Control of Seven-Segment-Display by AVR
(7SEGMENT.BAS)
The controlling bit patterns (see Table 4) are stored in the ROM ina
table named Value_table.
Upon program start, the ROM table is copied to array X which makes
access to the array (indexed variable) quite simple.
Characters 0 to F are displayed in an endless loop. The two instruc-
tions waitms 250 generate a waiting time of half a second. Two
wait instructions are needed because the argument has byte format
and is limited to 255!
With the exception of port I/O, program 7SEGMENT.BAS has no
AVR specific instructions. To port this program to 8051, all that is
required is to adapt the I/O related instructions. Listing 25 shows the
modified program for 8051 microcontrollers. The modifications are
marked in bold characters.
' Seven-segment control by AT89C2051
$sim ' comment for nommal operation
Pl = 255
Dim I As Byte
Dim X(16) As Byte
Restore Value_table
For I = 1 To 16
Read X(i)
Next
Do
For I = 1 To 16
Pl = Not X(i) ' inverted for simulation only
Waitms 250
Waitms 250
Next
Loop
111End
Value_table:
Data SH40 , 6H79 , S424 , &H30 , SH19 , SH12 , SHO2 , S&H78
Data SHOO , &H10 , &HO8 , SHO3 , SH46 , SH21 , SHOG , SHOE
Listing 25 Control of Seven-Segment-Display by 8051
(7SEGMENT.BAS)
In Listing 25 the output instruction was enhanced by the operator
not. The reason is the BASCOM-8051 simulator which was used for
program testing. Pressing the LCD button causes a display window
to appear that contains a seven-segment display, too. Figure 56
shows the open window. As the segments of this display are
switched on at Hi, the polarity had to be changed.
112ZBASCOM simulator
ofr =) S{| [e*| selec
| INTO. int | io | 1 SER |
Variables | Break |
Sf
BEE
Variable [Value [Hex Bin
i 5 oo000005 — 9000000000000101
Hii ‘oo000€6 —o000000011100110
cece |
eee
© Restore Value_table
O For I = 1 To 16
O | Read Ki)
O Next
Do
O For I= 1 To 16
° PL = Not K(i)
Om| Vaitms 250
°° Waitms 250
o Next
© Loop
‘
© Pauzed — 925(7,0036892361111 ms) Max stack: 38
Figure 56 Seven-Segment Display in BASCOM-8051 Simulator
BASCOM-8051 offers the flexibility to assign the segments to any
available pin. Right-click the seven-segment display to edit the prop-
erties of this display. Figure 57 shows how to edit the digit properties.
113Figure 57 Pin Assignment
4.3.3 Dot-Matrix Displays
In most cases, a dot-matrix display uses a 5 x 7 LED matrix for dis-
play purposes. As is common with LCDs, a lot more characters can
be displayed.
As an example, Figure 58 shows a dot-matrix TAO7-11 made by
Kingbright.
Figure 58 Dot-Matrix Display TAO7-11
To control such a dot-matrix display, the assignment of these 35
LEDs to the pins of the display must be known. Figure 59 shows the
internal circuit diagram of the TAQ7-11.
Column connections C1 to C5 link up the anodes of all LEDs in a
certain column. Row connections R1 to R7 do the same for all LEDs
in a certain row.
To switch a LED in the first column and third row, for example, line
C1 must be connected to Vcc and line R3 via a series resistor to
GND.
114TAO7-11
PINT 3 10 7 8
c1 02 C3 C4 CS
C1 C2 C3 C4 CS
Figure 59 Internal Circuit of Dot —Matrix Display TAO7-11
As shown in Figure 59, five column lines and seven row lines are
needed to control all LEDs of a 5x7 dot-matrix display. Without extra
hardware, each further display needs five additional column lines.
If a dot-matrix display is to be used as a character display, define the
characters to be displayed first. Figure 60 shows a graphic character
as an example. Let us define these characters next.
@O000000
@@00000
@e@e@0000
@ee@e@000
@©e0008000
Figure 60 Character to be defined
The LCD Designer, a tool included in BASCOM, can be used not only
for LCDs but for this purpose, too. Figure 61 shows the character to
be defined with the LCD Designer tool.
115Clear all
Setall
| 7 Ok
% Cancel
Figure 61 Design of a character
The LCD Designer generates the following instruction for this special
character:
Defledchar ?, 224, 224, 225, 227, 231, 239, 255, 224
' replace ? with number (0-7)
Of this instruction only the generated bit patterns are of interest here.
These bit patterns are saved in the memory with a DATA instruction
as follows:
Dotmatrix:
Data 224 , 224, 225 , 227, 231, 239, 255, 224
These eight bytes describe the bit pattern of the pixel lines from top
to bottom. Only five bits of each byte are significant.
The dot-matrix display is driven column after column. Therefore we
need bit patterns for columns, not for rows as generated by the LCD
Designer. The required conversion can be performed by the micro-
controller during initialization.
Figure 62 shows the circuit for driving the dot-matrix display. For
more clarity, the circuitry for PortA and PortC is presented only.
116JRESET
XTAL2
TALI
PD7 GRD)
PD6 (WR)
PDS (OCTA)
PD4
PD3 (INT1)
PD2 (INTO)
PD1 (TXD)
PDO (RxD)
Pa? (scky
PBB (MISO)
PBS (MOS!)
Ppa (SS)
PB3 (AINT)
PB2 (AINO)
Pet 1)
PE (TO)
ocie
ALE
icp
(ADT) PAT
(AD6) PAB
(D5) PAS
(AD4) PAS
(aD3) PAS
(D2) PA2
(D1) Pat
(D0) Pao
(ais) POT
(1d) PCB
(13) PCS
(12) PCa
(ait) PCa
(ato) PC
(AS) PCH
(a) PCO
Figure 62 Control Circuit for Dot-Matrix Display TAO7-11
Listing 26 is a program example for the display of a character gener-
ated by the LCD Designer as described.
' Control of Dot-Matrix Display by AVR
Dim A(5) As Byte
Dim I As Byte , J As Byte
Dim X As Byte , ¥ As Byte
Config Porta = Output
Config Porte = Output
Restore Dotmatrix
For I =0T07
If Y > SH7F Then
Set X.i
all rows Hi
all colums Lo
convert rows to colums
read from table
shift 3 MSB
test for MSB
117Else
Reset X.i
End If
AG) =x
Shift Y , Left
Next
Next
Set X.i ' set accessed columm Hi
End
Dotmatrix:
Data 224 , 224 , 225 , 227 , 231 , 239 , 255 , 224
Listing 26 Controlling a Dot-Matrix Display (DOTMATRIX2.BAS)
PortA serves as driver for the row lines. PortC drives the column
lines of the dot-matrix display. After initialization all LEDs of the dis-
play are switched off.
The conversion of the bit pattern from pixel rows to pixel columns
starts after resetting the data pointer to the first data byte of the bit
patterns. Because the three most significant bits of each pixel row
are not needed, they are cancelled by _ instruction
Shift Y , Left , 3. As shown in the next table, the remaining
five bits in each pixel row are inspected column by column. So the
pixel positions in variables A(1) to A(5) will be set or reset bit by bit
starting at the LSB.
224
224
225
227
231
239
255
224
ons2c0000
Onaaasco
Sloszcoo000
GBIOt 2320000
>
RlOa+2Aa2320CO
>
NS
>
>
118At a clock frequency of 4 MHz the whole conversion process takes
about 2.2 ms. This time will not be noticed during initialization.
An endless loop drives the dot-matrix display by outputting the con-
verted bit pattern column after column.
For enhancing the display to several devices either more column
driver lines (five for each device) or extra hardware for multiplexing
are required.
4.4 LCD Control
LCDs are receiving advanced features for the display of information.
The number of low-priced LCDs offered on the market is immense.
Fortunately, the HD44780 LCD controller by Hitachi or compatible
devices are used in most cases for alphanumeric displays.
Basically, it is distinguished between two kinds of device control. In
the direct mode the pins of the microcontroller drive the lines of the
connected LCD directly. In the other case, some LCDs are equipped
with a standardized RS232 or I°C interface. The number of required
interface lines decreases. For small microcontrollers, it is often the
latter aspect that is of importance.
4.4.1 Direct Control
The LCD controller type HD44780 provides the connected microcon-
troller with an 8-bit bus and a number of control lines. The pins of
such an LCD module have the following meanings:
Pin Designation Level Function
1 Vss GND GND
2 Vop +5V Supply voltage
3 Vo 0...+5V Contrast control
L: Instruction register
4 RS HL H: Data register
L: Read access
7 a Le H: Write access
6 E HIL Enable
7-14 DBO - DB7 H/L. Data lines
119There are two ways to connect a microcontroller in the direct mode.
See Figure 14 for configuring the connection mode.
If the microcontroller circuit works with an external memory or mem-
ory-mapped I/O, then a data bus exists and the LCD can be con-
nected in the bus mode. The SetUp of the STK200 evaluation board
has already been shown in Figure 14. Figure 63 depicts the connec-
tion of an LCD module with LCD controller HD44780 to the data bus
and the control lines of an AT90S8515 microcontroller.
JRESET
XTAL2 ALE }—
XTALY ioe bp
POT YRD) = (ADT) PAT |} ~~.
PDB (WR) = (ADB) PAB Jam
PDS (OC1A) (ADS) PAS PJ
PDs (AD4) PAG
PO3(NT1) —(AD3) PAB
PD2 (INTO) —(AD2) PA?
PDI (TxD) (D1) PAt
PDO(RXD) (ADO) PAD
PBT(SCK) (A158) POT
PBG (MISO) (A14) PCB
PBS(MOSI — (13) PCS
PB4 (SS) (12) PC4
PB3 (AIN1) (A11) PC3
PB2 (AINO) (aio) PC2 -}K—_ i
PBI (TI) @gyPC1 }— | *
PBO (TO) (as) PCO -}——
] )
| CoH.
Figure 63 LCD Connected to AT90S8515 in Bus Mode
The LCD controller type HD44780 has two internal 8-bit registers that
can be accessed from the connected microcontroller.
The instruction register (IR) saves the received commands (RS = 0).
The data register (DR) saves data (RS = 1) which are sent to the
Data Display RAM (DD RAM) or Character Generator RAM (CG
RAM). Address line A14 distinguishes between instructions and data.
120Together with the Read/Write signals, address line A15_ controls the
Enable line of the LCD module. A falling edge at the Enable input (E)
of the LCD controllers latches the data (D7-D0).
If there is no external bus the LCD can be connected in the pin mode
which means the SetUp must assign the pins of the LCD to the cor-
responding pins of the microcontroller.
The below table shows possible assignments:
LCD Pin Port
DB7 14. PORTB.7
DB6 13 PORTB.6
DBS 12 PORTB.5
DB4 11. PORTB.4
E 6 PORTB.3
RS 4 PORTB.2
RW 5 GND
Vss 1 GND
Vas 2 +5 Volt
Vo 30-5 Volt
In this configuration PORTB.1 and PORTB.0 (and the other Ports not
used here) are available for other purposes.
After correct initialization in the LCD SetUp the LCD can be con-
trolled using comfortable LCD instructions. Listing 27 shows a simple
LCD control program for a first test.
121' LED Control by AVR and 8051
$sim ' for similation only otherwise comment
Dim A As Byte
ML:
A = Waitkey()
If A = 27 Then Goto M2
cls
Upperline
Led A
Lowerline
Led Hex (a) ‘uncomment for AVR
' Ledhex A ‘ unconment for 8051
Print Chr(a)
Goto ML
v2:
End
Listing 27 LCD Control (LCD.BAS)
The program waits for a character to be sent. If the character sent is
ESC the program will end. Otherwise, the display (16 characters, 2
lines) shows the received character on both lines in different formats.
If one prefers to go inside BASCOM, then the internal routines can
be used, too. The following is an example for BASCOM-AVR.
SASM
Idi _templ, 5 ‘load register R24 with value
Reall _Ied control ‘it is a control value
"to control the display
Idi _temp1,65 "load register with new value (letter A)
Reall Write lod ‘write it to the LCD-display
SEND ASM
Subroutines _1cd_control and _write_lcd are written in as-
sembler and can be called from BASIC.
4.4.2 LCD with Serial Interface
LCDs with a serial interface offer a simplified connectivity. In the sim-
plest case two wires (TxD & GND) from the microcontroller to the
LCD are sufficient.
The comfortable LCD instruction cannot be used for this kind of LCD
control. Some knowledge of the LCD controller is required.
122As the DD RAM of the HD44780 LCD controllers has 80 bytes, one
HD44780 LCD controller can control one LCD with four lines of max.
20 characters each.
Table 5 shows the LCD position and DD RAM address for a 4x16
LCD (LM041L etc.) as an example.
DD
RAM 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1.Zeile 00 01 02 03 04 05 O06 O07 08 O09 OA OB OC OD OE OF
2.Zeile 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
3.Zeile 10 11 12 14 13 15 16 17 18 19 1A 1B 1C 1D 1E 1F
4.Zeile 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D _5E_ 5F
Table 5 Display position and DD RAM address for LCD 4x16
As shown in Table 5, not all memory space is used for display in a
4x16 LCD. DD RAM not used for the display is available as external
RAM. The access to that external RAM requires a complete RS-232.
Table 6 shows an extract from the instruction set of an HD44780LCD
controller. Table 7 describes some designations in Table 6.
123iction
RS DB7 ODB6 DB5 DB4 DB3 DB2 DB1 DBO Description
“Display
or At
;
intry Mode
ay On/Off
or/Display
tion Set
~G RAM
1D RAM
Write
0 0 0 0 0 0 0 0 1 Clears display
and sets cursor
to home position
0 0 0 0 0 60 60 14. X_ Sets cursor to
home position
0 0 0 0 0 0 1 VD S Defines direction
of cursor and
shift movements
0 0 0 0 0 1 D c B See explana-
tions of D, C,
and B
0 0 oO 0 4 SCG RL X X_ See explana-
tions of SIC and
RIL
0 0 0 1 DL N F x X — See explana-
tions of DL, N,
and F
0 0 4 ACG Sets CG RAM
address
o 14 AD Sets DD RAM
address
1 Deta Writes byte in
DD RAM or CG
RAM
Table 6 Coding of Instructions of LCD Controller HD44780
Name Description
After writing a character to RAM, the DD RAM or CG RAM address will be
VD incremented (I/D = 1) or decremented (I/D = 0).
Moving the contents of display to the right (S = 1) or left (S = 0)
S Cursor position does not change (calculator).
D__ Display on (D = 1) or off (D = 0). Data in DD RAM remain unchanged.
C Cursor on (C = 1) or off (D =
B Cursor blinking (B = 1) or not blinking (B = 0).
Moves the contents of display (S/C = 1) or the cursor (S/C = 0) by one posi-
SIC tion according to RIL.
RIL Moving to the right (R/L = 1) or left (R/L = 0) without changes in DD RAM.
DL Data bus 8 bit (DL = 1) or 4 bit (DL = 0).
N Number of display lines - one (N = 0) - several (N = 1).
F Font- 5x7 dots (F = 0) - 5 x 10 dots (F = 1).
X__Don't care.
Table 7 Explanation of instruction set of HD44780 LCD controllers
After this short description of the basics of LCD controller type
HD44780, the next program example can be interpreted.
124Listing 28 shows a BASCOM-AVR program controlling an LCD via
RS-232. Due to the serial interface all commands for the LCD con-
troller must be sent by print instructions from the microcontroller.
This program example is based on a serial LCD from Scott Edwards
Electronics [http://www.seetron.com]. Scott's web site offers a lot of
information about all types of LCDs.
' SW_UART.BAS for AVR
' Controlling a LCD with LCD Serial Backpack from
' SEETRON:
' C. Kuehnel
* 1999-11-21
Const Instr = 254
Const Clr =1
Const Led blank = 8
Const Led restore = 12
= 6880
HCO
8HO4
sHD4
Config Portd = Input
Porta = 956
Open "COMC.0:2400,8,N,1, inverted" For Output As #1
Print #1, Chr(instr) ; Chr(clr);
Print #1, Chr(instr) ; Chr(linel) ;
Print #1, "BASCOM-AVR writes to";
Print #1, Chr(instr) ; Chr(line2) ;
Print #1, "4 line/20 colum LoD";
Print #1, Chr(instr) ; Chr(line3);
Print #1, "via serial interface";
Print #1, Chr(instr) ; Chr(line4);
Print #1 , "from www.seetron.com!';
Wait 5
125While Pind.o = 1
Print #1 , Chr(instr) ; Chr(1cd blank) ;
Waitms 200 : Waitms 200
Print #1 , Chr(instr) ; Chr(1lcd_restore) ;
Wait 1: Waitms 250 : Waitms 250
Wend
Close #1
End
Listing 28 Control of a Serial LCD (SW_UART.BAS)
A number of constants are declared in the first part of the program.
PortD is initialized as input because the program looks for PinO of
PortD to run or end.
Before any display the serial interface must be initialized, too. No
complete serial interface is needed for this program example; the
transmit line (TxD) will do. Therefore, the UART software is good
enough for this purpose.
The asynchronous serial communication will be discussed in chapter
4.7. You may read this chapter to get first information, or accept the
initialization of the UART software with Open "COMC.0:2400,8,N,
1,inverted" For Output As #1 and the data output with
Print #1 , ... first. The data are output from PinO of PortC of
the microcontroller used at 2400 baud and with inverted polarity.
We have to distinguish between two types of data output:
Print #1, Chr(instr) ; Chr(linel);
Print #1 , "BASCOM-AVR writes to";
In the first instruction, data byte instr announces a command
(RS=0). The command itself is the data byte line (DD RAM = 00)
which sets the data pointer to the first position in DD RAM.
The second instruction transfers data to be displayed to the DD
RAM, starting at the preselected location.
Before entering the while-wend loop all data are written to the LCD.
In the loop, the display is cleared and reactivated (Restore) periodi-
cally. Because the arguments for instructions Wait and Waitms are
limited to one byte, several wait instructions need to be added to
generate longer wait times.
In BASCOM-8051 it is different. The UART software only supports
the GET and PUT statements, and the PRINTBIN and INPUTBIN
126statements to retrieve and send data. It is not possible to simply send
a string with print "abcdefg". COM1 and COM2 are hardware
ports that can be used with PRINT etc.
Listing 29 shows the LCD control program ported to BASCOM-8051.
PinO of Port1 serves as key input. The UART hardware sends the
data to the serially connected LCD.
' Serial_LOD.BAS for 8051
* Controlling a LCD with LCD Serial Backpack from
' SEETRON:
' C. Kuehnel
* 2001-01-01
Const Led blank = 8
Const Led restore = 12
Const Linel = sH80
Const Line2 = sHCO
Const Line3 = sH94
Const Line4 = sHD4
Dim I As Byte
Dim Key As Bit
Qpen "COM1:2400, inverted" For Output As #1 " RS232 inverted!
Print #1 , Chr(command) ; Chr(clr);
Print #1 , Chr(command) ; Chr(linel) ;
Print #1 , "BASCOM-AVR writes to";
Print #1, Chr(command) ; Chr(line2) ;
Print #1, "4 line/20 colum LoD";
Print #1 , Chr(command) ; Chr(line3);
Print #1, "via serial interface";
Print #1 , Chr(command) ; Chr(line4) ;
Print #1 , "from www.seetron.com";
Wait 5
Do
Print #1 , Chr(command) ; Chr(1cd_blank) ;
127Waitms 200 : Waitms 200
Print #1 , Chr(command) ; Chr(1cd_ restore) ;
Wait 1: Waitms 250 : Waitms 250
Key = P1.0
Loop Until Key = 0
Close #1
End
Listing 29 Control of a Serial LCD (SERIAL_LCD.BAS)
4.5 Connecting Keys and Keyboards
Keyboards for microcontrollers need not have the same features as
keyboards for PCs. Often simple keypads as shown in Figure 64 are
sufficient for input purposes.
This kind of keypad is available in two types:
e 1x12 single keys
© 3x4 key matrix
Figure 64 Keypad
If there are enough I/O lines available then the single key version can
be used. If not, three I/O lines can be saved when the key matrix is
used.
1284.5.1 Single Keys
In the single key version (1x12) the keypad shown in Figure 64 has
the internal connections shown in Figure 65.
All keys of the keypad are wired up on one side and connected to
pint. The other side of each key is connected to one of the pins 2 to
13.
Figure 65 Internal Wiring of Keypad 1x12
Figure 66 shows how to connect such a keypad to a microcontroller.
To simplify the diagram the keypad was reduced to four keys.
129°
oe
—
—
Figure 66 Reduced Keypad
The wired end (COMMON) of all keys is connected to GND. The
other side of each key is connected via pull-up resistors to the supply
voltage.
Most microcontrollers have internal pull-up resistors at their I/O ports.
These internal pull-up resistors can be used to reduce the number of
components on your board (initialize correctly!).
The next two lines of the code show the initialization of a port as input
with internal pull-ups for AVR microcontrollers.
Config Porta = Input ' Porta is input
Porta = 255 ' with internal pull-up
The first line initializes the data direction registers for input, and the
second line sets the data register to Hi to enable the pull-up resistors.
Pressing a key generates a falling edge at the respective I/O pin, and
the microcontroller can detect this event.
It is important to consider the bouncing of all kinds of mechanical
keys. Debouncing is no issue under BASCOM: debounce is a very
helpful instruction. Listing 30 shows the query of the reduced keypad
using the debounce instruction.
130' Query a keypad by AVR
Const Keys = 4
Config Portb = Output
Config Porta = Input
Porta = 255
Config Portc = Input
Portc = 255
Dim I As Byte
Dim Key As Byte
Port = 255
Do
For I = 1 To Keys
Key = 1
Select Case Key
Case 1 : Debounce Pina.0
Debounce Pina.1
Debounce Pina.2
: Debounce Pina.3
Case 2
Case 3
Case 4
End Select
Next
Loop
End
Display key:
Porth = Not Key
Retum
Test for 4 keys only
' Porth is output.
' Porta is input
' with internal pull-up
' Port is input
' with internal pull-up
' variable contains key number
' Switch LEDs off
' Query all keys
0 , Display_key , Sub
0, Display key , Sub
0, Display key , Sub
0, Display key , Sub
Display key number by LED
Listing 30 Query of a Keypad by AVR (KEY1.BAS)
Listing 31 shows the slightly modified program for an 8051 micro-
controller. The differences result from the differing port I/O only.
' Query a keypad by 8051
Const Keys = 4
Dim I As Byte
Dim Key As Byte
' Portl is drives LEDs
1 = 255
' Test. for 4 keys only
' Variable contains key number
' Switch LEDs off
' Port2 is input with intemal pull-up
131P2 = 255 ' needed for input
Do
For I = 1 To Keys ' Query all keys
Key = I
Select Case Key
Case 1 : Debounce P2.0 , 0 , Display key , Sub
Case 2 : Deboumce P2.1, 0 , Display key , Sub
Case 3 : Deboumce P2.2 , 0 , Display key , Sub
Case 4 : Debounce P2.3 , 0 , Display key , Sub
End Select
Next
Loop
End
Display key:
Pl = Not Key ' Display key number by LED
Retum
Listing 31 Query of a Keypad by 8051 (KEY1.BAS)
4.5.2 Matrix Keypad
If there is only a limited number of I/O lines available for the keypad,
a matrix keypad will be the better solution.
Figure 67 shows the changed internal wiring for the same keypad.
The single keys are wired up in the form of columns and rows, with
pins 1 to 3 connecting the columns and pins 4 to 7 the rows.
Pressing key "1" connects pin 1 and pin 7, for example.
132"5 _s"s a
ve | in .
ws oe oe
| "7" "8" | “9”
as 3%. Fe
nen "9" nn
+ as a
| fi]
r| ~{2]
| —dttt 4
ee
Figure 67 Internal Wiring of a 3x4 Keypad
Figure 68 shows how to connect a matrix keypad to an AVR micro-
controller when internal pull-up resistors are used.
133—| reset
ocig -—
xTaL2 ALE
tat op
— | Por uD) woz) PAY |}
D8 (MIR)
5 (OCT)
a
3 ANTI)
PD2 (NTO)
| Poimm) gota
——| PD0 (RxD) 00) FAD
Par ck) ats) Pe7 }—
——| Psaisoy aay pce L—
J pas qios) aay pcs
PB4YSS) GAIN PCA
PasAINT) — @@l)PCo
——| parang) — catoppce
ag Pci
P80 (70) (=) PCO
| —] parc
Figure 68 Connection of a Matrix Keypad
Pins PD4 to PD7 serve as inputs with internal pull-up resistors. Pins
PDO to PD2 set the queried column line to Lo.
A query of a matrix keypad divides into several queries of key col-
umns. Listing 32 shows two interlocked loops to query this matrix
keypad for an AVR microcontroller.
* Query a matrix keypad by AVR
Config Portb = Output
Ddra = 6HOF
Porta = SHEF
PD7-PD4 Input; PD3-PDO Output
with internal pull-up
Dim Colum As Byte
Dim Row As Byte
Dim Key As Byte ' Variable contains key number
Porth = 255 ' Switch LEDs off
Do ' Query all keys
For Colum = 0 To 2
If Colum = 0 Then Reset Porta.0
If Colum = 1 Then Reset Porta.1
If Colum = 2 Then Reset Porta.2
‘If Colum = 3 Then Reset Porta.3
For Row = 4 To 7
Select Case Row
134case 4 : Debounce Pina.7 , 0 , Calc key , Sub
case 5 : Debounce Pina.6 , 0, Calc key , Sub
Cage 6 : Debounce Pina.5 , 0, Calc_key , Sub
Case 7 : Deboumce Pina.4 , 0 , Calc_key , Sub
End Select
Next
Porta = SHFF
Next.
Loop
End
Calc _key:
Select Case Row
Case 4 : Key = Colum +1
Case 5 : Key = Colum + 4
Case 6 : Key = Colum +7
Case 7 : Key = Colum + 10
End Select
Portb = Not Key
Return
Listing 32 Matrix Keypad Query (KEY2.BAS)
In the inner loop For Row = 4 to 7 ... Next the keys of one
column will be queried. The column to be queried is activated in the
outer loop For Column = 0 To 2 ... Next by resetting the
respective I/O pin.
To query a 4x4 matrix (hex keypad, for example) the column query
must be changed to For Column = 0 To 3 ... Next.
Additionally, BASCOM-AVR has the function GETKBD () for querying
a 4x4 matrix keypad. See the BASCOM-AVR help for the required
details.
Instruction Config Kbd = Porta assigns any port of the AVR to
the matrix keypad. A keypad query now needs one function call only.
The next program lines show how easy it is to encode a keypad in-
put.
135Config Kod = Porta
Config Porth = Output
Dim Value As Byte
Value = Getkbd()
Portb = not Value
4.5.3 PC-AT Keyboard
PC-AT keyboards are nowadays offered at low prices and can be
used in microcontroller applications which don't use the whole func-
tionality. Old PC-XT keyboards have a different functionality and
won't be dealt with here.
The PC-AT keyboard sends a scan code when a key is pressed or
released. The BIOS of the PC evaluates this scan code.
Pressing key "A", for example, causes the keyboard to send the scan
code &H1C (Make Code). If the key is kept pressed, the keyboard
will send this scan code again after a defined time. This procedure
repeats as long as that key is pressed, or another key is pressed.
After releasing the key, the keyboard sends the scan code &HFO
followed by &H1C (Break Code). The Break Code differs from the
Make Code by the leading byte &HFO.
As shown in Figure 69, each key has its own scan code. Whether the
Shift key needs to be pressed is determined by the PC BIOS. In the
same way the PC BIOS controls the LEDs in the keyboard when one
of the keys Num Lock, Caps Lock or Scroll Lock is pressed.
136( M(B (E (B See 3) (Fi) (Fa) (Fa?
(ce) (45) GE) 5) 8) Ge) Se) Ge) 2) Gs) G2) (ee) Gs) (40) 5)
EB IESICOLETICTICSIESIESIOUICTICIE SIE)
caps 5A,
ie) Lis) 2) bs) GU) Js) bes) ene
wl)
| iW (WB wWAE
(oH (a If SPACE
14 1 29
Alt Ci
JLeths E014
Figure 69 Scan Codes of a PC-AT Keyboard
It is, however, definitely wrong to think that the 101 keys of a PC-AT
keyboard generate 101 different scan codes in byte format.
Some keys are so-called Extended Keys. Their scan codes have a
leading &HEO. Pressing key Pause generates the following sequence
of scan codes: &HE1, &H14, &H77, &HE1, &HFO, &H14, &HFO,
&H77!
Since the microcontroller is not supported by a BIOS, the scan codes
must be decoded in the application program. BASCOM-AVR sup-
ports querying the PC-AT keyboard by function Getatkbd () .
Before discussing the software, it is worthwhile to have a closer look
at the hardware interface between PC-AT keyboard and microcon-
troller.
Figure 70 shows the available connectors for a PC-AT keyboard (DIN
and PS/2 connector). As can be seen from pinout, the data exchange
is synchronous and serial. The data line is bidirectional. The clock is
always generated by the PC-AT keyboard.
Figure 71 shows the simple interfacing of a PC-AT keyboard to an
AT90S8515. Any pin can be chosen for this kind of interface.
1374 - Clock are
2-n.c.
an 3-GND
4-GND pape
5-+5V oe
6-n.c.
Figure 70 DIN and PS/2 Connector of PC-AT Keyboard
PC-AT Keyboard
Interface a
octe
XTAL2 ALE
XTALI oP.
[3V} | POT (RO) (ADT) PAT
PDB (WR) (ADE) PAB
PDS(OC1A) (ADS) PAS
PDA
—
PD3 (INT1) (AD3) PAB
KBD CLOCK >— PD2(INTO) —(AD2) PAZ
PD1 (TXD) (AD1) PAI
PDO (RXD) (ADO) PAO
[NO }
PBT(SCK) —(A15) PCT
PBG (MISO) (14) PCB
PBS (MOS!) — (13) PCS
Pe4 (55) (AZ PCA
PBS(AINI) —(A11) PCI
PB2(AIND) —(A10) PC2
Patt) 9) PCI
Pao (TO) 8) PCO
Figure 71 Interface between PC-AT Keyboard and AVR
Function Getatkbd() is here used for querying the PC-AT key-
board. Listing 33 shows a simple program example for this purpose.
138* Query a PC-AT keyboard by AVR
Config Keyboard = Pind.2 , Data = Pind.4 , Keydata = Keydata
Dim B As Byte
Print "hello"
Do
B = Getatkbd() ‘get a byte and store it into
"byte variable
‘When no real key is pressed the result is 0
'So test if the result was > 0
If B > 0 Then
Print B ; Chr(b)
End If
Loop
End
'This is the key translation table
Keydata:
‘normal keys lower case
Dttad0,0,0,0,0,0,0,0,0,0,0,0,0,0, d#,0
Dtad,0,0,0,0,13,49,0,0,0,12,15,97,19,0,0
Dia0, 9, 120,10,11,2,51,0,0,2, 18,19, 16,14,3,0
Dtad, 00,8, 10,18, 11,%,7,8,%, 109, 16,17,5,%,0
Dtad, 4,107,105, 11, 8,57,0,0, 4,45, 18, 48,12, 8,0
Dta0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0
Dta0,@,0,0,0,0,8,0,0,4,0,%.%,0,0.0
Dra, 4,5,53,5%,56,0,0,0,8,9,6,2,57,0,0
Dta0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Dta0,0,0,0,0,8,%3,0,0,0,0,8,6,8,%,0
Dita, 67,8, 8,0,0,35,0,0,2,%,0,%,2,37,0
Dta0, 8,6, 2,1,8,38,0,0,6,7,4,6,47,0,0
Dta0, 59,5,B,B,4,4,0,0,8,65, 6,8, 0,8,0
Dta0,0,0,0,0,%,0,0,0,0,3,%,0,42,0,0
Dtad, @,0,0,0,8,0,0,4,0,2,%,0,0,0,0
Dita 48, 4,5,3,5%,56,0,0,0,8,9,6,42,57,0,0
Listing 33 Query of a PC-AT Keyboard (ATKBD.BAS)
Before the PC-AT keyboard can be queried, the used pins must be
assigned and a table containing the scan codes must be prepared.
Pin2 of PortD receives the clock from the PC-AT keyboard while Pin4
serves as data line.
139Function Getkbd() queries the PC-AT keyboard for data by analyz-
ing the bit stream received from the keyboard (Figure 72). This bit
stream contains the scan codes.
“0/1/2|3]/4/5.6)7/Pi»|
Figure 72 Bit Stream from Keyboard Controller
The connected microcontroller circuitry serves as power supply for
the PC-AT keyboard. Note the power consumption of the PC-AT
keyboard used. In case it is not known, measure the power supply
current of the PC-AT keyboard used to avoid a damaging of the
power supply.
4.6 Data Input by IR Remote Control
Most audio or video systems available today have IR remote controls
for user interaction. Widespread are remote controls manufactured
by SONY or Philips which operate with a standardized transmission
protocol (RC5).
The RC5 protocol consists of a 14-bit data word. The data word uses
the so-called Manchester coding, a bi-phase code. Figure 73 shows
an IR command according to RC5.
Sti St2 Ctrl S4 $3 S2 S1 SO C5 C4 C3 C2 C1 CO
1100014 04 4 41 0414 0 1
Figure 73 RC5 Coded IR Command
The command begins with two start bits (St1, St2) which are always
set. The following bit (Ctrl) toggles for each command. Repeated
commands can be detected this way. The control bit is followed by
five system bits (S4-S0). The control bits contain the address of the
device to be controlled. Usually, TV sets have an address of 0, video
140recorder an address of 5, etc. Six command bits (C5-C0) close the
sequence. There are 64 different commands available for each de-
vice.
Table 8 shows an extract from a list of devices and their RC5 ad-
dresses.
System Device
0 Video T1
1 Tv2
5 VCR1
6 VCR2
17 Audio Tuner
20 cD
21 Phono
18 Recorder1
Table 8 RC5 Device Address
In correspondence with these explanations, the command in Figure
73 sends command value &H35 to VCR1.
141' Query an IR Remote Control by AVR
Const Tv = 0 ' TV address is 0
Config ReS = Pind.2 * Configures PinD.2 as RCS Input
Portd.2 = 1 ' Activates Pull-up
Enable Interrupts ' Getre5 uses timer0 interrupt
Dim Address As Byte , Command As Byte
Do
Getre5 (address , Command) ' Query IR remote control
If Address = Tv Then ' Check for the TV address
Print Address ; " " ; Conmand
End If
Loop
End
Listing 34 Query of an IR Remote Control (RC5.BAS)
As shown in Listing 34, function GETRCS() handles the whole RCS
protocol.
What about the hardware? Siemens offers the IR receiver SFH5S06-
36 for this purpose. It is very simple to connect this receiver to a mi-
crocontroller. Figure 74 shows the connection of an IR receiver
SFHS506 to an AVR. It is important that the internal pull-ups are acti-
vated.
In consideration of the different port situation between the 8051 and
the AVR, program RC5.BAS can be modified to suit BASCOM-AVR
without any problems.
142RESET
oc1B
XTAL2 ALE
TALI IcP
—— P07 ¢RD) (ADz) PAT
—— PD6 dWR) (AD6) PAS
—— PDS{OC1A) (ADS) PAS
uJ —— Ppa (AD4) PAd
—— PD34INT1) (AD 3) PAB
PD2(INTO) — (AD 2) PAZ
—— P01 7xD) (AD1) PAT
—— PDO(RXD) = (ADO) PAD
Pa? (CK) (A1 5) PCT
PRG (MISO) —(A14) PCB
PBS(MOSI (413) PCS
cy PB4 ¢8S) (12) PO
PB3(AIN1) (At) PC3
UW P82 (INO) (A10) PC2
vo —— Pat €11) (Ag) PC1
—— Ps0 (70) (a8) PCO
Figure 74 SFH506 connected to AT90S8515
4.7 Asynchronous Serial Communication
For asynchronous serial communication, microcontrollers use an
internal UART (Universal Asynchronous Receiver Transmitter), or it
must be implemented in the software (emulation).
In BASCOM, the I/O instructions common in BASIC (input and print)
are redirected to the serial port. That means instruction Input
reads characters from and instruction Print sends characters to the
serial port.
A signal converter is required to connect a microcontroller to the
COM port of a PC. Well-known are MAX232 or compatible devices.
Figure 75 shows a MAX231 connected to the UART pins of an
AT90S8515. The MAX231 is equivalent to MAX232 but needs one
capacitor only.
143JRESET
XTAL2
XTALI
PO7 GRO)
PDB (WR)
PDS (OC1A)
PD4
PO3 (NTI)
PO2 (NTO)
PDI (TxD)
PDO (RXD)
Paz (sCK)
PB6 (MISO)
PBS (MOS!)
PB4 (SS)
PBS (AINT)
P82 (AIND)
PBI (TI)
PO (TO)
octg
ALE
IP.
(ADT) PAT
(ADB) PAB
(ADS) PAS
(AD4) PAA
(AD3) PAI
(D2) PA2
(@D1) Pat
(@D0) PAO
(1)PoT
(ala) PCB
AID) POS
(A12) PCA
(att) Pca
(10) PC?
9) PCI
(as) PCO
ve
Tio
— TxD,
120
R10
TH
R20
ce
Rai
Figure 75 RS-232 Level Conversion by MAX231
ar
—C RxD
For communication, use the BASCOM-internal Terminal Emulator or
any other terminal program at the PC end. Program RS232MON,
which can be downloaded from authors' web site, can be used for
debugging at byte level.
BASIC.
BASCOM. Listing 35 shows how to use them.
' Serial I/O by AVR and 8051
Dim A As Integer
Do
Input "Input Number: ", A
Print " Number was"; A
Loop
End
Listing 35 Serial I/O (SERIAL1.BAS)
instructions Input and Print are also available
in
Variable A is declared as integer. Figure 76 shows the conversion of
that number to the range of integer numbers -32768 ... 32767.
144PEE
File Terminal
Ter Le rad re
jer was -32768
5535 Number was -1
5536 Number was 0
eee
Se Cee eer
era es
COM! S600N81 —
Figure 76 Input of an Integer
Very important for character input without finishing Carriage Return
(CR) is instruction Inputbin. Listing 36 shows a simple program
example.
' Serial I/O by AVR and 8051
Dim A As Byte
Dim B As Word ' B is a reserved word for BASCOM-8051
Do
Inputbin A, B
Printbin A, B ‘use Printbin A ; B for BASCOM-8051
Print
Loop
End
Listing 36 Character I/O (SERIAL2.BAS)
Variable A is declared as byte and variable B as word. Instruction
Inputbin waits for three characters (bytes) without a CR.
In BASCOM-8051, B is a reserved word. Therefore, the name of this
variable must be changed for BASCOM-8051. Moreover, the syntax
of instruction Printbin is different. See the remark in Listing 36.
145After receiving three bytes, instruction Printbin sends these three
bytes back. The output by Printbin is completed by a CR/LF out-
put by instruction Print.
Related to this kind of input are the functions Inkey() and Wait-
key(). Waitkey() waits until a character is received, while
Inkey () reads one character from the input buffer. Both functions
store that character in a variable. If the input buffer is empty,
Inkey() hands over the value of 0. Listing 37 shows a program
example and Figure 77 the respective outputs in the terminal win-
dow.
' Serial I/O by AVR and 8051
Dim A As Byte
Do
A = Waitkey() ' waits for one character
Print Chr(a) ; "is ASCII"; A
Loop Until A = 27
Do
A = Inkey() ' veads one character
Print Chr(a) ; "is ASCII." ; A
Waitms 100
Loop Until A = 27
End
Listing 37 Input by Waitkey() and Inkey() (SERIAL3.BAS)
ENR el
Fie Teminal
COM1:9600,N.8.1
|
Figure 77 Input by Waitkey() and Inkey()
146The first loop containing function Waitkey () will be reached after
program start.
Upon pressing key A on the PC keyboard, the Terminal Emulator
sends character A to the connected microcontroller. Waitkey ()
receives this character as expected. The procedure is repeated when
key 1 is pressed. The print instruction echoes the character and its
ASCII code to the Terminal Emulator each time this is done.
Pressing key ESC quits this first loop. The program progresses to the
second loop containing the function Inkey (). In this loop, function
Inkey () will return 0 as long as one character is received by the
serial port and written in the input buffer. In Figure 77, character x
was received before leaving the loop by pressing ESC again. A wait
time of 100 ms slows down the passing of the loop.
Beside serial communication with the internal UART of the micro-
controller used, there is the possibility of using an UART emulation.
Instructions OPEN and CLOSE serve to configure the communication
channels.
Instruction OPEN initializes the communication channel by assigning
a pin for input or output and selecting a baud rate.
These examples show the opening of a communication channel for
serial output:
' Open for AVR
Open "COMA.0:9600,8,N,1, INVERTED" For Output As #1
‘Open for 8051
Open "COM3.0:9600,8,N,1, INVERTED" For Output As #1
For AVR, PinO of PortA is opened as serial output (transmitter) with
a baud rate of 9600 Baud, one stop bit and inverted polarity of the
RS-232 signal.
For 8051, PinO of Port3 was initialized with the same parameters.
Each communication channel that is open at any time must be
closed by instruction CLOSE before the end of the program.
In the next program example, two microcontrollers will be serially
connected.
147Figure 78 shows the circuit diagram of those two linked microcon-
trollers. Used here are an AT90S8515 and a BASIC Stamp II (BS2).
For information on the BS2 see the Appendix.
Instead of a BS2, any microcontroller with a serial port, or a PC run-
ning a terminal program, can be used.
JRESET
oct
— raz Ae |
— oat icp LF
—|Po7 oro) aon par -}—
—— Poe 0wR) (ade) PAG | —
——| Posiociay ans) Pas F —
1 poe (ADS) PAA
— {Posty 03) PA3 |
— | Pozanto) 02) Paz sout vin
—|ro10%0) ~—@onypat SIN vss
—| PDO (RxD) (ADO) PAD IN RES |
vss bb
—|rar(scig —atypcr Po P15
—— | Pas miso) aia) pce Pt Pi
——|Pasiwosy — ataypcs P2 P13
—| Pasyss) wince Pa P12 \»
— Pasay —aityeca Pa Pit
——| Perino) — aroyec? Ps P10
rai ay (ag) Pct P6 Pa |
— | rao cro} a) PCO P7 Pe
Figure 78 Coupling of AT90S8515 and BASIC Stamp II
The AVR microcontroller uses its internal UART for communication
with a terminal as usual. Pins PDO and PD1 are connected to a
MAX232 for level conversion. This part of the circuit is not shown in
Figure 78.
In this program example, the second serial interface connected to the
BS2 is of importance. Pins PAO and PA1 form the communication
channel for the UART software.
At the BS2 end, pins P9 and P10 serve as serial interface. Pin P8
drives an LED for signalization.
Listing 38 shows the program for the AVR microcontroller and Listing
39 that for the BS2.
If it is intended to replace the AVR by an 8051 derivative, remember
to make the required changes in the source code:
148