Bascom Avr Programming
Bascom Avr Programming
Bascom Avr Programming
BASCOM
Programming of
Microcontrollers with Ease
An Introduction
by Program Examples
BASCOM Programming of Microcontrollers with Ease:
An Introduction by Program Examples
Universal Publishers/uPUBLISH.com
USA • 2001
ISBN: 1-58112-671-9
www.upublish.com/books/kuhnel.htm
Preface
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.
3
Acknowledgement
I 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.
4
Contents
1 Supported Microcontrollers ............................................................. 9
1.1 8051 Family .............................................................................. 9
1.2 AVR Family............................................................................. 11
2 BASCOM....................................................................................... 23
2.1 BASCOM Demos.................................................................... 23
2.2 BASCOM Commercial Versions............................................. 25
2.3 Update of BASCOM Commercial Versions ............................ 25
2.4 BASCOM Projects .................................................................. 27
2.4.1 Working on Projects ........................................................ 27
2.4.2 BASCOM Options ............................................................ 28
2.5 BASCOM Tools ...................................................................... 37
2.5.1 Simulation ........................................................................ 37
2.5.2 Terminal Emulator ........................................................... 40
2.5.3 LCD Designer .................................................................. 42
2.5.4 Library Manager ............................................................... 46
2.5.5 Programming Devices ..................................................... 50
2.6 Hardware for AVR RISC Microcontroller ................................ 55
2.6.1 DT006 AVR Development Board ..................................... 55
2.6.2 AVR-ALPHA with AT90S2313 ......................................... 56
2.7 Instead of "Hello World".......................................................... 57
2.7.1 AVR.................................................................................. 57
2.7.2 8051 ................................................................................. 58
2.7.3 Things in Common........................................................... 59
2.7.4 Simulation ........................................................................ 64
2.8 BASCOM Help System........................................................... 67
3 Some BASCOM Internals ............................................................. 69
3.1 Building new instructions ........................................................ 69
5
3.2 Parameters for Subroutines in BASCOM-AVR....................... 71
3.3 BASIC & Assembler................................................................ 73
3.3.1 AVR .................................................................................. 74
3.3.2 8051 ................................................................................. 75
4 Applications ................................................................................... 77
4.1 Programmable Logic............................................................... 77
4.2 Timer and Counter.................................................................. 81
4.2.1 AVR .................................................................................. 81
4.2.2 8051 ............................................................................... 104
4.3 LED Control .......................................................................... 107
4.3.1 Single LED ..................................................................... 107
4.3.2 Seven-Segment Displays ............................................... 108
4.3.3 Dot-Matrix Displays ........................................................ 114
4.4 LCD Control .......................................................................... 119
4.4.1 Direct Control ................................................................. 119
4.4.2 LCD with Serial Interface ............................................... 122
4.5 Connecting Keys and Keyboards.......................................... 128
4.5.1 Single Keys .................................................................... 129
4.5.2 Matrix Keypad ................................................................ 132
4.5.3 PC-AT Keyboard ............................................................ 136
4.6 Data Input by IR Remote Control.......................................... 140
4.7 Asynchronous Serial Communication................................... 143
4.8 1-WIRE Interface .................................................................. 151
4.9 SPI Interface ......................................................................... 161
2
4.10 I C Bus................................................................................ 167
4.11 Scalable Network Protocol S.N.A.P .................................... 173
4.11.1 S.N.A.P. Features ........................................................ 174
4.11.2 Description of S.N.A.P. Protocol .................................. 175
4.11.3 S.N.A.P. Monitor........................................................... 179
4.11.4 Digital I/O...................................................................... 183
6
4.12 CANDIP - Interface to CAN ................................................ 197
4.13 Random Numbers .............................................................. 209
4.14 Moving Average.................................................................. 214
5 Appendix ..................................................................................... 219
5.1 Decimal-Hex-ASCII Converter.............................................. 219
5.2 DT006 Circuit Diagram ......................................................... 220
5.3 Characters in Seven-Segment Display................................. 222
5.4 BASIC Stamp II .................................................................... 223
5.5 Literature .............................................................................. 224
5.6 Links ..................................................................................... 225
6 Index ........................................................................................... 231
7
8
1 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.
10
To elucidate the differences in the derivatives, Figure 2 shows the
block diagram of the C8051F0000 microcontroller from Cygnal [2].
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.
11
Atmel'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].
12
Device Flash [KB] EEPROM SRAM I/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
13
Figure 3 Block diagram AT90S8515
14
The I/O storage area covers 64 addresses for the peripheral device
functions of the CPU, like control registers, Timer/Counter and other
I/O functions. Figure 4 shows memory maps of the AT90S8515 pro-
gram and data memory.
0x000 0x0000
32 General Purpose
Working Registers
0x001F
Program 0x0020
Flash Memory 64 Input/Output
(4 K x 16 bit) Registers
0x005F
0x0060
Internal SRAM
(512 x 8 bit)
0x025F
0x0260
0xFFF
External SRAM
(0 - 64 K x 8 bit)
0xFFFF
Figure 4
Memory maps for program and data memory for AT90S8515
15
Timer/Counter
One 8-bit and one 16-bit Timer/Counter are available in conjunction
with a flexible 10-bit prescaler for different timer and counter applica-
tions.
Both Timer/Counter units can operate independently as a timer with
internal clock or as a counter with external triggering. The prescaler
divides the internal clock into four selectable timer clocks (CK/8,
CK/64, CK/256 and CK/1024).
The 8-bit Timer/Counter is a simple UpCounter.
The 16-bit Timer/Counter is more complex and supports two Output
Compare functions and one Input Capture function. Furthermore, it is
possible to use the Timer/Counter for Pulse-Width-Modulation
(PWM).
The Watchdog Timer is clocked by a separate on-chip oscillator. The
Watchdog period can be selected between 16 ms and 2048 ms.
SPI
The Serial Peripheral Interface (SPI) allows synchronous serial high-
speed communication.
UART
A comfortable Universal Asynchronous Receiver/Transmitter (UART)
allows flexible asynchronous serial communication.
Analog Comparator
The Analog Comparator compares voltages at two pins.
I/O Ports
The AT90S8515 has four I/O ports, which can be operate as digital
input or output controlled by the Data Direction Register (DDR). As
shown in Figure 5, most pins have alternative functions.
Comparing the pin configuration of the AVR microcontrollers and that
of the 8051 microcontroller family reveals one objective of this new
microcontroller family.
16
Figure 5 Pin configuration AT90S8515
All I/O ports are bidirectional with individually selectable Pull-up re-
sistors. The outputs can drop to 20 mA so that LEDs can be directly
driven.
The AVR microcontrollers support a high-voltage (12 V) parallel pro-
gramming mode and a low-voltage serial programming mode. The
serial programming mode via SPI provides a convenient way to
download programs and data into the device inside the user's sys-
tem.
To get an impression of the instruction set of the AVR microcontrol-
lers, Table 2 explains all instructions in a compact form.
17
Mnemonics Description Cycles
ARITHMETIC AND LOGIC INSTRUCTIONS
ADD Rd, Rr Add without Carry Rd ← Rd + Rr 1
ADC Rd, Rr Add with Carry Rd ← Rd + Rr + C 1
ADIW Rd, K Add Immediate to Word Rd+1:Rd ← Rd+1:Rd + K 2
SUB Rd, Rr Subtract without Carry Rd ← Rd - Rr 1
SUBI Rd, K Subtract Immediate Rd ← Rd - K 1
SBC Rd, Rr Subtract with Carry Rd ← Rd - Rr - C 1
SBCI Rd, K Subtract Immediate with Rd ← Rd - K - C 1
Carry
SBIW Rd, K Subtract Immediate from Rd+1:Rd ← Rd+1:Rd - K 2
Word
AND Rd, Rr Logical AND Rd ← Rd • Rr 1
ANDI Rd, K Logical AND with Immediate Rd ← Rd • K 1
OR Rd, Rr Logical OR Rd ← Rd v Rr 1
ORI Rd, K Logical OR with Immediate Rd ← Rd v K 1
EOR Rd, Rr Exclusive OR Rd ← Rd ⊕ Rr 1
COM Rd One’s Complement Rd ← $FF - Rd 1
NEG Rd Two’s Complement Rd ← $00 - Rd 1
SBR Rd,K Set bit(s) in Register Rd ← Rd v K 1
CBR Rd,K Clear bit(s) in Register Rd ← Rd • ($FFh - K) 1
INC Rd Increment Rd ← Rd + 1 Rd ← Rd + 1 1
DEC Rd Decrement Rd ← Rd - 1 1
TST Rd Test for Zero or Minus Rd ← Rd • Rd 1
CLR Rd Clear Register Rd ← Rd ⊕ Rd 1
SER Rd Set Register Rd ← $FF 1
MUL Rd,Rr Multiply Unsigned R1, R0 ← Rd × Rr 2
BRANCH INSTRUCTIONS
RJMP k Relative Jump PC ← PC + k + 1 2
IJMP Indirect Jump to (Z) PC ← Z 2
JMP k Jump PC ← k 3
RCALL k Relative Call Subroutine PC ← PC + k + 1 3
ICALL Indirect Call to (Z) PC ← Z 3
CALL k Call Subroutine PC ← k 4
RET Subroutine Return PC ← STACK 4
RETI Interrupt Return PC ← STACK 4
CPSE Rd,Rr Compare, PC ← PC + 2 or 3 1/2
Skip if Equal if (Rd = Rr)
CP Rd,Rr Compare Rd - Rr 1
CPC Rd,Rr Compare with Carry Rd - Rr - C 1
CPI Rd,K Compare with Immediate Rd - K 1
SBRC Rr, b Skip if bit in Register Cleared if (Rr(b)=0) 1/2
PC ← PC + 2 or 3
SBRS Rr, b Skip if bit in Register Set if (Rr(b)=1) 1/2
PC ← PC + 2 or 3
SBIC P, b Skip if bit in I/O Register if(I/O(P,b)=0) 2/3
Cleared PC ← PC + 2 or 3
SBIS P, b Skip if bit in I/O Register Set If(I/O(P,b)=1) 2/3
PC← PC + 2 or 3
BRBS s, k Branch if Status Flag Set if (SREG(s) = 1) then 1/2
PC←PC+k + 1
BRBC s, k Branch if Status Flag Cleared if (SREG(s) = 0) then 1/2
PC←PC+k + 1
18
BREQ k Branch if Equal if (Z = 1) then 1/2
PC ← PC + k + 1
BRNE k Branch if Not Equal if (Z = 0) then 1/2
PC ← PC + k + 1
BRCS k Branch if Carry Set if (C = 1) then 1/2
PC ← PC + k + 1
BRCC k Branch if Carry Cleared if (C = 0) then 1/2
PC ← PC + k + 1
BRSH k Branch if Same or Higher if (C = 0) then 1/2
PC ← PC + k + 1
BRLO k Branch if Lower if (C = 1) then 1/2
PC ← PC + k + 1
BRMI k Branch if Minus if (N = 1) then 1/2
PC ← PC + k + 1
BRPL k Branch if Plus if (N = 0) then 1/2
PC ← PC + k + 1
BRGE k Branch if Greater or Equal, if (N ⊕ V= 0) then 1/2
Signed PC ← PC+ k + 1
BRLT k Branch if Less Than, Signed if (N ⊕ V= 1) then PC ← 1/2
PC + k + 1
BRHS k Branch if Half Carry Flag Set if (H = 1) then 1/2
PC ← PC + k + 1
BRHC k Branch if Half Carry Flag if (H = 0) then 1/2
Cleared PC ← PC + k + 1
BRTS k Branch if T Flag Set if (T = 1) then 1/2
PC ← PC + k + 1
BRTC k Branch if T Flag Cleared if (T = 0) then 1/2
PC ← PC + k + 1
BRVS k Branch if Overflow Flag is Set if (V = 1) then 1/2
PC ← PC + k + 1
BRVC k Branch if Overflow Flag is if (V = 0) then 1/2
Cleared PC ← PC + k + 1
BRIE k Branch if Interrupt Enabled if ( I = 1) then 1/2
PC ← PC + k + 1
BRID k Branch if Interrupt Disabled if ( I = 0) then 1/2
PC ← PC + k + 1
DATA TRANSFER INSTRUCTIONS
MOV Rd, Rr Copy Register Rd ← Rr 1
LDI Rd, K Load Immediate Rd ← K 1
LDS Rd, k Load Direct from SRAM Rd ← (k) 3
LD Rd, X Load Indirect Rd ← (X) 2
LD Rd, X+ Load Indirect and Post- Rd ← (X), X ← X + 1 2
Increment
LD Rd, -X Load Indirect and Pre- X ← X - 1, Rd ← (X) 2
Decrement
LD Rd, Y Load Indirect Rd ← (Y) 2
LD Rd, Y+ Load Indirect and Post- Rd ← (Y), Y ← Y + 1 2
Increment
LD Rd, -Y Load Indirect and Pre- Y ← Y - 1, Rd ← (Y) 2
Decrement
LDD Rd,Y+q Load Indirect with Rd ← (Y + q) 2
Displacement
LD Rd, Z Load Indirect Rd ← (Z) 2
19
LD Rd, Z+ Load Indirect and Post- Rd ← (Z), Z ← Z+1 2
Increment
LD Rd, -Z Load Indirect and Pre- Z ← Z - 1, Rd ← (Z) 2
Decrement
LDD Rd, Z+q Load Indirect with Rd ← (Z + q) 2
Displacement
STS k, Rr Store Direct to SRAM Rd ← (k) 3
ST X, Rr Store Indirect (X) ← Rr 2
ST X+, Rr Store Indirect and Post- (X) ← Rr, X ← X + 1 2
Increment
ST -X, Rr Store Indirect and Pre- X ← X - 1, (X) ← Rr 2
Decrement
ST Y, Rr Store Indirect (Y) ← Rr 2
ST Y+, Rr Store Indirect and Post- (Y) ← Rr, Y ← Y + 1 2
Increment
ST -Y, Rr Store Indirect and Pre- Y ← Y - 1, (Y) ← Rr 2
Decrement
STD Y+q,Rr Store Indirect with (Y + q) ← Rr 2
Displacement
ST Z, Rr Store Indirect (Z) ← Rr 2
ST Z+, Rr Store Indirect and Post- (Z) ← Rr, Z ← Z + 1 2
Increment
ST -Z, Rr Store Indirect and Pre- Z ← Z - 1, (Z) ← Rr 2
Decrement
STD Z+q,Rr Store Indirect with (Z + q) ← Rr 2
Displacement
LPM Load Program Memory R0 ← (Z) 3
IN Rd, P In Port Rd ← P 1
OUT P, Rr Out Port P ← Rr 1
PUSH Rr Push Register on Stack STACK ← Rr 2
POP Rd Pop Register from Stack Rd ← STACK 2
BIT AND BIT-TEST INSTRUCTIONS
LSL Rd Logical Shift Left Rd(n+1)←Rd(n), 1
Rd(0)←0,C←Rd(7)
LSR Rd Logical Shift Right Rd(n)←Rd(n+1), 1
Rd(7)←0,C←Rd(0)
ROL Rd Rotate Left Through Carry Rd(0)←C, 1
Rd(n+1)←Rd(n),C←Rd(7
)
ROR Rd Rotate Right Through Carry Rd(7)←C, 1
Rd(n)←Rd(n+1),C←Rd(0
)
ASR Rd Arithmetic Shift Right Rd(n) ← Rd(n+1), n=0..6 1
SWAP Rd Swap Nibbles Rd(3..0) ↔ Rd(7..4) 1
BSET s Flag Set SREG(s) ← 1 1
BCLR s Flag Clear SREG(s) ← 0 1
SBI P, b Set bit in I/O Register I/O(P, b) ← 1 2
CBI P, b Clear bit in I/O Register I/O(P, b) ← 0 2
BST Rr, b bit Store from Register to T T ← Rr(b) 1
BLD Rd, b bit load from T to Register Rd(b) ← T 1
SEC Set Carry C←1 1
CLC Clear Carry C←0 1
SEN Set Negative Flag N←1 1
CLN Clear Negative Flag N←0 1
20
SEZ Set Zero Flag Z←1 1
CLZ Clear Zero Flag Z←0 1
SEI Global Interrupt Enable I←1 1
CLI Global Interrupt Disable I←0 1
SES Set Signed Test Flag S←1 1
CLS Clear Signed Test Flag S←0 1
SEV Set Two’s Complement V←1 1
Overflow
CLV Clear Two’s Complement V←0 1
Overflow
SET Set T in SREG T ←1 1
CLT Clear T in SREG T←0 1
SEH Set Half Carry Flag in SREG H←1 1
CLH Clear Half Carry Flag in H←0 1
SREG
NOP No Operation None 1
SLEEP Sleep 1
WDR Watchdog Reset 1
21
22
2 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
23
Installation 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.
24
Figure 7 Error messages due to exceeding the restricted code size
25
Figure 8 shows the downloading and extracting of updated files in an
existing installation of BASCOM-AVR.
26
Figure 9 No newer version available
If you use the AutoUpdate program from time to time you will always
have an actual installation of the used BASCOM IDE.
28
Figure 10 Selection of a device and external memory
29
Figure 11 Selection of files to be generated
30
Figure 12 Selection of baud rate and oscillator frequency
31
Figure 13 Selection of pins for serial communication
8-bit Mode E RS db7 db6 db5 db4 db3 db2 db1 db0
32
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.
33
Figure 15 Parameter selection for terminal emulator
34
Figure 16 Selection of editor options
35
Figure 17 Selection of a simulator
36
Figure 18 Selection of a programmer
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.
37
The 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
M1:
A = Waitkey()
If A = 27 Then Goto M2
Cls
Upperline
Lcd A
Lowerline
Lcd Hex(a)
Print Chr(a)
Goto M1
M2:
End
Listing 1 LCD Test (LCD.BAS)
38
Figure 19 BASCOM-8051 Simulator
40
Dim A As Byte
Loop Until A = 27
End
Listing 2 Test of serial communication (SERIAL.BAS)
41
The Terminal Emulator can be used for testing all communication
tasks of the serial interface of the used microcontroller.
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).
Figure 23
Custom-specific character definition in LCD Designer
42
The 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.
43
Deflcdchar 1 , 238 , 255 , 252 , 248 , 252 , 255 , 238 , 224
Deflcdchar 2 , 238 , 255 , 255 , 248 , 255 , 255 , 238 , 224
Deflcdchar 3 , 238 , 255 , 255 , 255 , 255 , 255 , 238 , 224
Cls
Config Lcd = 16 * 1
Lcd "Hello "
Home
Lcd Chr(1)
Home
Lcd " " ; Chr(2)
Home
Lcd " " ; Chr(3)
Home
Lcd " " ; Chr(1)
Home
Lcd " " ; Chr(2)
Home
Lcd " " ; Chr(3)
Listing 3 Customer-specific characters (LCD1.BAS)
44
Figure 25 LCD output in Simulator
45
2.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.
46
Figure 27 BASCOM-8051 LIB Manager
47
Copyright = Claus Kuehnel
WWW = http://www.ckuehnel.ch
Email = [email protected]
Comment = 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:
ld _temp1,Z+ ;get data from BLOCK1
st X+,_temp1 ;store data to BLOCK2
dec _temp2 ;
brne _blockmove ;if not done, loop more
ret ;return
[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.
48
Declare Sub Blockmove(source As Byte , Dest As Byte , Byval Length
As Byte)
End
49
For I = 1 To 40
Routine Blockmove (...) Block1(i) = Block2(i)
Next
Runtime 89,6 µs 474,0 µs
50
Figure 29 shows the circuit diagram of Jerry Meng's FBPRG Pro-
grammer driven from the parallel port of the PC
[http://www.qsl.net/fa1fb/]. A lot of people use Jerry's design with
success.
51
Figure 30 FBPRG in a DOS window
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].
52
After 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.
53
Figure 32 Buffer view
54
There are many other programming and evaluation devices on the
market. Frequently, the manufacturers of microcontrollers offer such
devices for first tests or prototyping.
55
Figure 34 DT006 Board
56
Figure 35 AVR-ALPHA Mini Module
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 ⋅
f 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.
57
In 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.
Do
' Do nothing
Loop
2.7.2 8051
Timer0 operates in Mode 2 as a 16-bit timer. The timer period can be
calculated using the following expression:
12
T = 65536 ⋅
f 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
Do
' Do nothing
Loop
59
Following 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 Reti (Return
from Interrupt) and supports the Push and Pop of all registers.
Inside the ISR Timer0_isr variable A is incremented (Incr A) and
Pin0 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.
60
Figure 36 Source text in BASCOM-AVR Editor
Before the first compilation the options must be set. The parameters
2
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.
61
Figure 37 shows a syntax check with errors. By double-clicking the
error line the last "e" is seen to be missing in instruction Enable.
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.
62
Report : SIM_TIMER
Date : 10-31-1999
Time : 19:07:06
---------------------------------------------------------------
Variable Type Address(hex) Address(dec)
---------------------------------------------------------------
COUNTER0 0032 50
TIMER0 0032 50
COUNTER1 Word 004C 76
TIMER1 Word 004C 76
CAPTURE1 Word 0044 68
COMPARE1A Word 004A 74
COMPARE1B Word 0048 72
PWM1A Word 004A 74
PWM1B Word 0048 72
ERR 0006 6
A Byte 0060 96
---------------------------------------------------------------
Warnings:
---------------------------------------------------------------
Listing 8 Report file for BASCOM-AVR (SIM_TIMER.RPT)
63
Listing 9 shows the report file generated for BASCOM-8051.
Baud Timer : 1
Baudrate : 0
Frequency : 11059200
ROM start : &H0
RAM start : &H0
LCD mode : 4-bit
StackStart : &H22
Used ROM : &HAD 173 (dec) > Ok
---------------------------------------------------------------
Variable Type Address(hex) Address(dec)
---------------------------------------------------------------
ERR Bit 0004 4
A Byte 0021 33
CONSTANTS
---------------------------------------------------------------
Constant Value
---------------------------------------------------------------
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 Ctrl+O.
Figure 38 shows the simulator with three open windows.
64
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 Pin0 of PortB and in memory
location 60H 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.
65
Evaluation 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
66
2.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.
67
Figure 41 Search Function in the BASCOM Help System
68
3 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.
Do
Call Toggle_p1(mask) ' Subroutine call
Toggle_p1 Mask ' Usage of new instruction
Loop
End
69
We can go into the simulator and see the equality again.
In the single-step mode, we set port P1 to &HA5, for example, and
see P1 toggling from &HA5 to &H66 and vice versa.
X = &B10101010
Y = &B00001111
Z = Mask(x , Y)
End
71
Running 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().
72
Figure 44 Parameter passing BYREF (default)
73
3.3.1 AVR
The assembler is based on the standard AVR mnemonics.
In the following program examples, the assembler instructions are
marked in bold.
$asm
Ld R1, X ' Load R1 with contents where
' X is pointing to
Swap R1 ' Swap nibbles
$end 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/R9
74
serve as data pointer for the READ instruction. R6 contains a few bit
variables:
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.
75
Dim A As Byte ' Bytevariable
A = &H5A ' Initialize Variable
$asm
MOV A,@R0 ' Load ACC with contents
' of variable A
Swap A ' Swap nibbles
$end Asm
$asm
MOV A,{A} ' Load ACC with contents
' of variable A
Swap A ' Swap nibbles
$end Asm
76
4 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.
A7 A6 A5 A4 A3 A2 A1 A0 Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0
1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 0
1 1 1 1 1 1 0 1 0 0 0 0 1 1 1 1
x x x x x x 1 1 1 1 1 1 1 1 1 1
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:
• If A = &B11111110 then set Q = &B11110000.
• If A = &B11111101 then set Q = &B00001111.
• In all 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
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
78
PortD. In a case structure the bit pattern is evaluated and the result
forces the pins on PortB.
The BITWAIT instructions query Pin0 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).
Do
bitwait Pina.0 , Set
bitwait Pina.0 , Reset
A = Pind
Select Case A
Case &B11111110 : Q = &B11110000
Case &B11111101 : Q = &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.
79
Listing 11 shows the timer controlled logic device. The complete I/O
handling is here accommodated in the interrupt handler.
Do
Nop
Loop
End
Timer0_isr:
A = Pind
Select Case A
Case &B11111110 : Q = &B11110000
Case &B11111101 : Q = &B00001111
Case Else Q = &B11111111
End Select
Portb = Q
Return
Listing 11 Timer controlled logic devices (LOGIC1.BAS)
80
' Logic with AT89S8252
Do
Bitwait P2.0 , Set
Bitwait P2.0 , Reset
A = P1 ' Read P1
Select Case A
Case &B11111110 : Q = &B11110000
Case &B11111101 : Q = &B00001111
Case Else Q = &B11111111
End Select
P3 = Q ' Write P3
Loop
End
Listing 12 Logical device with AT89S8252 (LOGIC.BAS)
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 T0 and T1, differs for the various types of the AVR family.
All timer program examples given below refer to the AT90S8515.
81
4.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:
prescaler
T = 2N ⋅
f OSC
N = 8 for Timer0 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 Timer0 and Timer1 for a clock fre-
quency of 4 MHz.
82
Dim 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
Do
Key = Pind
If Key = &H7F Then
Seconds = 0
Minutes = 0
Hours = 0
End If
While New_time = True
If Seconds = 60 Then
Seconds = 0 : Incr Minutes
End If
If Minutes = 60 Then
Minutes = 0 : Incr Hours
End If
If Hours = 24 Then Hours = 0
Temp = Makebcd(seconds)
If Key = &HFE Then Temp = Makebcd(minutes)
If Key = &HFD Then Temp = Makebcd(hours)
Portb = Not Temp
New_time = Not True
Wend
Loop
End
83
Timer1_isr:
New_time = True
Incr Seconds
Return
Listing 13 Second-Timer with Timer1 (TIMER3.BAS)
Set Tccr1b.3
84
The 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.
Timer0 has the overflow interrupt available only. Timer0 must be
loaded with a value of 256 - 195 to get an overflow after 195 cycles.
Listing 14 shows the initialization of Timer0 and PortB and an end-
less loop as the main program.
On Timer0 overflow the instruction Load Timer0 , Reload re-
loads the timer. Calculation 256 - Reload is performed internally.
Do
Nop
Loop
End
Timer0_isr:
' Reload Timer0 for Period of 50 ms
Load Timer0 , Reload
Portb.0 = Not Pinb.0 ' Toggle Portb.Pin0
Return
Listing 14 Clock generation using Timer0 (TIMER0.BAS)
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.
86
Caution: In case of low prescaler values, take into account the time
needed for register saving.
Do
Nop
Loop
End
Timer0_isr:
' Reload Timer0 for Period of 50 ms
Counter = Tcnt0 ' Read Timer0
Tcnt0 = Counter - Reload ' Reload Timer0
Portb.0 = Not Pinb.0 ' Toggle Portb.0
Return
Listing 15 Modified clock generation by Timer0 (TIMER0_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.
87
Instruction Cycles TCNT0 ( Prescaler=1)
PUSH R0 2 &H07
PUSH R1 2 &H09
PUSH R2 2 &H0B
PUSH R3 2 &H0D
PUSH R4 2 &H0F
PUSH R5 2 &H11
PUSH R6 2 &H13
PUSH R7 2 &H15
PUSH R8 2 &H17
PUSH R9 2 &H19
PUSH R10 2 &H1B
PUSH R11 2 &H1D
PUSH R16 2 &H1F
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 1 &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 &H4C
OUT 0x32,R16 1 &H4D
IN R24,0x16 1 &H81
...
The timer period should be 195 cycles of Timer0 again. After 77 cy-
cles (= &H4D) the calculated value of 129 (= &H81) is reloaded. With
a prescaler of 1, Timer0 will overflow after 256 - 129 + 77 = 204
cycles.
88
The remaining difference to the expected value of 195 results from
the difference between reading and writing TCNT0 (&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, Pin0 of PortB serves
as counter input T0. The leading or falling edge of the input signal
can trigger the counter. Register TCNT0 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.
Do
Portb = Count * 2 ' Shift one bit left for display
Loop
End
Timer0_isr:
Load Timer0 , Ticks
Incr Count
Return
Listing 16 Pulse Counter with Timer0 (COUNTER0.BAS)
89
The ISR manages reloading and increments variable Count.
In the endless loop, the variable counter is displayed by the LEDs
connected to PortB. As Pin0 serves as counter input T0, 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, Timer1 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 Timer1 = 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.
Do
Portb = Icr1l * 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 Timer1 = 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.
90
Figure 46 Initial State of TCCR1B in CAPTURE1.BAS
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
91
ICES1 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.
2/8
5/8
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.
92
Const True = 1
Const False = 0
Dim Hi As Byte
Dim Lo As Byte
Dim A As Byte
Dim Phase As bit
Dim Pattern As Byte ' bit pattern for display
Do
A = Pind ' Ask for Key
Select Case A
Case &B11111110 : Lo = 0 ' Lo Time short
Case &B11111101 : Lo = 32
Case &B11111011 : Lo = 64
Case &B11110111 : Lo = 96
Case &B11101111 : Lo = 128
Case &B11011111 : Lo = 160
Case &B10111111 : Lo = 192
Case &B01111111 : Lo = 255 ' Lo Time long
End Select
Hi = 255 - Lo
Incr Pattern ' Change bit Pattern
Waitms 100 ' Wait 100 ms
Loop
End
Timer0_isr:
If Phase = True Then
Portb = &HFF ' LED off
Timer0 = Lo ' Reload Timer0
Phase = False
Else
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 Timer0
3. Calculate the corresponding Hi time for reloading Timer0
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.
94
Config Timer1 = Pwm , Pwm = 10 , Compare A Pwm = Clear Down ,
Compare B Pwm = Clear Up
Temp1 = &H0000 ' Configure Timer1 for PWM
Pwm1a = Temp1
Pwm1b = Temp1
Tccr1b = Tccr1b Or &H02 ' Prescaler = 8
Do
bitwait Pind.0 , Reset ' Wait for key pressed
bitwait Pind.0 , Set ' Wait for key unpressed
Temp1 = Temp1 + &H10 ' Increment Variable
Pwm1a = Temp1 ' Set PWM Registers
Pwm1b = Temp1
Temp2 = Temp1 / &H10 ' Reset 4 LSB and shift right
Temp2 = Not Temp2 ' Invert bit pattern
Portb = Low(temp2) ' Output bit pattern
Loop
End
Listing 19 Digital-to-Analog Conversion by PWM (PWM1.BAS)
95
Figure 48 Initialization of TCCR1A
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.
Bits PWM11 and PWM10 define the resolution of PWM to 8 bit, 9 bit
or 10 bit.
96
PWM11 PWM10 Description
0 0 PWM not activated
0 1 8-bit PWM
1 0 9-bit PWM
1 1 10-bit PWM
97
Figure 49 Initialization of TCCR1B
98
Word &H000 &H010 &H020 &H030 &H040 &H050 &H060 &H070
PortB &H00 &H01 &H02 &H03 &H04 &H05 &H06 &H07
OC1A .001 .078 .156 .234 .311 .389 .467 .544
OC1B 4.93 4.86 4.78 4.70 4.62 4.55 4.47 4.39
Word &H080 &H090 &H0A0 &H0B0 &H0C0 &H0D0 &H0E0 &H0F0
PortB &H08 &H09 &H0A &H0B &H0C &H0D &H0E &H0F
OC1A .622 .700 .777 .855 .932 1.01 1.08 1.15
OC1B 4.32 4.24 4.16 4.08 4.01 3.93 3.85 3.77
Word &H100 &H110 &H120 &H130 &H140 &H150 &H160 &H170
PortB &H10 &H11 &H12 &H13 &H14 &H15 &H16 &H17
OC1A 1.23 1.31 1.39 1.46 1.54 1.62 1.69 1.77
OC1B 3.70 3.62 3.54 3.47 3.39 3.31 3.23 3.16
Word &H180 &H190 &H1A0 &H1B0 &H1C0 &H1D0 &H1E0 &H1F0
PortB &H18 &H19 &H1A &H1B &H1C &H1D &H1E &H1F
OC1A 1.85 1.93 2.00 2.08 2.16 2.24 2.31 2.39
OC1B 3.08 3.00 2.93 2.85 2.77 2.69 2.61 2.54
Word &H200 &H210 &H220 &H230 &H240 &H250 &H260 &H270
PortB &H20 &H21 &H22 &H23 &H24 &H25 &H26 &H27
OC1A 2.47 2.54 2.62 2.70 2.78 2.85 2.93 3.01
OC1B 2.46 2.39 2.31 2.23 2.15 2.08 2.00 1.92
Word &H280 &H290 &H2A0 &H2B0 &H2C0 &H2D0 &H2E0 &H2F0
PortB &H28 &H29 &H2A &H2B &H2C &H2D &H2E &H2F
OC1A 3.08 3.16 3.24 3.32 3.39 3.47 3.55 3.63
OC1B 1.85 1.77 1.69 1.61 1.54 1.46 1.38 1.30
Word &H300 &H310 &H320 &H330 &H340 &H350 &H360 &H370
PortB &H30 &H31 &H32 &H33 &H34 &H35 &H36 &H37
OC1A 3.70 3.78 3.86 3.93 4.01 4.09 4.17 4.24
OC1B 1.23 1.15 1.07 1.007 .929 .851 .774 .696
Word &H380 &H390 &H3A0 &H3B0 &H3C0 &H3D0 &H3E0 &H3F0
PortB &H38 &H39 &H3A &H3B &H3C &H3D &H3E &H3F
OC1A 4.32 4.40 4.47 4.55 4.63 4.71 4.78 4.86
OC1B .618 .541 .463 .385 .308 .230 .152 .075
99
5,000
4,500
4,000
3,500
3,000
Voltage
OCR1A
2,500
OCR1B
2,000
1,500
1,000
0,500
0,000 $000
$030
$060
$090
$120
$150
$180
$210
$240
$270
$300
$330
$360
$390
$0F0
$3F0
$1B0
$1E0
$2A0
$0C0
$2D0
$3C0
Word
tp1 tp2
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.
Enable Timer0
Enable Interrupts
Do
Value = Lopulse()
Portb = Value
Loop
End
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 Pin0 of PortD (defined in the third
line).
After the detection of a falling edge register TCNT0 is reset and
Timer0 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 Timer0 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 µs.
The run time from detecting the falling edge to detecting the rising
edge is 26 cycles, or minimum 6.5 µs. Therefore the capture range is
between 6.5 µs and 64 µs.
101
Using the assembler for edge detection will reduce the runtime.
Listing 21 shows the required changes. The changes are marked in
bold.
Enable Timer0
Enable Interrupts
Do
Value = Lopulse()
Portb = Value
Loop
End
102
' overflow isr stops timer0 and set tcnt0 to zero
Overflow_isr:
!push R24
Stop Timer0
Tcnt0 = 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 µs.
Do
Value = Lopulse()
Portb = Low(value)
Loop
End
103
At a clock frequency of 4 MHz Inputpin is queried every 7.7 µs.
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
T = 2N ⋅
f OSC
The timer can operate in four modes:
• Mode 0 : 13-bit timer (8-bit timer with 5-bit prescaler)
• Mode 1 : 16-bit timer.
• Mode 2 : 8-bit timer with auto-reload
• 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:
104
Figure 52 Block diagram of 8051 timer
105
In 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.
On Timer0 Timer0_isr
On Int0 Int0_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_timer0
Enable Interrupts 'Global Interrupt Enable
Do
P1.7 = Not P1.7 'Do Anything Forever
Waitms 100
Loop
End
'------------------------------------------------------
' Interrupt Handler
'------------------------------------------------------
Timer0_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
Return
Int0_isr:
Rl_value = Rl_value / 2 'Change Rl_value Value
Stop Timer0
Load Timer0 , Rl_value 'SetUp Timer0 with changed Rl_value
Start Timer0
P3.7 = Not P3.7 'Toggle P3.7
Return
'-------------------------------------------------------------
106
' Subroutines
'-------------------------------------------------------------
Init_io:
P3.7 = 1
P3.5 = 1
Set Tcon.0 'Falling edge triggers INT0
Enable Int0 'Enables INT0
Return
Init_timer0:
Load Timer0 , Rl_value 'Store Rl_value in Timer0
Enable Timer0 'Enable Timer0 Overflow Interrupt
Start Timer0 'Start Timer0
Return
Listing 23 Timer example (TIMER.BAS)
107
Figure 53 Connecting LEDs to PortB
108
Figure 55 shows the segment assignment and pin configuration of an
SA03-11 display.
109
Character Segments Output
g f e d c b a
0 1 0 0 0 0 0 0 &H40
1 1 1 1 1 0 0 1 &H79
2 0 1 0 0 1 0 0 &H24
3 0 1 1 0 0 0 0 &H30
4 0 0 1 1 0 0 1 &H19
5 0 0 1 0 0 1 0 &H12
6 0 0 0 0 0 1 0 &H02
7 1 1 1 1 0 0 0 &H78
8 0 0 0 0 0 0 0 &H00
9 0 0 1 0 0 0 0 &H10
A 0 0 0 1 0 0 0 &H08
B 0 0 0 0 0 1 1 &H03
C 1 0 0 0 1 1 0 &H46
D 0 1 0 0 0 0 1 &H21
E 0 0 0 0 1 1 0 &H06
F 0 0 0 1 1 1 0 &H0E
Table 4 Segment Control
Dim I As Byte
Restore Value_table
Do
For I = 1 To 16
Porta = X(i) ' Display character
Waitms 250 ' Wait .5 seconds
Waitms 250
Next
110
Loop
End
Value_table:
Data &H40 , &H79 , &H24 , &H30 , &H19 , &H12 , &H02 , &H78
Data &H00 , &H10 , &H08 , &H03 , &H46 , &H21 , &H06 , &H0E
Listing 24 Control of Seven-Segment-Display by AVR
(7SEGMENT.BAS)
The controlling bit patterns (see Table 4) are stored in the ROM in a
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.
P1 = 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
P1 = Not X(i) ' inverted for simulation only
Waitms 250
Waitms 250
Next
Loop
111
End
Value_table:
Data &H40 , &H79 , &H24 , &H30 , &H19 , &H12 , &H02 , &H78
Data &H00 , &H10 , &H08 , &H03 , &H46 , &H21 , &H06 , &H0E
Listing 25 Control of Seven-Segment-Display by 8051
(7SEGMENT.BAS)
112
Figure 56 Seven-Segment Display in BASCOM-8051 Simulator
113
Figure 57 Pin Assignment
114
Figure 59 Internal Circuit of Dot –Matrix Display TA07-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.
! ! ! ! !
! ! ! ! !
! ! ! ! "
! ! ! " "
! ! " " "
! " " " "
" " " " "
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.
115
Figure 61 Design of a character
The LCD Designer generates the following instruction for this special
character:
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.
116
Figure 62 Control Circuit for Dot-Matrix Display TA07-11
Restore Dotmatrix
Do
For I = 0 To 4
X=0
Set X.i ' set accessed column Hi
Portc = X
J=I+ 1
Porta = Not A(j)
Next
Loop
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 1 1 1 0 0 0 0 0
224 1 1 1 0 0 0 0 0
225 1 1 1 0 0 0 0 1
227 1 1 1 0 0 0 1 1
231 1 1 1 0 0 1 1 1
239 1 1 1 0 1 1 1 1
255 1 1 1 1 1 1 1 1
224 1 1 1 0 0 0 0 0
A(1) A(2) A(3) A(4) A(5)
118
At 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.
119
There 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.
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.
120
Together 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:
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
' LCD Control by AVR and 8051
$sim ' for simulation only otherwise comment
Dim A As Byte
M1:
A = Waitkey()
If A = 27 Then Goto M2
Cls
Upperline
Lcd A
Lowerline
Lcd Hex(a) ' uncomment for AVR
' Lcdhex A ' uncomment for 8051
Print Chr(a)
Goto M1
M2:
End
Listing 27 LCD Control (LCD.BAS)
$ASM
Ldi _temp1, 5 'load register R24 with value
Rcall _Lcd_control 'it is a control value
'to control the display
122
As 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 06 07 08 09 0A 0B 0C 0D 0E 0F
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
123
Instruction RS DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description
Clear Display 0 0 0 0 0 0 0 0 1 Clears display
and sets cursor
to home position
Cursor At 0 0 0 0 0 0 0 1 X Sets cursor to
Home home position
Set Entry Mode 0 0 0 0 0 0 1 I/D S Defines direction
of cursor and
shift movements
Display On/Off 0 0 0 0 0 1 D C B See explana-
tions of D, C,
and B
Cursor/Display 0 0 0 0 1 S/C R/L X X See explana-
Shift tions of S/C and
R/L
Function Set 0 0 0 1 DL N F X X See explana-
tions of DL, N,
and F
Set CG RAM 0 0 1 ACG Sets CG RAM
Addr address
Set DD RAM 0 1 ADD Sets DD RAM
Addr address
Data Write 1 Data Writes byte in
DD RAM or CG
RAM
Name Description
After writing a character to RAM, the DD RAM or CG RAM address will be
I/D 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 = 0).
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-
S/C tion according to R/L.
R/L 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 - 5 x 7 dots (F = 0) - 5 x 10 dots (F = 1).
X Don’t care.
124
Listing 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 Clr = 1
Const Lcd_blank = 8
Const Lcd_restore = 12
Dim I As Byte
Wait 5
125
While Pind.0 = 1
Print #1 , Chr(instr) ; Chr(lcd_blank);
Waitms 200 : Waitms 200
Print #1 , Chr(instr) ; Chr(lcd_restore);
Wait 1 : Waitms 250 : Waitms 250
Wend
Close #1
End
Listing 28 Control of a Serial LCD (SW_UART.BAS)
'--------------------------------------------------
' Serial_LCD.BAS for 8051
' Controlling a LCD with LCD Serial Backpack from
' SEETRON
' C. Kuehnel
' 2001-01-01
'--------------------------------------------------
Const Clr = 1
Const Lcd_blank = 8
Const Lcd_restore = 12
Dim I As Byte
Dim Key As Bit
Wait 5
Do
Print #1 , Chr(command) ; Chr(lcd_blank);
127
Waitms 200 : Waitms 200
Print #1 , Chr(command) ; Chr(lcd_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)
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.
128
4.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
pin1. The other side of each key is connected to one of the pins 2 to
13.
129
Figure 66 Reduced Keypad
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
Dim I As Byte
Dim Key As Byte ' Variable contains key number
Do
For I = 1 To Keys ' Query all keys
Key = I
Select Case Key
Case 1 : Debounce Pina.0 , 0 , Display_key , Sub
Case 2 : Debounce Pina.1 , 0 , Display_key , Sub
Case 3 : Debounce Pina.2 , 0 , Display_key , Sub
Case 4 : Debounce Pina.3 , 0 , Display_key , Sub
End Select
Next
Loop
End
Display_key:
Portb = Not Key ' Display key number by LED
Return
Listing 30 Query of a Keypad by AVR (KEY1.BAS)
Dim I As Byte
Dim Key As Byte ' Variable contains key number
131
P2 = 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 : Debounce P2.1 , 0 , Display_key , Sub
Case 3 : Debounce P2.2 , 0 , Display_key , Sub
Case 4 : Debounce P2.3 , 0 , Display_key , Sub
End Select
Next
Loop
End
Display_key:
P1 = Not Key ' Display key number by LED
Return
Listing 31 Query of a Keypad by 8051 (KEY1.BAS)
132
Figure 67 Internal Wiring of a 3x4 Keypad
133
Figure 68 Connection of a Matrix Keypad
Pins PD4 to PD7 serve as inputs with internal pull-up resistors. Pins
PD0 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.
End
Calc_key:
Select Case Row
Case 4 : Key = Column + 1
Case 5 : Key = Column + 4
Case 6 : Key = Column + 7
Case 7 : Key = Column + 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.
135
Config Kbd = Porta
Config Portb = Output
Value = Getkbd()
Portb = not Value
136
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 &HE0. Pressing key Pause generates the following sequence
of scan codes: &HE1, &H14, &H77, &HE1, &HF0, &H14, &HF0,
&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.
137
1 - Data
1 - Clock 2 - n.c.
2 - Data 3 - GND
3 - n.c. 4-+5V
4 - GND 5 - Clock
5-+5V 6 - n.c.
138
' Query a PC-AT keyboard by AVR
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
Keydata:
'normal keys lower case
Data 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , &H5E , 0
Data 0 , 0 , 0 , 0 , 0 , 113 , 49 , 0 , 0 , 0 , 122 , 115 , 97 , 119 , 50 , 0
Data 0 , 99 , 120 , 100 , 101 , 52 , 51 , 0 , 0 , 32 , 118 , 102 , 116 , 114 , 53 , 0
Data 0 , 110 , 98 , 104 , 103 , 121 , 54 , 7 , 8 , 44 , 109 , 106 , 117 , 55 , 56 , 0
Data 0 , 44 , 107 , 105 , 111 , 48 , 57 , 0 , 0 , 46 , 45 , 108 , 48 , 112 , 43 , 0
Data 0 , 0 , 0 , 0 , 0 , 92 , 0 , 0 , 0 , 0 , 13 , 0 , 0 , 92 , 0 , 0
Data 0 , 60 , 0 , 0 , 0 , 0 , 8 , 0 , 0 , 49 , 0 , 52 , 55 , 0 , 0 , 0
Data 48 , 44 , 50 , 53 , 54 , 56 , 0 , 0 , 0 , 43 , 51 , 45 , 42 , 57 , 0 , 0
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.
139
Function 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.
1 1 0 0 0 1 0 1 1 1 0 1 0 1
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
140
recorder 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 TV1
1 TV2
5 VCR1
6 VCR2
17 Audio Tuner
20 CD
21 Phono
18 Recorder1
Table 8 RC5 Device Address
141
' Query an IR Remote Control by AVR
Do
Getrc5(address , Command) ' Query IR remote control
End
Listing 34 Query of an IR Remote Control (RC5.BAS)
142
Figure 74 SFH506 connected to AT90S8515
143
Figure 75 RS-232 Level Conversion by MAX231
Dim A As Integer
Do
Input "Input Number: " , A
Print " Number was " ; A
Loop
End
Listing 35 Serial I/O (SERIAL1.BAS)
144
Figure 76 Input of an Integer
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)
145
After 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.
Dim A As Byte
Do
A = Waitkey() ' waits for one character
Print Chr(a) ; " is ASCII " ; A
Loop Until A = 27
Do
A = Inkey() ' reads one character
Print Chr(a) ; " is ASCII " ; A
Waitms 100
Loop Until A = 27
End
Listing 37 Input by Waitkey() and Inkey() (SERIAL3.BAS)
146
The 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:
147
Figure 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.
148
• B is a reserved word in BASCOM-8051; replace it by another term
for the name of the variable
• Modify the port designation
' SW UART by AVR
Dim A As Byte
Dim B As Byte
Do
Print "Input one character: ";
A = Waitkey()
Print Chr(a)
Print " Sent character = " ; Chr(a)
Printbin #1 , A
Inputbin #2 , B
Print " Received character = " ; Chr(b)
Print
Loop Until A = 27
Close #1
Close #2
End
Listing 38 AVR Software UART (SERIAL4.BAS)
After the configuration of the transmitter and receiver for serial com-
munication, the program will pass the loop as long as the ESC key is
pressed.
Function Waitkey() waits for a character from the terminal and sends
it - after some terminal outputs - to the connected BS2 (Printbin
#1 , A). Thereafter, the program waits for a character from BS2
(Inputbin #1 , A) and sends it to the terminal. Figure 79 shows
the dialog in the Terminal Emulator.
149
Figure 79 Dialog in Terminal Emulator
end
Listing 39 BS2 Transceiver (SERIAL.BS2)
151
The following program examples elucidate
applications of the 1–Wire Digital Thermo-
meter DS1820 without any exception (Figure
81). This device offers a number of interest-
ing features; its selection is not purely coinci-
dental.
Figure 82 shows the functionality of the
DS1820 in a block diagram.
Figure 81 DS1820
A 64-bit ROM contains the family code (8-bit), a serial number (48-
bit) and a CRC byte (8-bit). The serial number makes each device
unique and therefore always identifiable.
An 8-bit procedure is applied for the CRC check in DS1820. The
polynom
CRC = x 8 + x 5 + x 4 + 1
is the base of this CRC check.
The DS1820 measures the ambient temperature in a range from -55
°C to +125 °C in increments of 0,5 °C. The temperature value has an
internal resolution of 9 bit; see the next table.
152
Temperature Binary value Hex Value
+ 125°C &B0000000011111010 &H00FA
+ 25°C &B0000000000110010 &H0032
+ 1/2°C &B0000000000000001 &H0001
+ 0°C &B0000000000000000 &H0000
– 1/2°C &B1111111111111111 &HFFFF
– 25°C &B1111111111001110 &HFFCE
– 55°C &B1111111110010010 &HFF92
153
RAM Byte EEPROM
Temperature LSB 0
Temperature MSB 1
TH/User Byte 1 2 TH/User Byte 1
TH/User Byte 2 3 TH/User Byte 2
Reserved 4
Reserved 5
Count Remain 6
Count per °C 7
CRC 8
ROM COMMANDS
Reads the complete ROM
Read ROM
(possible for DS1820 only)
Addresses a DS1820 by means of the
Match ROM
64-bit ROM content
Skip addressing
Skip ROM
(possible for DS1820 only)
Search ROM Search for DS1820 in a network
Search for DS1820 in a network reporting
Alarm Search
an alarm
MEMORY COMMANDS
Convert Temperature Starts measuring temperature
Read Scratchpad Reads scratchpad memory
Stores the temperature threshold in the
Write Scratchpad
scratchpad memory
Copies the temperature threshold into the
Copy Scratchpad
EEPROM
Copies the temperature threshold back to
Recall EE
the scratchpad memory
Read Power Supply Queries the supply voltage
154
In the next example, a DS1820 is connected to Pin0 of PortA of an
AVR microcontroller. Note the pull-up resistor: without it a 1-wire
interface will not work!
Listing 40 shows how the connected DS1820 is identified by reading
the ROM. To modify this program for the 8051, all that needs to be
done is change the ports.
155
1wreset ' 1wire Reset
If Err = 1 Then ' On Error blink fast
Rate = Fast
Goto Blink
End If
156
A further bus reset closes the whole operation. If this bus reset is
done without any error occurring, all network operations were error-
less.
The program finishes by displaying the read data on PortB. Slow
blinking indicates an errorless end of the program.
The temperature measuring procedure is quite similar to the last
program example. Listing 41 shows the program source for AVR
microcontrollers.
Regarding the modification required to adjust to the BASCOM-8051,
the conditions are the same as those mentioned before.
157
1wreset ' 1wire Reset
If Err = 1 Then ' On Error blink fast
Rate = Fast
Gosub Blink
End If
158
After reading the scratchpad RAM its content is saved in the declared
array byte by byte. The result of the temperature measurement is
written to PortB (LSByte first, MSByte second).
The error indication – a blinking LED – does not differ from that of the
last program example.
The DS1820 uses a simple 8-bit CRC check for data security. To
secure data transmission, the master has to check the received data
as well.
Listing 42 shows a program example operating an 8-bit CRC check.
The 256 values, or possible results, are saved in a table at the end of
the program. To avoid misunderstanding – what is spoken of here is
16 DATA instructions of 16 data bytes each.
159
For J = 1 To 8
X = Z(j) ' Initialize input variable
Call Calc_crc(x) ' Calculate CRC
Portb = Not Crc ' Display CRC
Wait 1 ' Wait a little bit, comment later
Next
End
Crc_table:
Data 0 , 94 , 188 , 226 , 97 , 63 , 221 , 131 , 194 , 156 , 126 , 32 , 163 , 253 , 31 , 65,
Data 157 , 195 , 33 , 127 , 252 , 162 , 64 , 30 , 95 , 1 , 227 , 189 , 62 , 96 , 130 , 220,
Data 35 , 125 , 159 , 193 , 66 , 28 , 254 , 160 , 225 , 191 , 93 , 3 , 128 , 222 , 60 , 98,
Data 190 , 224 , 2 , 92 , 223 , 129 , 99 , 61 , 124 , 34 , 192 , 158 , 29 , 67 , 161 , 255,
Data 70 , 24 , 250 , 164 , 39 , 121 , 155 , 197 , 132 , 218 , 56 , 102 , 229 , 187 , 89 , 7,
Data 219 , 133 , 103 , 57 , 186 , 228 , 6 , 88 , 25 , 71 , 165 , 251 , 120 , 38 , 196 , 154,
Data 101 , 59 , 217 , 135 , 4 , 90 , 184 , 230 , 167 , 249 , 27 , 69 , 198 , 152 , 122 , 36,
Data 248 , 166 , 68 , 26 , 153 , 199 , 37 , 123 , 58 , 100 , 134 , 216 , 91 , 5 , 231 , 185,
Data 140 , 210 , 48 , 110 , 237 , 179 , 81 , 15 , 78 , 16 , 242 , 172 , 47 , 113 , 147 , 205,
Data 17 , 79 , 173 , 243 , 112 , 46 , 204 , 146 , 211 , 141 , 111 , 49 , 178 , 236 , 14 , 80,
Data 175 , 241 , 19 , 77 , 206 , 144 , 114 , 44 , 109 , 51 , 209 , 143 , 12 , 82 , 176 , 238,
Data 50 , 108 , 142 , 208 , 83 , 13 , 239 , 177 , 240 , 174 , 76 , 18 , 145 , 207 , 45 , 115,
Data 202 , 148 , 118 , 40 , 171 , 245 , 23 , 73 , 8 , 86 , 180 , 234 , 105 , 55 , 213 , 139,
Data 87 , 9 , 235 , 181 , 54 , 104 , 138 , 212 , 149 , 203 , 41 , 119 , 244 , 170 , 72 , 22,
Data 233 , 183 , 85 , 11 , 136 , 214 , 52 , 106 , 43 , 117 , 151 , 201 , 74 , 20 , 246 , 168,
Data 116 , 42 , 200 , 150 , 21 , 75 , 169 , 247 , 182 , 232 , 10 , 84 , 215 , 137 , 107 , 53
Listing 42 Calculation of 8-bit CRC (1WIRE3.BAS)
For test purposes, array Z(8) contains eight bytes simulating eight
bytes received from the scratchpad memory. These eight bytes are
checked and the result is displayed at PortB byte by byte.
When this program is simulated, the following sequence is displayed
at PortB: &H43, &H50, &HE1, &H23, &H0B, &HEA, &H5D.
160
For a normal program execution, remember to comment or erase
instructions $sim, wait 1 and Portb = not CRC later.
Dallas Semiconductors offers more details on the 8-bit CRC check.
The Appendix refers to useful links.
161
The Chip Select signals SS0 to SS3 activate the peripheral device to
be accessed.
Figure 84 shows the timing for data exchange between the micro-
controller and EEPROM NM25C04 via the SPI interface.
162
PortA is used for the SPI lines. Write instruction Config Spi =
... in one line!
Dim X As Byte
X = &HAA
Spiinit
Spiout X , 1
nop
End
Listing 43 SPI Byte Output (SPI.BAS)
163
' SPIMOVE by AVR
Dim A As Byte
A = &HAA
Spiinit
A = Spimove(a)
nop
End
Listing 44 SPI Read and Write at the Same Time (SPI1.BAS)
Listing 45 shows the source for data exchange via SPI using the on-
chip peripheral. It seems there is nothing changed.
If the resulting assembler code in the AVR Studio is inspected, great
differences will be found in the length of the assembler code.
164
Dim X As Byte
X = &HAA
Spiinit
Spiout X , 1
nop
End
Listing 45 Data Exchange via On-Chip SPI (SPI4.BAS)
The SPI Control Register organizes the whole SPI data exchange.
AVR Studio can show the initialization by instruction Spiinit in
detail. Figure 86 shows the initialization of the SPI Control Registers
after running instruction Spiinit.
165
Figure 87
Initialization of the SPI Control Register
Setting bit SPE connects the SPI pins internally to the predefined
pins of PortB. The AVR microcontroller operates as master
(MSTR=1) as long as no other bus member forces the AVR to slave
via SS line.
Bits CPOL and CPHA define the polarity and phase of the SPI clock.
Figure 88 shows the conditions in dependence of the initialization.
Bits SPR1 and SPR0 define the SPI clock rate. Here the clock is
CK/4. The evaluation board uses a clock frequency of 4 MHz and the
SPI clock is 1 MHz. As always data packages are sent, the net data
rate of 1 Mbit/s is not reached.
166
SCK (CPOL=0)
SCK (CPOL=1)
167
VCC
SDA
SCL
2
Figure 89 I C Bus Network
2
Before we deal with the first I C bus program example, I would like to
explain some frequently used terms.
168
Term Explanation
WORD 8 data bits
PAGE 16 consecutive memory locations
PAGE BLOCK 2048 bits organized in 16 pages
2
any I C device controlling data exchange (a micro-
MASTER
controller, for example)
2
SLAVE controlled I C device
2 2
I C device sending data to the I C bus (master or
TRANSMITTER
slave)
2 2
I C device receiving data from I C bus (master or
RECEIVER
slave)
2
TRANSCEIVER I C device containing transmitter and receiver
2 2
In the I C bus program example, one I C bus EEPROM is connected
to two I/O pins of the AVR microcontroller. Due to the required read
and write operations, memory devices are well suited for describing
2
of I C bus operations.
2
The slave address of each I C bus device contains the Device Type
Identifier. The used EEPROM of the NM24Cxx family has the follow-
ing slave address. The Device Type Identifier is here &B1010.
1 0 1 0 A2 A1 A0 R//W
Device A2 A1 A0 Memory
NM24C02 addr addr addr 2K
NM24C04 addr addr x 4K
NM24C08 addr x x 8K
NM24C16 x x x 16 K
169
2
As shown in the table, one I C network can address max. 16 Kbit
(16384 bits) of memory. It does not matter whether one NM24C16 or
eight NM24C02 or other configurations are used.
For addressing an EEPROM, there are two different addressing lev-
els:
1. Hardware configuration by pins A2, A1 and A0 (Device Address
Pins) with pull-up or pull-down resistors. All unused pins (marked
with x in the table) must be connected to GND.
2. Software addressing of the used memory segment (Page Block)
within the memory of the used device.
For addressing the memory in EEPROM the respective command
must provide the following information:
[DEVICE TYPE]
[DEVICE ADDRESS]
[PAGE BLOCK ADDRESS]
[BYTE ADDRESS]
In the program example, the EEPROM NM24C16 is used. Because
of its 16 Kbit memory there is no hardware configuration possible.
Pins A2, A1 and A0 must be connected to GND.
Bits A2, A1 and A0 of the slave address point to an internal memory
segment (PAGE BLOCK). The LSB of the slave address defines
writing (Hi) or reading (Lo).
Byte Write (write one byte to any memory location) and Random
Read (read one byte from any memory location) are two basic func-
2
tions for data exchange via the I C bus. To make access to the
memory in an EEPROM more effective, there are further possibilities
for access like Page Write, Current Address Read and Sequential
Read.
The program example focuses on the basic functions. Using the
knowledge acquired, it should be no problem to complete the special
functions. Figure 90 shows the bit sequences for the Byte Write and
Random Read operations.
170
Byte Write S A A A P
Random Read S A A S A P
Every command begins with a start condition (S). The start condition
2
is defined by a falling edge on SDA during SCL = Hi. Each I C bus
device permanently detects the levels on the SDA and SCL lines to
find a valid start condition. If no valid start condition is found, no de-
vices will answer.
The first byte after a start condition is the slave address showing a
write access to the addressed memory segment. The transmitting
2
device releases the I C bus after eight transmitted bits. During the
ninth clock the receiver forces line SDA to Lo to ACKnowledge (A)
the eight bits received. This acknowledge mechanism is a software
agreement for a successful data exchange.
The second byte sent addresses the memory location inside the
addressed memory segment for a following read or write operation.
The last transmitted bits are followed by the acknowledge check.
In a Byte Write operation the data byte is sent as the third byte. The
last transmitted bits are again followed by the acknowledge check.
In a Random Read operation following the check for acknowledge, a
new start condition must be sent. The first byte after this new start
condition is a slave address and an indicated read access to the
memory location addressed before. After the last bits have been
sent, the check for acknowledge is carried out again to read the ad-
dressed EEPROM cell.
2
During a read access the I C bus slave sends eight data bits and
then checks the acknowledge from the master. If acknowledge is
detected and no stop condition is sent from the master, the slave will
send further data. If acknowledge is not detected, the slave will stop
sending data and waits for a stop condition to return to standby.
Each data exchange ends with a stop condition (P). The stop condi-
tion is defined by a rising edge on line SDA during SCL = Hi. The
171
stop condition additionally switches the EEPROMs of the NM24Cxx
family to the current saving standby mode.
Listing 46 shows the program example for writing and reading the
EEPROM NM24Cxx reflecting the bit sequences shown in Figure 90.
Temp = Page_addr
Shift Temp , Left
End
172
2
Listing 46 Access to I C EEPROM NM24C16 by AVR (IIC.BAS)
173
protocols which is suitable for both small microcontrollers and larger
systems.
The scalable network protocol S.N.A.P. (Scalable Node Address
Protocol) is the result of this development.
174
4.11.2 Description of S.N.A.P. Protocol
Communication between network nodes is in the form of data pack-
ages. These data packages can have different lengths. The total
length will be determined by the number of address and data bytes,
the error detection method and some specific bytes.
The Header Definition Bytes, HDB2 and HDB1, determine the
structure of the data package (telegram) and its length. Each tele-
gram can have an uncertain number of preamble bytes before the
synchronization byte. The preamble byte must differ from the syn-
chronization byte.
The following example shows a small S.N.A.P. package with CRC16
error detection:
PRE ... SYNC HDB2 HDB1 DAB1 SAB1 DB1 CRC2 CRC1
It means:
Name Description
PRE Preamble
SYNC Synchronization
HDB2 Header Definition Byte 2
HDB1 Header Definition Byte 1
DAB1 Receiver address
SAB1 Transmitter address
DB1 Data byte
CRC2 Most significant byte of CRC16
CRC1 Least significant byte of CRC16
Without the optional preamble bytes the whole data package is eight
bytes long. The bytes are right positioned with its LSB (least signifi-
cant bit; bit7...bit0).
175
bit 7 6 5 4 3 2 1 0 HEX DEC
0 1 0 1 0 1 0 0 54 84
bit 7 6 5 4 3 2 1 0
HDB2 DAB SAB PFB ACK
Name Description
DAB Number of bytes for destination address
SAB Number of bytes for source address
PFB Number of bytes for protocol specific flags
ACK ACK/NAK bits
CMD Command bit
EDM Error detection method
NDB Number of data bytes
176
DAB Definition
0 0 Destination address 0 Byte
0 1 Destination address 1 Byte
1 0 Destination address 2 Byte
1 1 Destination address 3 Byte
SAB Definition
0 0 Source address 0 Byte
0 1 Source address 1 Byte
1 0 Source address 2 Byte
1 1 Source address 3 Byte
PF Definition
0 0 Protocol specific flags 0 Byte
0 1 Protocol specific flags 1 Byte
1 0 Protocol specific flags 2 Byte
1 1 Protocol specific flags 3 Byte
The flag bytes are reserved for the time being, but not defined yet.
They are planned for further enhancements of the S.N.A.P. protocol.
ACK Definition
0 0 No acknowledge
0 1 Transmitter requests for acknowledge
1 0 Receiver sends back ACK
1 1 Receiver sends back NAK
CMD Definition
0 No command mode
1 Command mode (DB1 contains command)
177
command. Different commands are possible due to the byte format
256.
It is dependent on the error detection method how safely a communi-
cation link works. The 16-bit CRC is a preferred method in this area.
EDM Definition
0 0 0 No error detection
0 0 1 Repeat three times
0 1 0 8-bit check sum
0 1 1 8-bit CRC-CCITT
1 0 0 16-bit CRC-CCITT
1 0 1 32-bit CRC-CCITT
1 1 0 Error correction
1 1 1 Spec. error detection
178
NDM Definition
0 0 0 0 0 Byte
0 0 0 1 1 Byte
0 0 1 0 2 Byte
0 0 1 1 3 Byte
0 1 0 0 4 Byte
0 1 0 1 5 Byte
0 1 1 0 6 Byte
0 1 1 1 7 Byte
1 0 0 0 8 Byte
1 0 0 1 16 Byte
1 0 1 0 32 Byte
1 0 1 1 64 Byte
1 1 0 0 128 Byte
1 1 0 1 256 Byte
1 1 1 0 512 Byte
1 1 1 1 Spec. number
The addresses are reduced to one byte. Only one byte will be trans-
ferred. Header Definition Bytes HDB2 and HDB1 contain the follow-
ing values:
179
bit 7 6 5 4 3 2 1 0 HEX DEC
HDB2 DAB SAB PFB ACK
0 1 0 1 0 0 0 0 50 80
Read next 5
If the telegram can be evaluated, then the
Bytes program checks the receiver address.
Only if all information is correct, the program
reads from byte SADR the address of the
transmitter and from byte DB1 the respective
HDB2 ?
data byte. Both data will be displayed on LCD
N
Y in the example.
Listing 47 shows the details of the S.N.A.P.
HDB1 ?
application. The area of the associated func-
N
Y tion is specially marked.
Addr ?
N
Y
Display
SAD & DB1
on LCD
Figure 91
Program structure
SNAP-MON
180
' -----[ Title ]-------------------------------------------
'
' File....: SNAP-MON.BAS
' Purpose.: SNAP Monitor with 16 x 1 LCD
' Author..: Claus Kuehnel (based on SNAP-024.BAS from HTH)
' Version.: 1.00
' MCU.....: AT90S8515
' Started.. 991211
' Updated.:
'
' -----[ Program Description ]-----------------------------
'
' This program shows how to implement the S.N.A.P protocol
' in BASCOM and is an simple example to receive data from
' another node and display it on the LCD.
' This example uses no error detection method.
'
' If the node is addressed by another node (PC or another
' MCU) it shows what node sent the packet and the value of
' DB1 in hexadecimal on the LCD. In the example below node
' with address &H05 is sending &HEF in the data byte.
'
' 16x1 LCD display
' +------------------+
' | FROM:05 DATA:EF |
' +------------------+
'
' The packet structure is defined in the received packets
' first two bytes (HDB2 and HDB1). The following packet
' structure is used.
'
' DD=01 - 1 Byte destination address
' SS=01 - 1 Byte source address
' PP=00 - No protocol specific flags
' AA=00 - Acknowledge is required
' C=0 - Command mode not supported
' EEE=000 - No error detection
' NNNN=0001 - 1 Byte data
'
'
' -----[ Aliases ]----------------------------------------
'
Spkr Alias Portb.1 ' Speaker output pin
'
' -----[ Constants ]---------------------------------------
'
Const Sync = &B01010100 ' Synchronisation byte
Const Hdb2_ = &B01010000 ' 1-Byte Addr., No Flags, No ACK
Const Hdb1_ = &B00000001 ' No Error Detection, 1 Data Byte
Const Myaddress = &H04 ' Address for this node (1-255)
_start:
Temp1 = Waitkey() ' Wait for data on serialport
182
' Done, go back to Start and wait for a new packet
Goto _start
End If
End
To modify the program for BASCOM-8051, the port line for the
speaker (Spkr Alias Portb.1 to Spkr Alias P3.1, for ex-
ample) and the display instructions lcd hex(var) to lcdhex var
need to be changed.
Here, too, the addresses are reduced to one byte each. Two data
bytes, DB2 and DB1, and two CRC bytes, CRC2 and CRC1, will be
transmitted.
Header Definition Bytes HDB2 and HDB1 contain the following val-
ues:
183
bit 7 6 5 4 3 2 1 0 HEX DEC
HDB2 DAB SAB PFB ACK
0 1 0 1 0 0 0 1 51 81
Listing 48 shows the program that waits for receiving a telegram and
evaluates it according to Figure 92.
184
_Start
Figure 92
Program Structure SNAP-IO.BS2
185
' -----[ Title ]-------------------------------------------
'
' File......: SNAP-IO.BAS
' Purpose...: Turns LEDs on and off
' Author....: Christer Johansson
' Version...: 1.01
' Started...: 980503
' Updated...: 980918
' Modified..: 991229 by Claus Kuehnel
'
' -----[ Program Description ]-----------------------------
'
' This program shows how to implement the S.N.A.P protocol
' in BASCOM-AVR and is an simple example to turn LEDs ON or
' OFF.
' This example uses 16-bit CRC-CCITT as error detection
' method which gives secure data transfer.
'
' The packet structure is defined in the received packets
' first two bytes (HDB2 and HDB1). The following packet
' structure is used.
'
' DD=01 - 1 Byte destination address
' SS=01 - 1 Byte source address
' PP=00 - No protocol specific flags
' AA=01 - Acknowledge is required
' D=0 - No Command Mode
' EEE=100 - 16-bit CRC-CCITT
' NNNN=0010 - 2 Byte data
'
' Overview of header definition bytes (HDB2 and HDB1)
'
' HDB2 HDB1
' +-----------------+-----------------+
'|DDSSPPAA|DEEENNNN|
' +-----------------+-----------------+
'
'
' -----[ Constants ]---------------------------------------
'
Const Preamble_ = &B01010101 ' Preamble byte
Const Sync_ = &B01010100 ' Synchronisation byte
Const Crcpoly = &H1021 ' CRC-CCITT
Const Hdb2_ = &H51
Const Hdb1_ = &H42
Const Myaddress = 123 ' Address for this node (1-255)
Preamble = Preamble_
Sync = Sync_
187
'
' Associated Function (place it between +++ lines)
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Portb = Db1
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'
Ack_:
' Send ACK (i.e tell master that packet was OK)
' Set ACKs bit in HDB2 (xxxxxx10)
Hdb2 = Hdb2 Or &B00000010
Hdb2 = Hdb2 And &B11111110
Goto Send
Nak:
' Send NAK (i.e tell master that packet was bad)
' Set ACK bits in HDB2 (xxxxxx11)
Hdb2 = Hdb2 Or &B00000011
Goto Send
Send:
' Swap SAB1 <-> DAB1 address bytes
Temp2 = Sab1
Sab1 = Dab1
Dab1 = Temp2
189
' Subroutine for calculating CRC value in variable Tmp_Byte1
Calc_crc:
Tmpw1 = Temp1 * 256
Crc = Tmpw1 Xor Crc
For Temp2 = 0 To 7
If Crc.15 = 0 Then Goto Shift_only
Tmpw2 = Crc * 2
Crc = Tmpw2 Xor Crcpoly
Goto Nxt
Shift_only:
Crc = Crc * 2
Nxt:
Next
Return
190
Figure 93 Configuration of the Serial Interface
After this first step, the telegrams can be built up. Figure 94 shows
the respective window.
191
Figure 94 SnapLab - Transmit and Receive
For the input of the data bytes to be sent to the network node, the
number pad of the PC keyboard should be used.
For the input of data byte 84 for example, strike 0-8-4 keeping the Alt
key pressed. The character will be sent when the Alt key is released.
After the start of program RS232MON and the configuration of the
serial port, the telegram can be inputted as described. Figure 95
shows the input and the response from the network node. The byte
sequences appear very cryptic.
193
Figure 95 S.N.A.P. Telegram in RS232MON
A short look at the receive window (F3) shows that the telegram was
transmitted without any errors (Figure 96).
194
Figure 96 Hexdump of a Received S.N.A.P. Telegram
Due to the acknowledge bits (10) the Header Definition Byte HDB2 of
the response is 82 (=&H52). The data bytes are unchanged. Source
and destination addresses are swapped and the 16-bit CRC is
changed.
195
Figure 97 Wrong CRC Byte in S.N.A.P. Telegram
The CRC check in the network node detects the error and sets the
acknowledge bits to 11B. As Figure 98 shows, byte HDB2 in the re-
sponse is 83 (= &H53) as a result.
196
Figure 98 Hexdump of a Received S.N.A.P. Telegram
197
The generation and transmission of the resulting message is the task
of the CAN controller. When the CAN controller gets access to the
bus, all other network nodes are receivers of this message.
As soon as the message is received, an acceptance check is per-
formed: the identifier is read, and it is determined whether the data
are relevant to this node or not. If so they will be processed, if not
they will be ignored.
The contents-related addressing guarantees a high system and con-
figuration flexibility. It is very easy to add new network nodes to an
existing CAN network.
The CAN protocol supports two formats of message frames which,
essentially, differ in the length of the identifier (ID) only.
The identifier length is 11 bits in the standard format and 29 bits in
the enhanced format. The whole message frame for CAN data
transmission comprises seven fields. Figure 99 shows a CAN stan-
dard frame.
A standard format message begins with the start bit - Start of Frame
(SOF). The Arbitration Field following it contains the identifier (ID)
and the Remote Transmission Request bit (RTR). This bit marks the
frame as Data Frame or Remote Frame without any data.
The Control Field contains the Identifier Extension bit (IDE) that dis-
tinguishes between standard and enhanced format, a reserved bit for
further enhancements and the Data Length Code (DLC) specifying
the number of data bytes in the frame.
As defined by the DLC, the Data Field can have a length of 0 to 8
bytes.
The CRC Field contains a 15-bit CRC for error detection. The Ac-
knowledge Field (ACK) comprises the ACK slot (one recessive bit).
The bit in that ACK slot is sent recessive and will be overwritten
dominant from all nodes that receive the message correctly (positive
198
acknowledge). This acknowledge is independent of the result of the
acceptance check.
The End of Frame marks the end of a message. Intermission is the
minimum number of bit times between two consecutive messages. If
there is no further bus access the bus will be idle.
These basics should explain the context and can be consolidated in
the relevant CAN literature.
Based on the AT90S8515, the Swedish company LAWICEL
[http://www.candip.com] developed the microcontroller module
CANDIP/AVR. CANDIP/AVR contains all components required to
build an interface to the CAN bus. Figure 100 shows the
CANDIP/AVR module.
199
• Up to 13 digital I/O points on DIP28 board, each capable of sink-
ing 20 mA as output.
• SPI port for expansion.
• One interrupt line available for user functions (INT1).
• SJA1000 CAN controller working at 16MHz, supporting CAN2.0B.
• 82C250 High Speed CAN transceiver 1Mbit (ISO-11898).
• CAN controller can be interrupt driven (INT0).
• MAX202 RS-232 transceiver which together with the AVR can
send/receive up to 115 kbit/s.
• MAX825M reset circuit, the normal RESET and inverted RESET
is via external pins.
• No interpreted software, it is programmed with compilers.
• Possibilities to implement higher level protocols such as
CANopen, DeviceNet etc.
Figure 101 shows the block diagram of the CANDIP/AVR module
with external components.
200
Figure 101
Block Diagram of CANDIP/AVR Module with External Components
201
Figure 102 CANDIP/AVR Activity Board
202
Figure 103 CANDIP/AVR Network
$crystal = 3686400
$baud = 57600
Const Own_id = 0
' Our CAN-ID
Const Acceptmask = &HFF
' Our accept mask
Const Resreq = 1
' Reset Request
Const Rbs = 1
' Receive Buffer Status
Const Rrb = 4
' Release Receive Buffer
Const Txreq = 1
' Transmit Request
Const Tba = 4
' Transmit Buffer Access
Always = 1
Inpb = &H0C
' Default button status
Inpbold = &H0C
Mcucr = &HC0
' Enable External Memory Access With Wait - state
Ddrb = &H03
' Set PB0+PB1 as output and PB2+PB3 as input with pull-up
Portb = &H0F
' and turn off LED's
Ddrd = &H00
' Set PD3+PD4+PD5 as inputs with pull-up
Portd = &H38
Nodeid = Pind
' Read Jumper inputs on Port D and save as Node ID.
Rotate Nodeid , Right , 3
Nodeid = Nodeid And &H07
Nodeid = 7 - Nodeid
' Invert, how to make it better in BASCOM?
205
Initsja
While Always = 1
Inpb = Pinb And &H0C
' Read inputs PB2 & PB3
End
Sub Initsja
' Initiate CAN controller 125kbit
Local B As Byte
B = Inp(can_ctrl)
B = B And Resreq
While B = 0
out can_ctrl,resreq
B = Inp(can_ctrl)
B = B And Resreq
Wend
out Can_ac, Own_id
out Can_am, Acceptmask
out Can_tmg_0,3
out Can_tmg_1,&H1C
out Can_ocr,&HDE
out Can_clkdiv,7
out Can_ctrl,&H5E
out Can_cmd,&H0C
End Sub
Do
' Loop until transmit buffer is empty
Tmp1 = Inp(can_status)
Tmp1 = Tmp1 And Tba
Loop Until Tmp1 = Tba
Id = &H500 + Nodeid
' Create ID based on NodeId
Ln = 1
Tmp1 = Id
Rotate Tmp1 , Right , 3
Tmp2 = Low(tmp1)
out Can_tx_id, Tmp2
Tmp1 = Id And &H07
Rotate Tmp1 , Left , 5
Tmp1 = Tmp1 + Ln
Tmp2 = Low(tmp1)
206
out Can_tx_len, Tmp2
out Can_tx_buf0, b
out Can_cmd, Txreq
End Sub
Sub Checkcan
Local Id As Word
Local Tmp1 As Word
Local Ln As Byte
Local Tmp2 As Byte
Tmp2 = Inp(can_status)
Tmp2 = Tmp2 And Rbs
207
Subroutine Transmitcanio sends the CAN message to the net-
work. After the subroutine call, the routine waits until the Transmit
Buffer Status signalizes a free buffer. When the Transmit Buffer is
free, the CPU can write a prepared message to the buffer.
Preparing the CAN message means defining identifier, data length,
and data bytes. According to Figure 103 the identifiers are &H500
and &H501. The data length is one byte for the input state of the two
input lines.
These definitions are followed by the output of identifier, data length,
data byte, and a Transmission Request. The Transmission Request
requests the CAN controller to send this CAN message.
All received CAN messages that have passed the Acceptance Filter
are written to the Receive Buffer. Subroutine Checkcan checks the
Receive Buffer for CAN messages and processes them, if neces-
sary. The subroutine reads identifier, data length, and data byte from
the Receive Buffer.
If the received CAN messages came from the respectively other
node, the transmitted input state is displayed by the connected LEDs.
After the received CAN message has been processed, the Receive
Buffer is released again.
On the basis of the described program example CANDIPIO.BAS,
further CAN applications can be developed using BASCOM-AVR.
A lot of supporting hardware is now available if an 8051 derivative is
preferred to be used for the CAN application. There are 8051 deriva-
tives with integrated CAN controllers or modules comparable with
CANDIP/AVR.
Based on Infineon's C505CA, LAWICEL is offering the CANDIP/505.
Features of the CANDIP/505 microcontroller module:
• Standard 28 pin DIP board with 0.1" pins (use a standard DIP28
carrier).
• 4 layer board for good EMI performance.
• Needs a 5V DC/30mA power source only (plus 70mA for CAN
transceiver).
• Infineon type C505CA working at 16MHz.
• 64k bytes user FLASH, 1k bytes user XRAM and 128 bytes user
EEPROM.
• ADC with 10bit resolution / 4 channels.
208
• Software controller SPI port for expansion.
• On chip full CAN-Controller (CAN 2.0B).
• 82C250 High Speed CAN transceiver 1Mbit (ISO-11898).
• MAX202 RS-232 transceiver.
• MAX825M Reset circuit.
• No interpreted software, it is programmed with compilers.
• Possibilities to implement higher level protocols such as
CANopen, DeviceNet, etc.
• PC-Bootloader for program download in Flash-EPROM via the
CAN interface.
• Demo software for the individual hardware components.
For fast and comfortable debugging of CAN applications, LAWICEL
offers the Activity Board (ACB2) for CANDIP/505.
209
Dim Value As Integer
Dim Seed As Integer
X = Seed * 259
X=X+3
Seed = X And &H7FFF
Y = Seed * Z
Y = Y / &H7FFF
Y=Y+1
Random = Y
End Function
Listing 50 Generation of random numbers (RANDOM.BAS)
210
ing random numbers to the microcontroller that can use these num-
ber as measuring results, for example.
A good source of random numbers is the URL
http://www.random.org/ nform.html. The number of random numbers
as well as the minimum and maximum values can be defined in an
input form. Figure 104 shows such a (completed) input form.
211
Figure 105 Requested Random Numbers
300
250
200
150
100
50
0
15
22
29
36
43
50
57
64
71
78
85
92
99
1
212
To save the generated random numbers for later use, the contents of
the browser window are saved as text file. The proposal in the
browser was RANDNUM.TXT and is used without any changes.
Important is the saving as text file, because the alternative HTML file
contains a lot of information not used here.
A terminal program can send this text file to the microcontroller now.
A simple program was installed for test purposes (Listing 51). The
program will be ported to BASCOM-8051 when PortB is changed to
P3, for example, and line Config Portb ... is erased.
Do
Input Str_input Noecho
Value = Val(str_input)
Portb = Not Value
Loop
End
Listing 51 Test Program GETRANDOM.BAS
213
4.14 Moving Average
The calculation of the moving averageis a basic function of many
measuring instruments.
Each measured value has a variation range. In an audio signal such
a variation can be heard as noise. The calculation of a moving aver-
age is one means to reduce, or suppress, noise in any signal.
Figure 107 shows the principle of calculating a moving average.
214
' MEAN.BAS by BASCOM-AVR
Lenght = 5
Dim Buffer(lenght) As Byte
Do
Index = Lenght - 1
Do
Temp = Buffer(index)
Incr Index
Buffer(index) = Temp
Decr Index
Decr Index
Loop Until Index = 0
End
215
Function Random(byval Z As Integer) As Integer
Local X As Integer
Local Y As Long
X = Seed * 259
X=X+3
Seed = X And &H7FFF
Y = Seed * Z
Y = Y / &H7FFF
Y=Y+1
Random = Y
End Function
Listing 52 Moving Average (MEAN.BAS)
300
200
100
0
106
121
136
151
166
181
196
211
16
31
46
61
76
91
1
216
300
250
200
150
100
50
0
106
121
136
151
166
181
196
211
1
16
31
46
61
76
91
Figure 109 Moving average over 16 positions
Better smoothing gives a more even curve but must be paid for with
a delay.
Choosing the length of the shift register as power of 2 (2, 4, 8 etc.)
allows the awkward division operation to be replaced by a simple
shift operation.
For a shift register length of 16, the division by 16 can be replaced by
a shift by 4:
217
218
5 Appendix
219
36 0x24 $ 100 0x64 d
37 0x25 % 101 0x65 e
38 0x26 & 102 0x66 f
39 0x27 ' 103 0x67 g
40 0x28 ( 104 0x68 h
41 0x29 ) 105 0x69 i
42 0x2A * 106 0x6A j
43 0x2B + 107 0x6B k
44 0x2C , 108 0x6C l
45 0x2D - 109 0x6D m
46 0x2E . 110 0x6E n
47 0x2F / 111 0x6F o
48 0x30 0 112 0x70 p
49 0x31 1 113 0x71 q
50 0x32 2 114 0x72 r
51 0x33 3 115 0x73 s
52 0x34 4 116 0x74 t
53 0x35 5 117 0x75 u
54 0x36 6 118 0x76 v
55 0x37 7 119 0x77 w
56 0x38 8 120 0x78 x
57 0x39 9 121 0x79 y
58 0x3A : 122 0x7A z
59 0x3B ; 123 0x7B {
60 0x3C < 124 0x7C |
61 0x3D = 125 0x7D }
62 0x3E > 126 0x7E ~
63 0x3F ? 127 0x7F DEL DEL
220
221
5.3 Characters in Seven-Segment Display
222
5.4 BASIC Stamp II
The BASIC Stamp II (BS2) is a microcontroller programmable in
BASIC. Based on Microchip's PIC16C57 and equipped with Paral-
lax's PBASIC2 Firmware, a microcontroller is obtained that executes
BASIC tokens saved in an EEPROM. The whole infrastructure is
available in a 24pin DIL module. Figure 110 shows the BS2 Module.
223
5.5 Literature
224
5.6 Links
225
S.N.A.P - Scaleable Node Address Protocol
Description of S.N.A.P. including some sample programs and possibil-
ity of download
http://www.hth.com/snap/
CANDIP - How easy and inexpensive can CAN be?
LAWICEL's Web Site with description of the CANDIP device
http://www.candip.com
SJA1000 Stand-alone CAN Controller
Philips' web site for download of CAN controller data sheet
http://www.semiconductors.philips.com
226
6 Index
231
232
233
Other books by Claus Kuhnel:
234
Practical guide for advanced hobbyists or de-
sign professionals.
Development tools and code available on the
Web.
ISBN: 0-7506-9963-9
Paperback
Measurements: 6 x 9.25 In.
Pages: 256pp
Publication Date: May 07, 1998
Price: $36.95
The AVR RISC Microcontroller Handbook is a comprehensive guide to
designing with Atmel's new controller family, which is designed to offer high
speed and low power consumption at a lower cost. The main text is divided
into three sections: hardware, which covers all internal peripherals; soft-
ware, which covers programming and the instruction set; and tools, which
explains using Atmel's Assembler and Simulator (available on the Web) as
well as IAR's C compiler.
Introduction to PIC microcontroller operation.
Applications for designers and hobbyists.
Integrated hardware and software coverage.
ISBN: 0-7506-9891-8
Paperback
Measurements: 6.25 x 9.25 In.
Pages: 208pp
Publication Date: February 19, 1997
Price: $34.95
BASIC Stamp introduces microcontroller theory using the Parallax BASIC
Stamp I and II. The BASIC Stamp microcontroller is based on Microchip's
PIC hardware with some modifications, and is very approachable for be-
ginning users. The book covers both the hardware and software ends of
the chip's operation. Once the basic theory is established, the majority of
BASIC Stamp walks you through applications suitable for designers as well
as the home hobbyist. These applications can be used as is, or as a basis
for further modifications to suit your needs.
235
236