0% found this document useful (0 votes)
30 views1,724 pages

Manual Bascom AVR

The BASCOM-AVR user manual introduces BASCOM, a user-friendly programming tool for microprocessors developed by MCS Electronics since 1995. It includes installation instructions, IDE features, and hardware information, along with contributions from various users and developers. The manual aims to facilitate easy and enjoyable work with microprocessors through comprehensive guidance and sample codes.

Uploaded by

Wilfredo Flores
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views1,724 pages

Manual Bascom AVR

The BASCOM-AVR user manual introduces BASCOM, a user-friendly programming tool for microprocessors developed by MCS Electronics since 1995. It includes installation instructions, IDE features, and hardware information, along with contributions from various users and developers. The manual aims to facilitate easy and enjoyable work with microprocessors through comprehensive guidance and sample codes.

Uploaded by

Wilfredo Flores
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1724

© MCS Electronics v.o.f.

, 1995-2021
BASCOM-AVR user manual
Introduction
by MCS Electronics

Dear reader.

Thank you for your interest in BASCOM.

BASCOM was "invented" in 1995. It was intended for personal usage only. I
decided to make it public as I found no other tool that was so simple to use.
Since that time, a lot of options and extensions were added. Without the help
and patience of the many users, BASCOM would not be what it is today :
"the best and most affordable tool for fast proto typing".

We hope that BASCOM will contribute in making your work with


microprocessors Easy and enjoyable.

Please notice that the samples in the manual are intended as simple
samples. You should have a look at the sample code provided in the
SAMPLES directory.

The MCS Electronics Team


BASCOM-AVR

© 2021 MCS Electronics

All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the
written permission of the publisher.

Products that are referred to in this document may be either trademarks and/or registered trademarks of the
respective owners. The publisher and the author make no claim to these trademarks.

While every precaution has been taken in the preparation of this document, the publisher and the author assume no
responsibility for errors or omissions, or for damages resulting from the use of information contained in this document
or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be
liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or
indirectly by this document.

Printed: 21-4-2021

Special thanks to:


Publisher
MCS Electronics All the people who contributed to this document, all the
forum members that contributed in a positive way, all beta
Managing Editor testers , and all customers.
M.C.Alberts
While there is not enough space to mention all
contributors, there are a few that I feel must be mentioned
Technical Editors
:
M.C.Alberts Josef Franz Vögel. He wrote the Trig libraries, the
AVR-DOS file system and the DOUBLE library.

Cover Designer Luciano, Ian, Adrian and Kimmi, they are very active on
the user forum. They take the time to give other forum
B.F.de Graaff members free help and advise. They do this for free just to
help other BASCOM users.

MWS for his help and debugging.

MAK for pushing XMEGA, his samples and testing.

Peter Maroudas, RIP, for his work on the FT800 and FT801
implementation.

Ben Zijlstra, RIP, for being a true ambassador for BasCom.


4 BASCOM-AVR

Table of Contents
Foreword 0

Part I Index 27
1 Keyword...................................................................................................................................
Reference 28
2 Changes................................................................................................................................... 32
What is new
.........................................................................................................................................................
in 2084 32
What is new
.........................................................................................................................................................
in 2083 33
What is new
.........................................................................................................................................................
in 2082 35
What is new
.........................................................................................................................................................
in 2081 36
What is new
.........................................................................................................................................................
in 2080 37
What is new
.........................................................................................................................................................
in 2078-2079 38
3 About MCS
...................................................................................................................................
Electronics 42
Custom Designs
......................................................................................................................................................... 44
Application
.........................................................................................................................................................
Notes 45
About this.........................................................................................................................................................
Help 45

Part II Installation 47
1 Installation
...................................................................................................................................
of BASCOM 47
2 Updates ................................................................................................................................... 55
3 Move to new
...................................................................................................................................
PC 60
4 Installation
...................................................................................................................................
on multiple computers 61
5 Registration
................................................................................................................................... 61

Part III BASCOM IDE 63


1 Running ...................................................................................................................................
BASCOM-AVR 63
2 File New ................................................................................................................................... 70
3 File Open................................................................................................................................... 70
4 File Close................................................................................................................................... 70
5 File Save................................................................................................................................... 70
6 File Save...................................................................................................................................
As 71
7 File Print...................................................................................................................................
Preview 71
8 File Print................................................................................................................................... 71
9 File Project
................................................................................................................................... 71
10 File ZIP ................................................................................................................................... 74
11 File Exit ................................................................................................................................... 75
12 Edit Undo
................................................................................................................................... 75
13 Edit Redo................................................................................................................................... 75
14 Edit Cut ................................................................................................................................... 75
15 Edit Copy................................................................................................................................... 75
16 Edit Paste
................................................................................................................................... 75
17 Edit Find................................................................................................................................... 75
18 Edit Find...................................................................................................................................
Next 78

© 2021 MCS Electronics


Contents 5

19 Edit Replace
................................................................................................................................... 78
20 Edit Goto................................................................................................................................... 79
21 Edit Toggle
...................................................................................................................................
Bookmark 79
22 Edit Goto...................................................................................................................................
Bookmark 79
23 Edit Indent
...................................................................................................................................
Block 79
24 Edit Unindent
...................................................................................................................................
Block 79
25 Edit Remark
...................................................................................................................................
Block 79
26 Edit Insert
...................................................................................................................................
ASCII 80
27 Edit Fold...................................................................................................................................
All Subs and Functions 80
28 Edit Unfold
...................................................................................................................................
All Code 81
29 Edit Encrypt
...................................................................................................................................
Selected Code 81
30 Edit Proper
...................................................................................................................................
Indent 82
31 Edit Show
...................................................................................................................................
Excluded Code 83
32 Edit Show
...................................................................................................................................
Dead Code 84
33 View PinOut
................................................................................................................................... 86
34 View PDF...................................................................................................................................
viewer 90
35 View Error
...................................................................................................................................
Panel 92
36 View Tip ................................................................................................................................... 92
37 View Project
...................................................................................................................................
Files 93
38 View Code
...................................................................................................................................
Explorer 93
39 View Vertical
...................................................................................................................................
Splitter 99
40 Program...................................................................................................................................
Compile 100
41 Program...................................................................................................................................
Syntax Check 101
42 Program...................................................................................................................................
Show Result 102
43 Program...................................................................................................................................
Simulate 103
44 Program...................................................................................................................................
Send to Chip 116
45 Tools Terminal
...................................................................................................................................
Emulator 120
46 Tools LCD
...................................................................................................................................
Designer 122
47 Tools LIB
...................................................................................................................................
Manager 124
48 Tools Graphic
...................................................................................................................................
Converter 125
49 Tools Stack
...................................................................................................................................
Analyzer 126
50 Tools Plugin
...................................................................................................................................
Manager 126
51 Tools Batch
...................................................................................................................................
Compile 127
52 Tools PDF
...................................................................................................................................
Update 130
53 Tools Resource
...................................................................................................................................
Editor 132
54 Tools Font
...................................................................................................................................
Editor 133
55 Options...................................................................................................................................
Compiler 135
Options .........................................................................................................................................................
Compiler Chip 135
Options .........................................................................................................................................................
Compiler Output 137
Options .........................................................................................................................................................
Compiler Communication 138
Options .........................................................................................................................................................
Compiler I2C, SPI, 1WIRE 139
Options .........................................................................................................................................................
Compiler LCD 140
56 Options...................................................................................................................................
Communication 141

© 2021 MCS Electronics


6 BASCOM-AVR

57 Options...................................................................................................................................
Environment 142
58 Options...................................................................................................................................
Simulator 151
59 Options...................................................................................................................................
Programmer 152
Supported
.........................................................................................................................................................
Programmers 154
ISP programmer
.................................................................................................................................................. 155
PG302 programmer
.................................................................................................................................................. 156
Sample ..................................................................................................................................................
Electronics cable programmer 156
KITSRUS ..................................................................................................................................................
Programmer 157
MCS Universal
..................................................................................................................................................
Interface Programmer 158
STK500..................................................................................................................................................
Programmer 160
Lawicel ..................................................................................................................................................
BootLoader 164
AVR ISP..................................................................................................................................................
Programmer 164
USB-ISP..................................................................................................................................................
Programmer 165
MCS Bootloader
.................................................................................................................................................. 174
PROGGY .................................................................................................................................................. 176
FLIP .................................................................................................................................................. 177
USBprog ..................................................................................................................................................
Programmer / AVR ISP mkII 180
KamProg ..................................................................................................................................................
for AVR 180
USBASP .................................................................................................................................................. 183
STK600.................................................................................................................................................. 184
ARDUINO .................................................................................................................................................. 187
BIPOM MINI-MAX/C
.................................................................................................................................................. 190
mySmartUSB..................................................................................................................................................
Light 190
UPDI Programmer
.................................................................................................................................................. 192
LIBUSB ......................................................................................................................................................... 195
60 Options...................................................................................................................................
Monitor 204
61 Options...................................................................................................................................
Printer 204
62 Options...................................................................................................................................
Select Settings File 205
63 Window...................................................................................................................................
Cascade 206
64 Window...................................................................................................................................
Tile 207
65 Window...................................................................................................................................
Tile Vertically 208
66 Window...................................................................................................................................
Arrange Icons 208
67 Windows
...................................................................................................................................
Maximize All 208
68 Window...................................................................................................................................
Minimize All 208
69 Help About
................................................................................................................................... 209
70 Help Index
................................................................................................................................... 210
71 Help MCS
...................................................................................................................................
Forum 210
72 Help MCS
...................................................................................................................................
Shop 211
73 Help Support
................................................................................................................................... 212
74 Help Knowledge
...................................................................................................................................
Base 212
75 Help Credits
................................................................................................................................... 213
76 Help Update
................................................................................................................................... 214
77 Help Wiki
................................................................................................................................... 216
78 BASCOM
...................................................................................................................................
Editor Keys 216
79 Program...................................................................................................................................
Development Order 217
80 PlugIns ................................................................................................................................... 217
Font Editor
......................................................................................................................................................... 217

Part IV BASCOM HARDWARE 221

© 2021 MCS Electronics


Contents 7

1 Additional
...................................................................................................................................
Hardware 221
2 AVR Internal
...................................................................................................................................
Hardware 221
3 AVR Internal
...................................................................................................................................
Registers 222
4 AVR Internal
...................................................................................................................................
Hardware TIMER0 224
5 AVR Internal
...................................................................................................................................
Hardware TIMER1 225
6 AVR Internal
...................................................................................................................................
Hardware Watchdog timer 227
7 AVR Internal
...................................................................................................................................
Hardware Port B 227
8 AVR Internal
...................................................................................................................................
Hardware Port D 229
9 Adding ...................................................................................................................................
XRAM with External Memory Interface 230
10 Adding ...................................................................................................................................
XRAM to XMEGA using EBI 234
11 Adding ...................................................................................................................................
SRAM 4-port Non Multiplexed 236
12 Attaching
...................................................................................................................................
an LCD Display 245
13 Memory...................................................................................................................................
usage 246
14 Statements
...................................................................................................................................
and Hardware Resources 257
15 Using the
...................................................................................................................................
UART 257
16 USING RS485
................................................................................................................................... 264
17 Using the
...................................................................................................................................
I2C protocol 266
18 Using the
...................................................................................................................................
1 WIRE protocol 278
19 Using the
...................................................................................................................................
SPI protocol 282
20 Using USI
...................................................................................................................................
(Universal Serial Interface) 289
21 Power Up
................................................................................................................................... 293
22 Reference
...................................................................................................................................
Designs 294
EM4095 .........................................................................................................................................................
RFID Reader 294

Part V Chips 304


1 AVR ................................................................................................................................... 304
2 AT86RF401
................................................................................................................................... 304
3 AT90 ................................................................................................................................... 304
AT90CAN32
......................................................................................................................................................... 304
AT90CAN128
......................................................................................................................................................... 305
AT90S1200
......................................................................................................................................................... 306
AT90S2313
......................................................................................................................................................... 307
AT90S2323
......................................................................................................................................................... 307
AT90S2333
......................................................................................................................................................... 308
AT90S2343
......................................................................................................................................................... 308
AT90S4414
......................................................................................................................................................... 310
AT90S4433
......................................................................................................................................................... 310
AT90S4434
......................................................................................................................................................... 312
AT90S8515
......................................................................................................................................................... 313
AT90S8535
......................................................................................................................................................... 313
AT90PWM2-3
......................................................................................................................................................... 314
AT90PWM216
......................................................................................................................................................... 315
AT90US82
......................................................................................................................................................... 316
AT90USB162
......................................................................................................................................................... 317
AT90USB646
......................................................................................................................................................... 318
AT90USB1286
......................................................................................................................................................... 319
AT90USB1287
......................................................................................................................................................... 320
4 ATTINY ................................................................................................................................... 320

© 2021 MCS Electronics


8 BASCOM-AVR

ATTINY12
......................................................................................................................................................... 320
ATTINY13
......................................................................................................................................................... 321
ATTINY13A
......................................................................................................................................................... 321
ATTINY15
......................................................................................................................................................... 321
ATTINY20
......................................................................................................................................................... 321
ATTINY22
......................................................................................................................................................... 322
ATTINY24
......................................................................................................................................................... 322
ATTINY25
......................................................................................................................................................... 323
ATTINY26
......................................................................................................................................................... 323
ATTINY43U
......................................................................................................................................................... 324
ATTINY44
......................................................................................................................................................... 324
ATTINY45
......................................................................................................................................................... 324
ATTINY48
......................................................................................................................................................... 325
ATTINY84
......................................................................................................................................................... 326
ATTINY85
......................................................................................................................................................... 326
ATTINY87
......................................................................................................................................................... 326
ATTINY88
......................................................................................................................................................... 327
ATTINY167
......................................................................................................................................................... 327
ATTINY261
......................................................................................................................................................... 328
ATTINY441
......................................................................................................................................................... 328
ATTINY461
......................................................................................................................................................... 329
ATTINY828
......................................................................................................................................................... 329
ATTINY841
......................................................................................................................................................... 330
ATTINY861
......................................................................................................................................................... 331
ATTINY1634
......................................................................................................................................................... 331
ATTINY2313
......................................................................................................................................................... 331
ATTINY2313A
......................................................................................................................................................... 332
ATTINY4313
......................................................................................................................................................... 333
ATTINY4313A
......................................................................................................................................................... 333
5 ATMEGA
................................................................................................................................... 334
ATMEGA8
......................................................................................................................................................... 334
ATMEGA8A
......................................................................................................................................................... 334
ATMEGA8U2
......................................................................................................................................................... 334
ATMEGA16
......................................................................................................................................................... 336
ATMEGA16A
......................................................................................................................................................... 337
ATMEGA16U2
......................................................................................................................................................... 337
ATMEGA16U4
......................................................................................................................................................... 339
ATMEGA16M1
......................................................................................................................................................... 340
ATMEGA32
......................................................................................................................................................... 341
ATMEGA32A
......................................................................................................................................................... 342
ATMEGA32C1
......................................................................................................................................................... 343
ATMEGA32M1
......................................................................................................................................................... 344
ATMEGA32U2
......................................................................................................................................................... 344
ATMEGA32U4
......................................................................................................................................................... 346
ATMEGA48
......................................................................................................................................................... 347
ATMEGA48P-ATMEGA48PA
......................................................................................................................................................... 347
ATMEGA48PB
......................................................................................................................................................... 348
ATMEGA64
......................................................................................................................................................... 349
ATMEGA64C1
......................................................................................................................................................... 350
ATMEGA64M1
......................................................................................................................................................... 351
ATMEGA88
......................................................................................................................................................... 351
ATMEGA88A
......................................................................................................................................................... 352
ATMEGA88P-ATMEGA88PA
......................................................................................................................................................... 353
ATMEGA88PB
......................................................................................................................................................... 354
ATMEGA103
......................................................................................................................................................... 354
ATMEGA128
......................................................................................................................................................... 356
ATMEGA128RFA1
......................................................................................................................................................... 357

© 2021 MCS Electronics


Contents 9

ATMEGA161
......................................................................................................................................................... 358
ATMEGA162
......................................................................................................................................................... 358
ATMEGA163
......................................................................................................................................................... 359
ATMEGA164P
......................................................................................................................................................... 360
ATMEGA164PA
......................................................................................................................................................... 360
ATMEGA165
......................................................................................................................................................... 362
ATMEGA165A
......................................................................................................................................................... 362
ATMEGA168
......................................................................................................................................................... 364
ATMEGA168P
......................................................................................................................................................... 364
ATMEGA168PB
......................................................................................................................................................... 365
ATMEGA169
......................................................................................................................................................... 365
ATMEGA169P
......................................................................................................................................................... 366
ATMEGA169PA
......................................................................................................................................................... 367
ATMEGA323
......................................................................................................................................................... 368
ATMEGA324A
......................................................................................................................................................... 369
ATMEGA324P
......................................................................................................................................................... 370
ATMEGA324PA
......................................................................................................................................................... 370
ATMEGA324PB
......................................................................................................................................................... 371
ATMEGA325
......................................................................................................................................................... 372
ATMEGA328
......................................................................................................................................................... 373
ATMEGA328P
......................................................................................................................................................... 373
ATMEGA328PB
......................................................................................................................................................... 374
ATMEGA329
......................................................................................................................................................... 375
ATMEGA406
......................................................................................................................................................... 375
ATMEGA603
......................................................................................................................................................... 376
ATMEGA640
......................................................................................................................................................... 378
ATMEGA644
......................................................................................................................................................... 379
ATMEGA644P
......................................................................................................................................................... 379
ATMEGA644PA
......................................................................................................................................................... 380
ATMEGA645
......................................................................................................................................................... 381
ATMEGA649
......................................................................................................................................................... 382
ATMEGA649PA
......................................................................................................................................................... 382
ATMEGA1280
......................................................................................................................................................... 384
ATMEGA1281
......................................................................................................................................................... 385
ATMEGA1284
......................................................................................................................................................... 386
ATMEGA1284P
......................................................................................................................................................... 386
ATMEGA2560
......................................................................................................................................................... 388
ATMEGA2561
......................................................................................................................................................... 389
ATMEGA3250P
......................................................................................................................................................... 390
ATMEGA6450P
......................................................................................................................................................... 391
ATMEGA8515
......................................................................................................................................................... 392
ATMEGA8535
......................................................................................................................................................... 392
6 ATXMEGA
................................................................................................................................... 393
ATXMEGA
......................................................................................................................................................... 393
ATXMEGA8E5
......................................................................................................................................................... 401
ATXMEGA16A4
......................................................................................................................................................... 402
ATXMEGA16D4
......................................................................................................................................................... 403
ATXMEGA16E5
......................................................................................................................................................... 404
ATXMEGA32A4
......................................................................................................................................................... 405
ATXMEGA32A4U
......................................................................................................................................................... 407
ATXMEGA32D4
......................................................................................................................................................... 407
ATXMEGA32E5
......................................................................................................................................................... 408
ATXMEGA64A1
......................................................................................................................................................... 409
ATXMEGA64A3
......................................................................................................................................................... 411
ATXMEGA64D3
......................................................................................................................................................... 411
ATXMEGA64D4
......................................................................................................................................................... 412
ATXMEGA128A1
......................................................................................................................................................... 413

© 2021 MCS Electronics


10 BASCOM-AVR

ATXMEGA128A3
......................................................................................................................................................... 415
ATXMEGA128A4U
......................................................................................................................................................... 416
ATXMEGA128B1
......................................................................................................................................................... 416
ATXMEGA128B3
......................................................................................................................................................... 418
ATXMEGA128C3
......................................................................................................................................................... 418
ATXMEGA128D3
......................................................................................................................................................... 419
ATXMEGA128D4
......................................................................................................................................................... 420
ATXMEGA192A3
......................................................................................................................................................... 421
ATXMEGA192D3
......................................................................................................................................................... 422
ATXMEGA256A3
......................................................................................................................................................... 423
ATXMEGA256A3B
......................................................................................................................................................... 424
ATXMEGA256A3BU
......................................................................................................................................................... 426
ATXMEGA256D3
......................................................................................................................................................... 426
ATXMEGA384C3
......................................................................................................................................................... 428
7 XTINY ................................................................................................................................... 428
XTINY ......................................................................................................................................................... 428
ATXTINY202
......................................................................................................................................................... 432
ATXTINY204
......................................................................................................................................................... 433
ATXTINY212
......................................................................................................................................................... 434
ATXTINY214
......................................................................................................................................................... 435
ATXTINY402
......................................................................................................................................................... 436
ATXTINY404
......................................................................................................................................................... 437
ATXTINY406
......................................................................................................................................................... 438
ATXTINY412
......................................................................................................................................................... 439
ATXTINY414
......................................................................................................................................................... 440
ATXTINY416
......................................................................................................................................................... 441
ATXTINY417
......................................................................................................................................................... 442
ATXTINY804
......................................................................................................................................................... 443
ATXTINY806
......................................................................................................................................................... 444
ATXTINY807
......................................................................................................................................................... 445
ATXTINY814
......................................................................................................................................................... 446
ATXTINY816
......................................................................................................................................................... 447
ATXTINY817
......................................................................................................................................................... 448
ATXTINY1604
......................................................................................................................................................... 449
ATXTINY1606
......................................................................................................................................................... 450
ATXTINY1607
......................................................................................................................................................... 451
ATXTINY1614
......................................................................................................................................................... 452
ATXTINY1616
......................................................................................................................................................... 453
ATXTINY1617
......................................................................................................................................................... 454
ATXTINY3216
......................................................................................................................................................... 455
ATXTINY3217
......................................................................................................................................................... 456
8 ATMEGAX
................................................................................................................................... 457
MEGAX ......................................................................................................................................................... 457
ATMEGAX4809
......................................................................................................................................................... 458

Part VI BASCOM Language Fundamentals 464


1 Changes
...................................................................................................................................
compared to BASCOM-8051 464
2 Language
...................................................................................................................................
Fundamentals 465
3 Mixing ASM
...................................................................................................................................
and BASIC 478
4 Assembler
...................................................................................................................................
mnemonics 483
5 Reserved
...................................................................................................................................
Words 488
6 Error Codes
................................................................................................................................... 488
7 Newbie ...................................................................................................................................
problems 493
8 Tips and...................................................................................................................................
tricks 500

© 2021 MCS Electronics


Contents 11

9 ASCII chart
................................................................................................................................... 505

Part VII BASCOM Language Reference 509


1 #AUTOCODE
................................................................................................................................... 509
2 #IF ELSE
...................................................................................................................................
ELSEIF ENDIF 509
3 Compiler
...................................................................................................................................
Directives 511
$AESKEY ......................................................................................................................................................... 511
$ASM ......................................................................................................................................................... 511
$BAUD ......................................................................................................................................................... 512
$BAUD1......................................................................................................................................................... 513
$BGF ......................................................................................................................................................... 514
$BIGSTRINGS
......................................................................................................................................................... 516
$BOOT ......................................................................................................................................................... 517
$BOOTVECTOR
......................................................................................................................................................... 518
$CRYPT......................................................................................................................................................... 529
$CRYSTAL......................................................................................................................................................... 530
$DATA ......................................................................................................................................................... 531
$DBG ......................................................................................................................................................... 532
$DEFAULT......................................................................................................................................................... 534
$EEPLEAVE
......................................................................................................................................................... 535
$EEPROM ......................................................................................................................................................... 535
$EEPROMHEX
......................................................................................................................................................... 537
$EEPROMSIZE
......................................................................................................................................................... 537
$EXTERNAL
......................................................................................................................................................... 538
$FILE ......................................................................................................................................................... 539
$FORCESOFTI2C
......................................................................................................................................................... 540
$FRAMEPROTECT
......................................................................................................................................................... 542
$FRAMESIZE
......................................................................................................................................................... 545
$HWSTACK......................................................................................................................................................... 553
$HWCHECK,
.........................................................................................................................................................
$SWCHECK, $SOFTCHECK 556
$INC ......................................................................................................................................................... 558
$INCLUDE......................................................................................................................................................... 559
$INITMICRO
......................................................................................................................................................... 561
$LCD ......................................................................................................................................................... 562
$LCDPUTCTRL
......................................................................................................................................................... 564
$LCDPUTDATA
......................................................................................................................................................... 566
$LCDRS......................................................................................................................................................... 567
$LCDVFO ......................................................................................................................................................... 569
$LIB ......................................................................................................................................................... 570
$LOADER ......................................................................................................................................................... 572
$LOADERSIZE
......................................................................................................................................................... 588
$MAP ......................................................................................................................................................... 589
$NOCOMPILE
......................................................................................................................................................... 590
$NOFRAMEPROTECT
......................................................................................................................................................... 590
$NOINIT......................................................................................................................................................... 591
$NORAMCLEAR
......................................................................................................................................................... 591
$NORAMPZ......................................................................................................................................................... 591
$NOTRANSFORM
......................................................................................................................................................... 592
$NOTYPECHECK
......................................................................................................................................................... 593
$PROJECTTIME
......................................................................................................................................................... 593
$PROG ......................................................................................................................................................... 594
$PROGRAMMER
......................................................................................................................................................... 595
$REDUCEIVR
......................................................................................................................................................... 596
$REGFILE......................................................................................................................................................... 598
$RESOURCE
......................................................................................................................................................... 599
$ROMSTART
......................................................................................................................................................... 601

© 2021 MCS Electronics


12 BASCOM-AVR

$SERIALINPUT
......................................................................................................................................................... 602
$SERIALINPUT1
......................................................................................................................................................... 604
$SERIALINPUT2LCD
......................................................................................................................................................... 605
$SERIALOUTPUT
......................................................................................................................................................... 605
$SERIALOUTPUT1
......................................................................................................................................................... 606
$SIM ......................................................................................................................................................... 607
$STACKDUMP
......................................................................................................................................................... 607
$SWSTACK
......................................................................................................................................................... 609
$TIMEOUT
......................................................................................................................................................... 612
$TINY ......................................................................................................................................................... 614
$TYPECHECK
......................................................................................................................................................... 614
$VERSION
......................................................................................................................................................... 615
$WAITSTATE
......................................................................................................................................................... 616
$XA ......................................................................................................................................................... 616
$XRAMSIZE
......................................................................................................................................................... 617
$XRAMSTART
......................................................................................................................................................... 617
$XTEAKEY
......................................................................................................................................................... 618
4 1WIRE ................................................................................................................................... 619
1WIRECOUNT
......................................................................................................................................................... 619
1WRESET
......................................................................................................................................................... 622
1WREAD......................................................................................................................................................... 624
1WSEARCHFIRST
......................................................................................................................................................... 626
1WSEARCHNEXT
......................................................................................................................................................... 628
1WVERIFY
......................................................................................................................................................... 631
1WWRITE
......................................................................................................................................................... 633
5 ADR , ADR2
................................................................................................................................... 635
6 ALIAS ................................................................................................................................... 639
7 Math ................................................................................................................................... 640
ABS ......................................................................................................................................................... 640
ACOS ......................................................................................................................................................... 641
AND ......................................................................................................................................................... 642
ASIN ......................................................................................................................................................... 644
ATN ......................................................................................................................................................... 645
ATN2 ......................................................................................................................................................... 646
CHECKFLOAT
......................................................................................................................................................... 648
COS ......................................................................................................................................................... 649
COSH ......................................................................................................................................................... 650
DEG2RAD
......................................................................................................................................................... 651
EXP ......................................................................................................................................................... 652
FIX ......................................................................................................................................................... 653
FRAC ......................................................................................................................................................... 653
INT ......................................................................................................................................................... 654
LOG10 ......................................................................................................................................................... 655
LOG ......................................................................................................................................................... 656
NOT ......................................................................................................................................................... 656
OR ......................................................................................................................................................... 659
POWER ......................................................................................................................................................... 662
QSIN ......................................................................................................................................................... 663
QCOS ......................................................................................................................................................... 667
RAD2DEG
......................................................................................................................................................... 668
ROUND ......................................................................................................................................................... 668
SGN ......................................................................................................................................................... 669
TANH ......................................................................................................................................................... 670
TAN ......................................................................................................................................................... 671
SQR ......................................................................................................................................................... 671
SINH ......................................................................................................................................................... 672

© 2021 MCS Electronics


Contents 13

SIN ......................................................................................................................................................... 673


XOR ......................................................................................................................................................... 674
8 AVR-DOS
...................................................................................................................................
File I/O 676
BLOAD ......................................................................................................................................................... 676
BSAVE ......................................................................................................................................................... 678
CHDIR ......................................................................................................................................................... 679
CLEARATTR......................................................................................................................................................... 679
DIR ......................................................................................................................................................... 680
DISKFREE ......................................................................................................................................................... 681
DISKSIZE ......................................................................................................................................................... 682
DriveCheck
......................................................................................................................................................... 683
DriveGetIdentity
......................................................................................................................................................... 684
DriveInit......................................................................................................................................................... 685
DriveReset
......................................................................................................................................................... 685
DriveReadSector
......................................................................................................................................................... 686
DriveWriteSector
......................................................................................................................................................... 687
EOF ......................................................................................................................................................... 688
FILEATTR ......................................................................................................................................................... 689
FILEDATE ......................................................................................................................................................... 690
FILEDATETIME
......................................................................................................................................................... 691
FILELEN......................................................................................................................................................... 692
FILETIME ......................................................................................................................................................... 692
FLUSH ......................................................................................................................................................... 693
FREEFILE ......................................................................................................................................................... 694
GETATTR ......................................................................................................................................................... 695
INITFILESYSTEM
......................................................................................................................................................... 696
KILL ......................................................................................................................................................... 696
LINEINPUT......................................................................................................................................................... 697
LOC ......................................................................................................................................................... 698
LOF ......................................................................................................................................................... 699
MKDIR ......................................................................................................................................................... 700
NAME ......................................................................................................................................................... 701
RMDIR ......................................................................................................................................................... 701
SETATTR ......................................................................................................................................................... 702
WRITE ......................................................................................................................................................... 705
9 BITWAIT................................................................................................................................... 706
10 BITS ................................................................................................................................... 707
11 BREAK ................................................................................................................................... 708
12 BYVAL ................................................................................................................................... 709
13 CALL ................................................................................................................................... 709
14 CHECKSUM
................................................................................................................................... 711
CHECKSUM
.........................................................................................................................................................
CHECKSUMXOR 711
CRC8 ......................................................................................................................................................... 712
CRC8UNI......................................................................................................................................................... 714
CRC16 ......................................................................................................................................................... 716
CRC16UNI
......................................................................................................................................................... 719
CRC32 ......................................................................................................................................................... 720
CRCMB ......................................................................................................................................................... 721
15 Conversion
................................................................................................................................... 722
ASC ......................................................................................................................................................... 722
BCD ......................................................................................................................................................... 726
BIN ......................................................................................................................................................... 728
BINVAL ......................................................................................................................................................... 729
BIN2GRAY
......................................................................................................................................................... 729
CHR ......................................................................................................................................................... 731

© 2021 MCS Electronics


14 BASCOM-AVR

FORMAT......................................................................................................................................................... 732
FUSING ......................................................................................................................................................... 734
GRAY2BIN
......................................................................................................................................................... 735
HEXVAL......................................................................................................................................................... 736
HEX ......................................................................................................................................................... 737
MANCHESTERDEC
......................................................................................................................................................... 738
MANCHESTERENC
......................................................................................................................................................... 739
STR ......................................................................................................................................................... 740
STR2DIGITS
......................................................................................................................................................... 741
VAL ......................................................................................................................................................... 743
16 CAN ................................................................................................................................... 744
CANBAUD
......................................................................................................................................................... 744
CANGETINTS
......................................................................................................................................................... 745
CANID ......................................................................................................................................................... 746
CANCLEARALLMOBS
......................................................................................................................................................... 746
CANCLEARMOB
......................................................................................................................................................... 747
CANRECEIVE
......................................................................................................................................................... 747
CANRESET
......................................................................................................................................................... 748
CANSELPAGE
......................................................................................................................................................... 748
CANSEND
......................................................................................................................................................... 749
17 CLEAR ................................................................................................................................... 750
18 CLOCKDIVISION
................................................................................................................................... 751
19 CLOSE ................................................................................................................................... 752
20 COMPARE
................................................................................................................................... 755
21 CONFIGURATION
................................................................................................................................... 756
CONFIG ......................................................................................................................................................... 757
CONFIG .........................................................................................................................................................
1WIRE 759
CONFIG .........................................................................................................................................................
ACI 764
CONFIG .........................................................................................................................................................
ACX 764
CONFIG .........................................................................................................................................................
ACAX|ACBX 765
CONFIG .........................................................................................................................................................
ADC 767
CONFIG .........................................................................................................................................................
ADCA|ADCB 769
CONFIG .........................................................................................................................................................
ADC0-ADCX 783
CONFIG .........................................................................................................................................................
ATEMU 786
CONFIG .........................................................................................................................................................
BASE 788
CONFIG .........................................................................................................................................................
BCCARD 789
CONFIG .........................................................................................................................................................
CANBUSMODE 792
CONFIG .........................................................................................................................................................
CANMOB 796
CONFIG .........................................................................................................................................................
CLOCK 798
CONFIG .........................................................................................................................................................
CLOCKDIV 812
CONFIG .........................................................................................................................................................
COM1 812
CONFIG .........................................................................................................................................................
COM2 814
CONFIG .........................................................................................................................................................
COMx 816
CONFIG .........................................................................................................................................................
DACA|DACB 819
CONFIG .........................................................................................................................................................
DACX 824
CONFIG .........................................................................................................................................................
DATE 826
CONFIG .........................................................................................................................................................
DCF77 828
CONFIG .........................................................................................................................................................
DEBOUNCE 835
CONFIG .........................................................................................................................................................
DMA 836
CONFIG .........................................................................................................................................................
DMACHx 837
CONFIG .........................................................................................................................................................
EDMA 843
CONFIG .........................................................................................................................................................
EDMAx 844
CONFIG .........................................................................................................................................................
DMXSLAVE 848
CONFIG .........................................................................................................................................................
DP 851
CONFIG .........................................................................................................................................................
EEPROM 851
CONFIG .........................................................................................................................................................
ERROR 852

© 2021 MCS Electronics


Contents 15

CONFIG .........................................................................................................................................................
EVENT_SYSTEM 853
CONFIG .........................................................................................................................................................
EVENT_SYSTEM XTINY 856
CONFIG .........................................................................................................................................................
EXTENDED_PORT 858
CONFIG .........................................................................................................................................................
FT800 858
CONFIG .........................................................................................................................................................
GRAPHLCD 862
CONFIG .........................................................................................................................................................
HITAG 867
CONFIG .........................................................................................................................................................
I2CBUS 871
CONFIG .........................................................................................................................................................
I2CDELAY 872
CONFIG .........................................................................................................................................................
I2CSLAVE 875
CONFIG .........................................................................................................................................................
INPUT 880
CONFIG .........................................................................................................................................................
INPUTBIN 881
CONFIG .........................................................................................................................................................
INTx 882
CONFIG .........................................................................................................................................................
INTVECTORSELECTION 884
CONFIG .........................................................................................................................................................
KBD 885
CONFIG .........................................................................................................................................................
KEYBOARD 886
CONFIG .........................................................................................................................................................
LCD 889
CONFIG .........................................................................................................................................................
LCDBUS 895
CONFIG .........................................................................................................................................................
LCDMODE 898
CONFIG .........................................................................................................................................................
LCDPIN 898
CONFIG .........................................................................................................................................................
MODBUS 902
CONFIG .........................................................................................................................................................
OSC 902
CONFIG .........................................................................................................................................................
PORT 904
CONFIG .........................................................................................................................................................
PORT_MUX 906
CONFIG .........................................................................................................................................................
POWERMODE 910
CONFIG .........................................................................................................................................................
POWER_REDUCTION 916
CONFIG .........................................................................................................................................................
PRIORITY XMEGA 918
CONFIG .........................................................................................................................................................
PRIORITY XTINY 920
CONFIG .........................................................................................................................................................
PRINT 921
CONFIG .........................................................................................................................................................
PRINTBIN 922
CONFIG .........................................................................................................................................................
PS2EMU 923
CONFIG .........................................................................................................................................................
RAINBOW 925
CONFIG .........................................................................................................................................................
RC5 929
CONFIG .........................................................................................................................................................
RND 932
CONFIG .........................................................................................................................................................
SDA 934
CONFIG .........................................................................................................................................................
SCL 936
CONFIG .........................................................................................................................................................
SERIALIN 939
CONFIG .........................................................................................................................................................
SERIALOUT 945
CONFIG .........................................................................................................................................................
SINGLE 947
CONFIG .........................................................................................................................................................
SHIFTIN 948
CONFIG .........................................................................................................................................................
SPI 948
CONFIG .........................................................................................................................................................
SPIx XTINY 953
CONFIG .........................................................................................................................................................
SPIx XMEGA 955
CONFIG .........................................................................................................................................................
SERVOS 958
CONFIG .........................................................................................................................................................
SUBMODE 962
CONFIG .........................................................................................................................................................
SYSCLOCK XMEGA 964
CONFIG .........................................................................................................................................................
SYSCLOCK XTINY 965
CONFIG .........................................................................................................................................................
TCA0 967
CONFIG .........................................................................................................................................................
TCB0-TCB1 970
CONFIG .........................................................................................................................................................
TCD0 972
CONFIG .........................................................................................................................................................
TCXX 977
CONFIG .........................................................................................................................................................
TCPIP 980
CONFIG .........................................................................................................................................................
TIMER0 991
CONFIG .........................................................................................................................................................
TIMER1 994
CONFIG .........................................................................................................................................................
TIMER2 997
CONFIG .........................................................................................................................................................
TWI, TWIx 999
CONFIG
.........................................................................................................................................................
TWISLAVE 1005
CONFIG
.........................................................................................................................................................
TWIxSLAVE 1010
CONFIG
.........................................................................................................................................................
USB 1014

© 2021 MCS Electronics


16 BASCOM-AVR

CONFIG
.........................................................................................................................................................
USI 1021
CONFIG
.........................................................................................................................................................
VPORT 1025
CONFIG
.........................................................................................................................................................
VREF 1027
CONFIG
.........................................................................................................................................................
WAITSUART 1028
CONFIG
.........................................................................................................................................................
WATCHDOG 1029
CONFIG
.........................................................................................................................................................
X10 1032
CONFIG
.........................................................................................................................................................
XPIN 1034
CONFIG
.........................................................................................................................................................
XRAM 1036
22 CONTINUE
................................................................................................................................... 1043
23 CONST................................................................................................................................... 1045
24 COUNTER0
...................................................................................................................................
and COUNTER1 1047
25 CPEEK................................................................................................................................... 1048
26 CPEEKH
................................................................................................................................... 1049
27 CRYSTAL
................................................................................................................................... 1051
28 DATA ................................................................................................................................... 1052
29 Date and
...................................................................................................................................
Time 1055
DAYOFWEEK
......................................................................................................................................................... 1055
DAYOFYEAR
......................................................................................................................................................... 1065
DATE$ ......................................................................................................................................................... 1066
DATE ......................................................................................................................................................... 1068
SECELAPSED
......................................................................................................................................................... 1077
SECOFDAY
......................................................................................................................................................... 1077
SYSSEC......................................................................................................................................................... 1079
SYSSECELAPSED
......................................................................................................................................................... 1080
SYSDAY......................................................................................................................................................... 1081
TIME$ ......................................................................................................................................................... 1083
TIME ......................................................................................................................................................... 1083
30 DBG ................................................................................................................................... 1085
31 DCF77TIMEZONE
................................................................................................................................... 1085
32 DEBUG................................................................................................................................... 1086
33 DEBOUNCE
................................................................................................................................... 1087
34 DECR ................................................................................................................................... 1089
35 DECLARE
...................................................................................................................................
FUNCTION 1090
36 DECLARE
...................................................................................................................................
SUB 1093
37 DEFxxx
................................................................................................................................... 1098
38 DELAY................................................................................................................................... 1098
39 DIM ................................................................................................................................... 1099
40 DISABLE
................................................................................................................................... 1111
41 DO-LOOP
................................................................................................................................... 1114
42 DTMFOUT
................................................................................................................................... 1115
43 ECHO ................................................................................................................................... 1117
44 ELSE ................................................................................................................................... 1119
45 ENABLE
................................................................................................................................... 1120
46 ENCODER
................................................................................................................................... 1124
47 END ................................................................................................................................... 1126
48 EXIT ................................................................................................................................... 1127
49 FLIP ................................................................................................................................... 1129

© 2021 MCS Electronics


Contents 17

50 FOR-NEXT
................................................................................................................................... 1130
51 GET ................................................................................................................................... 1132
52 GETADC
................................................................................................................................... 1135
53 GETATKBD
................................................................................................................................... 1140
54 GETATKBDRAW
................................................................................................................................... 1144
55 GETKBD
................................................................................................................................... 1145
56 GETRC................................................................................................................................... 1147
57 GETRC5
................................................................................................................................... 1148
58 GETREG
................................................................................................................................... 1152
59 GOSUB
................................................................................................................................... 1153
60 GOTO ................................................................................................................................... 1154
61 HIGH ................................................................................................................................... 1155
62 HIGHW................................................................................................................................... 1156
63 Encryption-Decryption
................................................................................................................................... 1157
AESENCRYPT
......................................................................................................................................................... 1157
AESDECRYPT
......................................................................................................................................................... 1159
DESENCRYPT
......................................................................................................................................................... 1161
DESDECRYPT
......................................................................................................................................................... 1163
XTEAENCODE
......................................................................................................................................................... 1165
XTEADECODE
......................................................................................................................................................... 1167
64 I2C-TWI
................................................................................................................................... 1168
I2CINIT......................................................................................................................................................... 1168
I2CRECEIVE
......................................................................................................................................................... 1172
I2CSEND......................................................................................................................................................... 1173
I2START,I2CSTOP,
.........................................................................................................................................................
I2CRBYTE, I2CWBYTE, I2CREPSTART 1174
65 IDLE ................................................................................................................................... 1181
66 IF-THEN-ELSE-END
...................................................................................................................................
IF 1181
67 INCR ................................................................................................................................... 1183
68 INP ................................................................................................................................... 1183
69 LCD Commands
................................................................................................................................... 1185
BOX ......................................................................................................................................................... 1185
BOXFILL
......................................................................................................................................................... 1187
CIRCLE......................................................................................................................................................... 1187
CLS ......................................................................................................................................................... 1190
CURSOR......................................................................................................................................................... 1193
DEFLCDCHAR
......................................................................................................................................................... 1196
DISPLAY
......................................................................................................................................................... 1197
FOURTHLINE
......................................................................................................................................................... 1200
GLCDCMD
......................................................................................................................................................... 1201
GLCDDATA
......................................................................................................................................................... 1201
HOME ......................................................................................................................................................... 1202
INITLCD
......................................................................................................................................................... 1202
LCD ......................................................................................................................................................... 1204
LCDAUTODIM
......................................................................................................................................................... 1207
LCDAT ......................................................................................................................................................... 1207
LCDCMD......................................................................................................................................................... 1209
LCDDATA
......................................................................................................................................................... 1210
LCDCONTRAST
......................................................................................................................................................... 1210
LCDFONT
......................................................................................................................................................... 1211
LINE ......................................................................................................................................................... 1212

© 2021 MCS Electronics


18 BASCOM-AVR

LOCATE......................................................................................................................................................... 1215
LOWERLINE
......................................................................................................................................................... 1215
PSET ......................................................................................................................................................... 1216
RGB8TO16
......................................................................................................................................................... 1219
SETFONT
......................................................................................................................................................... 1219
SHIFTCURSOR
......................................................................................................................................................... 1221
SHIFTLCD
......................................................................................................................................................... 1222
SHOWPIC
......................................................................................................................................................... 1223
SHOWPICE
......................................................................................................................................................... 1223
THIRDLINE
......................................................................................................................................................... 1225
UPPERLINE
......................................................................................................................................................... 1225
70 LOAD ................................................................................................................................... 1226
71 LOADADR
................................................................................................................................... 1226
72 LOADLABEL
................................................................................................................................... 1227
73 LOADWORDADR
................................................................................................................................... 1227
74 LOCAL................................................................................................................................... 1228
75 LOOKDOWN
................................................................................................................................... 1231
76 LOOKUP
................................................................................................................................... 1233
77 LOOKUPSTR
................................................................................................................................... 1234
78 LOW ................................................................................................................................... 1235
79 MACRO
................................................................................................................................... 1236
80 MAKEBCD
................................................................................................................................... 1237
81 MAKEDEC
................................................................................................................................... 1237
82 MAKEINT
................................................................................................................................... 1238
83 MAX ................................................................................................................................... 1238
84 MEMCOPY
................................................................................................................................... 1240
85 MEMFILL
................................................................................................................................... 1242
86 MIN ................................................................................................................................... 1243
87 MOD ................................................................................................................................... 1244
88 NBITS ................................................................................................................................... 1245
89 NOP ................................................................................................................................... 1246
90 ON INTERRUPT
................................................................................................................................... 1247
91 ON VALUE
................................................................................................................................... 1251
92 OPEN ................................................................................................................................... 1254
93 OUT ................................................................................................................................... 1262
94 PEEK ................................................................................................................................... 1263
95 POKE ................................................................................................................................... 1264
96 POPALL
................................................................................................................................... 1265
97 POWER
...................................................................................................................................
MODE 1265
98 POWERDOWN
................................................................................................................................... 1266
99 POWERSAVE
................................................................................................................................... 1267
100 PS2MOUSEXY
................................................................................................................................... 1267
101 PULSEIN
................................................................................................................................... 1268
102 PULSEOUT
................................................................................................................................... 1269
103 PUSHALL
................................................................................................................................... 1270

© 2021 MCS Electronics


Contents 19

104 PUT ................................................................................................................................... 1270


105 RC5SEND
................................................................................................................................... 1273
106 RC5SENDEXT
................................................................................................................................... 1274
107 RC6SEND
................................................................................................................................... 1276
108 READ ................................................................................................................................... 1279
109 READEEPROM
................................................................................................................................... 1280
110 READHITAG
................................................................................................................................... 1283
111 READMAGCARD
................................................................................................................................... 1286
112 REDO ................................................................................................................................... 1288
113 READSIG
................................................................................................................................... 1290
114 REM ................................................................................................................................... 1293
115 REPLACECHARS
................................................................................................................................... 1293
116 RESET................................................................................................................................... 1294
117 RESTORE
................................................................................................................................... 1295
118 RETURN
................................................................................................................................... 1296
119 RND ................................................................................................................................... 1297
120 ROTATE
................................................................................................................................... 1299
121 SEEK ................................................................................................................................... 1300
122 SELECT-CASE-END
...................................................................................................................................
SELECT 1303
123 SET ................................................................................................................................... 1305
124 SETREG
................................................................................................................................... 1307
125 SENDSCAN
................................................................................................................................... 1308
126 SENDSCANKBD
................................................................................................................................... 1310
127 SHIFT ................................................................................................................................... 1313
128 SHIFTIN
................................................................................................................................... 1315
129 SHIFTOUT
................................................................................................................................... 1319
130 SONYSEND
................................................................................................................................... 1320
131 SIZEOF................................................................................................................................... 1323
132 SORT ................................................................................................................................... 1325
133 SOUND................................................................................................................................... 1326
134 RAINBOW
................................................................................................................................... 1328
RB_SELECTCHANNEL
......................................................................................................................................................... 1328
RB_SETCOLOR
......................................................................................................................................................... 1329
RB_SEND
......................................................................................................................................................... 1330
RB_CHANGEPIN
......................................................................................................................................................... 1331
RB_ADDCOLOR
......................................................................................................................................................... 1334
RB_ANDCOLOR
......................................................................................................................................................... 1334
RB_ORCOLOR
......................................................................................................................................................... 1336
RB_SUBCOLOR
......................................................................................................................................................... 1336
RB_CLEARSTRIPE
......................................................................................................................................................... 1337
RB_CLEARCOLORS
......................................................................................................................................................... 1338
RB_FILL
......................................................................................................................................................... 1338
RB_FILLCOLORS
......................................................................................................................................................... 1339
RB_FILLSTRIPE
......................................................................................................................................................... 1341
RB_SWAPCOLOR
......................................................................................................................................................... 1341
RB_ROTATELEFT
......................................................................................................................................................... 1342

© 2021 MCS Electronics


20 BASCOM-AVR

RB_ROTATERIGHT
......................................................................................................................................................... 1343
RB_SHIFTLEFT
......................................................................................................................................................... 1344
RB_SHIFTRIGHT
......................................................................................................................................................... 1345
RB_SETTABLECOLOR
......................................................................................................................................................... 1345
RB_GETCOLOR
......................................................................................................................................................... 1349
RB_LOOKUPCOLOR
......................................................................................................................................................... 1350
RB_COLOR
......................................................................................................................................................... 1350
RB_COPY
......................................................................................................................................................... 1352
135 Serial Data
...................................................................................................................................
RS232-RS485 1354
BAUD ......................................................................................................................................................... 1354
BAUD1-BAUDx
......................................................................................................................................................... 1355
BUFSPACE
......................................................................................................................................................... 1357
INKEY ......................................................................................................................................................... 1358
INPUT ......................................................................................................................................................... 1359
INPUTHEX
......................................................................................................................................................... 1362
INPUTBIN
......................................................................................................................................................... 1363
ISCHARWAITING
......................................................................................................................................................... 1364
MAKEMODBUS
......................................................................................................................................................... 1365
PRINT ......................................................................................................................................................... 1367
PRINTBIN
......................................................................................................................................................... 1370
SERIN ......................................................................................................................................................... 1371
SPC ......................................................................................................................................................... 1373
SEROUT......................................................................................................................................................... 1374
WAITKEY
......................................................................................................................................................... 1377
136 SPI ................................................................................................................................... 1379
SPIIN ......................................................................................................................................................... 1379
SPIINIT......................................................................................................................................................... 1380
SPIMOVE......................................................................................................................................................... 1381
SPIOUT......................................................................................................................................................... 1384
SPI1INIT,
.........................................................................................................................................................
SPI1IN, SPI1OUT, SPI1MOVE 1384
137 STRINGS
................................................................................................................................... 1385
CHARPOS
......................................................................................................................................................... 1385
DELCHAR
......................................................................................................................................................... 1386
DELCHARS
......................................................................................................................................................... 1387
INSERTCHAR
......................................................................................................................................................... 1388
INSTR ......................................................................................................................................................... 1389
LCASE ......................................................................................................................................................... 1390
LEFT ......................................................................................................................................................... 1391
LEN ......................................................................................................................................................... 1392
LTRIM ......................................................................................................................................................... 1392
MID ......................................................................................................................................................... 1393
RIGHT ......................................................................................................................................................... 1393
QUOTE......................................................................................................................................................... 1394
RTRIM ......................................................................................................................................................... 1394
SPACE......................................................................................................................................................... 1395
SPLIT ......................................................................................................................................................... 1396
STRING......................................................................................................................................................... 1397
TRIM ......................................................................................................................................................... 1398
UCASE......................................................................................................................................................... 1399
138 START................................................................................................................................... 1400
139 STCHECK
................................................................................................................................... 1402
140 STOP ................................................................................................................................... 1406
141 SUB ................................................................................................................................... 1407
142 SWAP ................................................................................................................................... 1407

© 2021 MCS Electronics


Contents 21

143 TCP/IP................................................................................................................................... 1408


BASE64DEC
......................................................................................................................................................... 1408
BASE64ENC
......................................................................................................................................................... 1410
GETDSTIP
......................................................................................................................................................... 1412
GETDSTPORT
......................................................................................................................................................... 1413
GETSOCKET
......................................................................................................................................................... 1415
GETTCPREGS
......................................................................................................................................................... 1416
IP2STR......................................................................................................................................................... 1417
MAKETCP
......................................................................................................................................................... 1417
SETIPPROTOCOL
......................................................................................................................................................... 1418
SETTCP......................................................................................................................................................... 1420
SETTCPREGS
......................................................................................................................................................... 1422
SNTP ......................................................................................................................................................... 1423
SOCKETCLOSE
......................................................................................................................................................... 1425
SOCKETCONNECT
......................................................................................................................................................... 1429
SOCKETDISCONNECT
......................................................................................................................................................... 1432
SOCKETLISTEN
......................................................................................................................................................... 1432
SOCKETSTAT
......................................................................................................................................................... 1433
TCPCHECKSUM
......................................................................................................................................................... 1435
TCPREAD
......................................................................................................................................................... 1438
TCPREADHEADER
......................................................................................................................................................... 1439
TCPWRITE
......................................................................................................................................................... 1439
TCPWRITESTR
......................................................................................................................................................... 1441
UDPREAD
......................................................................................................................................................... 1444
UDPREADHEADER
......................................................................................................................................................... 1447
UDPWRITE
......................................................................................................................................................... 1449
UDPWRITESTR
......................................................................................................................................................... 1450
URL2IP......................................................................................................................................................... 1454
144 TOGGLE
................................................................................................................................... 1457
145 VARPTR
................................................................................................................................... 1459
146 VER ................................................................................................................................... 1459
147 VERSION
................................................................................................................................... 1460
148 WAIT ................................................................................................................................... 1461
149 WAITMS
................................................................................................................................... 1461
150 WAITUS
................................................................................................................................... 1462
151 WHILE-WEND
................................................................................................................................... 1463
152 WRITEEEPROM
................................................................................................................................... 1464
153 X10DETECT
................................................................................................................................... 1467
154 X10SEND
................................................................................................................................... 1468

Part VIII ASM Libraries and Add-Ons 1472


1 FT800 ................................................................................................................................... 1473
Commands
......................................................................................................................................................... 1475
AlphaFunc .................................................................................................................................................. 1479
Begin_G .................................................................................................................................................. 1479
BitmapHandle
.................................................................................................................................................. 1481
BitmapLayout
.................................................................................................................................................. 1481
BitmapSize.................................................................................................................................................. 1482
BitmapSource
.................................................................................................................................................. 1484
BitmapTransform
.................................................................................................................................................. 1485
BlendFunc .................................................................................................................................................. 1487
Call_C.................................................................................................................................................. 1488
Cell .................................................................................................................................................. 1489

© 2021 MCS Electronics


22 BASCOM-AVR

Clear_B
.................................................................................................................................................. 1489
ClearColorA
.................................................................................................................................................. 1490
ClearColorRGB
.................................................................................................................................................. 1491
ClearColorRGBdw
.................................................................................................................................................. 1492
ClearStencil
.................................................................................................................................................. 1493
ClearTag
.................................................................................................................................................. 1493
ClearScreen
.................................................................................................................................................. 1494
CMD8 .................................................................................................................................................. 1494
CMD16.................................................................................................................................................. 1495
CMD32.................................................................................................................................................. 1495
CmdAppend
.................................................................................................................................................. 1496
CmdBgColor
.................................................................................................................................................. 1496
CmdButton
.................................................................................................................................................. 1497
CmdCalibrate
.................................................................................................................................................. 1498
CmdCalibratex
.................................................................................................................................................. 1499
CmdClock
.................................................................................................................................................. 1499
CmdColdStart
.................................................................................................................................................. 1502
CmdDial
.................................................................................................................................................. 1503
CmdDlStart
.................................................................................................................................................. 1504
CmdFgColor
.................................................................................................................................................. 1504
CMDFTSTACK
.................................................................................................................................................. 1505
CmdGauge
.................................................................................................................................................. 1506
CmdGetMatrix
.................................................................................................................................................. 1509
CmdGetPtr
.................................................................................................................................................. 1509
CmdGradColor
.................................................................................................................................................. 1510
CmdGradient
.................................................................................................................................................. 1511
CmdInflate
.................................................................................................................................................. 1512
CmdInterrupt
.................................................................................................................................................. 1513
CmdKeys
.................................................................................................................................................. 1513
CmdLoadIdentity
.................................................................................................................................................. 1515
CmdLoadImage
.................................................................................................................................................. 1516
CmdLogo
.................................................................................................................................................. 1516
CmdMemCpy
.................................................................................................................................................. 1517
CmdMemCrc
.................................................................................................................................................. 1517
CmdMemSet
.................................................................................................................................................. 1518
CmdMemWrite
.................................................................................................................................................. 1518
CmdMemZero
.................................................................................................................................................. 1519
CmdNumber
.................................................................................................................................................. 1519
CmdProgress
.................................................................................................................................................. 1521
CmdRegRead
.................................................................................................................................................. 1522
CmdRotate
.................................................................................................................................................. 1523
CmdRotateA
.................................................................................................................................................. 1524
CmdScale
.................................................................................................................................................. 1525
CmdScreenSaver
.................................................................................................................................................. 1526
CmdScrollBar
.................................................................................................................................................. 1526
CmdSetFont
.................................................................................................................................................. 1528
CmdSetMatrix
.................................................................................................................................................. 1528
CmdSketch
.................................................................................................................................................. 1528
CmdSlider
.................................................................................................................................................. 1529
CmdSnapShot
.................................................................................................................................................. 1531
CmdSpinner
.................................................................................................................................................. 1531
CmdStop
.................................................................................................................................................. 1534
CmdSwap
.................................................................................................................................................. 1534
CmdText
.................................................................................................................................................. 1534
CmdToggle
.................................................................................................................................................. 1536
CmdTrack
.................................................................................................................................................. 1538
CmdTranslate
.................................................................................................................................................. 1540
CmdTranslateP
.................................................................................................................................................. 1541

© 2021 MCS Electronics


Contents 23

Color_A .................................................................................................................................................. 1542


ColorMask.................................................................................................................................................. 1542
ColorRGB .................................................................................................................................................. 1543
ColorRGBdw
.................................................................................................................................................. 1544
Display_E.................................................................................................................................................. 1544
End_G.................................................................................................................................................. 1545
Jump .................................................................................................................................................. 1545
LineWidth.................................................................................................................................................. 1546
Macro_R .................................................................................................................................................. 1547
PointSize.................................................................................................................................................. 1547
RD8 .................................................................................................................................................. 1548
RD16 .................................................................................................................................................. 1548
RD32 .................................................................................................................................................. 1549
RestoreContext
.................................................................................................................................................. 1550
Return_C .................................................................................................................................................. 1550
SaveContext
.................................................................................................................................................. 1551
ScissorSize
.................................................................................................................................................. 1551
ScissorXY.................................................................................................................................................. 1552
StencilFunc
.................................................................................................................................................. 1553
StencilMask
.................................................................................................................................................. 1554
StencilOp.................................................................................................................................................. 1554
Tag .................................................................................................................................................. 1555
TagMask .................................................................................................................................................. 1556
Vertex2f .................................................................................................................................................. 1556
Vertex2ii.................................................................................................................................................. 1557
UpdateScreen
.................................................................................................................................................. 1558
WaitCmdFifoEmpty
.................................................................................................................................................. 1559
WR8 .................................................................................................................................................. 1559
WR16 .................................................................................................................................................. 1560
WR32 .................................................................................................................................................. 1560
Getting.........................................................................................................................................................
Started 1561
How to .........................................................................................................................................................
add another SPI device with the FT800 1562
How to .........................................................................................................................................................
Screen Capture 1563
Demos ......................................................................................................................................................... 1564
2 EXTENDED
...................................................................................................................................
I2C 1595
3 FM24C16
................................................................................................................................... 1597
4 FM24C64_256
................................................................................................................................... 1599
5 FM24C64_256-XMEGA
................................................................................................................................... 1600
6 FM25C256
................................................................................................................................... 1602
7 HEXVAL
................................................................................................................................... 1607
8 I2C_MULTIBUS
................................................................................................................................... 1607
9 I2C_TWI
................................................................................................................................... 1607
10 I2C_TWI-MULTI
................................................................................................................................... 1608
11 I2C_USI
................................................................................................................................... 1610
12 I2C_USI_SLAVE
................................................................................................................................... 1611
13 I2CV2 ................................................................................................................................... 1617
14 MCSBYTE
................................................................................................................................... 1617
15 MCSBYTEINT
................................................................................................................................... 1618
16 PULSEIN
................................................................................................................................... 1618
17 SERIN ................................................................................................................................... 1619
18 TCPIP ................................................................................................................................... 1619

© 2021 MCS Electronics


24 BASCOM-AVR

19 M128-1wire-PortF
................................................................................................................................... 1620
20 TVOUT................................................................................................................................... 1620
21 RAINBOWBSC
................................................................................................................................... 1628
22 LCD ................................................................................................................................... 1628
LCD4BUSY
......................................................................................................................................................... 1628
LCD4_anypin_oled_RS0010
......................................................................................................................................................... 1629
LCD_RX1602A5
......................................................................................................................................................... 1630
LCD4.LIB
......................................................................................................................................................... 1630
LCD4E2......................................................................................................................................................... 1631
GLCD ......................................................................................................................................................... 1632
GLCDSED
......................................................................................................................................................... 1632
PCF8533
......................................................................................................................................................... 1632
LCD-EPSON
......................................................................................................................................................... 1634
LCD_DOGS104a_I2C
......................................................................................................................................................... 1634
glcdR7565R
......................................................................................................................................................... 1638
glcdSSD1325_96x64
......................................................................................................................................................... 1639
GLCDEADOGMXL240-7-I2C
......................................................................................................................................................... 1640
GLCDdSSD1306-I2C
......................................................................................................................................................... 1642
LCD_I2C_PCF8574
......................................................................................................................................................... 1643
23 AVR-DOS
................................................................................................................................... 1647
AVR-DOS
.........................................................................................................................................................
File System 1647
MMCSD_HC.LIB
......................................................................................................................................................... 1668
24 CF Card
................................................................................................................................... 1668
Compact.........................................................................................................................................................
FlashCard Driver 1668
Elektor.........................................................................................................................................................
CF-Interface 1670
XRAM CF-Interface
.........................................................................................................................................................
for simulation 1671
New CF-Card
.........................................................................................................................................................
Drivers 1672
25 Floating
...................................................................................................................................
Point 1672
FP_TRIG
......................................................................................................................................................... 1672
DOUBLE......................................................................................................................................................... 1675
26 I2C SLAVE
................................................................................................................................... 1675
CONFIG.........................................................................................................................................................
I2CSLAVE 1675
I2C TWI.........................................................................................................................................................
Slave 1676
27 SPI ................................................................................................................................... 1676
SPISLAVE
......................................................................................................................................................... 1676
28 DATE TIME
................................................................................................................................... 1679
EUROTIMEDATE
......................................................................................................................................................... 1679
DATETIME
......................................................................................................................................................... 1680
29 PS2-AT...................................................................................................................................
Mouse and Keyboard Emulation 1681
AT_EMULATOR
......................................................................................................................................................... 1681
PS2MOUSE_EMULATOR
......................................................................................................................................................... 1681
30 BCCARD
................................................................................................................................... 1681
BCCARD
......................................................................................................................................................... 1681
BCDEF......................................................................................................................................................... 1682
BCCALL
......................................................................................................................................................... 1683
BCRESET
......................................................................................................................................................... 1689
31 USB ................................................................................................................................... 1690
USB Add
.........................................................................................................................................................
On 1690
32 MODBUS
...................................................................................................................................
Slave/Server 1703

Part IX Tools 1707


1 LCD RGB-8
...................................................................................................................................
Converter 1707

© 2021 MCS Electronics


Contents 25

2 BASCOMP
................................................................................................................................... 1708

Part X International Resellers 1710


1 International
...................................................................................................................................
Resellers 1710

Index 1711

© 2021 MCS Electronics


Part

I
Index 27

1 Index

Version 2.0.8.4 document build 94

MCS Electronics may update this documentation without notice.


Products specification and usage may change accordingly.
MCS Electronics will not be liable for any miss-information or errors found in this
document.

All software provided with this product package is provided 'AS IS' without any
warranty expressed or implied.

MCS Electronics will not be liable for any damages, costs or loss of profits arising
from the usage of this product package.

No part of this document may be reproduced or transmitted in any form or by any


means, electronic or mechanical, including photocopying and recording, for any
purpose, without written permission of MCS Electronics.

Copyright MCS Electronics v.o.f. All rights reserved.

© 2021 MCS Electronics


28 BASCOM-AVR

1.1 Keyword Reference


1WIRE
1Wire routines allow you to communicate with Dallas 1wire chips.
1WRESET 622 , 1WREAD 624 , 1WWRITE 633 , 1WSEARCHFIRST 626 , 1WSEARCHNEXT 628

,1WVERIFY 631 , 1WIRECOUNT 619

CAN
CONFIG CANBUSMODE 792 , CONFIG CANMOB 796 , CANBAUD 744 , CANRESET 748 ,
CANCLEARMOB 747 , CANCLEARALLMOBS 746 , CANSEND 749 , CANRECEIVE 747 , CANID 746 ,
CANSELPAGE 748 , CANGETINTS 745

Conditions and Loops


Conditions execute a part of the program depending on a condition being True or
False
IF-THEN-ELSE-END IF 1181 , WHILE-WEND 1463 , ELSE 1119 , DO-LOOP 1114 , SELECT CASE
- END SELECT 1303 , FOR-NEXT 1130 , CONTINUE 1043 , REDO 1288

Conditional Compilation
#IF #ELSE #ELSEIF #ENDIF , VAREXIST 509

Configuration
Configuration commands initialize the hardware to the desired state.
CONFIG 757 , CONFIG ACI 764 , CONFIG ADC 767 , CONFIG ADCx 769 , CONFIG BCCARD
789 , CONFIG CLOCK 798 , CONFIG COM1 812 , CONFIG COM2 814 , CONFIG DAC 819 ,

CONFIG DATE 826 , CONFIG DMXSLAVE 848 , CONFIG EEPROM 851 ,CONFIG
EXTENDED_PORT 858 , CONFIG PS2EMU 923 , CONFIG ATEMU 786 , CONFIG I2CSLAVE 875
, CONFIG INPUT 880 , CONFIG GRAPHLCD 862 , CONFIG KEYBOARD 886 , CONFIG
TIMER0 991 , CONFIG TIMER1 994 , CONFIG LCDBUS 895 , CONFIG LCDMODE 898 ,
CONFIG 1WIRE 759 , CONFIG LCD 889 , CONFIG OSC 902 , CONFIG SERIALOUT 945 ,
CONFIG SERIALIN 939 , CONFIG SPI 948 , CONFIG SPIx 955 , CONFIG SYSCLOCK 964 ,
CONFIG LCDPIN 898 , CONFIG PRIORITY 918 , CONFIG SDA 934 , CONFIG SCL 936 ,
CONFIG DEBOUNCE 835 , CONFIG WATCHDOG 1029 , CONFIG PORT , 904 COUNTER0 AND
COUNTER1 1047 , CONFIG TCPIP 980 , CONFIG TWISLAVE 1005 , CONFIG SINGLE 947 ,
CONFIG X10 1032 , CONFIG XRAM 1036 , CONFIG USB 1014 , CONFIG DP 851 , CONFIG TCXX
977 , CONFIG VPORT 1025 CONFIG ERROR 852 , CONFIG POWER REDUCTION 916 , CONFIG

EVENT_SYSTEM 853 , CONFIG DMA 836 , CONFIG DMACHx 837 , CONFIG SUBMODE 962 ,
CONFIG POWERMODE 910 , CONFIG XPIN 1034 , CONFIG FT800 858 , CONFIG I2CBUS 871 ,
CONFIG EDMA 843 , CONFIG EDMAx 844 , CONFIG INPUTBIN 881 , CONFIG MODBUS 902 ,
CONFIG PORT_MUX 906 , CONFIG VREF 1027 , , CONFIG TCA 967 , CONFIG TCB 970 , CONFIG
TCD 972

Conversion
A conversion routine is a function that converts a number or string from one form to
another.
BCD 726 , GRAY2BIN 735 , BIN2GRAY 729 , BIN 728 , MAKEBCD 1237 , MAKEDEC 1237 ,
MAKEINT 1238 , FORMAT 732 , FUSING 734 , BINVAL 729 , CRC8 712 , CRC16 716 , CRC16UNI
719 , CRC32 720 , HIGH 1155 , HIGHW 1156 , LOW 1235 , AESENCRYPT 1157 , AESDECRYPT 1159 ,

FLIP 1129 , CRCMB 721 , CRC8UNI 714 , MANCHESTERDEC 738 , MANCHESTERENC 739 ,
DESENCRYPT 1161 , DESDECRYPT 1163

© 2021 MCS Electronics


Index 29

DateTime
Date Time routines can be used to calculate with date and/or times.
DATE 1068 , TIME 1083 , DATE$ 1066 , TIME$ 1083 , DAYOFWEEK 1055 , DAYOFYEAR 1065 ,
SECOFDAY 1077 , SECELAPSED 1077 , SYSDAY 1081 , SYSSEC 1079 , SYSSECELAPSED 1080

Delay
Delay routines delay the program for the specified time.
WAIT 1461 , WAITMS 1461 , WAITUS 1462 , DELAY 1098

Directives
Directives are special instructions for the compiler. They can override a setting from
the IDE.
$ASM 511 , $BAUD 512 , $BAUD1 513 , $BIGSTRINGS 516 , $BGF 514 , $BOOT 517 ,
$CRYSTAL 530 , $DATA 531 , $DBG 532 , $DEFAULT 534 , $EEPLEAVE 535 , $EEPROM 535 ,
$EEPROMHEX 537 , $EEPROMSIZE 537 , $EXTERNAL 538 , $HWSTACK 553 , $INC 558 ,
$INCLUDE 559 , $INITMICRO 561 , $LCD 562 , $LCDRS 567 , $LCDPUTCTRL 564 ,
$LCDPUTDATA 566 , $LCDVFO 569 , $LIB 570 , $LOADER 572 , $LOADERSIZE 588 , $MAP 589
, $NOCOMPILE 590 , $NOINIT 591 , $NORAMCLEAR 591 , $NORAMPZ 591 , $PROJECTTIME
593 , $PROG 594 , $PROGRAMMER 595 , $REGFILE 598 , $RESOURCE 599 , $ROMSTART 601

$SERIALINPUT 602 , $SERIALINPUT1 604 , $SERIALINPUT2LCD 605 , $SERIALOUTPUT 605 ,


$SERIALOUTPUT1 606 , $SIM 607 , $SWSTACK 609 , $TIMEOUT 612 , $TINY 614 ,
$WAITSTATE 616 , $XRAMSIZE 617 , $XRAMSTART 617 , $XA 616 , $CRYPT 529 ,
$NOTRANSFORM 592 , $FILE 539 , $AESKEY 511 , $XTEAKEY 618 , $STACKDUMP 607 ,
$NOFRAMEPROTECT 590 , $FRAMEPROTECT 542 , $FORCESOFTI2C 540 , $BOOTVECTOR
518 , $REDUCEIVR 511 , $TYPECHECK 614 , $NOTYPECHECK 593

File
File commands can be used with AVR-DOS, the Disk Operating System for AVR.
BSAVE 678 , BLOAD 676 , GET 1132 , VER 1459 , DISKFREE 681 , DIR 680 , DriveReset 685 ,
DriveInit 685 , LINE INPUT 697 , INITFILESYSTEM 696 , EOF 688 , WRITE 705 , FLUSH 693 ,
FREEFILE 694 , FILEATTR 689 , FILEDATE 690 , FILETIME 692 , FILEDATETIME 691 , FILELEN
692 , SEEK 1300 , KILL 696 , DriveGetIdentity 684 , DriveWriteSector 687 , DriveReadSector
686 , LOC 698 , LOF 699 , PUT 1270 , OPEN 1254 , CLOSE 752 , CHDIR 679 , MKDIR 700 , RMDIR
701 , NAME 701 , GETATTR 695 , SETATTR 702 , CLEARATTR 679

Graphical LCD
Graphical LCD commands extend the normal text LCD commands.
GLCDCMD 1201 , GLCDDATA 1201 , SETFONT 1219 , LINE 1212 , PSET 1216 , SHOWPIC 1223 ,
SHOWPICE 1223 , CIRCLE 1187 , BOX 1185 , RGB8TO16 1219

I2C
I2C commands allow you to communicate with I2C chips with the TWI hardware or
with emulated I2C hardware.
I2CINIT 1168 , I2CRECEIVE 1172 , I2CSEND 1173 , I2CSTART, I2CREPSTART, I2CSTOP,
I2CRBYTE,I2CWBYTE 1174

IO
I/O commands are related to the I/O pins and ports of the processor chip.
ALIAS 639 , BITWAIT 706 , TOGGLE 1457 , RESET 1294 , SET 1305 , SHIFTIN 1315 , SHIFTOUT
1319 , DEBOUNCE 1087 , PULSEIN 1268 , PULSEOUT 1269

© 2021 MCS Electronics


30 BASCOM-AVR

Micro
Micro statements are specific to the micro processor chip.
IDLE 1181 , POWER mode 1265 , POWERDOWN 1266 , POWERSAVE 1267 , ON INTERRUPT 1247 ,
ENABLE 1120 , DISABLE 1111 , START 1400 , END 1126 , VERSION 1460 , CLOCKDIVISION 751 ,
CRYSTAL 1051 , STOP 1406

Memory
Memory functions set or read RAM , EEPROM or flash memory.
ADR 635 , ADR2 635 , WRITEEEPROM 1464 , CPEEK 1048 , CPEEKH 1049 , PEEK 1263 , POKE 1264 ,
OUT 1262 , READEEPROM 1280 , DATA 1052 , INP 1183 , READ 1279 , RESTORE 1295 ,
LOOKDOWN 1231 , LOOKUP 1233 , LOOKUPSTR 1234 , LOADADR 1226 , LOADLABEL 1227 ,
LOADWORDADR 1227 , MEMCOPY 1240 , GETREG 1152 , SETREG 1307 , VARPTR 1459 , MEMFILL
1242

Remote Control
Remote control statements send or receive IR commands for remote control.
RC5SEND 1273 , RC6SEND 1276 , GETRC5 1148 , SONYSEND 1320

RS-232
RS-232 are serial routines that use the UART or emulate a UART.
BAUD 1354 , BAUD1 1355 , BUFSPACE 1357 , CLEAR 750 , ECHO 1117 , WAITKEY 1377 ,
ISCHARWAITING 1364 , INKEY 1358 , INPUTBIN 1363 , INPUTHEX 1362 , INPUT 1359 , PRINT 1367 ,
PRINTBIN 1370 , SERIN 1371 , SEROUT 1374 , SPC 1373 , MAKEMODBUS 1365

SPI
SPI routines communicate according to the SPI protocol with either hardware SPI or
software emulated SPI.
SPIIN 1379 , SPIINIT 1380 , SPIMOVE 1381 , SPIOUT 1384 , SPI1IN 1379 , SPI1INIT 1380 ,
SPI1MOVE 1381 , SPI1OUT 1384

String
String routines are used to manipulate strings.
ASC 722 , CHARPOS 1385 , UCASE 1399 , LCASE 1390 , TRIM 1398 , SPLIT 1396 , LTRIM 1392 , INSTR
1389 , SPACE 1395 , STRING 1397 , RTRIM 1394 , LEFT 1391 , LEN 1392 , MID 1393 , RIGHT 1393 , VAL

743 , STR 740 , CHR 731 , CHECKSUM 711 , CHECKSUMXOR 711 , HEX 737 , HEXVAL 736 ,

QUOTE 1394 , REPLACECHARS 1293 , STR2DIGITS 741 , DELCHAR 1386 , DELCHARS 1387 ,
INSERTCHAR 1388

TCP/IP
TCP/IP routines can be used with the W3100/IIM7000/IIM7010/W5100/W5200/
W5300 modules.
BASE64DEC 1408 , BASE64ENC 1410 , IP2STR 1417 , UDPREAD 1444 , UDPWRITE 1449 ,
UDPWRITESTR 1450 , TCPWRITE 1439 , TCPWRITESTR 1441 , TCPREAD 1438 , GETDSTIP 1412 ,
GETDSTPORT 1413 , SOCKETSTAT 1433 , SOCKETCONNECT 1429 , SOCKETLISTEN 1432 ,
GETSOCKET 1415 , SOCKETCLOSE 1425 , SETTCP 1420 , GETTCPREGS 1416 , SETTCPREGS 1422 ,
SETIPPROTOCOL 1418 , TCPCHECKSUM 1435 , SOCKETDISCONNECT 1432 , SNTP 1423 ,
TCPREADHEADER 1439 , UDPREADHEADER 1447 , URL2IP 1454

© 2021 MCS Electronics


Index 31

Text LCD
Text LCD routines work with normal text based LCD displays.
HOME 1202 , CURSOR 1193 , UPPERLINE 1225 , THIRDLINE 1225 , INITLCD 1202 , LOWERLINE 1215
, LCD 1204 , LCDAT 1207 , FOURTHLINE 1200 , DISPLAY 1197 , LCDCONTRAST 1210 , LOCATE 1215 ,
SHIFTCURSOR 1221 , DEFLCDCHAR 1196 , SHIFTLCD 1222 , CLS 1190 , LCDAUTODIM 1207 ,
LCDCMD 1209 , LCDDATA 1210 , LCDFONT 1211

Trig & Math


Trig and Math routines work with numeric variables.
ACOS 641 , ASIN 644 , ATN 645 , ATN2 646 , EXP 652 , RAD2DEG 668 , FRAC 653 , TAN 671 ,
TANH 670 , COS 649 , COSH 650 , LOG 656 , LOG10 655 , ROUND 668 , ABS 640 , INT 654 ,
MAX 1238 , MIN 1243 , SQR 671 , SGN 669 , POWER 662 , SIN 673 , SINH 672 , FIX 653 , INCR 1183
, DECR 1089 , DEG2RAD 651 , CHECKFLOAT 648 , MOD 1244 , QSIN 663 , QCOS 667 , AND 642 ,
OR 659 , XOR 674 , NOT 656

Various
This section contains all statements that were hard to put into another group
CONST 1045 , DBG 1085 , DECLARE FUNCTION 1090 , DEBUG 1086 , DECLARE SUB 1093 , DEFXXX
1098 , DIM 1099 , DTMFOUT 1115 , EXIT 1127 , ENCODER 1124 , GETADC 1135 , GETKBD 1145 ,

GETATKBD 1140 , GETRC 1147 , GOSUB 1153 , GOTO 1154 , LOCAL 1228 ,ON VALUE 1251 , POPALL
1265 , PS2MOUSEXY 1267 , PUSHALL 1270 , RETURN 1296 , RND 1297 , ROTATE 1299 , SENDSCAN
1308 , SENDSCANKBD 1310 , SHIFT 1313 , SOUND 1326 , STCHECK 1402 , SUB 1407 , SWAP 1407 ,

VARPTR 1459 , X10DETECT 1467 , X10SEND 1468 , READMAGCARD 1286 , REM 1293 , BITS 707 ,
BYVAL 709 , CALL 709 , #IF 509 , #ELSE 509 , #ENDIF 509 , READHITAG 1283 , SORT 1325 ,
XTEADECODE 1167 , XTEAENCODE 1165 , BREAK 708 , COMPARE 755 , NOP 1246 , SIZEOF 1323

RAINBOW WS2812
Rainbow or WS2812 LED statements and functions.
CONFIG RAINBOW 925 , RB_ADDCOLOR 1334 , RB_ANDCOLOR 1334 , RB_ORCOLOR 1336 ,
RB_SUBCOLOR 1336 , RB_CLEARSTRIPE 1337 , RB_CLEARCOLORS 1338 , RB_FILL 1338 ,
RB_FILLCOLORS 1339 , RB_FILLSTRIPE 1341 , RB_SELECTCHANNEL 1328 , RB_SEND 1330 ,
RB_SETCOLOR 1329 , RB_SWAPCOLOR 1341 , RB_ROTATELEFT 1342 , RB_ROTATERIGHT 1343 ,
RB_SHIFTLEFT 1344 , RB_SHIFTRIGHT 1345 , RB_CHANGEPIN 1331 , RB_SETTABLECOLOR 1345 ,
RB_GETCOLOR 1349 , RB_LOOKUPCOLOR 1350 , RB_COLOR 1350 , RB_COPY 1352

FT800-FT801-FT810
CMD8 1494 , CMD16 1495 , CMD32 1495 , RD8 1548 , RD16 1548 , RD32 1549 , WR8 1559 , WR16 1560 ,
WR32 1560

XMEGA
READSIG 1290 , ATXMEGA 393

XTINY
XTINY 428

MEGAX
MEGAX 457

© 2021 MCS Electronics


32 BASCOM-AVR

1.2 Changes
1.2.1 What is new in 2084
version 2084.001

- mega4809 added to xtiny platform. See also MEGAX 457


- xtiny support added to i2cslave add on.
- LCD I2C 1643 driver from O-Family included that supports up to 8 LCD.
- xtiny alias portx,ddrx and pinx have been changed from the port_out to the virtual
address. this also required the following :
- 1wire,i2c,getrc,pulsein,pulseout,serout,serin,i2cbus and rainbow changed for new
port mapping
- config COM 816 for xtiny has a new option to chose the alternative pin. TXPIN=option
- xtiny TCB0: CCMP_OTP renamed into CCMP_OUTPUT. Also reversed enable/disable.
And ASYNC enabled/disabled were reversed too.
- xmega dat files corrected for DACA/DACB.
- xmega config eeprom=quick|mapped did not simulate properly
- xtiny config port_mux did not set the proper register value for TCAx and TCBx
- portmux support complete rewritten. data is stored in the dat files. see also
config_portmux 906 for important information.
most choices list the pin number name now.
- sizeof 1323 () function added. it returns the size of a variable in memory.
- xtiny config sysclock prescaler value 6 was missing.
- simulator fix for xtiny (register offset). Also register name length extended to 32
characters
- htrc110.LBX added * for used equ so they can be adjusted by the user
- DTR option for terminal emulator. you can set the DTR pin level for the terminal
emulator just like you can for the RTS pin.
- mysmartusb light programmer problem with EEPROM programming solved
- const _TEXTLCDKIND 889 added which contains the text LCD kind like : 162 for 16x2
- the tool tip info (SHIFT key) shows the length of a string constant when moving
over a string constant.
- xtiny support added for AVR-DOS
- serin/serout implemented for xmega and xtiny
- SWAP 1407 can swap a long/dword too
- glcdST7565R.lib adjusted for RAMPX boundary in showpic
- xtiny enable/disable set wrong bits for the timers
- xtiny start/stop switch the enable bit for timers
- datetime.lib modified for xtiny
- split() did not raise an error when using non-strings. The result array must be a
string array.
- syntax check/compile did reset the stk200 programmer reset pin
- xtiny tcb1 added which was missing.
- UPDI programmer speed increased. baud is selectable. 225000 is the maximum for
the default updi clock.
- IDE did not compile for the right processor when multiple $regfile directives were
used with #IF#ENDIF.
- Font size increased in IDE. Default is now SEGUI 12. When you use a different
language in options, this might not be visible.
Also changed IDE so that high resolution monitor should show better font when
bigger fonts are chosen. The icons/images still need to be changed to vector drawn
images so they can scale better.
- more xtiny samples
- IDE can update 55 a number of add ons

© 2021 MCS Electronics


Index 33

1.2.2 What is new in 2083

For the Xtiny the following changes were made to


2083.008:
- xtiny 8 pin chips set the wrong tx pin for config com. as a work around, you can
define a portb alias that points to portA
- printing a constant using the str() function : print str(number_constant) would
include a leading space for positive numbers. Variables do not have
this (VB behavior).
- xtiny config xpin was missing the INVERTIO option in the DAT files.
- passing a big string for which the size could not be determined, would not release
space which would result in a quick crash.
to determine the size of passed strings, you best declare with the size indicator
like : someString as String * cSize
- config spi0 for xtiny 202,402,212,412(8 pins) did not set the SS pin in the proper
state.
- config vref was not described in the help
- adc.bas sample added for xtiny
- xtiny dat files updated for config adc and signature row offset adjusted.
- xtiny adc1 can also be configured now
- xtiny renamed ACI to AC : config ac0. Also added ac1 and ac2
- xtiny config dac1 and dac2 added.
- xtiny config port_mux added.
- xtiny SPI sample added
- showing report in project mode inside the editor as a TAB did not set focus to the
report.
- xtiny dac.bas sample added
- xtiny portmux.bas sample added
- optional custom defined menu shortcuts added. See help : Options Environment
- RESET MICRO added which will soft reset the micro. for xtiny/xmega a hardware
soft reset is performed. For normal AVR a jump to the start address is
performed.
- getadc can also read and process the internal temp sensor when you define a const
named _adc_kelvin. The value is unimportant. see adc.bas example
- multiple asm .def with different register but same name will give an error now
since .defs are global.
- num2str for xtiny/xmega offset added to avoid str() causing problems when passed
to a function

Public release

- new option SAFE for variables. Dim 1099 b as bit SAFE , see help.
- added BOOTONLY option to $LOADER 572 directive. $loader bootaddress[,
BOOTONLY] this will write just the boot loader code to the BIN file. The HEX remains
as is.
- you can select the Options_Select_Settings_File 205 now. This setting is stored in the
registry.
- project files are stored with absolute files names inside the prj file. An absolute file
name is relative to the location.
- simulator bug fixed where SI file simulation data was not processed properly.
- MemFill 1242 added.
- using instr() with {xxx} for the search string does not work : pos=instr
(someAString,"{065}")

© 2021 MCS Electronics


34 BASCOM-AVR

- using compare_a/compare_b=clear for timer0 resulted in SET instead of CLEAR.


- bascomp command line utility updated to support new file structure
- multiple instances bug fixed.
- mcs.lbx was not in sync with mcs.lib (it was not compiled when a last minute
change was made)
- when using channel specifier without # you will get an error
- stk500v2 based programmers like mkII and stk500v2 could give a program error
when your code contains empty blocks And the processor has multiple 64KB
segments. applies to normal mega only.
- crc8 712 overloaded version added for big strings.
- 2082 broke the default printing function
- added DES asm instruction.
- added DesEncrypt 1161 and DesDecrypt 1163 which are also supported by the simulator
- inputbin 1363 accepts an optional variable for the number of bytes to receive.
delimited by a ;
- simulator 103 update.
- simulator double click cycles, will reset cycles
- simulator allows to load a custom serial data file from file
- Xtiny 428 support, requires a commercial add on
- CTS/RTS bug fixed : only part of the buffer was used
- added PA version of dat files M88PAdef,M644PAdef,M48PAdef,M168PA. These are
almost the same as the P versions. They are binary compatible and have the same ID
- searching in files would not search in the specified folder when the folder name
contained a space. Instead the root folder was used.
- $programmer option did not support conditional compilation. It was global. Now
supports #IF/#ENDIF. but only when 'Use new method' is used in environment IDE
options.
- CLEAR serialinx buffer did not clear the RTS pin when cts/rts was used for xmega
uarts 4-7.
- xmega high baud calculation > 2MB and higher did not support double rate flag
resulting in a wrong baud rate
- for next using a step for bytes could fail when the byte boundary was crossed.
- xmega num2str code rewritten and xmega routine rewritten that used
_XmegaFix_Rol_R1014 and _XMEGAFIX_CLEAR. These routines are not used
anymore!
- using a string function with select case, could result in improper branching,
depending on the user function.
select case mid(someString,start,len) for example.

- bascom-AVR and the SETUP are now code signed.


- CONFIG XPIN for the E-series : slewrate will be set the whole port, not for an
individual pin
- crc16uni 719 can handle 65535 bytes
- low/high can be used as a procedure too for BASCOM-8051 compatibility.
- UPDI programmer can write fuses

Please notice that this version has significant changes in order to support the Xtiny
platform.
While everything was extensively tested, it is still possible you encounter a bug.
When you encounter a problem you did not had with 2082 you best contact support.

© 2021 MCS Electronics


Index 35

1.2.3 What is new in 2082


- rearranging memory order for usb support caused a bug in config clock : the date
time bytes are not mapped after each other. Fixed.
- START/STOP statements worked on the wrong register for the TINY1634
- i2c_twi_multi lib had a problem in the readbyte function.
- SPIMOVE 1381 added for Xmega
- split screen did not allow copy & paste
- USI slave support added for tiny1634
- All DAT files are now stored in a sub folder named DAT. This means you
need to copy your DAT file to this folder if you made custom DAT files.
- some registers of tcc1 were missing in xmega D3 series
- read only files could not be opened anymore. fixed.
- On win10 you could get a HID error message.
- w5500 tcp lbx : removed RST status bit check since the bit never becomes 0 and
hangs the code
- url2ip 1454 bug fix. one byte of the IP address could get trashed
- url2ip added to w5500
- new samples for w5500 wiznet chip
- accessing a zero based array inside a sub coulld result in an index error.
- simulator did not support writing to xmega portx_CLR _SET and TGL registers
- using search in files function could result in 'out of bound' error.
- manchesterEnc 739 and manchesterDec 738 functions added for manchester coding/
decoding
- assigning a byte with a string constant with spaces, resulted in 0, not 32.
- VARPTR 1459 () function returned &H1000 too much for Xmega ERAM data type.
- using getadc() with 2 numeric parameters or constants like : getadc(4,&H20) would
not set the right bits.
- i2csend and i2creceive updated for xmega. after the start/slave address, the status
is now checked and does not send data in case of a bus problem. this to prevent a
hangup in the twi logic.
- printing supports selection of text and page range now. you need to use print
preview for this.
- OUT instruction did not clear RAMPZ for Xmega with ROM > 64KB and normal
SRAM.
- PS2MOUSEXY 1267 accepts an additional optional parameter for mouse wheel support.
Notice that you MUST download an update of the ps2 lib add on
- config spi on non xmega did not support the extended mode for HW SPI
- config tcpip 980 now supports SPI1 for the SPI bus
- windows 10 DEP and ASLR support added.
- printbin: when using automatic rs485 and printing a long/dword constant on a chip
with extended port register, R23 was trashed. Example : printbin &HABCDEF00
- FLIP() function resulted in an error about $REGS
- terminal emulator component is replaced in order to support windows DEP/ASLR.
This means that some features from the terminal emulator have changed.
- printbin 1370 can print a variable amount of bytes now. while ; is used to separate
multiple variables, the comma can be used to specify the amount of bytes
like : printbin ar(1) , numbytes ; othervar
this makes the syntax compatible with the old syntax. We recommend to use the
new syntax
- terminal emulator custom messages extended to 16
- UPDI programmer 192 added for new AVR processors with UPDI interface.
- A table is added to $LOADER 572 with the size of maxwordbit. This constant depends
on the number of flash pages.

FILE LOCATION
With DOS things were simple : all files could go in a folder and sub folder. To make a
backup all you had to do was using XCOPY.

© 2021 MCS Electronics


36 BASCOM-AVR

With Windows things are not so simple : files are located all over the PC. Some
folders are write protected and to make a backup is not so simple.
A lot of customers are looking for the SAMPLE files. These are put in the documents
folder and can be accessed using the File, Open Sample option.
In 2082 the preferred folder for installation is C:\MCS\BASCAVR2082
But of course you are free to install in any other folder of your choice.
The samples are installed in a sub folder of the application folder too.
In the Environment Options of the IDE you can specify which folder you want to use
for the sample files.

About UPDI
The new UPDI processors have a total different architecture compared to normal AVR.
In fact the differences are similar to XMEGA. For this reason we refer to these
processors as XTINY since they are tiny Xmega processors.
Because of the work and support for XMEGA fresh in mind, the actual UPDI compiler/
DAT support will be available very soon in a next update as an add on.
The TINY816/817 will be the first processor to be supported.

1.2.4 What is new in 2081


- CONTINUE 1043 statement added
- REDO 1288 statement added
- NOP 1246 is now also a BASCOM BASIC statement
- The editor supports jump to implementation : hold CTRL key and hover the mouse
over an identifier. When it becomes underlined and blue you can click it with the left
mouse key.
Use CTRL+BACKSPACE to jump back
- when defining a constant named Updateeprom 1099 , the eeprom will be updated.
which means that the value will only be written when it differs. The value of the
constant does not matter.
- config timer1 for tiny 25/45/85 set the wrong register bits.
- the watchdog is disabled as part of the init procedure. it is now disabled BEFORE the
optional call to init_micro 561 and not after as in 2079.
- passing string constants with embedded {034} resulted in an extra (unwanted)
space.
- accessing passed string array in sub without length info, but with constant index
failed.
- crcmb 721 funtion added to help. (checksum for modbus)
- for xmega i2cstop 1174 you can define a constant named _TWI_STOP_1 or
_TWI_STOP_2 to change the behavior.
- makemodbus 1365 () function 1, 2 and 4 added to modbus.lib
- support for xmega added to getrc 1147
- PDF download now also checks/download the BASCOM-AVR manual
- PRINTBIN did not accept a constant for the optional channel : printbin #someconst.
Fixed.
- update 214 from within the application simplified. see help.

- printbin raised error while printing multiple variables


- simulator did not show proper hex value for single variables.
- fusing which uses ftoa uses a table which could be loaded on a page boundary. this
could lead to rampz problems. fixed.
- crc8UNI 714 added for normal crc8 CCITT
- config clock 798 additional option : highESR=1 to enable high ESR mode in xmega
with 32 bit RTC

© 2021 MCS Electronics


Index 37

- FM24C64_256 1600 -XMEGA.lib added for xmega. read the lib notes.
- tcpip-w5500.lbx has been updated to support usage from boot space. See $loader
572
- stk500 board. osc can be set from menu
- using spimove 1381 () inside a sub with a parameter for the count, would load the
wrong data.
- i2cwbyte 1174 would raise an error if a multi dim array was used.
- get/put/seek in AVR-DOS used in combination with $bigstrings would fail for
numeric data
- xmega i2cstop 1174 has two new optional mode. See help.
- CONFIG SPI 948 has a new option : EXTENDED=1 to have extended data size
reading/writing.
- support for rgbW 925 leds added (ws2812 with extra white led)
- CONFIG USI 1021 has a new option to support optional pins.

1.2.5 What is new in 2080


- tiny461 329 and tiny861 331 only did set pcie0 when you enable the PCINT because
there is just one interrupt in the chip. In 2080, both PCIE0 and PCIE1 are enabled/
disabled.
- added m48PB, m88PB, 168PB and m328PB dat files.
- new Rainbow functions : RB_Color 1350 and RB_Copy 1352 added by Galahat
- simulator did not show maximum values of DWORD correct.
- RB_GETCOLOR 1349 and RB_LOOKUPCOLOR 1350 functions did return false result when
index was a variable.
- some font problems solved.
- simulator could crash for xmega processors.
- when using non-mono font like Arial, text selection does not work properly. Use a
font like CONSOLAS.
- Added option 'Use Monofont' for backwards compatibility
- Some new atmel PDF files could not be loaded with the PDF viewer. Viewer is
rewritten and requires a new DLL named BASPDF.DLL
- getadc 1135 () on m640.m1280/m2560 or any other processor with 6 mux bits did not
set mux5 bit for getadc(32) and higher.
- generic byte compare 755 () function added, based on code and idea from MWS.
(Magic White Smoke)
- varexist() did not support ALIAS.
- XMega64A1-SRAM 4-Port-Sample.bas sample added for setup EBI 4 port on XMega.
See also Adding XRAM to XMEGA using EBI 236
- when bascom-avr.xml options file exists in the bascom application folder, that
option file will be used.
- format 732 is extended to use a variable for the mask.
- config xpin 1034 did not support alias for the pin.
- bufspace 1357 () did not support UART 5-8
- INSERTCHAR 1388 and DELCHAR 1386 use Z pointer which must be cleared for XMEGA.
fixed in mcs.lib
- programmer did not fetch correct chip from editor when code was not saved. this
would give a chip mismatch.
- assigning a negative value to a dword did not throw an error.
- code explorer 93 can show estimated stack usage.
- higher standard baud rates added to terminal emulator
- added support for EDMA in xmega8/16/32 E5. See config EDMA 843
- version 1460 () function did not append to string but would overwrite existing string
data.
- right 1393 () adds an additional null byte when a numeric constant is used for the
number of characters to copy.
- new dim 1099 option to specify multiple items : dim a,b,c,d as byte failed when using
multiple indexed items.

© 2021 MCS Electronics


38 BASCOM-AVR

- all dat files updated with CONFIG information.


- printing values from multi index variables failed : print index(index1,index2)
- m1284pdef.dat updated with missing TIFR3 register.
- more fonts in various sizes from Adam Siwek.
- power() 662 function for doubles did not work correct when assigned to a function
- some new atmel PDF files can not be loaded with the PDF viewer. Viewer is
rewritten.
- SSD1306 i2c oled driver updated for Xmega.
- m649A and m649P dat files added.
- LCDFONT 1211 prm, added. prm selects the font table (0-3) of a text LCD.
- CONFIG POWER_REDUCTION 916 set register to 0 in some conditions. Also added
LCD and other new Xmega power reduction options.
- CONFIG OSC extended with calibration register settings and DFLL.
- val() for doubles has a bug for XMega >64KB chips
- added flip 1129 (byte) function to mirror bits in a byte
- xmega128B3 dat file added
- readsig 1290 also works for normal AVR processors.
- inputbin and printbin load 1 element too many with arrays using base 0.
- config inputbin 881 added to allow reading packets of up to 64 KB
- added support for LCD text OLED RS0010 lcd4_anypin_oled_RS0010.lib
- FT81x 1473 support added
- M324PB 371 dat file added.
- I2CINIT 1168 enhanced for multiple TWI
- I2C_TWI-MULTI.lib 1608 added to support multiple TWI busses.
- second SPI on m328PB added : INIT1SPI 1384 , SPI1OUT, SPI1MOVE, SPI1IN
- user donated library I2C DOGS104 1634 driver, SSD1803A included.
- URL2IP 1454 (url) function added to W5100 to do DNS lookup using google DNS server
- when defining a const Updateeprom 1464 , the eeprom will be updated. which means
that the value will only be written when it differs
- BASE64ENC 1410 and BASE64DEC 1408 can work on byte arrays too.

2017, 2080 release


- SGN 1422 extended to byte, integer, word, dword and long
- LOADLABEL 1227 assigns a 24 bit address when used with a DWORD
- CTRL+SPACE for code help.

1.2.6 What is new in 2078-2079


Beta version 2079

- Support for WS2812 RGB led : CONFIG RAINBOW 925 . This is the rainbow lib from
Galahat, see : http://bascom-forum.de/mediawiki/index.php/Rainbow_Lib
- SETATTR 702 and CLEARATTR 679 added to AVR-DOS, by Josef.
- shift & rotate left/right did not work for xmega port registers
- IDE : improved speed for showing deadcode/unused variables
- IDE : stacktrace speed up. big projects made the stacktrace slow.
- included FT801 support. See CONFIG FT800 858 . Notice that the INC files have been
renamed into FT80x
- fixed attiny261,461 and 861 interrupt entries. this chip has only 1 pcint.
- added check when $loadersize 588 and $boot 517 are combined.
- Dim 1099 supports a list ; dim a,b,c,d as byte. It also supports identifiers like %,#,&
and !
- Font Editor plugin is replaced by integrated Font Editor: Tools, Font Editor 133
- Sample added for USI Slave lib 1611
- fonts contributed by Adam Siwek included. You can find them in the
Samples\LCDgraph\Fonts folder.
- report 102 can be opened in IDE as text file.

© 2021 MCS Electronics


Index 39

- mySmartUSB light 190 programmer support added.


- support added for W5500 980 tcp/ip chip
- W5500 socketconnect 1429 has a 4-th parameter : nowait. When you make it 1, there
is no wait for connection.
- $ROMSTART 601 added : $romstart = &H8000 , will let the code start at &H8000.
Default is 0.
- jtag ice mkII programmer new firmware 7.26 from AVR studio resulted in signoff
problem. Workaround implemented.
- editor can show unused code in conditional compilation. Edit, Show Excluded Code
83 menu option.

- usbasp programmer updated. chosen clock frequency will work.


- makemodbus() did not support locals/passed parameters properly.
- crc16 716 can now directly read a range from eeprom memory to calculate a checksum for
you. To enable it, just add const CRC16_EEPROM=1 to the beginning of your code.
- simulator fix for xmega low IO registers. registers were simulated with a 32 byte
offset as in plain AVR.
- config lcd 889 has 2 new options : BEFORE and AFTER. with a parameter value of 1 a
sub will be called _lcdBefore and _lcdAfter
just before the LCD is used. This allows for example to turn off interrupts when
executing LCD code.
Only text LCD is supported.
- getadc 1135 () when used on normal AVR with offset parameter, and both parameters
numeric will give an error when MUX5 bit must be set.
Use getadc() with just the channel parameter.
- multi dim arrays, added ERAM byte support, and used registers are saved now.
- saving programming buffer as HEX file created wrong HEX files which would not
load in AVR Studio. This would occur for chips with multiple segments like xmega128

- Full Kamprog 180 support added.


- multi dim arrays had no check on invalid index value (non dimmed)
- using a constant float without leading 0 resulted in an error message : var=
var + .12344
- INPUT did not support DWORD.
- added user definable command buttons to terminal emulator 120 .
- using {} in constants was not working as expected : Const Cmd_suffix_ver1 = Asc
( "{013}") was not interpreted as 13 but 123 (the { sign)
- changed PDF download 130 from HTTP to FTP. This is quicker and better for the load
of the server. PORT 211 is used for FTP. So you need to have port 211 open on your
firewall.
- atxmega128c3 added.
- FT800 1473 , vertex2ii , the X is clipped. Change call in sub vertex2II into Cmd32
_vertex2ii(___wtmpb , R18 , R17 , R16)
- support for EADOGXL240-7 I2C 1640 added, see eadogxl240-7.bas. This is a customer
sponsored lib.
- added support for SSD1306 I2C 1642 OLED, see SSD1306-I2C.BAS.
- i2c multi bus lib did not clear ERR bit correctly.
- when a multi dim array is only used within sub/functions and submode=new is
used, an error was raised since the index table was not written at that stage.

- multi dim arrays can only be used to read/assign variables. Using them in functions
and statements will not work.
- str 740 () can have an optional parameter to specify the amount of digits. This works
for double, but now also for singles.
- MOD 1244 for singles changed in fp_trig.lib so it uses the same algorithm as excel/
VBA.
- FOR..NEXT with WORD data type and STEP with values other than 1 failed : for w=1
to 10 step 2

© 2021 MCS Electronics


40 BASCOM-AVR

- when opening a single file in non-project mode, the code explorer does not get
updated until you set the cursor on the code.
This also resulted in not updating the pinout viewer.
- R0-R31 internal variables are now exposed as byte variables. This is simpler than
using getreg/setreg.
- added option to skip eeprom cell test. This allows to write all FF to the EEPROM
whithout erasing the chip.
- terminal emulator font color could not be selected from the font dialog.

- various programmers : added chip name to info panel when chip does not match. no
match will result in a red font, a match will show in green.
- added an error message when $hwstack,$swstack and $framesize are missing from
the source. Also put back compatibility to 2077 when these directives are not
specified.
- hovering the indention line will show the begin of the structure in the tool tip (just
try it).
- Terminal emulator 120 has 8 user definable buttons
- SEROUT 1374 defaults to CONST SEROUT_EXTPULL=1 to be in Hi-Z mode. In this
mode a pull up resistor is required. To use PORT output mode, set the constant to 0 :
CONST SEROUT_EXTPULL=0

2.0.7.8.001 public release

- changing a bit on a passed array inside a sub/function gave a bit index error.

- while moving all single FP code to fp_trig.lib, some double (but WRONG) functions
were moved to the top. It causes various problems.
- clear buffer did not reset the RST pin in case CTS/RTS was used.
- val()/asc2float contained a bug for converting big values not fitting into the
mantissa. The exponent was not increased.
- asc 722 () can have an additional index parameter : byte=Asc(string|string constant[,
index]). Use this instead of asc(mid(
- user functions/subs can have a custom color
- added support for i2c lcd display RX1602A5. Use : config lcd = 16x2 , chipset =
st7032. See sample LCD-RX1602A5.bas
- using overlay pointing to a string array resulted in a wrong overlay address.

- additional XTEA2.LIB added. This lib complies with the original standard.

- Tab order can be changed with drag and drop.


- USI master TWI mode added.
- when config submode=new was used, the syntax check could give false errors.

- mkII programmer would give a warning about chip mismatch when atmel chip ID
was the same.
- pulsein.lib was missing from distribution.
- documented beta switches $NOTYPECHECK 593 , $TYPECHECK 614 and $REDUCEIVR 596

- when using a serial boot loader compiled with an older version, and when calling it
from code (not after a reset) you need to reset the u2x flag in ucsrxA.
Or you can compile both the bootloader and main code with the new version. When
you want the old behaviour, you can remark the u2x constant in the dat file.

- FLIP programmer will not erase EEPROM anymore.


- use ALT key to select blocks of text in the editor.
- hint window location fixed for multi monitors systems.
- rgb8to16 1219 () function added to convert RGB8 to RGB16.

© 2021 MCS Electronics


Index 41

- xmega, config OSC : when using external osc, the oscillator ready test was not
working properly. enable the internal osc as a workaround in 2077. fixed in this
release.
- arduino leonardo can be programmed with myAVR MK2/AVR910. You need to give a
manual reset before pressing F4.
- attiny87 dat file contained an error : INTADR = 1 ; it was 2 but must be 1

- xmega spi length parameter supported globals only. now it supports locals and
parameters as well.
- syntax check gave errors when config submode=new was used in some cases.

- 1wirecount returned with ERR set, even when sensors were found.

- simulator 103 has trace log option to dump all executed lines to a file.

- error list content can be copied to clipboard with right mouse popup menu

- xmega uarts 5-8 serial buffered output enable the wrong uart.
- indention line colors can be customized.
- proper indent 82 will not indent comment
- getkbd 1145 () required change for xmega. (xmega does not use port register for pull
up)
- added dword support to lookup()
- config rnd 932 =16|32 added to support bigger random numbers.

- attiny441 stk500 settings changed. attiny441 and attiny841 verified with real chips.
some mods made to the dat files.
- increased internal constant string storage length to 1024. for cases like : s="some
very long constant". previously the max size was 256.
- xmegaE5 timers 4/5 support added.
- xmegaE timer4/5 OVF bit need a manual reset, writing a 1 to intflags register. it is
not cleared automatically.
- xm128a1U dat file added
- code folding added to editor. Press F11 to fold a sub/function
- all project files can be placed in an archive 74 (zip) file.
- AVR-DOS, GET and PUT support $bigstrings 516
- $boot 517 extended to support >64KB processors. $boot can be used together
with $inc to include a boot loader in your code.
- FM25C256 example with BMA.bas sample added which demons xmega ramtron lib
with shared bus.
- baudX=value added for Xmega. This will change the baud rate on an xmega at run
time.
- special multi bus i2c added for normal AVR processors. See config i2cbus 871 .

- muli dimensional array support added like : dim ar(10,50,3,5,2).

- long/dword data types added to SORT statement.


- report extended with bit position in memory and length of dimensioned strings

- Lookup 1233 supports a numeric variable too for the label : novar = LOOKUP( value,
label|address).
- soft spi supports DATA ORDER LSB and MSB
- str 740 () second optional parameter added to help. It specifies number of digits after
the DP. Only for doubles.
- m324/m164/m644/m1280 config timer0, disconnect option fixed.

- settings xml file can be passed as parameter to allow different settings files and
versions.

© 2021 MCS Electronics


42 BASCOM-AVR

- added option to show invisible characters.


- added support for DWORD to SWAP 1407
- added insertionsort.bas sample
- m64C1 and M32C1 dat files added.
- History Backup option added : it will create a unique copy of the source file each
time you save a file.
- code explorer can show INC files under their own branch (options, environment, IDE
142 )

- Qsin 663 and Qcos 667 integer trig added.

1.3 About MCS Electronics


About the Founder
Since I was young, I was intrigued by remote control, robots, transmitters, in short,
all kinds of electronics. I created countless electronic devices. I designed a lot of
PCB's by hand using ink and later using tape.
At the ETS(electronic technical school in Amsterdam) we had a Philips main frame
with terminals which could be programmed in a simple form of BASIC.
When working at Philips in Hilversum i also worked with an industrial computer that
could be programmed in BASIC.
The Apple II we got later on at the ETS could also be programmed in BASIC.

When the ATARI came with the 1040ST and an affordable PCB design tool, I bought
my first real computer. I bought the ATARI just for the purpose of PCB design. The
netlists had to be manually entered.

Only Dot matrix printers where available at that time. And the prints were not really
usable. That only changed when laser printers became available.
I found out that a nice BASIC interpreter, which was similar to GW-BASIC, was
included in the OS(TOS). For some reason, I liked this language. It was easy to
master and very intuitive.
I made some programs for the PTT(now KPN) that were revolutionary at that time.

For hobby purpose i used the 8052AH BASIC programmable processor from Intel. I
made a lot of interfaces using PIO, relay, etc. My home was automated in 1986.
Because of my work for the PTT i was also able to get caller info, something not
available as a service yet. I used the 8052AH to show the caller info on an LCD.
The 8052 was great but the UV eeproms had to be erased using UV light. It was slow.

I found out, that Atmel made the 89C2051, which was a 20 pin chip with flash
memory. I was excited to find out that there was a small micro processor that could
be erased/reprogrammed without the need to UV erase the EPROM.

In those days, electronic circuits consisted of numerous CMOS and TTL chips. I saw
the 89C2051 as an ideal replacement for a lot of CMOS/TTL chips. It would make PCB
design much simpler. So the 2051 became a replacement chip. Like a small black box
chip. Now one was able to design his own chips!

The idea to be able to change the behaviour of an electronic circuit, just by


reprogramming it without using a solder iron, intrigued me. Today, it is a common
practice, to update firmware, to fix bugs or add features. In 1993, it was not so
common, at least not to my knowledge.

I initially wrote a complete tool for DOS. I rewrote the tool, when I was reasonably
satisfied that Windows 3.1 was stable. The tool was for my own usage. When I

© 2021 MCS Electronics


Index 43

discovered that it would be usable to others, I decided to add Help files and a
simulator and to sell it for a small fee to support my hobby. Today you can get
electronic devices for little money. But a resistor used to cost 5 cents !

In 1995, MCS started to sell BASCOM-LT, a BASIC compiler for Windows 3.1. It was
the first Windows application that offered a complete and affordable solution, editor,
compiler, simulator and programmer. BASCOM-LT was a 8051 BASIC compiler. The
reason it became popular was that it included a lot of functionality that was easy to
use from BASIC. Using an LCD display was simple, just a configuration line to define
the used pins and voila, a working application in minutes. When you needed a
different LCD display, you could simply change the CONFIG line.

When a different processor was needed, you only had to change the name of the
definition file. No need for a lot of .h files.

Another reason for its success, was that we hide much of the complexity for the user.
No ASM to deal with, simple statements. Of course free updates and support.

Small companies that used the BASIC Stamp also recognized another advantage :
There was no need for expensive modules and the code ran much quicker.

When Windows 95 became an industry standard, users also wanted a 32 bit version.
A big part of BASCOM-LT was rewritten with the additional support for arrays and
floating point (single).

With the many different 8051 variants, it was impossible to support all the chips.
Having device definition “DAT” files, made it easy for the user to configure the 8051
variants.

When Atmel launched the AVR chip, the 8051 compiler was rewritten, once again, to
support the powerful AVR chips. The result was BASCOM-AVR.

The AVR chip has a lot of internal memory. It uses simple linear memory addressing.
The best part, is that you can make the chip program itself. No wonder this chip
family became so popular.

Since the AVR chip is so powerful, we could extend the compiler as well. We could
add features, which are almost impossible to add to the 8051.

With more and more users, there was no way I could manage everything in my spare
time. So in order to guarantee the future of BASCOM, I decided to work full time for
MCS.

Today, MCS is still a small company, with only 3 employees and a few contract
workers.

We believe in free updates and support. With the number of (demo) users, it is
however not possible to support everybody. You need to realize that reading and
answering emails is time consuming.

Not to mention to duplicate used hardware. We are unique, in that we even support
hardware!

In order to migrate to a new version, it is important that you keep your software up
to date. This will make migration more simple.

Things we find important :

© 2021 MCS Electronics


44 BASCOM-AVR

· The environment. We reuse all usable packing material like foam, plastic bubbles,
when we ship your order.

· That everybody can use micro processors. They are like all other chips but you can
define their behaviour.

· Customer privacy: We keep your name, details and code confidential. We do not
sell or share any of your details.

· Free updates. They have been free since 1995 but there is no guarantee that they
will remain free for ever. The intention is to keep them free. In order to apply for
free updates you MUST register your software within 1 year.

· Free, but limited, support. Limited only, because we do not have the resources to
read/answer all emails. Professional users can get an SLA with guaranteed
response time. This is a paid option/service.

· Support for new chips. It is important to be able to support newly released chips.

· The customer : We simply add what is requested most. It does not matter what, as
long as it is requested a lot and it does makes sense and doesn't conflict with other
features.

· That you have fun with electronics, no matter where you live, no matter which
religion you have, no matter how old you are, if you are male or female, purple or
white.

· That you can use the demo for free. The DEMO has no nag screens. You should
purchase the full version if you use it commercial. Please do not use cracked
software. Only download from the www.mcselec.com domain. Copies from other
sites may contain spy ware, virus or other malware. When we detect a cracked
version the compiler generates tiny bugs at random which are hard to detect. We
ban all IP numbers of users with a cracked version.

Mark Alberts
Managing Dire
MCS Electronics

1.3.1 Custom Designs


MCS does produce hardware to support special options. Like the EM4095 Reference
Design 294 or the TCP TWI motherboard and adapter boards. We try to avoid SMD
parts. In some cases this is not possible however.
For a prototype or small series, through hole components are simple to use. We do
this with the hobbyist in mind. So our reference designs use little SMD parts too.

You can contact us also for :


- custom bascom software
- customer ASM drivers
- windows software development
- electronic or software projects
- PCB design (Eagle)

© 2021 MCS Electronics


Index 45

1.3.2 Application Notes


When you want to show your application at our web as a reference example on what
you can achieve with BASCOM, we like to show it at our web, but of course with your
permission.
We never publish anything without your explicit permission.

AN's are also welcome. When you developed a great AN you want to share with other
BASCOM users, just send it and we will make an AN out of it. It is important that the
comment in the source is in English.
You can also share your code at the MCS Electronics user forum.

1.3.3 About this Help


This help manual is available in CHM format for the IDE. And also in HTML on line.
A PDF version can also be downloaded. You can do that using the Tools, PDF function
of the IDE.

Some topics show examples. Some examples are partial samples. Some examples
demonstrate a number of statements.
And some topics contain full examples.
When you want to use examples you can best load the examples that come with the
IDE.
By default they are installed in the SAMPLES folder.

The samples from the distribution are checked with each release since they are
intended to be compiled.
So they contain a $regfile directive, and default stack settings. And when print is
used, communication set up.

The samples from the help are only intended to demonstrate a statement or function
and are extremely simple. Often $regfile and stack is omitted.
When you want to use the sample from the help you can copy & paste it.
Do not forget to include $regfile, $hwstack, $swstack and $framesize when it is not
included in the sample. The sample will compile without this info too but for later
reference it is best to include this info.
Some examples from the help are from 1995 and the compiler has been extended.
When you encounter a sample from the help that does not work, send an email to
support so it can be corrected.

© 2021 MCS Electronics


Part

II
Installation 47

2 Installation
2.1 Installation of BASCOM
After you have downloaded the ZIP file you need to UNZIP the file.
On Windows XP, for the DEMO version, you may run the setupdemo.exe file from
within the Zipped file. For the full version you should unzip the ZIP file.

The commercial version comes with a license file in the form of a DLL. This file is
always on the disk where the file SETUP.EXE is located. When explorer does not show
this file, you must set the option in explorer to view system files (because a DLL is a
system file).
For the commercial version the setup file is named SETUP.EXE

Some resellers might distribute the DLL file in a zipped file. Or the file might have the
extension of a number like "123". In this case you must rename the extension to DLL.

Make sure the DLL is in the same directory as the SETUP.EXE file.

When you are using the DEMO version you don't need to worry about the license file.

When you are installing on a NT machine like NT4 , W2000, XP, Vista, Win7, Win8 or
Win10, you need to have Administrator rights.
After installing BASCOM you must reboot the computer before you run
BASCOM.

The installation example will describe how the FULL version installs. This is almost
identical to the installation of the DEMO version.

Before installing the software : make sure you downloaded from mcselec.com
domain. Or that you purchased from an authorized reseller.
When in doubt you can always check the executable on your PC using your browser at
virustotal.com. In fact it is good practice to check files before you install them.
virustotal.com will use 50 or more virus scanners.
This will give a good idea about the safety of a file.

Run the SETUPDEMO.EXE (or SETUP.EXE) by double clicking on it in explorer.

Depending on the windows version and your user rights, windows might give the
following message :

© 2021 MCS Electronics


48 BASCOM-AVR

You need to click the YES button.

The following window will appear:

(screen shots may differ a bit)

Click on the Next button to continue installation.

© 2021 MCS Electronics


Installation 49

The following license info window will appear:

Read the instructions , select 'I accept the agreement' and press the Next button.

The following window will be shown :

Read the additional information and click the Next button to continue.

© 2021 MCS Electronics


50 BASCOM-AVR

Now the next screen will appear:

You can select the drive and path where you like BASCOM to be installed. You can
also accept the default value which is :
C:\MCS\BASCAVR2082
or you can install into a folder like :
C:\Program Files\MCS Electronics\BASCOM-AVR

Microsoft likes software to be installed into the Program Files folder. But this also
means that all sub folders must be stored elsewhere since all folders under Program
Files are write protected by Windows.
Using a user writable folder, all the files can be stored in one location.
It is a good idea to install each new version into its own folder. This way, you can use
multiple versions at the same time. As of version 2082, the settings file is stored in
the application folder too.

When you are finished click the Next Button to continue.


When the directory exists, because you install a newer version, you will get a warning
:

In case of this warning, select Yes. Or select NO and select a different folder.

You will now see the following window:

© 2021 MCS Electronics


Installation 51

You can select the folder where the sample files are installed. This can be :
c:\users<USER>Documents\samples
or c:\MCS\BASCAVR2082\Samples

We recommend to use the second option so all files are placed under the application
folder.
After you made your choice, click the Next button.

You are now presented with an optional component : parallel printer programming
support.
Nowadays there are plenty serial and USB programmers available. Only select this
option when you still use the LPT port for ISP programming.

© 2021 MCS Electronics


52 BASCOM-AVR

Click the Next button to continue.

You will now be presented a choice for the program group name and location.

You can choose to create into a new Program Group named 'BASCOM-AVR' , or you
can modify the name, or install into an existing Program Group. Press the Next-
button after you have made your choice.

© 2021 MCS Electronics


Installation 53

Now the files will be installed.

After the main files are installed, some additional files will be installed. This depends
on the distribution.

These additional files can be PDF files when the program is distributed on a CD-ROM.

© 2021 MCS Electronics


54 BASCOM-AVR

When the installation is ready you will see the last screen :

You have to reboot your computer when you want to make advantage of the
programmers that BASCOM supports. You can also do this at a later stage.

The BASCOM-AVR Program folder is created:

You can view the "Read me" and "License" files content and you can start BASCOM-
AVR.
BASCOM supports both HTML Help and old Win help(HLP). The HLP file is not
distributed in the setup. You need to use the Update Wiz to download it. But it is
advised to use the HTML-Help file.

© 2021 MCS Electronics


Installation 55

When you used to use the HLP file, and find it missing now, turn on 'Use HTML Help'
in Options, Environment, IDE. 142

When the UpdateWiz is not installed, you can download it from the register 55 .
The option Help, Update 214 will also download the wiz.

Till version 2074 all sample files were placed under the MCS Electronics\BASCOM-AVR
folder.
Version 2075 places the sample files under the user Documents\MCS
Electronics\BASCOM-AVR\Samples folder.
While we prefer to keep all files at one location and sub folders, this is not allowed in
Windows 7 where the Program Files folder and all it's sub folders are write
protected.
In version 2082 you can decide where the samples must be installed

The BASCOM-AVR application contains a number of folders.


\DAT : processor data files. These files contain processor info. When you
use $REGFILE, the value should match with one of the files.
\LIB : library files. They have the extension LIB or LBX. LBX is a compiled LIB file. A
library files contains ASM sub routines.
\INC : include files. Notice that these server only the compiler. Do not change or
store include files here. Normal include files are stored along with the samples.
\PDF : PDF files with the bascom-avr manual and processor files from microchip/
atmel.
\PINOUT : processor pinout and XML description files
\SAMPLES : this depends on the user choice during installation

2.2 Updates
The update process is simple if you follow all steps.
· Go to the main MCS website at https://www.mcselec.com
· In the left pane under 'Main Menu' you will find a link named 'Registration/Updates'
· Optional you can enter the address yourself : https://register.mcselec.com

© 2021 MCS Electronics


56 BASCOM-AVR

Notice that the website uses two different accounts : one for the forum/shop and
one for the registration/updates. You will see the following screen:

· When you don't have an account yet, Click the link and select 'Create new account'

© 2021 MCS Electronics


Installation 57

You need to provide a username, password, email and full name. Company name is
optional.
When you filled in the information, click 'Submit Registration'.

· After you click submit, you can get various error messages. For example that a
username already exists. Press the Back-button in your browser, and correct the
problem, then try again
· If the registration is successful you will get a message that the registration
succeeded.
· Watch your mail : you will receive an email with a confirmation link. You need to
click this link in order to finalize your account
· Now you can login. You will see the following or similar screen :

· You need to chose 'Product registration'.


· The following screen will be shown:

© 2021 MCS Electronics


58 BASCOM-AVR

· Select a product from the list.


· Enter the serial number

It is important that you enter a valid serial number. Do not try to enter serial
numbers from cracked versions. When you enter invalid serial numbers, you will loose
support and the ability to update. We will also ban your IP number from our web. The
valid serial number is shown in the Help, About box.

When the product is selected, the serial number is entered and you press 'Register
product' you will see the following message :

© 2021 MCS Electronics


Installation 59

· This does mean that you registered successfully.


· MCS Electronics will validate all registrations once in a while. When the product is
validated you will receive an email. After you receive the email, you can login to the
register again.
· Note that you need to register within 2 years after purchase. Only the original buyer
can register and is qualified to get updates and support.
· Once registered you will see the following or similar screen :

At the top you can see which products are registered, and which status they have.
When you want to do a FULL SETUP, you need to download the full version.
You do not need to uninstall a previous version. You can install an update into the
same directory or a new directory.
When you uninstall a previous version, it will remove the license file which is not part
of the setup.exe

So in the event that you do run uninstall first, make a backup of the license dll
named bscavrL.DLL

© 2021 MCS Electronics


60 BASCOM-AVR

For BASCOM, the ZIP file you download contains only one setup.exe. You need to run
this executable.
It is also important that you put the license DLL into the same directory as setup.exe
Setup will copy this file to the BASCOM application directory. You can also manual
copy this file.
The license file is on CD-ROM, diskette, or the media (email) you received it on. It is
only supplied once.
Without the file, BASCOM will not run.

The file is named bscavrL.DLL for BASCOM-AVR


When you got the license by email, it was zipped and probably had a different
extension. Consult the original installation instructions.
The file is only provided once, we can not, and do not provide it again.

Add on products can contain multiple files like lib, bas, pdf, etc.

Please note that LIC files are license files for the Update Wiz, but they are not the
BASCOM main licence file.

See Installing BASCOM 47 on how to do a full install.

IMPORTANT

As of version 2080, the Update Wiz is phased out. This means that you need to
download and install the full setup.exe
The BASCOM-IDE has a new simplified update method. See also Help, UPDATE 214

2.3 Move to new PC


When you want to move BASCOM to a new PC. You have a number of options.

1 - Run the installer with admin rights from CD-ROM on your new PC. The setup will
copy the license file automatically.
2 - Download the latest version of the setup.exe from https://register.mcselec.com ,
extract the setup.exe , and run setup.exe with admin rights

For the register link above, you need access(an account). This account is not the
same as for the shop/forum.
You need to create an account if you don't have one.
This procedure is explained in the help topic 'Updates 55 '

Then, after the installation, copy the license file bscavrL.DLL to the bascom-avr
application directory of the new PC.
Or let setup.exe do this for you. When you put the license file in the same directory
as setup.exe, setup will copy/install the file for you.

In general it is always better to install the latest version.

© 2021 MCS Electronics


Installation 61

2.4 Installation on multiple computers


The following applies to the licensed version and the license key.

You may install BASCOM on multiple computers. For example on your laptop and your
desk PC. There is no limit to the number of PC's you install the software. But you may
only use one PC at the same time. Since you can only operate one PC at the same
time, this is not a real restriction.
When you install on multiple PC's and others work on these PC's at the same time as
you, you need multiple licenses!

We do not want to bother customers with anti piracy dongle and internet controlled
licenses.

2.5 Registration
The software must be registered in order to get updates. This is explained in the
Updates 55 topic.

We want to emphasize that it is important that you register soon as possible, at least
within 1 year after purchase.
When you do not register timely, the license will not be approved. This means that
you can no longer update the software.
Of course the software keeps working as is. It does not depend on the registration.
But when you need support, we check if you use an actual version.

© 2021 MCS Electronics


Part

III
BASCOM IDE 63

3 BASCOM IDE
3.1 Running BASCOM-AVR
After you have installed BASCOM, you will find a program entry under MCS
Electronics\BASCOM-AVR

Double-click the BASCOM-AVR icon to run BASCOM.

The following window will appear. (If this is your first run, the edit window will be
empty.)

The most-recently opened file will be loaded automatically. Like most Windows
programs, there is a menu and a toolbar. The toolbar can be customized. To do this,
place the mouse cursor right beside the 'Help' menu.
Then right-click. You can turn on/off the toolbars or you can choose 'Customize'.

This will show the following window:

© 2021 MCS Electronics


64 BASCOM-AVR

You have the option to create new Toolbars or the reset the toolbars to the default.
To place a new button on a menu bar, select the 'Commands' TAB.

In the example above, the Program Category has been selected and at the right pane,
all buttons that belong to the Program-category are shown.
You can now select a button and drag & drop it to the Toolbar. To remove a button
from the Toolbar, you drag it out of the Toolbar and release the left mouse button.

On the Options-TAB you can further customize the Toolbar:

© 2021 MCS Electronics


BASCOM IDE 65

To preserve screen space there are no large icons available.


Option Description
Menus show recent used With this option the IDE will learn the menu options
commands first you use. It will show only the most used menu
options. The idea is that you can find your option
quicker this way.
Show full menus after a short This option will show the remaining menu options
delay after short delay so you do not need to click another
menu option to show all menu options.
Reset my usage data This option will reset the data the IDE has collected
about your menu choices.
Show Tool tips on toolbars This option is on by default and it will show a tool
tip when you hold the mouse cursor above a toolbar
button
Show shortcut keys in Tool tips This option is on by default and it will show the
shortcut in the tool tip. For example CTRL+C for the
Copy button.

The Editor
The editor supports syntax highlighting. Code you enter can be reformatted
automatically.
When you press CTRL+J you can select a template. A template is a small piece of
code that can be inserted automatically.
When you press CTRL+J you can select a template or you can type the template
name and press CTRL+J. If there is only one template starting with that name, the
template will be inserted. Otherwise the options are shown.

© 2021 MCS Electronics


66 BASCOM-AVR

Templates are stored in the file bascavr.tpl

When you press SHIFT and move the mouse cursor over a variable, constant or other
element you will get a tool tip with info.

In the sample above the variable 's' was selected and the tool tip shows that it is a
string with a length of 16 bytes in the modules crc8-16-32.bas

Intellisense
The editor has built in intellisense.
It is important that your code contains the $REGFILE directive like : $REGFILE =
"M88def.dat".
When you press CTRL+SPACE you get a list of statements, sub routines, functions,
labels, asm registers, etc. This list depends on the place of the cursor in the code.

- At the start of a line you will get a list like : .


You can select a value from the list and press enter to insert it into the code.

- When you type a letter of some letters like pr


Here you can see the position is set to the first item that starts with PR : PRINT

- After PRINT when a variable is expected : Here


you get functions, variables and constants

© 2021 MCS Electronics


BASCOM IDE 67

- After CONFIG Here you get a list of all CONFIG statements.

- After CONFIG param (the = sign). Here you get a lost of parameter
values.

- After GOTO, GOSUB Here you get a list with labels.

- After CALL Here you get a lost with sub routines.

- Inside $ASM-$END ASM Here you get a list of ASM mnemonics.

- After ASM mnemonic Here you get a list of registers.

© 2021 MCS Electronics


68 BASCOM-AVR

PLEASE NOTICE :
- intellisense is considered a beta function in 2079. It is subject to change.
- values for CONFIG might not be shown. This is because all these values need to be
present in the DAT files. And each processor has specific options.

Select Text
Selection of text can be done by double clicking the text, by holding SHIFT down and
moving the cursor or you can select a block of text by pressing the ALT key and
dragging the mouse cursor.

TABS
When you have loaded multiple files, each file will be shown in a TAB. The active TAB
can be closed or dragged to a new position. When a file is modified the TAB caption
will be shown in red.

SHIFT + MOUSE
When you move the mouse cursor to the TAB caption you will see the full path of the
loaded file.

When you press the SHIFT key and move the mouse cursor you can get information in
a tool tip.
For example when you hover over an indention line :

© 2021 MCS Electronics


BASCOM IDE 69

The tooltip shows info about the structure. So you know that the green line belongs
to While Unseen > 0

When we hover over a code element like CH :

This time since CH is a variable. the data type is shown.

In 2084 String constants will be shown with their length.

The Reference window will list all referenced variables :

When you click an item, the cursor will be changed automatically.

Custom Configuration
You can load a custom configuration file by specifying the filename as a parameter.
This allows you to run different versions of the software with different setting/option
files.
The configuration file has the XML extension. It can be found by clicking the XML data
folder link in the Help, About window.
By default bascom uses the file : \Users\<USER>\AppData\Roaming\MCS
Electronics\bascom-avrXXXX.xml
The XXXX is the version. For example 2082.

When you want to use a custom file we would recommend to store it in the bascom-
avr application folder. This way you can run multiple versions of bascom, all with their
own settings.

The name of the settings file must be provided as a parameter to BasCom. For
example to use a settings file named mysettings.xml :
bascavr.exe mysettings.xml

When BasCom is started it will check if the provided file exists and will load the
settings of that file.
If the files does not exist, the normal setting file ise used.

The reason for unique file names is that once in a while a menu option is added. That
is no problem when you update, but when you want to use the xml with an older file
you could get errors because of non existing menus.

© 2021 MCS Electronics


70 BASCOM-AVR

3.2 File New


This option creates a new window in which you will write your program.
The focus is set to the new window.
You can have multiple windows open at the same time.
Only one window can have the focus. When you execute other functions such as
Simulate 103 or Program Chip 116 , BASCOM will use the files that belong to the current
active program. This is in most cases the program which has the focus.

File new shortcut: , CTRL + N

3.3 File Open


With this option you can load an existing program from disk.

BASCOM saves files in standard ASCII format. Therefore, if you want to load a file
that was made with another editor be sure that it is saved as an ASCII file. Most
programs allow you to export the file as a DOS or ASCII file.

Note that you can specify that BASCOM must reformat the file when it opens it with
the Options Environment 142 option. This should only be necessary when loading files
made with another editor.

File open shortcut : , CTRL+O

3.4 File Close


Close the current program.

The current editor window will be closed. When you have made changes to the
program, you will be asked to save the program first. You can then decide to save,
cancel, or not to save the changes you have made.

File close shortcut :

3.5 File Save


With this option, you save your current program to disk under the same file name.
The file name is visible in the Windows caption of the edit window.

If the program was created with the File New 70 option, you will be asked to name
the file first. Use the File Save As 71 option to give the file another name.

Note that the file is saved as an ASCII file.

© 2021 MCS Electronics


BASCOM IDE 71

File save shortcut : , CTRL+S

3.6 File Save As


With this option, you can save your current program to disk under a different file
name.
When you want to make some changes to your program, but you do not want to
make changes to the current version you can use the "Save As" option. It will leave
your program as it was saved, and will create a new file with a new name so you end
up with two copies. You then make changes to the new created file.

Note that the file is saved as an ASCII file.

File save as shortcut :

3.7 File Print Preview


With this option, you can preview the current program before it is printed.
Note that the current program is the program that has the focus.

File print preview shortcut :

3.8 File Print


With this option, you can print the current program.
Note that the current program is the program that has the focus.

File print shortcut : , CTRL+P

3.9 File Project


Originally the IDE was not designed to support projects. Each file you open is a
project.
Most chips were not even suited for big projects.
Some projects use a lot of include files. It is a good idea to break up your code in
modular tested modules.
You can simply include the modules with $include 559 .

In order to make working with a project more convenient, a number of Project options
have been added. The Project menu can be found under the File menu. The Project
menu has 4 sub menu items and a MRU list(most recent used projects).
When in project mode, the main project file will be compiled. In normal mode, the
active window is considered the project and will be compiled. The same is true for the
simulator and programmer.

A simple project explorer has been added that will list all project files. The active
project will be shown in blue. The relative path is shown.

© 2021 MCS Electronics


72 BASCOM-AVR

You can add a new file to the active project. By default the INC extension will be
selected. It will be good practice to give included files the INC extension. The main
project should have the BAS extension. When you click the ADD button, a file
selection dialog will appear. You can select multiple files by using the SHIFT and/or
CTRL keys.

When you add a file to a project, it will be added to the project list. When you double
click the file in the list it will be selected. Or when it was not loaded before, it will be
loaded from disk.
That a file is part of a project collection does not mean that the file will be used or
included : you still need to $INCLUDE 559 a file that you want to use in your project.

You can also remove a file from the project. This will not remove or delete the file
from disk. The file will only be removed from the project collection.

Only one file can be the main project. This is the file that will be compiled. The main
file is colored in blue.

When you updated from a previous version, you need to reset the docking in
order to make the Project List window visible. This option you can find under Options,
Environment, IDE 142

Project New
This option will close all files and the current project and will query for a project file
name. The file will have the PRJ extension.

© 2021 MCS Electronics


BASCOM IDE 73

Project Open
This option will close all open files and let you select an existing project file. A project
file has the PRJ extension.
The PRJ file contains no code, it only contains data about the project files.
All files from the project will be loaded when they were loaded when you closed the
project.
The position and size will be set exactly as when you closed.

Project Save
This option will save all project files. It will also save other opened non-project files.

Project Close
This option will close the active project. This will end the project mode. The project
mode is started when you open a PRJ file either with OPEN or by clicking a PRJ file
from the MRU menu.

When you close bascom and you have the Option 'Auto Load All Files' checked, then
like usual, all open files will be saved and when you run bascom again, they will all be
opened. This might be confusing since you work in normal mode by default. It is
recommended to deactivate the 'Auto Load All Files' when working with projects.

In project mode, you can also drag and drop files to the IDE. If they have the BAS or
INC extension, they will be added to the project. In normal mode, the file will be
opened.

© 2021 MCS Electronics


74 BASCOM-AVR

3.10 File ZIP


This option will put all project files into a ZIP file.
The file will be given the ZIP extension and is saved into the same folder as the main
file.
When your file is named main.bas, the file main.zip will be created.

The following files will be included :


- all files which are included with $INCLUDE
- all files which are included with $INC
- all files which are included with $BGF

If a file is included in the code but can not be found you will get a warning.

This option does take conditional compilation into account.


Meaning that :

#const a=1
#if a=2
$Include "FT800.inc"
$Include "FT800_Functions.inc"
#endif

The files ft800.inc and ft800_functions.inc are not included since the condition does
not match.

© 2021 MCS Electronics


BASCOM IDE 75

3.11 File Exit


With this option, you can leave BASCOM.
If you have made changes to your program, you can save them upon leaving
BASCOM.

All of the files you have open, at the moment you choose exit, will be remembered.
The next time you run BASCOM, they will be opened automatically.

File exit shortcut :

3.12 Edit Undo


With this option, you can undo the last text manipulation.

Edit Undo shortcut : , CTRL+Z

3.13 Edit Redo


With this option, you can redo the last undo.

Edit Redo shortcut : , CTRL+SHIFT+Z

3.14 Edit Cut


With this option, you can cut selected text into the clipboard.

Edit cut shortcut : , CTRL+X

3.15 Edit Copy


With this option, you can copy selected text into the clipboard.

Edit copy shortcut : , CTRL+C

3.16 Edit Paste


With this option, you can paste text from the clipboard starting at the current cursor
position.

Edit paste shortcut : , CTRL+V

3.17 Edit Find


With this option, you can search for text in your program.
Text at the current cursor position will automatically be placed in the find dialog box.
All text you search for is saved so the next time you search, you can retrieve the
search phrase from a list.
To clear the history, right click the mouse above the 'Text to Find' label and select
'Clear History' from the popup menu.

© 2021 MCS Electronics


76 BASCOM-AVR

The following options available:

Option Description
Case Sensitive When selected, the case must match. Searching for PRINT will not
find pRint. With this option turned off, Print will find print, PRINT,
PRinT, etc.
Whole words only When selected, only whole words are considered. A whole word is
a word that is surrounded by spaces, or that is at the start of a
line. Looking for PRINT will find : "Print test" and "print" and
"print print". But not "printer"
Regular You can use a regular expression to find a match.
expressions
^ A circumflex at the start of the string matches the start of
a line.
$ A dollar sign at the end of the expression matches the end
of a line.
. A period matches any character.
* An asterisk after a string matches any number of
occurrences of that string followed by any characters, including
zero characters. For example, bo* matches bot, bo and boo but
not b.
+ A plus sign after a string matches any number of
occurrences of that string followed by any characters except zero
characters. For example, bo+ matches boo, and booo, but not bo
or be.

[] Characters in brackets match any one character that


appears in the brackets, but no others. For example [bot]
matches b, o, or t.
[^] A circumflex at the start of the string in brackets means
NOT. Hence, [^bot] matches any characters except b, o, or t.
[-] A hyphen within the brackets signifies a range of

© 2021 MCS Electronics


BASCOM IDE 77

characters. For example, [b-o] matches any character from b


through o.

\ A backslash before a wildcard character tells the Code


editor to treat that character literally, not as a wildcard. For
example, \^ matches ^ and does not look for the start of a line.
Forward This is the search direction. By default it will search forward.
Specifies the size of the software stack.
Backward This is the search direction. You can use backwards in case you
pressed F3 too many times and want to go back to the previous
found text.
Global All the text of the current editor will be searched.
Selected text Only the selected text will be searched.
From cursor Search from the current cursor position to the end of the code.

Entire scope Search from the current cursor position to the end, then search
till the start of the cursor position. This will search the entire text.

Find in Files
The Find in Files option can be used to search for text in files.

Option Description
Case Sensitive When selected, the case must match. Searching for PRINT will not
find pRint. With this option turned off, Print will find print, PRINT,
PRinT, etc.
Whole words When selected, only whole words are considered. A whole word is a
only word that is surrounded by spaces, or that is at the start of a line.
Looking for PRINT will find : "Print test" and "print" and "print

© 2021 MCS Electronics


78 BASCOM-AVR

print". But not "printer"


Regular You can use a regular expression to find a match.
expressions
^ A circumflex at the start of the string matches the start of a
line.
$ A dollar sign at the end of the expression matches the end
of a line.
. A period matches any character.
* An asterisk after a string matches any number of
occurrences of that string followed by any characters, including
zero characters. For example, bo* matches bot, bo and boo but not
b.
+ A plus sign after a string matches any number of
occurrences of that string followed by any characters except zero
characters. For example, bo+ matches boo, and booo, but not bo
or be.

[] Characters in brackets match any one character that


appears in the brackets, but no others. For example [bot] matches
b, o, or t.
[^] A circumflex at the start of the string in brackets means
NOT. Hence, [^bot] matches any characters except b, o, or t.
[-] A hyphen within the brackets signifies a range of
characters. For example, [b-o] matches any character from b
through o.

\ A backslash before a wildcard character tells the Code editor


to treat that character literally, not as a wildcard. For example, \^
matches ^ and does not look for the start of a line.
Search all This option will search through all project files. Files considered are
project files $INCLUDE files. Nested $include files are not considered.
Search all open This option will search though all open files. This are loaded files
files visible in the TABS
Search in You can specify a custom folder to search for the text.
directories
Search in This option will restrict the search to the current file.
current file

Edit Find shortcut : , CTRL+F

3.18 Edit Find Next


With this option, you can search again for the last specified search item.
Edit Find Next shortcut : , F3

3.19 Edit Replace


With this option, you can replace selected text in your program.

Edit Replace shortcut : , CTRL+R

© 2021 MCS Electronics


BASCOM IDE 79

3.20 Edit Goto


With this option, you can immediately go to a specified line number.

Edit go to line shortcut : ,CTRL+G

3.21 Edit Toggle Bookmark


With this option, you can set/reset a bookmark, so you can jump in your code with
the Edit Go to Bookmark option. Shortcut : CTRL+K + x where x can be 1-8

Bookmarks are stored in a file named <project>.BM

3.22 Edit Goto Bookmark


With this option, you can jump to a bookmark.

There can be up to 8 bookmarks. Shortcut : CTRL+Q+ x where x can be 1-8

Bookmarks are stored in a file named <project>.BM

3.23 Edit Indent Block


With this option, you can indent a selected block of text.

Edit Indent Block shortcut : , CTRL+SHIFT+I

3.24 Edit Unindent Block


With this option, you can unindent a block.

Edit Unindent Block shortcut : , CTRL+SHIFT+U

3.25 Edit Remark Block


With this option, you can Remark or Unremark a selected block of text.
While you can use '( and ') to remark a block of code, you might prefer the old BASIC
way using just one ' .
When a remark is found, it will be removed. When there is no remark, it will insert a
remark.

© 2021 MCS Electronics


80 BASCOM-AVR

3.26 Edit Insert ASCII


This option will show a pop up window from which you can select an ASCII character.

In BASCOM you can embed ASCII characters by using brackets embedded with the
ASCII code like : {065}
For example : Dim S As String : S="AB{067}"
This is the same as S="AAA"

The pop up lists shows all ASCII values and when you click the OK-button, the
brackets are added.

3.27 Edit Fold All Subs and Functions


When Code folding is enabled in Options, Environment, IDE, Editor 142 , this options
will fold/collapse all sub procedures and functions.
Other structures that can be folded with F11 remain unaltered.
Using SHIFT+F11 or CTRL+ENTER, you can fold/unfold the current block.

Consider this example :

© 2021 MCS Electronics


BASCOM IDE 81

Both the Sub and For/Next can be folded but the Fold All Subs and Functions option,
will only fold the sub :

See Also
Edit Unfold All Code 81

3.28 Edit Unfold All Code


This option will unfold all folded code so all code becomes visible.

See Also
Edit Fold All Subs and Functions 80

3.29 Edit Encrypt Selected Code


This add on option allows you to encrypt portions of your code.

Because the encryption can not be undone, you will get this warning:

If you chose YES, the selected code will be encrypted and will result in lines like :

$CRYPT 6288E522B4A1429A6F16D639BFB7405B
$CRYPT 7ABCF89E7F817EB166E03AFF2EB64C4B
$CRYPT 645C88E996A87BF94D34726AA1B1BCCC

© 2021 MCS Electronics


82 BASCOM-AVR

$CRYPT 9405555D91FA3B51DEEC4C2186F09ED1
$CRYPT 6D4790DA2ADFF09DE0DA97C594C1B074

Only the compiler can decrypt and process these lines. There is no way you can
change the $CRYPT lines back into source code !
So make a backup of your code before you use this option. Typically, it will only be
used on finished projects.
If the encrypted code contains errors, you will get error messages pointing to the
$CRYPT 529 lines.

This option is not available/enabled by default. You need to buy a license that
will unlock this option. Our sales requires your BASCOM serial number too.

3.30 Edit Proper Indent


This option will properly indent your code.

Indention is used to make code better readable.


Every structure will be indented. And nested will increase indenting.

This code :

For C = 0 To 100
B = A(c)
Print "Read " ; C ; ":" ; B ; "/" ; Hex(b)
Waitms 4
Next

Will be transformed into :

For C = 0 To 100
B = A(c)
Print "Read " ; C ; ":" ; B ; "/" ; Hex(b)
Waitms 4
Next

And this is a sample with nesting :

Do
Input "Data to write ? (0-255)" , D

Print "Reading content of EEPROM (via ERAM Byte)"


For C = 0 To 100
B = A(c)
Print "Read " ; C ; ":" ; B ; "/" ; Hex(b)
Waitms 4
Next
Loop

© 2021 MCS Electronics


BASCOM IDE 83

When indenting does not work you need to check your code for mistakes. For
example for endif instead of End If.

Proper indenting is also required for proper drawing of indention 83 .

3.31 Edit Show Excluded Code


This option turns on/off marking of excluded code.
Excluded code is code that is not compiled as part of the project because conditional
compilation parameters exclude the code.
Excluded code is shown in Italic and gray but you can change the default colors.

For example when using an XMEGA processor, the _XMEGA constant will be set to 1.
When the option is turned off, it will show normal like :

#if _xmega
print "XMEGA"
#else
print "NORMAL"
#endif

When then option is turned on, the editor will show it like :

#if _xmega
print "XMEGA"
#else
print "NORMAL"
#endif

When you have a lot of conditional code it is hard to see which code is executed.
When you turn the option on, it is much easier to see.
Check out this example:

© 2021 MCS Electronics


84 BASCOM-AVR

In order for this option to work correct, your code should not contain syntax errors.

See Also
#IF, #ELSEIF . #ELSE 509 , Show Dead Code 84

3.32 Edit Show Dead Code


This option turns on/off marking of 'dead' code.
Dead code is code that does not do a thing and could be removed.
Dead code is shown in Italic and gray.

© 2021 MCS Electronics


BASCOM IDE 85

Dead code is similar to Excluded code with the difference that excluded code is not
compiled while dead code is compiled.

Dead code is a new feature in 2080 and intended to show you which variables or code
are not used.
You can decide if the code is really dead, and need to be removed, or not.

Since this is a new feature, you should take care before deleting 'dead code'

The example above demonstrates a few dead code elements:


- the local dead as byte, is not used in the code
- the function result is assigned twice without that the result is used, this does not
make sense
- the GOTO skips over some code which is never used (print)

See Also
Edit Show Excluded Code 83

© 2021 MCS Electronics


86 BASCOM-AVR

3.33 View PinOut


The Pin Out viewer is a dock able window that shows the case of the active chip.
The active chip is determined by the value of $REGFILE 598 .

When you move the mouse cursor over a pin, you will see that the pin will be colored
red. At the bottom of the window, a pin description is show. In the sample above you
will see that each line has a different color. This means that the pin has multiple
alternative functions.
The first blue colored function is as generic IO pin.
The second green colored function is RESET pin.
The third black colored function is PIN change interrupt.

A pin can have one or more functions. Some functions can be used together.
When you move the mouse cursor away, the pin will be colored blue to indicate that
you viewed this pin. For example, when you need to look at it again.

You can also search for a pin description. Enter some text and return.
Here is an example when you search the VCC pin :

© 2021 MCS Electronics


BASCOM IDE 87

When pins are found that have the search phrase in the description, the pin will be
colored blue.
By clicking 'Clear Pin HL' you can clear all colored pins.

Some chips might have multiple cases. You can select the case from the package list.

© 2021 MCS Electronics


88 BASCOM-AVR

When you change from package, all pin colors will be cleared.
When you double click a pin, the pin will be colored green. Another double click will
color it red/blue.
When a pin is green, it will not be colored red/blue. The green color serves as a kind
of bookmark.
The only exception is the search function. It will make bookmarked green pins, blue
too.

Use the right mouse to access a popup menu. This menu allows you to zoom the
image to a bigger or smaller size.

Double click the chip to show the chip data.

© 2021 MCS Electronics


BASCOM IDE 89

When you want to search for a chip, click the 'Chip Search' button.
It will show the following window:

You can provide criteria such as 2 UARTS. All criteria are OR-ed together. This means
that when one of the criteria is met, the chip will be included in the list.

© 2021 MCS Electronics


90 BASCOM-AVR

Only chips supported by BASCOM will be listed. When a chip has SRAM, and is
not supported yet, it will be in the near future since the goal is to support all chips.

When you find an error in the pin description, please send an email to support so it
can be corrected.

3.34 View PDF viewer


The PDF viewer is dock able panel which is located by default on the right side of the
IDE.

The viewer itself contains a tree with the topics and the actual PDF viewer.
The tree topics can be searched by right clicking on the tree. Choose 'Search' and
enter a search text.
When a topic has sub topics, the topic is bold.

When you have enabled 'Auto open Processor PDF' in Options, Environment, PDF, the
data sheet will be automatically loaded when you change the $REGFILE value.
It can be shown in a new sheet or it can replace the current PDF.

Open a PDF.
Copy selected text to the clipboard. You can not copy from protected PDF
documents.
First page.

© 2021 MCS Electronics


BASCOM IDE 91

Previous page.
Current page indicator. You can enter a page number to jump to a different
page.
Next page.
Last page.
Find text in PDF.

Zoom in.
Zoom out.
Rotate page to the left and right.

Print page(s).

When you right click in the PDF, a pop up menu with the most common options will
appear.
In Options, Environment, PDF 142 you can specify how data sheets must be
downloaded.

Data sheets can be downloaded automatic. When the $REGFILE is changed and the
PDF is not present, you will be asked if the PDF must be downloaded.
If you choose to download, it will be downloaded from the Atmel website.

When you click 'Do not show this message again' , you will not be asked anymore if
you want to download the Mega32.PDF. You will be asked to download other PDF
documents when they do not exist.

During the download you will see a similar window:

You can also download all newer PDF's from the Atmel website with the option :
Tools, PDF Update 130

© 2021 MCS Electronics


92 BASCOM-AVR

When PDF's are downloaded with the UpdateWiz, they are downloaded from the MCS
Electronics website.

3.35 View Error Panel


This option will show the Error panel.

When there are no errors, the list will be empty. You will also be able to close the
window.
When there are errors :

You will not be able to close the window until the error is solved and the program is
checked/compiled.
The panel is dockable and by default docked to the bottom of the IDE.

When you right click the mouse inside the error panel, a menu will popup with one
option : Copy to Clipboard. All data from the error window will be copied to the
windows clipboard if you select this option.

3.36 View Tip


Action
Shows the Tip of the day Window

© 2021 MCS Electronics


BASCOM IDE 93

You can click the Next-button to show another tip. Or you can close the window.
When you do not want to see the tips when BASCOM is started, you can unselect the
'Show tips at startup' option.

You can submit your own tips at the register : http://register.mcselec.com

3.37 View Project Files


Action
Shows the Project Explore Window.

The project explorer window is intended to be used in project mode. Project mode is a
mode where all files belong to one project. Here you have a main file and optional
include files.
The project explorer is a dock able window. It lists all files assigned to the project.
When you double click a file, it will be opened in the editor.
- Use the ADD button to add files to the project
- Use the REMOVE button to remove files from the project. Files you remove are only
removed from the project, they are not removed from disk
- Use SET MAIN to set the main project file. The main project file is the file that is
compiled.

3.38 View Code Explorer


Action
Shows the Code Explorer Window

© 2021 MCS Electronics


94 BASCOM-AVR

The code explorer shows code elements in a tree. By double clicking an element the
cursor will be set to the matching code in the editor.
You can also drag an element into the editor window.
By clicking the right mouse a pop up menu will allow you to filter out constants and
variables (registers) from the definition file.

The following code elements will be shown in the explorer:


- Aliases. These are the user ALIAS 639 es.
- Assembler. This is for single line asm using !
- Assembler Block. This is for assembler blocks using $asm .. $end asm. If you add
comment after $asm, it will be shown in the tree as well. Example : $asm ; Test

© 2021 MCS Electronics


BASCOM IDE 95

- Constants. Both user defined constants (CONST 1045 ) and constants from the
definition file are shown.
- Declarations. Subs and Functions are both shown. Each with their own color.
- Functions. These are the user function implementations.
- Labels. When labels are used in subs and functions, the sub/functions name is listed
first.
- Macros. These are the user macro's created with MACRO 1236 .
- Subs. These are the user sub implementations.
- Variables. These are the variables from the user code and definition file. Each shown
with their own color. Locals are shown under a branch of the sub/function.
- CallStack. This is optional. Since it takes time to trace the call stack it is turned off
by default. Use right mouse click and the pop up menu to activate it.
The call stack shows a tree of the calls you make to user subs and functions. And
each sub/function also shows the user functions it calls.
When multiple calls are made, three dots are added for each additional call.
- Information. Processor, free ERAM and SRAM. Estimated $hwstack, $swstack
and $framesize.

The calculated stack settings are based on the program call tree and local
variables. This is just a tool to give you an idea about stack usage. Not taken into
account is the stack required by the assembler routines. This means that you need to
add a certain amount to the calculated values. When your code uses interrupts you
need to increase the calculated $HWSTACK by 32. Otherwise increase it by 16.
The $FRAMESIZE should have a minimum value of 24. Add a value of 16
to $SWSTACK.
Applications using AVR-DOS should use a minimum of 128 for all stacks.
A future version will also take the assembler code into account.

When the Code Explorer has the focus, pressing CTRL+F will search in the code
explorer and not in the editor.

The code explorer works in a separate thread. It will be updated a few seconds after
you have quit typing.
By making the Code Explorer window invisible, the explorer is deactivated.

The popup menu has the following options:

Show Register Constants


This option can toggle between showing and hiding the register constants. When
register constants are shown the tree can become big.
User constants and register constants are shown in a different color.

© 2021 MCS Electronics


96 BASCOM-AVR

Show Register Variables


This option can toggle between showing and hiding the register variables. When
register variables are shown the tree can become big.
User variables and register variables are shown in a different color.

Show Call Stack


This option can show the Call Stack. This reveals the nesting of your code.

Show Errors
This option deserves a warning. The option is turned off by default. It can be useful
to find errors but it can also point to errors which are not considered an error for the
compiler. The compiler has a separate parser. The parser from the IDE is a different
new parser. While in 2080 all DAT files are updated, you still can get errors which are
no real errors. You might want to report them to support. Please send a small as
possible program that will show the error.

Show Unused Items


When this option is turned on, all unused items will be shown in grey. For example :

© 2021 MCS Electronics


BASCOM IDE 97

In this sample, _temp1 , so_rx_data and DataPtr are unused or unreferenced.


_temp1 is an internal variable and so is DataPtr. They do not occupy any space.
But so_rx_data is a user variable which is not referenced. You could remove or
remark it.

Refresh
This option will parse the project and update the code explorer tree.

Find References
This option can find all references for an item. For example when you go to Variables,
and select a variable the option becomes enabled in the menu. After choosing this
option, the references will be added to the tree.

© 2021 MCS Electronics


98 BASCOM-AVR

Now by clicking the item you will go to the point in your code where the item is
referenced/used.

Show References
This options shows a panel on the bottom of the code explorer tree. When you
activate the tooltip keeping SHIFT pressed and hovering an item in the editor, the
references panel will be updated with all references of that item. A single click on an
item in this list will set the cursor in the IDE to referred item.

Consider this simple piece of code :


Dim S As Single
Input "s " , S
Print S

When pressing SHIFT and hovering the mouse over the variable S , the tooltip will be

shown :
The references list will be updated as well. The item in bold points to the definition, in
this case the DIM S.
The following two items in the list point to the INPUT "s ", S and the Print S.

The panel can be shown or hidden using the right click menu from the explorer.

© 2021 MCS Electronics


BASCOM IDE 99

3.39 View Vertical Splitter


You can split the editor window into two parts. By default you use the horizontal
splitter marked with the arrow.

This will create a split screen :

With the option Vertical Splitter, you switch between horizontal en vertical splitter.
The splitter is located near the code explorer window.

This will result in a vertical split window.

© 2021 MCS Electronics


100 BASCOM-AVR

When you chose the vertical splitter option again the window will be split horizontal
again.

Notice that in order to show two different code windows you need to open the two
windows and use Tile Vertically 208 .

3.40 Program Compile


With this option, you compile your current program.

Your program will be saved automatically before being compiled.

The following files will be created depending on the Option Compiler Settings. 135

File Description
xxx.BIN Binary file which can be programmed into the microprocessor.
xxx.DBG Debug file that is needed by the simulator.
xxx.OBJ Object file for simulating using AVR Studio. Also needed by
the internal simulator.
xxx.HEX Intel hexadecimal file, which is needed by some
programmers.
xxx.ERR Error file. Only created when errors are found.
xxx.RPT Report file.
xxx.EEP EEPROM image file

If a serious error occurs, you will receive an error message in a dialog box and the
compilation will end.

All other errors will be displayed at the bottom of the edit window, just above the
status bar.

When you click on the line with the error info, you will jump to the line that contains

© 2021 MCS Electronics


BASCOM IDE 101

the error. The margin will also display the sign.

At the next compilation, the error window will disappear or reappear if there are still
errors.
See also 'Syntax Check' 101 for further explanation of the Error window.

Program compile shortcut: , F7

3.41 Program Syntax Check


With this option, your program is checked for syntax errors. No file will be created
except for an error file, if an error is found.

Program syntax check shortcut , CTRL + F7

When there is an error, an error window will be made visible at the bottom of the
screen.

You can double click the error line to go to the place where the errors is found. Some
errors point to a line zero that does not exist. These errors are caused by references

© 2021 MCS Electronics


102 BASCOM-AVR

to the assembler library and are the result of other errors.


The error window is a dockable window that is docked by default to the bottom of the
screen. You can drag it outside this position or double click the caption(Errors) to
make it undock :

Here the panel is undocked. Like most windows you can close it. But the error must
be resolved (corrected and syntax checked/recompiled) for this window can be
closed !
By double clicking the caption (top space where the name of the window is show) you
can dock it back to it's original position.

When you have closed the window and want to view it again, you can choose the
View, Error Panel option from the main menu.

3.42 Program Show Result


Use this option to view information concerning the result of the compilation.

See the Options Compiler Output 137 for specifying which files will be created.

The files that can be viewed are "report" and "error".

File show result shortcut : ,CTRL+W

Information provided in the report:


Info Description
Report Name of the program
Date and time The compilation date and time.
Compiler The version of the compiler.
Processor The selected target processor.
SRAM Size of microprocessor SRAM (internal RAM).
EEPROM Size of microprocessor EEPROM (internal EEPROM).
ROMSIZE Size of the microprocessor FLASH ROM.
ROMIMAGE Size of the compiled program.
BAUD Selected baud rate.
XTAL Selected XTAL or frequency.
BAUD error The error percentage of the baud rate.
XRAM Size of external RAM if available.
Stack start The location in memory, where the hardware stack points to. The
HW-stack pointer grows downward.
S-Stacksize The size of the software stack.
S-Stackstart The location in memory where the software stack pointer points
to. The software stack pointer grows downward.

© 2021 MCS Electronics


BASCOM IDE 103

Framesize The size of the frame. The frame is used for storing local
variables.
Framestart The location in memory where the frame starts.
LCD address The address that must be placed on the bus to enable the LCD
display E-line.
LCD RS The address that must be placed on the bus to enable the LCD
RS-line
LCD mode The mode the LCD display is used with. 4 bit mode or 8 bit mode.
LCD DB7-DB4 The port pins used for controlling the LCD in pin mode.
LCD E The port pin used to control the LCD enable line.
LCD RS The port pin used to control the LCD RS line.
Variable The variable name and address in memory
Constant Constants name and value

Some internal constants are :

_CHIP : number that identifies the selected chip


_RAMSIZE : size of SRAM
_ERAMSIZE : size of EEPROM
_XTAL : value of crystal
_BUILD : number that identifies the version of the compiler
_COMPILER : number that identifies the platform of the compiler

Warnings This is a list with variables that are dimensioned but not used.
Some of them
EEPROM binary This is a list of all ERAM variables with their value. It is only
image map shown when DATA 1052 lines are used to create the EEP file.
(EEPROM binary image).

When the option : Load Report in IDE, is set, the report will be shown as a text file in
the IDE.

3.43 Program Simulate


With this option, you can simulate your program. So what exactly is simulating? For
BASCOM it means that the generated object code is processed with a virtual AVR
processor.
The simulator can simulate the AVR instructions. It can also simulate the hardware
for a part. The goal of the simulator is to allow you to debug your code. The goal was
not to create 100% virtual AVR hardware.
This means that some hardware is simulated but with different timing.

You can simulate your programs with AVR Studio or any other Simulator available
such as ISIS or you can use the built in Simulator.

The simulator that will be used when you press F2, depends on the selection you
made in the Options Simulator TAB. The default is the built in Simulator.

Program Simulate shortcut : , F2

To use the built in Simulator the files DBG and OBJ must be selected from the Options
Compiler Output 137 TAB.

© 2021 MCS Electronics


104 BASCOM-AVR

The OBJ file is the same file that is used by the AVR Studio simulator.

The DBG file contains info about variables and many other info required to simulate a
program.

The yellow dot means that the line contains executable code. The blue arrow is visible
when you start simulating. It will point to the line that will be executed.

The Simulator window is divided into a few sections:

The Toolbar
The toolbar contains the buttons you can press to start an action.

This is the RUN button, it starts a simulation. You can also press F5. The
simulation will pause when you press the pause button. It is advised, that you step
through your code at the first debug session. When you press F8, you step through
the code line by line which is a clearer way to see what is happening.

This is the PAUSE button. Pressing this button will pause the simulation.

This is the STOP button. Pressing this button will stop the simulation. You can't
continue from this point, because all of the variables are reset. You need to press the
RUN button when you want to simulate your program again.

This is the STEP button. Pressing this button (or F8) will simulate one code line of
your BASIC program. The simulator will go to the RUN state. After the line is

© 2021 MCS Electronics


BASCOM IDE 105

executed the simulator will be in the PAUSE state. If you press F8 again, and it takes
a long time too simulate the code, press F8 again, and the simulator will go to the
pause state.

This is the STEP OVER button or SHIFT+F8). It has the same effect as the STEP
button, but sub programs are executed completely, and the simulator does not step
into the SUB program.

This is the RUN TO button. The simulator will RUN until it gets to the current line.
The line must contain executable code. Move the cursor to the desired line before
pressing the button.

This button will show the processor registers window.

The values are shown in hexadecimal format. To change a value, click the cell in the
VAL column, and type the new value. When you right click the mouse, you can choose
between the Decimal, Hexadecimal and Binary formats.
The register window will show the values by default in black. When a register value
has been changed, the color will change into red. Each time you step through the
code, all changed registers are marked blue. This way, the red colored value indicate
the registers that were changed since you last pressed F8(step code). A register that
has not been changed at all, will remain black.

This is the IO button and will show processor Input and Output registers.

© 2021 MCS Electronics


106 BASCOM-AVR

The IO window works similar as the Register window.


A right click of the mouse will show a popup menu so you can choose the format of
the values.
And the colors also work the same as for the registers : black, value has not been
changed since last step(F8). Red : the value was changed the last time your pressed
F8. Blue : the value was changed since the begin of simulation. When you press the
STOP-button, all colors will be reset to black.

Pressing this button shows the Memory window.

The values can be changed the same way as in the Register window.
When you move from cell to cell you can view in the status bar which variable is
stored at that address.
The SRAM TAB will show internal memory and XRAM memory.
The EEPROM TAB will show the memory content of the EEPROM.
The colors work exactly the same as for the register and IO windows. Since internal
ram is cleared by the compiler at startup, you will see all values will be colored blue.
You can clear the colors by right clicking the mouse and choosing 'Clear Colors'.

The refresh variables button will refresh all variables during a run (F5). When
you use the hardware simulator, the LEDS will only update their state when you have

© 2021 MCS Electronics


BASCOM IDE 107

enabled this option. Note that using this option will slow down simulation. That is why
it is an option. When you use F8 to step through your code you do not need to turn
this option on as the variables are refreshed after each step.

When you want to simulate the processors internal timers you need to
turn this option on. Simulating the timers uses a lot of processor time, so you might
not want this option on in most cases. When you are debugging timer code it is
helpful to simulate the timers.
The simulator supports the basic timer modes. As there are many new chips with new
timer modes it is possible that the simulator does not support all modes. When you
need to simulate a timer the best option may be to use the latest version of AVR
Studio and load the BASCOM Object file.
Even AVR Studio may have some flaws, so the best option remains to test the code in
a real chip.

The TIMER simulation only simulates TIMER0 and 16 bit TIMER1. And only
counting/time modes are supported. PWM mode is not simulated.

This option allows you to use a real terminal emulator for the serial
communication simulation.
Normally the simulator send serial output to the blue window, and you can also enter
data that needs to be sent to the serial port.
When you enable the terminal option, the data is sent to the actual serial port, and
when serial data is received by the serial port, it will be shown.

This option turns on/off trace information. When enabled, a file with the
name of your project will be created with the .TRACELOG extension.
This file will contain the file, line number and source code that is executed. It is
intended to check which parts of your code execute.

Under the toolbar section there is a TAB with a number of pages:

VARIABLES

© 2021 MCS Electronics


108 BASCOM-AVR

This section allows you to see the value of program variables. You can add variables
by double clicking in the Variable-column. A list will pop up from which you can select
the variable.
To watch an array variable, type the name of the variable with the index.

During simulation you can change the values of the variables in the Value-column,
Hex-column or Bin-column. You must press ENTER to store the changes.

To delete a variable, you can press CTRL+DEL.

To enter more variables, press the DOWN-key so a new row will become visible.

It is also possible to watch a variable by selecting it in the code window, and then
pressing enter. It will be added to the variable list automatically.
Notice that it takes time to refresh the variables. So remove variables that do not
need to be watched anymore for faster simulation speed.

LOCALS

The LOCALS window shows the variables found in a SUB or FUNCTION. Only local
variables are shown. You can not add variables in the LOCALS section.
Changing the value of local variables works the same as in the Variables TAB.

WATCH

© 2021 MCS Electronics


BASCOM IDE 109

The Watch-TAB can be used to enter an expression that will be evaluated during
simulation. When the expression is true the simulation is paused.

To enter a new expression, type the expression in the text-field below the Remove
button, and press the Add-button.
When you press the Modify-button, the current selected expression from the list will
be replaced with the current typed value in the text field.

To delete an expression, select the desired expression from the list, and press the
Remove-button.
During simulation when an expression becomes true, the expression that matches will
be selected and the Watch-TAB will be shown.

uP

This TAB shows the value of the microprocessor status register (SREG).

The flags can be changed by clicking on the check boxes.

The software stack, hardware stack, and frame pointer values are shown. The
minimum or maximum value that occurred during simulation is also shown. When

© 2021 MCS Electronics


110 BASCOM-AVR

one of these data areas enter or overlap another one, a stack or frame overflow
occurs.
This will be signaled with a pause and a check box.

Pressing the snapshot-button will save a snapshot of the current register values and
create a copy of the memory.
You will notice that the Snapshot-button will change to ‘Stop’

Now execute some code by pressing F8 and press the Snapshot-button again.

A window will pop up that will show all modified address locations.
This can help to determine which registers or memory a statement uses.

When you write an ISR (Interrupt Service Routine) with the NOSAVE option, you can
use this to determine which registers are used and then save only the modified
registers.

INTERRUPTS

This TAB shows the interrupt sources. When no ISR's are programmed all buttons will
be disabled.
When you have written an ISR (using ON INT...), the button for that interrupt will be
enabled. Only the interrupts that are used will be enabled.

By clicking an interrupt button the corresponding ISR is executed.


This is how you simulate the interrupts. When you have enabled 'Sim Timers' it can
also trigger the event.

The pulse generator can be used to supply pulses to the timer when it is used in

© 2021 MCS Electronics


BASCOM IDE 111

counter mode.
First select the desired pin from the pull down box. Depending on the chip one or
more pins are available. Most chips have 2 counters so there will usually be 2 input
pins.
Next, select the number of pulses and the desired delay time between the pulses,
then press the Pulse-button to generate the pulses.

The delay time is needed since other tasks must be processed as well.

The option ‘Sim timers’ must be selected when you want to simulate timers/counters.

TERMINAL Section
Under the window with the TABS you will find the terminal emulator window. It is the
dark blue area.

In your program when you use PRINT, the output will be shown in this window.

When you use INPUT in your program, you must set the focus to the terminal window
and type in the desired value.

You can also make the print output go directly to the COM port.
Check the Terminal option to enable this feature.
The terminal emulator settings will be used for the baud rate and COM port.
Any data received by the COM port will also be shown in the terminal emulator
window.

Notice that most microprocessors have only 1 UART. The UART0-TAB is used to
communicate with tis UART. The UART1-TAB need to be selected in order to view the
UART1 output, or to send data to UART1.
In version 2083, UART0-UART3 are simulated. Unavailable UARTS are not shown.

Software UARTS are not supported by the simulator. They can not be simulated.

UART0
UART0 has some specific options. When you right click the mouse you will get a
popup menu.
- Serial Input File.
This option selects a file with the SI extension. It must be named the same as your
main file but having the SI extension. The content will be used as serial data input.
Each time the processor checks UART0 it will read a byte fom the file as if it were
sent.

- Load custom serial Input File


This option allows you to select a specific SI file. An Open Dialog will be shown and you can select
the file.

- Copy
This option copies data sent to the simulated terminal.

- Paste
This option sends data to the simulated terminal.

- Log to File
This option creates a file with the LOG extension. It will have the name of your main file with the
LOG extension. All data send to the simulated UART terminal will be send to the log file as well.

- Show in HEX

© 2021 MCS Electronics


112 BASCOM-AVR

This option shows output in HEX format between brackets like [45] [6E] etc.

SOURCE Section
Under the Terminal section you find the Source Window.
It contains the source code of the program you are simulating. All lines that contain
executable code have a yellow point in the left margin.
You can set a breakpoint on these lines by selecting the line and pressing F9.

By holding the mouse cursor over a variable name, the value of the variable is shown
in the status bar.
If you select a variable, and press ENTER, it will be added to the Variable window.

In order to use the function keys (F8 for stepping for example), the focus must be set
to the Source Window.
In version 2083, the simulator source window will have the same fonts as the editor
window. The source window is read only. You an not change the source code in the
simulator!

A blue arrow will show the line that will be executed next.

When you right click a menu will be shown with the following options:

Option Description
Run (F5) Run code.
Step /Pause (F8) Step through code or pause running code
Step Over Step code but step over sub routines and functions..
(SHIFT+F8)
Run To (F10) Run to the current line. This line should have a yellow dot
(contains executable code)

© 2021 MCS Electronics


BASCOM IDE 113

Goto Line This option let you chose a line to jump to. Use this with care
(ALT+G). since it will jump right to the code. This means that some parts
of your code are not executed.
Clear All This option clears all breakpoints set with F9.
Breakpoints
Toggle breakpoint This option will toggle a break point. It will only work on a line
(F9) with executable code.
Find (CTRL+F) Option to find text, similar to the function in the source editor
Find Next (F3) Option to find next instance similar to the function in the source
editor.
Show Registers Option to show/hide internal registers R0-R31
Show IO Option to show/hide IO registers
Show Memory Option to show/hide memory content for SRAM and EEPROM
Log Terminal This option let you select a file name for the simulator output
output log file.
Clear EEPROM This option will reset the EEPROM content to empty(FF). This is
required sometimes since between sessions the EEPROM content
is saved in an EEP file when this option is checked in Options,
Simulator, Save EEPROM state.
And when you restart simulation the EEP content is read. This
option will clear the content.

The hardware simulator.

By pressing the hardware simulation button the windows shown below will be
displayed.

The top section is a virtual LCD display. It works to display code in PIN mode, and bus
mode. For bus mode, only the 8-bit bus mode is supported by the simulator.

Below the LCD display area are LED bars which give a visual indication of the ports.

By clicking an LED it will toggle.


PA means PORTA, PB means PORTB, etc.

© 2021 MCS Electronics


114 BASCOM-AVR

IA means PINA, IB means PINB etc. (Shows the value of the Input pins)
It depends on the kind of microprocessor you have selected, as to which ports will be
shown.

Right beside the PIN led's, there is a track bar. This bar can be used to simulate the
input voltage applied the ADC converter. Note that not all chips have an AD
converter. You can set a value for each channel by selecting the desired channel
below the track bar.

Next to the track bar is a numeric keypad. This keypad can be used to simulate the
GETKBD() function.

When you simulate the Keyboard, it is important that you press/click the keyboard
button before simulating the getkbd() line !!!

To simulate the Comparator, specify the comparator input voltage level using
Comparator IN0.

Enable Real Hardware Simulation


By clicking the button you can simulate the actual processor ports in-circuit!
The processor chip used must have a serial port.

In order simulate real hardware you must compile the basmon.bas file.

To do this, follow this example:


Lets say you have the DT006 simmstick, and you are using a 2313 AVR chip.

Open the basmon.bas file and change the line $REGFILE = "xxx" to $REGFILE =
"2313def.dat"
Now compile the program and program the chip.
It is best to set the lock bits so the monitor does not get overwritten if you
accidentally press F4.
The real hardware simulation only works when the target micro system has a serial
port. Most have and so does the DT006.

Connect a cable between the COM port of your PC and the DT006. You probably
already have one connected. Normally it is used to send data to the terminal
emulator with the PRINT statement.

The monitor program is compiled for 19200 baud. The Options Communication
settings must be set to the same baud rate!
The same settings for the monitor program are used for the Terminal emulator, so
select the COM port, and the baud rate of 19200.

Power up or reset the DT006. It probably already is powered since you just previously
compiled the basmon.bas program and stored it in the 2313.
When you press the real hardware simulation button now the simulator will send and
receive data when a port, pin or DDR register is changed.

This allows you to simulate an attached hardware LCD display for example, or
something simpler, like an LED. In the SAMPLES dir, you will find the program DT006.
You can compile the program and press F2.

When you step through the program the LED's will change!

All statements can be simulated this way but they have to be able to use static
timing. Which means that 1-wire will not work because it depends on timing. I2C has

© 2021 MCS Electronics


BASCOM IDE 115

a static bus and thus will work.

NOTE: It is important that when you finish your simulation sessions that you click the
button again to disable the Real hardware simulation.

When the program hangs it probably means that something went wrong with the
serial communication. The only way to escape is to press the Real hardware

Simulation button again.

The Real Hardware Simulation is a cost effective way to test attached hardware.

The refresh variables button will refresh all variables during a run(F5). When
you use the hardware simulator, the LEDS will only update their state when you have
enabled this option. Note that using this option will slow down the simulation.

Watchdog Simulation
Most AVR chips have an internal Watchdog. This Watchdog timer is clocked from an
internal oscillator. The frequency is approximately 1 MHz. Voltage and temperature
variations can have an impact on the WD timer. It is not a very precise timer. So
some tolerance is needed when you refresh/reset the WD-timer. The Simulator will
warn you when a WD overflow will occur. But only when you have enabled the WD
timer.

The status bar

The status bar shows the PC (program counter) and the number of cycles. You can
reset the cycles by positioning the mouse cursor on the status bar and then right
click. You will then get a pop up menu with the option to reset the cycles. You can
also double click the cycles to reset it to 0.

You can use this to determine how much time a program statement takes.
Do not jump to a conclusion too quick, the time shown might also depend on the
value of a variable.
For example, with WAITMS var this might be obvious, but with the division of a value
the time might vary too.

Start Simulation
To start a simulation the program need to be compiled. So typically you press F7 to
compile your code. Make sure that the BIN, DBG and OBJ files are created (Options,
Compiler, Output).
When the code is compiled without errors, you can simulate your project. To do so
press F2.
By default the simulator is in STOP mode. The status bar will show PC = 0 (program
counter) and Cycles = 0. Some instructions use more cycles than other. A NOP for
example takes 1 cycle. When the processor has an oscillator running on 8 MHz, and
the 8 DIV fuse is set, it means the processor will have a clock of 1 MHz. Meaning that
each second, 1 million cycles can be executed. So you could execute a million NOP
instructions in 1 second.
The simulator however is not able to do so. The simulator reads the object data, and
decodes the data and simulates the instructions and the hardware. Also, the software
need to give time to windows otherwise the code will stall windows and your other
programs.

© 2021 MCS Electronics


116 BASCOM-AVR

When the AVR is initialized, the RAM is cleared. This will takes time. So when you
press F8 the first time, you will notice that the blue arrow will be visible on the first
line of the main project. It depends on the used processor how long it will take till the
initialization is done. When done, the simulator will go into PAUSE mode.
Press F8 again to step through the code. You will notice that the blue arrow will jump
only to code with a yellow dot which indicates that the line contains executable code.
DIM statements for example are important for the compiler but do not create code.
So these statements will be skipped.
Using the BREAK instruction you can pause the simulator. This is a good way when
instead of F8, you use F5 to RUN the code. You can also set a break point using F9.
This will be visible with a red dot.

When your code uses INC modules, the simulator will show the name of the current
module.

3.44 Program Send to Chip


Program send to chip shortcut , F4

When you access the programmer from the main menu, you will notice the submenu.
From the sub menu you can choose 'Program' or 'Manual Program'.
Program will erase and program the processor without any user intervention.
Manual Program will only show the programmer window. You can manually choose
the options to program the chip when the programmer supports it.

Auto Program also needs the option 'Auto Flash' to be set in the Programmer options
152 .

© 2021 MCS Electronics


BASCOM IDE 117

The following section applies to the Programmer window (program chip directly NOT
selected) otherwise this is not shown to the user.

“Buffer” below refers to the buffer memory that holds data to be programmed to, or
read from the chip.

Menu item Description


File Exit Return to editor
File, Test With this option you can set the logic level to the LPT pins.
This is only intended for the Sample Electronics programmer.
Buffer Clear Clears buffer
Buffer Load from file Loads a file into the buffer
Buffer Save to file Saves the buffer content to a file
Chip Identify Identifies the chip
Write buffer into chip Programs the buffer into the chip ROM or EEPROM
Read chip code into Reads the code or data from the chips code memory or data
buffer memory
Chip blank check Checks if the chip is blank or erased
Chip erase Erase the content of both the program memory and the data
memory
Chip verify Verifies if the buffer is the same as the chip program or data
memory
Chip Set lock bits Writes the selected lock bits LB1 and/or LB2. Only an erase
will reset the lock bits
Chip auto program Erases the chip and programs the chip. After the programming
is completed, verification is performed.

The following window will be shown for most programmers:

© 2021 MCS Electronics


118 BASCOM-AVR

Note that a chip must be ERASED before it can be programmed.

By default the Flash ROM TAB is shown and the binary data is displayed.
When you have an EEPROM in your project, the EEPROM TAB will show this data too.

The most important TAB is in many cases the Lock & Fuse Bits TAB.
When you select it , the lock and fuse bits will be read.

© 2021 MCS Electronics


BASCOM IDE 119

These Lock and Fuse bits are different in almost every chip !
You can select new settings and write them to the chip. But be careful ! When you
select a wrong oscillator option , you can not program the chip anymore without
applying an external clock signal.
This is also the solution to communicate with the chip again : connect a clock pulse to
the oscillator input. You could use an output from a working micro, or a clock
generator or simple 555 chip circuit.

When you found the right settings, you can use $PROG 594 to write the proper
settings to new, un-programmed chips. To get this setting you press the 'Write PRG'
button.
After a new chip is programmed with $PROG, you should remark the line for safety
and quicker programming.

The 'Write PRG' will write the settings, read from the Microprocessor, it will NOT insert
the unsaved settings you have made manual. Thus, you must first use the 'Write XXX'
buttons to write the changed fuse bits settings to the chip, then you can use the
'Write PRG'.

Notice that the Write xxx buttons are disabled by default. Only after you have
changed a lock or fuse bit value, the corresponding button will be enabled. You must
click this button in order to apply the new Lock or Fuse bit settings.

Many new chips have an internal oscillator. The default value is in most cases 8 MHz.
But since in most cases the 'Divide by 8' option is also enabled, the oscillator value
will be 1 MHz. We suggest to change the 'Divide by 8' fuse bit so you will have a
speed of 8 MHz.
In your program you can use $crystal 530 = 8000000 then.

$crystal will only inform the compiler which oscillator speed you have selected.

© 2021 MCS Electronics


120 BASCOM-AVR

This is needed for a number of statements. $crystal will NOT set the speed of the
oscillator itself.

Do not change the fuse bit that will change the RESET to a port pin. Some chips
have this option so you can use the reset pin as a normal port pin. While this is a
great option it also means you can not program the chip anymore using the ISP.

3.45 Tools Terminal Emulator


With this option you can communicate via the RS-232 interface to the microcomputer.
The following window will appear:

Information you type and information that the computer board sends are displayed in
the same window.

Note that you must use the same baud rate on both sides of the transmission. If you
compiled your program with the Compiler Settings at 4800 baud, you must also set
the Communication Settings to 4800 baud.

The setting for the baud rate is also reported in the report file.

NOTE: The focus MUST be on this window in order to see any data (text, etc)
sent from the processor. You will NOT see any data sent by the processor right after a
reset. You must use an external hardware reset AFTER the terminal Emulator window
is given focus in order to see the data. Using the Reset shortcut, you will not be
able to see any data because pressing the shortcut causes the Terminal emulator to
lose focus. This is different than “Hyper Terminal” which always receives data even
when the Hyper terminal window does not have focus. Use Hyper terminal if you need
to see the program output immediately after programming or reset. Or use the option
'Keep terminal emulator open' from the Options, Communication.

File Upload
Uploads the current program from the processor chip in HEX format. This option is
meant for loading the program into a monitor program for example. It will send the

© 2021 MCS Electronics


BASCOM IDE 121

current compiled program HEX file to the serial port.

File Escape
Aborts the upload to the monitor program.

File Exit
Closes terminal emulator.

Terminal Clear
Clears the terminal window.

Terminal Open Log


Opens or closes the LOG file. When there is no LOG file selected you will be asked to
enter a filename or to select a filename. All info that is printed to the terminal window
is captured into the log file. The menu caption will change into 'Close Log' and when
you choose this option the file will be closed.

Terminal Send ASCII


This option allows you to send any ASCII character you need to send. Values from
000 to 255 may be entered.

Terminal Send Magic number


This option will send 4 bytes to the terminal emulator. The intention is to use it
together with the boot loader examples. Some of the boot loader samples check for a
number of characters when the chip resets. When they receive 4 'magic' characters
after each other, they will start the boot load procedure. This menu options send
these 4 magic characters.

Terminal Setting
This options will show the terminal settings so you can change them quickly.
It is the same as Options, Communication 141 .

Terminal User Commands


This option will show or hide the toolbar with the user definable command buttons.

There are 16 user definable buttons named CMD1-CMD16. When you hover the
mouse cursor above the button, the button data will be shown.
When you right click the mouse above the button, you can enter the data for the
button.
Example for CMD4:

© 2021 MCS Electronics


122 BASCOM-AVR

In the sample above the data "test" will be sent. No carriage return(CR) or line feed
(LF) will be sent. If you want to send them as well you need to include them as
special characters.
Special characters are entered with their 3 digit ASCII value between brackets :
{xxx}
For example to send CR + LF you wend enter {013}{010}

See Also
Options, Communication 141

3.46 Tools LCD Designer


With this option you can design special characters for LCD-text displays.

The following window will appear:

© 2021 MCS Electronics


BASCOM IDE 123

The LCD-matrix has 7x5 points. The bottom row is reserved for the cursor but can be
used.
You can select a point by clicking the left mouse button. If a cell was selected it will
be unselected.

Clicking the Set All button will set all points.


Clicking the Clear All button will clear all points.

When you are finished you can press the Ok button : a statement will be inserted in
your active program-editor window at the current cursor position. The statement
looks like this :

Deflcdchar ?,1,2,3,4,5,6,7,8

You must replace the ?-sign with a character number ranging from 0-7.
The eight bytes define how the character will appear. So they will be different
depending on the character you have drawn.

See Also
Font Editor 217

© 2021 MCS Electronics


124 BASCOM-AVR

3.47 Tools LIB Manager


With this option the following window will appear:

The Libraries are shown in the left pane. When you select a library, the routines that
are in the library will be shown in the right pane.

After selecting a routine in the left pane, you can DELETE it with the DELETE button..

Clicking the ADD button allows you to add an ASM routine to the library.

The COMPILE button will compile the lib into an LBX file. When an error occurs you
will get an error. By watching the content of the generated lbx file you can determine
the error.

A compiled LBX file does not contain comments and a huge amount of mnemonics are
compiled into object code. This object code is inserted at compile time of the main
BASIC program. This results in faster compilation time.

The DEMO version comes with the compiled MCS.LIB file which is named MCS.LBX.
The ASM source (MCS.LIB) is included only with the commercial edition.

With the ability to create LBX files you can create add on packages for BASCOM and
sell them. For example, the LBX files could be distributed for free, and the ASM
source could be sold.

Some library examples :

· MODBUS crc routine for the modbus slave program.


· Glcd.lib contains the graphical LCD asm code

© 2021 MCS Electronics


BASCOM IDE 125

Commercial packages available from MCS:

· I2CSLAVE library
· BCCARD for communication with www.basiccard.com chipcards

See Also
$LIB 570 for writing your own libraries

3.48 Tools Graphic Converter


The Graphic converter is intended to convert BMP files into BASCOM Graphic Files (.
BGF) that can be used with Graphic LCD displays.

The following dialog box will be shown:

To load a picture click the Load button.


The picture can be maximum 128 pixels high and 240 pixels width.

When the picture is larger it will be adjusted.

You can use your favorite graphic tool to create the bitmaps and use the Graphic
converter to convert them into black and white images.

When you click the Save-button the picture will be converted into black and white.
Any non-white color will be converted into black.

The resulting file will have the BGF extension. (bascom graphics format)

You can also paste a picture from the clipboard by clicking the Paste button.

Press the Ok-button to return to the editor.

The picture can be shown with the ShowPic 1223 statement or the ShowpicE 1223
statement.

© 2021 MCS Electronics


126 BASCOM-AVR

The BGF files are RLE encoded to save space.

It is important that the font selection 6*8 or 8*8 match the font size in the
CONFIG GRAPHLCD. For example :
Config Graphlcd = 240x128 , Dataport = Porta , Controlport = Portc , Ce = 2 , Cd = 3
, Wr = 0 , Rd = 1 , Reset = 4 , Fs = 5 , Mode = 8
In this case you would use 8*8.

When you use your own drawing routine you can also save the pictures
uncompressed by setting the Uncompressed check box. The resulting BGF files can
not be shown with the showpic or showpicE statements anymore in that case!

The BGF format is made up as following:

· first byte is the height of the picture


· second byte is the width of the picture
· for each row, all pixels are scanned from left to right in steps of 6 or 8
depending on the font size. The resulting byte in stored with RLE compression

The RLE method used is : byte value, AA(hex), repeats.


So a sequence of 5, AA, 10 means that a byte with the value of 5 must be repeated
16 times (hex notation used)

Option Description
Height The height in pixels of the image.
Width The width in pixels of the image.
Font The T6963 supports 6x8 and 8x8 fonts. This is the font select that
must match the CONFIG statement. For other displays, use 8*8.
Type The size of the display. When the size is not listed, use one with the
same width.
SED Series If your display is a SEDxxxx chip, select this option.
Uncompresse Images are RLE encoded. Select this option when you do not want to
d compress the image.

3.49 Tools Stack Analyzer


The Stack analyzer helps to determine the proper stack size.

See $DBG 532 for the proper usage of this option.

3.50 Tools Plugin Manager


The Plug in Manager allows you to specify which Plug-in's needs to be loaded the next
time you start BASCOM.

© 2021 MCS Electronics


BASCOM IDE 127

Just select the plug in's you want to load/use by setting the check box.
The plug in's menu's will be loaded under the Tools Menu.

To add a button to the toolbar, right click the mouse on the menu bar, and choose
customize.

When you want to write your own plug in's, contact [email protected]

3.51 Tools Batch Compile


The Batch Compiler is intended to compile multiple files.
Shortcut : CTRL+B

The Batch compile option was added for internal test usage. It is used by MCS to test
the provided test samples.
The following window is shown :

© 2021 MCS Electronics


128 BASCOM-AVR

There are a number of menu options.

File Load Batch


Load an earlier created and saved batch file list from disk.

File Save Batch


Save a created list of files to disk
When you have composed a list with various files it is a good idea to save it for later
re usage.

File Save Result


Save the batch compile log file to disk. A file named batchresult.txt will be saved in
the BASCOM application directory.

File Exit
Close window

Batch Compile
Compile the checked files. By default all files you added are checked. During
compilation all files that were compiled without errors are unchecked.

© 2021 MCS Electronics


BASCOM IDE 129

This screen print shows that $inc.bas could not be compiled.


And that array.bas was not yet compiled.

Batch Add Files


Add files to the list. You can select multiple *.BAS files that will be added to the list.

Batch Add Dir


Add a directory to the list. All sub directories will be added too. The entire directory
and the sub directories are searched for *.BAS files. They are all added to the list.

Batch Clear List


Clear the list of files.

Batch Clear Good


Remove the files that were compiled without error. You will keep a list with files that
compiled with an error.

All results are shown in an error list at the bottom of the screen.
When you double click an item, the file will be opened by the editor.

See Also
$NOCOMP 590

© 2021 MCS Electronics


130 BASCOM-AVR

3.52 Tools PDF Update


Use this option to update all Atmel PDF files.
The Atmel data sheets are stored in the \PDF subdirectory.
The following window will be shown :

There is only one option available : Check. When you click the Check-button, the MCS
server will be checked for newer versions of the PDF documents.
You need to make sure that BASCOM is allowed to contact the internet.
You also need to have port 211 open. This port is used in FTP mode to contact the
MCS server.

The MCS server is synchronizing all PDF files each day with the ATMEL server. This
means that the copy on the MCS server can be maximum 24 hours old.

The check will read all available DAT files and check if there is a reference to the PDF.
When an item is disabled(grayed) then it means there is no link to the PDF in the DAT
file.

During the check the window will look like this :

© 2021 MCS Electronics


BASCOM IDE 131

All PDF's that are newer will have a check mark. These need an update.
You can manual unselect or select the PDF's.
In the log window at the bottom of the window you can view which files will be
downloaded.

When you want to download the selected files, press the Download-button.
This will close all PDF documents in the PDF viewer. A backup of each PDF file
downloaded will be made before it is downloaded. You need to restore it when
something goes wrong during the download(server drops the connection for
example).
When a document is downloaded, the check mark will be removed.

After all documents are downloaded, they documents are opened again in the PDF
viewer.

As of version 2077 the PDF documents are downloaded from the MCS Electronics
server.
Previously they were downloaded from Atmels webserver. When Atmel change the file
name the link is broken and you can not update the file.
To solve this all files are stored on the MCS server and each day all files are
synchronized with atmel so all files are maximum 1 day old.

As of version 2079 the PDF files are downloaded using FTP. This results in a better
performance. Just make sure port 411 is open in your firewall for outgoing
connections.

© 2021 MCS Electronics


132 BASCOM-AVR

3.53 Tools Resource Editor


The resource editor can be used to edit the resource strings of your application.
The resource editor will create a <project>.BCR file.
The resource editor is part of the Resource Add On, and is only available when you
have this add on installed.

The simplest way to get the resources from your application is to create a BCS file
using the DUMP option.
Then import them with the resource editor.

The following options are available when you right click with the mouse in the
resource editor.

Option Description
Search Search for a string.
Find Next Find next occurrence.
Delete Row Delete the current row.
Add Row Add a new row for a new string.
Import This option will import the BCS file which you can create with
the $RESOURCE DUMP option.
Set Language Name Change the language name of the current language/column.
Add Language Add a new column for a new language.
Delete Language Delete the current column (language).

The resource editor is pretty simple. The only task is allow you to edit the various
strings. You can also use notepad or Excel to create the BCR file which is explained in
the $RESOURCE 599 topic.

© 2021 MCS Electronics


BASCOM IDE 133

3.54 Tools Font Editor


The Font Editor was a Plug in which is now integrated into the Tools menu.
The editor is intended to create Fonts that can be used with Graphical display such as
SED1521, KS108, color displays, etc.

When you choose this option the following window will appear:

You can open an existing Font file, or Save a modified file.

The supplied font files are installed in the Samples\lcdgraph folder.


You can copy an image from the clipboard, and you can then move the image up ,
down, left and right.

When you select a new character, the current character is saved. The suggest button
will draw an image of the current selected character.

When you keep the left mouse button pressed, you can set the pixels in the grid.
When you keep the right mouse button pressed, you can clear the pixels in the grid.

When you choose the option to create a new Font, you must provide the name of the
font, the height of the font in pixels and the width of the font in pixels.

The Max ASCII is the last ASCII character value you want to use. Each character will
occupy space. So it is important that you do not choose a value that is too high and
will not be used.

© 2021 MCS Electronics


134 BASCOM-AVR

When you display normal text, the maximum number is 127 so it does not make
sense to specify a value of 255.

A font file is a plain text file.


Lets have a look at the first few lines of the 8x8 font:

Font8x8:
$asm
.db 1,8,8,0
.db 0,0,0,0,0,0,0,0 ;
.db 0,0,6,95,6,0,0,0 ; !

The first line contains the name of the font. With the SETFONT 1219 statement you can
select the font. Essential, this sets a data pointer to the location of the font data.

The second line ($ASM) is a directive for the internal assembler that asm code will
follow.
All other lines are data lines.

The third line contains 4 bytes: 1 (height in bytes of the font) , 8 (width in pixels of
the font), 8 (block size of the font) and a 0 which was not used before the 'truetype'
support, but used for aligning the data in memory. This because AVR object code is a
word long.

This last position is 0 by default. Except for 'TrueType' fonts. In BASCOM a TrueType
font is a font where every character can have it's own width. The letter 'i' for example
takes less space then the letter 'w'. The EADOG128 library demonstrates the
TrueType option.
In order to display TT, the code need to determine the space at the left and right of
the character. This space is then skipped and a fixed space is used between the
characters. You can replace the 0 by the width you want to use. The value 2 seems a
good one for small fonts.

All other lines are bytes that represent the character.


Graphical LCD uses 1 byte to set 8 pixels black/white.
The LCD driver will for load the height in bytes i the example this is 1 byte.
Then the driver will load the width in bytes of the character. in the example this is 8.
This means that data lines are 8 bytes long.
And finally the block size in bytes of one character will be loaded. This is simply the
first parameter times the second parameter. In the example this is 8 too. The last
parameter is loaded to see if TT spacing must be used.

Depending on the ASCII value of the character to show, the driver will located the
proper place in the table by multiplying the block size with the ASCII value. This will
be added to the start of the table address.

Now the driver will load and write a byte and thus will set 8 pixels.
The pixels are shown from top to bottom like this :

x
x
x
x
x
x
x
x

© 2021 MCS Electronics


BASCOM IDE 135

Then the next byte will be loaded and send to the lcd.

xy
xy
xy
xy
xy
xy
xy
xy

and this will repeat for the number of bytes specified.

Then if the height is more than 1 byte, the next block will be loaded.
This also means that each font height must be a multiple of 8 pixels.
This restriction is only because writing a full byte is the fastest way to update an LCD.

3.55 Options Compiler


With this option, you can modify the compiler options.

The following TAB pages are available:

Options Compiler Chip 135


Options Compiler Output 137
Options Compiler Communication 138
Options Compiler I2C , SPI, 1WIRE 139
Options Compiler LCD 140

3.55.1 Options Compiler Chip

© 2021 MCS Electronics


136 BASCOM-AVR

The following options are available:

Options Compiler Chip


Item Description
Chip Selects the target chip. Each chip has a corresponding x.DAT file
with specifications of the chip. Note that some DAT files are not
available yet.
XRAM Selects the size of the external RAM. KB means Kilo Bytes.

For 32 KB you need a 62256 STATIC RAM chip.


HW Stack The amount of bytes available for the hardware stack. When you
use GOSUB or CALL, you are using 2 bytes of HW stack space.

When you nest 2 GOSUB’s you are using 4 bytes (2*2). Most
statements need HW stack too. An interrupt needs 32 bytes.
Soft Stack Specifies the size of the software stack.

Each local variable uses 2 bytes. Each variable that is passed to a


sub program uses 2 bytes too. So when you have used 10 locals in
a SUB and the SUB passes 3 parameters, you need 13 * 2 = 26
bytes.
Frame size Specifies the size of the frame.

Each local variable is stored in a space that is named the frame


space.
When you have 2 local integers and a string with a length of 10,
you need a frame size of (2*2) + 11 = 15 bytes.
The internal conversion routines used when you use INPUT num, or
STR(), or VAL(), etc, also use the frame. They need a maximum of
16 bytes. So for this example 15+16 = 31 would be a good value.
XRAM wait state Select to insert a wait state for the external RAM.
External Access Select this option to allow external access of the micro. The 8515
enable for example can use port A and C to control a RAM chip. This is
almost always selected if XRAM is used
Default Press or click this button to use the current Compiler Chip settings
as default for all new projects.

© 2021 MCS Electronics


BASCOM IDE 137

3.55.2 Options Compiler Output

Options Compiler Output


Item Description
Binary file Select to generate a binary file. (xxx.bin)
Debug file Select to generate a debug file (xxx.dbg)
Hex file Select to generate an Intel HEX file (xxx.hex)
Report file Select to generate a report file (xxx.rpt)
Error file Select to generate an error file (xxx.err)
AVR Studio Select to generate an AVR Studio object file (xxx.obj)
object file Using the OBJ file you can debug with AVR Studio. This also allows
to use tools like ICE.
In Studio 6.0 (fixed in 6.1) you need to make these changes in
Studio :

Locate the file atmelstudio.pkgundef under the installation folder for


Atmel. Studio.

Remove (or remark) the below lines from the file and save the file.

[$RootKey$\Languages\Language Services\Basic]

[$RootKey$\AutomationProperties\TextEditor\Basic]

Size warning Select to generate a warning when the code size exceeds the Flash
ROM size.
Swap words This option will swap the bytes of the object code words. Useful for
some programmers. Should be disabled for most programmers.

© 2021 MCS Electronics


138 BASCOM-AVR

Don't use it with the internal supported programmers.


Optimize code This options does additional optimization of the generated code.
Since it takes more compile time it is an option.
Show internal Internal variables are used. Most of them refer to a register. Like
variables _TEMP1 = R24. This option shows these variables in the report.

3.55.3 Options Compiler Communication

Options Compiler Communication


Item Description
Baud rate Selects the baud rate for the serial communication statements. You
can also type in a new baud rate.
It is advised to use $BAUD 512 in the source code which overrides this
setting.
Frequency Select the frequency of the used crystal. You can also type in a new
frequency. It is advised to use $CRYSTAL 530 in the source code which
overrides this setting. Settings in source code are preferred since it is
more clear.

The settings for the internal hardware UART are:

No parity , 8 data bits , 1 stop bit

Some AVR chips have the option to specify different data bits and different stop bits
and parity.

Note that these settings must match the settings of the terminal emulator. In the

© 2021 MCS Electronics


BASCOM IDE 139

simulator the output is always shown correct since the baud rate is not taken in
consideration during simulation. With real hardware when you print data at 9600
baud, the terminal emulator will show weird characters when not set to the same
baud rate, in this example, to 9600 baud.

3.55.4 Options Compiler I2C, SPI, 1WIRE

Options Compiler I2C, SPI, 1WIRE


Item Description
SCL port Select the port pin that serves as the SCL-line for the I2C related
statements.
SDA port Select the port pin that serves as the SDA-line for the I2C related
statements.
1WIRE Select the port pin that serves as the 1WIRE-line for the 1Wire
related statements.
Clock Select the port pin that serves as the clock-line for the SPI related
statements.
MOSI Select the port pin that serves as the MOSI-line for the SPI related
statements.
MISO Select the port pin that serves as the MISO-line for the SPI related
statements.
SS Select the port pin that serves as the SS-line for the SPI related
statements.
Use hardware Select to use built-in hardware for SPI, otherwise software
SPI emulation of SPI will be used. The 2313 does not have internal HW
SPI so it can only be used with software SPI mode.
When you do use hardware SPI, the above settings are not used
anymore since the SPI pins are dedicated pins and can not be
chosen by the user.

© 2021 MCS Electronics


140 BASCOM-AVR

It is advised to use the various CONFIG 757 commands in your source code. It make
more clear in the source code which pins are used.

3.55.5 Options Compiler LCD

Options Compiler LCD


Item Description
LCD type The LCD display used.
Bus mode The LCD can be operated in BUS mode or in PIN mode. In
PIN mode, the data lines of the LCD are connected to the
processor port pins. In BUS mode the data lines of the LCD
are connected to the data lines of the BUS.

Select 4 when you have only connect DB4-DB7. When the


data mode is 'pin' , you should select 4.
Data mode Select the mode in which the LCD is operating. In PIN
mode, individual processor pins can be used to drive the
LCD. In BUS mode, the external data bus is used to drive
the LCD.
LCD address In BUS mode you must specify which address will select the
enable line of the LCD display. For the STK200, this is C000
= A14 + A15.
RS address In BUS mode you must specify which address will select the
RS line of the LCD display. For the STK200, this is 8000 =
A15
Enable For PIN mode, you must select the processor pin that is
connected to the enable line of the LCD display.
RS For PIN mode, you must select the processor pin that is

© 2021 MCS Electronics


BASCOM IDE 141

connected to the RS line of the LCD display.


DB7-DB4 For PIN mode, you must select the processor pins that are
connected to the upper four data lines of the LCD display.
Make upper 3 bits high Some displays require that for setting custom characters,
in LCD designer the upper 3 bits must be 1. Should not be used by default.

It is advised to use the CONFIG LCD command. This way the settings are stored in
your source code and not in the separate CFG file.

3.56 Options Communication


With this option, you can modify the communication settings for the terminal
emulator.

Item Description
Comport The communication port of your PC that you use for the terminal
emulator.
Baud rate The baud rate to use.
Parity Parity, default None.
Data bits Number of data bits, default 8.
Stop bits Number of stop bits, default 1.
Handshake The handshake used, default is none.
Emulation Emulation used, default TTY and VT100.
Font Font type and color used by the emulator.
Back color Background color of the terminal emulator.

© 2021 MCS Electronics


142 BASCOM-AVR

Keep TE open This option will keep the terminal emulator COM port open when you
close the window or move the focus away. Some serial programmers
which close the COM port when they need to program, will not work
in this mode when they use the same COM port.
Use Existing When you select this option, you will get a list with the available COM
COM ports ports only at places you can select a COM port.
When you insert an USB virtual COM port, it will be added to list
automatically. Removing virtual COM ports will also update the
available COM port list.
When you do not select this option you get a list with COM1-COM255.

Note that the baud rate of the terminal emulator and the baud rate setting of the
compiler options 138 , must be the same in order to work correctly.

The reason why you can specify them both to be different is that you can use the
terminal emulator for other purposes too.

3.57 Options Environment


The Environment TAB has a few TABS of it's own.

Options Environment Editor

© 2021 MCS Electronics


BASCOM IDE 143

OPTION DESCRIPTION
Auto Indent When you press return, the cursor is set to the next line at
the current column position.
Don't change case When set, the reformat won't change the case of the line
after you have edited it.

Default is that the text is reformatted so every word


begins with upper case.
Reformat BAS files Reformat files when loading them into the editor.
All lines are reformatted so that multiple spaces are
removed.

This is only necessary when you are loading files that


where created with another editor. Normally you won't
need to set this option.
Reformat code Reformat code when entered in the editor.
The reformat option will change the modified line.
For example a = a + 1 will be changed into : a = a +
1 . When you forget a string end marker ", one will be
added, and endif will be changed into End If. And finally, ?
is changed into Print.
Smart TAB When set, a TAB will place the cursor to the column where
text starts on the previous line.
Syntax highlighting This options highlights BASCOM statements in the editor.
Show margin Shows a margin on the right side of the editor. You can
specify the position. By default this is 80.
Comment The position of the comment. Comment is positioned to
the right of your source code. Except when comment is
first character of a line.
TAB-size Number of spaces that are generated for a TAB.
Key mapping Choose default, Classic, Brief or Epsilon.
No reformat extension File extensions separated by a space that will not be
reformatted when loaded. For example when DAT is
entered, opening a DAT file can be done without that it is
reformatted.
Size of new editor When a new editor window is created you can select how
window the windows will be created. Normal or Maximized (full
window)
Line Numbers Show line numbers in the margin.
Show Subs/Labels This option will show sub modules/functions and labels at
the top of the editor window in a drop down box. To get
more screen space you can disable this option.
Remove Empty Lines This option will remove empty lines when you paste data
from the clipboard into the editor. When you copy & paste
text from the help file (or any other source) you will find
that windows inserts empty lines. This option will change
two CR+LF into one.

Indention
When indention lines are drawn, you can select the color of each level. The default is
gray.
When you move the mouse over an indention line, the tooltip will show the start of
the structure.

© 2021 MCS Electronics


144 BASCOM-AVR

The sample above shows the info for the green indention line.
Obvious when the code fits into the screen, it is simple to see that the green line
belongs to #IF _XMEGA. But when there is a lot of code in the editor, and you can not
see all of the code, it can be a big help.

Code Folding
This option activates so called Code Folding. Code Folding allows you to hide/fold
portions of your code.

The screen shot above shows :


1 - The Sub DEMO is folded. So you only see Sub Demo in your code. To indicate
that the sub is folded there is a marker at the end of the line (3 dots)
Another indicator is the + sign. This means that the node is folded.
2 - When you put the cursor above the marker, you get a hint with the folded text/
code.
3 - The minus means that you can fold that node. When you click the - it will turn
into a + and the code is folded.

This is how it looks when the node at (3) is clicked:

© 2021 MCS Electronics


BASCOM IDE 145

When folding code, all child code (all levels under the node) will be folded/unfolded as
well.
A node is a point in your code that is part of a structure like sub/end sub , function/
end function, for/next, do/loop, while/wend

When you press F11, the current SUB or FUNCTION will be folded/unfolded. The
Editor menu also has options to fold/unfold all code.

Draw Indention Lines


This option will draw vertical indent lines for structures.

Drawing indention lines may result in slower screen painting. Errors in your code
might result in wrong painting of the lines.

Options Environment Font

© 2021 MCS Electronics


146 BASCOM-AVR

OPTION DESCRIPTION
Background The background color of the editor window. Choose a color that is the
color same as your background. In a white room, using white would be best
for your eyes.
Keyword The color of the reserved words. Default Navy.
color
The keywords can be displayed in bold too.
Comment The color of comment. Default green.
color
Comment can be shown in Italic too.
ASM color Color to use for ASM statements. Default purple.
HW registers The color to use for the hardware registers/ports. Default maroon.
color
String colorThe color to use for string constants : "test"
Variable color
The color to use for variables. Default is black.
User Function
The color to use for user SUBS and FUNCTIONS. The default is fuchsia
Color .
Editor font Click on this button to select another font for the editor window. A
good choice is Fixedsys.
Show Hidden This option will show special characters in the editor. Special
Characters characters are characters such as CR and LF. And all characters with
an ASCII value above 127. You can use this option to find odd
characters in your code which could result in compilation errors.

© 2021 MCS Electronics


BASCOM IDE 147

Options Environment IDE

OPTION DESCRIPTION
Tool tips Show tool tips when hovering over form elements such as buttons.
File Click to select a directory where your program files are stored. By default
location Windows will use the My Documents path.
Sample Click to select the folder where the SAMPLE files are located. They are
Location either stored in a sub folder of the application, or in a folder under the
Documents\MCS Electronics\BASCOM-AVR\samples folder
Use HTML Chose between old help and CHM Help. CHM is the preferred help file.
Help Since HLP is not supported under Vista, it is advised to switch to CHM/
HTML Help. The HLP file is not distributed but using the UpdateWiz you
can still download the HLP file.
Code hints Select this option to enable code hints. You can get code hints after you
have typed a statement that is recognized as a valid statement or
function.
Hint Time The delay time in mS before a code hint will be shown.
Hint Color The background color of the hints.
Allow Select this option when you want to run multiple instances of BASCOM.
multiple When not enabled, running a second copy will terminate the first
Instances instance.
Auto save The code is always saved when you compile. When you select this

© 2021 MCS Electronics


148 BASCOM-AVR

on compile option, the code is saved under the same name. When this option is not
selected, you will be prompted for a new filename.
Auto Check this option to make periodic backups. When checked you can
backup specify the backup time in minutes. The file will also be saved when you
press the compiler button.
History This option creates a history backup of the source file each time you save
Backup it. When you Compile code, the active source will be saved too before
compilation and hence it will create a history file as well.
The history file is a version of the code saved in the HISTORY folder. This
folder is located in the same folder as the main project.
The file will be named <FILE>~yymmdd hhnnss.hst
Where <FILE> is the original file name, and yymmdd is the date and
hhNNss is the time.
Auto load When enabled, this option will load the last file that was open into the
last file editor, when you start BASCOM.
Auto load When enabled, this option will load all files that were open when you
all files closed BASCOM.
Check for Select this option to check for updates when the IDE is started.
updates
Show This option will enable/disable the TAB for multiple windows. While the
TABS TAB is convenient to switch between windows, it will also consume
screen space. You can disable this option to get more screen space.
Reset This will reset the dockable windows to the default position.
docking
Search This option can enable/disable the auto completion in the Find dialog.
Find Auto When it is active and you type some text, based on historical input, the
Complete text will be completed. This is not always desired and can be disabled.
Language This will set the language in the main menu to the selected language.
Not all listed languages are supported/translated yet.
Clear Do Some messages have a 'do not ask again' option. To reset this and thus
not Ask show the messages, you can click this button.
Use New When compiling a project, the main file is searched for some settings like
Method $regfile, $hwstack, $swstack and $framesize. This information is passed
to the compiler DLL.
This search is fast but simple : it will not work correct when using
directives such as :
#IF someConditon
$regfile = "m88def.dat"
#ELSE
$regfile = "m2650def.dat"
#ENDIF
The parser used for the code explorer is capable to get the information
but requires more time because it will parse the entire project. So you
have the option to chose the old method(default) or the new method. It
is good practice to start your project with the required info :
$regfile = "yourmicro.dat"
$hwstack=32 '
$swstack=32
$framesize=32
Code The Code explorer will put all elements in one tree without file names.
Explorer Setting this option however will create a tree of elements with all file
with names under a branch named 'Inc Files'.
separate
INC files

© 2021 MCS Electronics


BASCOM IDE 149

Code explorer with separate inc files Code explorer without separate inc
files

Options Environment PDF

© 2021 MCS Electronics


150 BASCOM-AVR

OPTION DESCRIPTION
Auto open processor This option will automatic load the PDF of the selected micro
PDF processor in the PDF viewer. The $REGFILE value
determines which data sheet is loaded. The PDF must exist
otherwise it can not be loaded.
Open PDF in new sheet Every time you change the value of the $REGFILE the
processor PDF can be shown in the same sheet, or a new
sheet can be shown with the PDF. A good option in case
your project uses multiple processors.
Auto save/load project Load all PDF's when the project is opened that were loaded
PDF when the project was closed.

Custom ShortCuts
When you want to define your own short cuts you can create an ini file named
shortcuts.ini.
This ini file is just a text file you can create with notepad. Store this file in the
BASCOM application folder.
To enable the user shortcuts you need to make an option named : ENABLED with the
value -1.

This is an example of the default values


[MENU]
enabled=-1
FileNew=CTRL+N
FileSave=CTRL+S
FilePrint=CTRL+P
EditUndo=CTRL+Z
EditRedo=SHIFT+CTRL+Z
EditCut=CTRL+X
EditCopy=CTRL+C

© 2021 MCS Electronics


BASCOM IDE 151

EditPaste=CTRL+V
EditFind=CTRL+F
EditFindNext=F3
EditReplace=CTRL+R
EditGoto=CTRL+G
EditIndent=SHIFT+CTRL+I
EditUnIndent=SHIFT+CTRL+U
EditUnremarkBlock=CTRL+M
EditProperIndent=CTRL+ALT+P
Compile=F7
SyntaxCheck=CTRL+F7
ProgramShowResult=CTRL+W
ProgramSimulate=F2
ProgramSendToChip=F4
ProgramResetChip=SHIFT+F4
TerminalEmulator=CTRL+T
LCD_Designer=CTRL+L
LibManager=CTRL+I
BatchCompile=CTRL+B
ShowDevMng=CTRL+D

To turn the custom shortcuts off set the ENABLED to 0.

3.58 Options Simulator


With this option you can modify the simulator settings.

OPTION DESCRIPTION

© 2021 MCS Electronics


152 BASCOM-AVR

Use integrated Set this option to use BASCOM’s simulator. You can also use
simulator AVR Studio by clearing this option.
Run simulator after Run the selected simulator after a successful compilation.
compilation
Program The path with the program name of the external simulator.
Parameter The parameter to pass to the program. {FILE}.OBJ will
supply the name of the current program with the extension .
OBJ to the simulator.

3.59 Options Programmer


With this option you can modify the programmer settings.

OPTION DESCRIPTION
Programmer Select one from the list.
Play sound Name of a WAV file to be played when programming is finished.

Press the directory button to select a file.


Erase Warning Set this option when you want a confirmation when the chip is
erased.
Auto flash Some programmers support auto flash. Pressing F4 will program
the chip without showing the programmer window.
Auto verify Some programmers support verifying. The chip content will be
verified after programming.
Upload code and Set this option to program both the FLASH memory and the
data EEPROM memory
Program after When compilation is successful, the chip will be programmed
compile

© 2021 MCS Electronics


BASCOM IDE 153

Set focus to When the chip is programmed, the terminal emulator will be shown
terminal
emulator

Parallel printer port programmers


LPT address Port address of the LPT that is connected to the programmer.
Port delay An optional delay in uS. It should be 0. But on some systems a
delay might be needed.

Serial port programmer


COM port The com port the programmer is connected to.
STK500 EXE The path of stk500.exe. This is the full file location to the files
stk500.exe that comes with the STK500.
USB For mkII and other Atmel USB programmers you can enter the
serial number here. Or you can look it up from the list.
Baud Some serial programmers have an optional baud rate you can
chose.
The usual values are supported. When you want special custom
baud rate you can replace the baud rate by creating a file named :
progbaud.lst
In this text file you can place all the baud rate. For example :
123
300
600
1200
2400
4800
9600
9610
19200
38400
57600
128000
256000
115200
500000

Then save the file. The file must reside in the bascom-avr
application folder. The file is loaded when you run bascom. It will
depend on your PC hardware if the baud you use will actually
work.

Other
Use HEX Select when a HEX file must be sent instead of the bin file.
Program The program to execute. This is your programmer software.
Parameter The optional parameter that the program might need.

Use {FILE} to insert the binary filename(file.bin) and {EEPROM} to


insert the filename of the generated EEP file.

When ‘Use Hex’ is checked the filename (file.hex) will be inserted


for {FILE}. In all cases a binary file will be inserted for {EEPROM}
with the extension .EEP

Use {CHIP} to insert the official device name of the chip. The

© 2021 MCS Electronics


154 BASCOM-AVR

device name is required by some programmers.

See Also
Supported programmers 154

3.59.1 Supported Programmers


BASCOM supports the following programmers

AVR ICP910 based on the AVR910.ASM application note 164

STK200 ISP programmer from Atmel 164

The PG302 programmer from Iguana Labs 156

The simple cable programmer from Sample Electronics. 156

KITSRUS KIT122 Programmer 157

MCS Universal Interface Programmer 158

The MCS Universal Interface supports a number of programmers as well. In fact it is


possible to support most parallel printer port programmers.

STK500 programmer and Extended STK500 programmer. 160

Lawicel BootLoader 164

USB-ISP Programmer 165

MCS Bootloader 174

PROGGY 176

FLIP 177

USBprog Programmer / AVR ISP mkII 180 (AVRISP)

KamProg for AVR 180

USBASP 183

STK600 184

ARDUINO 187

BIPOM MINI-MAX/C 190

mySmartUSB light 190

UPDI Programmer 192

© 2021 MCS Electronics


BASCOM IDE 155

3.59.1.1 ISP programmer


BASCOM supports the STK200 and STK200+ and STK300 ISP programmer from
Atmel.

This is a very reliable parallel printer port programmer.


The STK200 ISP programmer is included in the STK200 starter kit.
Most programs were tested with the STK200.

For those who don't have this kit and the programmer the following schematic shows
how to make your own programmer:

The dongle has a chip with no identification but since the schematic is all over the
web, it is included. MCS also sells a STK200 compatible programmer.

Here is a tip received from a user :

If the parallel port is disconnected from the interface and left floating, the '244 latch
outputs will waver, causing your micro controller to randomly reset during operation.
The simple addition of a 100K pull-up resistor between pin 1 and 20 of the latch, and
another between pin 19 and 20, will eliminate this problem. You'll then have HIGH-Z
on the latch outputs when the cable is disconnected (as well as when it's connected
and you aren't programming), so you can use the MOSI etc. pins for I/O.

© 2021 MCS Electronics


156 BASCOM-AVR

3.59.1.2 PG302 programmer


The PG302 is a serial programmer. It works and looks exactly as the original PG302
software.

Select the programmer from The Option Programmer menu or right click on the
button to show the Option Programmer 152 menu

THIS PROGRAMMED IS MARKED FOR REMOVAL. Send a note to support if you use it.

3.59.1.3 Sample Electronics cable programmer


Sample Electronics submitted the simple cable programmer.

They produce professional programmers too. This simple programmer you can make
yourself within 10 minutes.
What you need is a DB25 centronics male connector, a flat cable and a connector that
can be connected to the target MCU board.

The connections to make are as following:

DB25 pin Target MCU pin Target MCU Target MCU pin 8515 DT104
(AT90S8535) M103/M128
2, D0 MOSI, pin 6 PE.0, 2 MOSI, 6 J5, pin 4
4, D2 RESET, pin 9 RESET, 20 RESET, 9 J5, pin 8
5, D3 CLOCK, pin 8 PB.1,11 CLOCK, 8 J5, pin 6
11, BUSY MISO, pin 7 PE.1, 3 MISO, 7 J5, pin 5
18-25,GND GROUND GROUND GND,20 J5, pin 1

The MCU pin numbers are shown for an 8535! And 8515
Note that 18-25 means pins 18,19,20,21,22,23,24 and 25

You can use a small resistor of 100-220 ohm in series with the D0, D2 and D3 line in
order not to short circuit your LPT port in the event the MCU pins are high.

© 2021 MCS Electronics


BASCOM IDE 157

It was tested without these resistors and no problems occurred.

Tip : when testing programmers etc. on the LPT it is best to buy an I/O card for
your PC that has a LPT port. This way you don’t destroy your LPT port that is on the
motherboard in the event you make a mistake!

The following picture shows the connections to make. Both a setup for the DT104 and
stand-alone PCB are shown.

I received the following useful information:

I have been having spurious success with the simple cable programmer from Sample
Electronics for the AVR series.
After resorting to hooking up the CRO I have figured it out (I think). When trying to
identify the chip, no response on the MISO pin indicates that the Programming Enable
command has not been correctly received by the target.

The SCK line Mark/Space times were okay but it looked a bit sad with a slow rise time
but a rapid fall time. So I initially tried to improve the rise
time with a pull-up. No change ie still could not identify chip. I was about to add some
buffers when I came across an Atmel app note for their serial programmer "During
this first phase of the programming cycle, keeping the SCK line free from pulses is
critical, as pulses will cause the target AVR to loose synchronization with the
programmer. When synchronization is lost, the only means of regaining
synchronization is to release the RESET line for more than 100ms."

I have added a 100pF cap from SCK to GND and works first time every time now. The
SCK rise time is still sad but there must have been enough noise to corrupt the initial
command despite using a 600mm shielded cable.

3.59.1.4 KITSRUS Programmer


The K122 is a KIT from KITSRUS. (www.kitsrus.com)

The programmer supports the most popular 20 and 40 pins AVR chips.

On the Programmer Options tab you must select this programmer and the COM port it

© 2021 MCS Electronics


158 BASCOM-AVR

is connected to.

On the Monitor Options tab you must specify the upload speed of 9600, Monitor delay
of 1 and Prefix delay 1.

When you press the Program button the Terminal Emulator screen will pop up:

A special toolbar is now visible.


You must press the Program enable button to enable the programmer.
When you enable the programmer the right baud rate will be set.
When you are finished you must press the Enable button again to disable it.
This way you can have a micro connected to your COM port that works with a
different BAUD rate.
There is an option to select between FLASH and EEPROM.
The prompt will show the current mode which is set to FLASH by default.

The buttons on the toolbar allow you to :


ERASE, PROGRAM, VERIFY, DUMP and set the LOCK BITS.
When DUMP is selected you will be asked for a file name.
When the DUMP is ready you must CLOSE the LOGFILE where the data is stored. This
can be done to select the CLOSE LOGFILE option form the menu.

THIS PROGRAMMED IS MARKED FOR REMOVAL. Send a note to support if you use it.

3.59.1.5 MCS Universal Interface Programmer


The MCS Universal Interface programmer allows you to customize the pins that are
used for the ISP interface. The file prog.settings stores the various interfaces.

The content :

;how to use this file to add support for other programmers

;first create a section like [newprog]

; then enter the entries:

; BASE= $hexaddress

© 2021 MCS Electronics


BASCOM IDE 159

; MOSI= address in form of BASE[+offset] , bit [,inverted]

; CLOCK= same as MOSI

; RESET=same as MOSI

; MISO=same as MOSI

; The bit is a numer that must be written to set the bit

; for example 128 to set bit 7

; Optional is ,INVERTED to specify that inverse logic is used

; When 128 is specified for the bit, NOT 128 will be written(127)

[FUTURELEC]

;tested and ok
BASE=$378
MOSI=BASE+2,1,inverted
CLOCK=BASE,1
RESET=BASE,2
MISO=BASE+1,64

[sample]
;tested and ok
BASE=$378
MOSI=BASE,1
CLOCK=BASE,8
RESET=BASE,4
MISO=BASE+1,128,INVERTED

[stk200]
;tested and ok
BASE=$378
MOSI=BASE,32
CLOCK=BASE,16
RESET=BASE,128
MISO=BASE+1,64

Four programmers are supported : Futurelec, Sample and STK200/STK300 and


WinAVR/ SP12.
To add your own programmer open the file with notepad and add a new section
name. For the example I will use stk200 that is already in the file.

[stk200]
The LPT base address must be specified. For LPT1 this is in most cases $378. $ means
hexadecimal.

The pins that are needed are MOSI, CLOCK, RESET and MISO.
Add the pin name MOSI =

After the pin name add the address of the register. For the STK200 the data lines are

© 2021 MCS Electronics


160 BASCOM-AVR

used so BASE must be specified. After the address of the register, specify the bit
number value to set the pin high. Pin 0 will be 1, pin 1 would be 2, pin 2 would be 4
etc. D5 is used for the stk so we specify 32.

When the value is set by writing a logic 0, also specify, INVERTED.


After you have specified all pins, save the file and restart BASCOM.
Select the Universal Programmer Interface and select the entry you created.
After you have selected an entry save your settings and exit BASCOM. At the next
startup of BASCOM, the settings will be used.

The following picture shows the LPT connector and the relation of the pins to the LPT
registers.

Always add your entry to the bottom of the file and email the settings to
[email protected] so it can be added to BASCOM.

3.59.1.6 STK500 Programmer


When you select the STK500 programmer, BASCOM will run the file named stk500.
exe that is installed with AVR Studio.

That is why you have to specify the file location of the stk500.exe
The normal STK500 support will erase, and program the flash.
The STK500.EXE supports a number of Atmel programmers which all use the STK500
V1 or V2 protocol.
For the AVR ISP mkII, you need to supply the serial number of the USB programmer.
The USB port will be used then instead of the serial port.

You can also use the native driver which does not use/need the stk500.exe
If you select this programmer, you will see the following window when you launch the
programmer with F4(manual program)

© 2021 MCS Electronics


BASCOM IDE 161

When the source code is compiled and the BIN file exists, it is loaded automatic into
the buffer.
When an EEPROM image file exists (EEP), it is loaded too into the EEPROM buffer.
When it does not exist you will see a warning which you can ignore.
When the target device is not read yet, the CHIP will be unidentified which is marked
as ???.
In the status bar you can see the loaded file, and the size of the file. Notice that
16000 will be shown as 16 KB.
You can select the EEPROM-TAB to view the EEPROM image. Memory locations can be
altered. Select a cell, and type a new value. Then press ENTER to confirm. You can
immediately see the new value.
When you select the Lock and Fusebits-TAB the lock and fuse bits will be read.

© 2021 MCS Electronics


162 BASCOM-AVR

As you can see that as soon as the target chip is determined, the chip name is shown
under the tool bar.
The FLASH size and EEPROM size are shown also.
As soon as you alter a lock or fuse bit, the corresponding Write-button will be
enabled. You need to click it to write the new value. The lock and fuse bits are read
again so you can see if it worked out. The lock and fuse bits shown will depend on the
used chip. Every chip has different fuse bits. Some fuse bits can not be altered via the
serial programming method. The native stk500 driver uses the serial programming
method. Some fuse bits require the parallel or high voltage programming method. For
example the fuse bit 'enable serial downloading' can not be changed with the serial
programming method.
Fuse bits of interest are : the clock divider and the oscillator fuse bits. When you
select a wrong oscillator fuse bit (for example you select an external oscillator) the
chip will not work anymore till you connect such an external oscillator! Of course a
simple 555 chip can generate a clock signal you can use to 'wake' a locked chip.

Once you have all settings right, you can press the 'Write PRG' button which will
insert some code into your program at the current cursor position. This is the $PROG
directive.
For example : $prog &HFF , &HED , &HD0 , &HFF
When you compile your program with the $PROG 594 directive it will generate a PRG
file with the lock and fuse bit settings.
If you then auto program(see later) a chip, it will use these settings.
$PROG is great to load the right lock and fuse bits into a new chip. But be careful : do
not enable $PROG till you are done with development. Otherwise programming will be
slow because of the extra reading and writing steps.

© 2021 MCS Electronics


BASCOM IDE 163

The following menu options are available:

Option Description
File
Exit Close programmer.

Buffer
Clear Clear buffer. Will put a value of 255 (FF hex) into each memory
location. When the FLASH-TAB has the focus, the FLASH buffer
will be cleared. When the EEPROM-TAB has the focus, the
EEPROM buffer will be cleared. 255 is the value of an empty
memory location.
Load from File This will shown an open file dialog so you can select a binary
file (BIN)
The file is loaded into the buffer.
Save to File Will save the current buffer to a file.
Reload Reloads the buffer from the file image.

Chip
Identify Will attempt to read the signature of the chip. When the
signature is unknown(no DAT file available) or there is no chip
or other error, you will get an error. Otherwise the chip name
will be shown.
Write buffer to chip This will write the active buffer(FLASH or EEPROM) into the
chip.
Read chipcode When the chip lock bit is not set you can read the FLASH or
EEPROM into the buffer.
Blank check Check if the chip FLASH or EEPROM is empty.
Erase Erases the chip FLASH. It depends on the fusebits if the
EEPROM is erased too. Normally the EEPROM is erased too but
some chip have a fuse bit to preserve EEPROM when erasing
the chip.
A chip MUST be erased before it can be programmed.
Verify Checks if the buffer matches the chip FLASH or EEPROM.
Auto program This will eraser, and program the FLASH and EEPROM and
if $PROG is used, it will set the lock and fusebits too.

Under Options, you can find a setting to change the clock frequency.

The clock frequency should not be higher then a quarter of the oscillator
frequency.
This means that a chip with an internal 8 MHz oscillator which has the 8-divider fuse
enabled, will have a clock frequency of 1 Mhz.
The programming clock may not exceed 250 KHz in this case.

STK500 board
When using the STK500 board, you can change the target voltage and the reference
voltage. In 2081 you can also change the board oscillator frequency.
The BOARD menu has a sub menu named STK500. This sub menu has a few options :
- Read Settings : you should do this first
- Vtarget : this is the target voltage. Make sure the chip can handle the voltage you
enter

© 2021 MCS Electronics


164 BASCOM-AVR

- Vref : this is the reference voltage. It may not exceed Vtarget.


- Osc : this is the oscillator frequency.
- Write settings : this will write the new settings to the STK500 board. After doing so,
read back the settings to see if the values are correct. You will notice that not all
values you enter are possible. This is exactly the same when you use AVR Studio.

3.59.1.7 Lawicel BootLoader


The Lawicel Boot loader must be used with the StAVeR. The StAVeR contains a boot
loader so you only need a serial interface, no parallel programmer or other
programmers.

You can also use Hyper terminal.

When you have selected the Lawicel Boot loader from the Options, Programmer, the
following window will appear when you press F4.

As the window suggests, press the reset button on the activity board or StAVeR, and
the chip will be programmed. This is visible by a second wind that will be shown
during programming.

When the programming succeeds, both windows will be closed.

When an error occurs, you will get an error message and you can clock the Cancel
button in order to return to the Editor.

THIS PROGRAMMED IS MARKED FOR REMOVAL. Send a note to support if you use it.

3.59.1.8 AVR ISP Programmer


The AVRISP programmer is AVR ICP910 based on the AVR910.ASM application note.

The old ICP910 does not support Mega chips. Only a modified version of the AVR910.
ASM supports Universal commands so all chips can be programmed.

The new AVRISP from Atmel that can be used with AVR Studio, is not compatible! You
need to select STK500 programmer 160 because the new AVRISP programmer from
Atmel, uses the STK500 protocol.

© 2021 MCS Electronics


BASCOM IDE 165

When you do not want to use the default baud rate that AVR910 is using, you can
edit the file bascavr.ini from the Windows directory.
Add the section [AVRISP]
Then add: COM=19200,n,8,1

This is the default. When you made your own dongle, you can increase the baud rate

You need to save the file and restart BASCOM before the settings will be in effect.

3.59.1.9 USB-ISP Programmer


The USB-ISP Programmer is a special USB programmer that is fully compatible with
BASCOM's advanced programmer options.
Since many new PC's and especial Laptop's do not have a parallel programmer
anymore, MCS selected the USB-ISP programmer from EMBUD.

The drivers can be downloaded from the MCS Electronics website.


Please download from
http://www.mcselec.com/index.php?option=com_docman&task=doc_download&gid=204&Ite
mid=54
After downloading, unzip the files in the BASCOM-AVR application directory in a sub
directory named USB.

When you connect the programmer, Windows (98, ME, 2000, XP) will recognize the
new device automatically.

Then the Hardware wizard will be started :

© 2021 MCS Electronics


166 BASCOM-AVR

Select 'No, not this time' and click Next, as there is no driver at Microsoft's web.

The Wiz will show :

You need to select 'Install from a list or specific location' and click Next.

© 2021 MCS Electronics


BASCOM IDE 167

You can specify the path of the USB driver. This is by default :

C:\Program Files\MCS Electronics\BASCOM-AVR\USB

Use the Browse-button to select it, or a different location, depending on your installation.

As the driver is not certified by Micros ft, you will see the following window:

You need to select 'Continue Anyway'. A restore point will be made if your OS
supports this and the driver will be installed.
After installation you must see the following window :

© 2021 MCS Electronics


168 BASCOM-AVR

After you press Finish you will see Windows can use the programmer :

In BASCOM , Options, Programmer you can select the new programmer now.

© 2021 MCS Electronics


BASCOM IDE 169

New models of the USB programmer allow to set the speed.


The USB-ISP programmer is very quick and supports all options that the Sample
Electronics and STK200 programmers support. It is good replacement for the STK200.

When you use other USB devices that use the FTDI drivers, there might occur a
problem. Manual install the drivers of these other devices, then install the USB-ISP
driver.

USB-ISP on VISTA
For Vista and Vista 64, please follow the this installation description.

© 2021 MCS Electronics


170 BASCOM-AVR

When connection the ISP-PROG I to your PC the following window will show up. Here
I have to select the top selection: Locate and Install driver software (recommended)
Vista starts it search for the driver and will come finally with the question to Insert
the driver disk.

© 2021 MCS Electronics


BASCOM IDE 171

As we have no driver CD, you have to select: I don’t have the disc. Show me other options

Now we select the Browse selection and locate the driver folder.

© 2021 MCS Electronics


172 BASCOM-AVR

And select Next button.

As Vista 64 only allows certified drivers the following message will pop-up.

Just select Install this driver software anyway and Vista 64 will now start with installing the
driver. Be patient as it depends on your system configuration how long it will take.

© 2021 MCS Electronics


BASCOM IDE 173

Finally Vista 64 will tell you that the driver is installed. To check your configuration you can go to
your device manager to see if it is there.

© 2021 MCS Electronics


174 BASCOM-AVR

3.59.1.10 MCS Bootloader


The MCS Boot loader is intended to be used with the $LOADER 572 sample.
It uses the X-modem Checksum protocol to upload the binary file. It works very
quick.
The Boot loader sample can upload both normal flash programs and EEPROM images.
The Boot loader sends a byte with value of 123 to the AVR Boot loader. This boot
loader program then enter the boot loader or will jump to the reset vector (0000) to
execute the normal flash program.

When it receives 124 instead of 123, it will upload the EEPROM.


When you select a BIN file the flash will be uploaded. When you select an EEP file, the
EEPROM will be uploaded.

The Boot loader has some specific options.

© 2021 MCS Electronics


BASCOM IDE 175

BOOTSIZE
You can choose the boot size which is 1024 for the BASCOM $LOADER example.
Since this space is used from the normal flash memory, it means your application has
1024 less words for the main application. (A word is 2 byte, so 2KB less)
The XMEGA has a separate boot space so for Xmega you can set the value to 0.

RESET
The boot loader is started when the chip is reset. Thus you need to reset the chip
after you have pressed F4(program). But when you have connected the DTR line to
the chip reset (with a MAX232 buffer) you can reset the chip automatically. You do
need to set the 'Reset via DTR' option then. You can also chose to use the RTS line.
When your program does not use the boot vector or needs a special sequence to
activate the loader, you can chose the soft reset. To send ASCII characters you can
embed them between brackets {}. For example {065} will be sent as the character A
or byte with value 65.

CLOSE
By choosing 'Close programmer window when ready' the window will be closed when
the loader returns 0.
In all other cases it will remain opened so you can look at a possible cause.

EEP
If an EEP (EEPROM image file) exists, the loader can send this file instead of the flash
binary file. If you enable this option, you will be asked if you want to send the EEP
instead of the BIN file.

After you have pressed F4 to following window will appear :

© 2021 MCS Electronics


176 BASCOM-AVR

As you can see the loader sends a byte with value of 123.
You need to reset the chip, and then you will see that the loader returned 123 which
means it received the value.
It will start the upload and you see a progress bar. After the loader is ready, you see
a finish code of 0.
A finish code of 0 means that all wend well.
Other finish codes will not close the window even if this option is enabled.
You need to manual close the window then.

ERROR CODES
-6001 - Bad format in file name
-6002 - file not found
-6003 - file not found in folder
-6004 - folder not found
-6005 - canceled
-6006 - time out
-6007 - protocol error
-6008 - too many errors
-6009 - block sequence error
-6016 - session aborted

The most likely error is -6006 when the bootloader is not present or does not respond
timely after the initial handshake. Increase the $timeout in the boot loader in that
case.

3.59.1.11 PROGGY
PROGGY is a popular USB programmer written by Red_Mamba.

You need to install it and make sure that the registry key :
HKEY_CURRENT_USER\Software\Red_Mamba\Atmel programator exists with
the parameter : InstallPath

InstallPath should point to the executable which name is atme.exe


When you install PROGGY, it will be handled for you. When you have an older version,
you need to update.

BASCOM will call the programmer with the following options : -p -s -e

© 2021 MCS Electronics


BASCOM IDE 177

The -e will cause the programmer to exit after the programming.

3.59.1.12 FLIP
FLIP is a free USB bootloader from Atmel. With FLIP you can program an AVR without
additional (ISP) programmer hardware.
Because it is a USB bootloader it only work with AVR with built in USB functionality.

FLIP is supported by the BASCOM-IDE so you can use it direct by pressing the
Program Chip (F4) button and download a HEX file.

FLIP can be downloaded from the Atmel site.


Search for "FLIP bootloader" on the Atmel Website for the latest version:
https://www.microchip.com/developmenttools/ProductDetails/flip

1. Download FLIP from Atmel Website


2. Install FLIP
3. In BASCOM-IDE Select FLIP from Options >>> Programmer , in order to program
quickly without the FLIP executable
4. Now you can press Program Chip (F4) to program the HEX file into the chip

As with other programmers, you press F4 to program the HEX file into the chip. A
small window will become visible.

A number of dialogs are possible:

In this case, you try to program a chip which is not supported by FLIP. The Mega88 is
not an USB chip so the error makes sense.

If you are using an USB AVR you could get following dialog box:
This dialog informs you about a missing DFU device and/or the device is not in boot
loader mode:

In this case, the boot loader is not found. You can run the boot loader by following
the sequence from the dialog box.
In order to make this work, the HWB (Hardware Bootloader Button) and RST (Reset
Button) input both need a small switch to ground.

© 2021 MCS Electronics


178 BASCOM-AVR

When HWB is pressed(low) during a reset, the boot loader will be executed.

Abbreviations:

• ISP: In-system programming


• RST: Rest
• USB: Universal serial bus
• DFU: Device firmware upgrade
• FLIP: Flexible in-system programmer

FAQ - Using FLIP with XMEGA-A3BU Xplained Board


from Atmel (under Windows 7 32-Bit)
1. Read Atmel App Note: AVR1916: USB DFU Boot Loader for XMEGA
2. Download FLIP
3. Install FLIP 3.4.5 or higher for Windows (Java Runtime Environment included)
4. Connect the USB Cable during pressing Switch0 SW0 (Hardware Bootloader
button) on the XMEGA-A3BU Xplained board
5. The USB Driver can be found in the FLIP Software directory (e.g.: C:\Program
Files\Atmel\Flip 3.4.5\usb)
6. You can also search for DFU ATXMEGA256A3BU in the Windows 7 device manager
and reinstall the driver by pointing it to this directory (e.g.: C:\Program
Files\Atmel\Flip 3.4.5\usb)
7. Then you will find this here in the device manager Atmel USB Devices >>>>
ATxmega256A3BU
8. In BASCOM-IDE Select FLIP from Options >>> Programmer , in order to program
quickly without the FLIP executable
9. Now you can press Program Chip (F4) to program the HEX file into the chip

If you see following dialog:

Just connect the USB Cable during pressing Switch0 SW0 on the XMEGA-A3BU
Xplained board
Hit OK button then the XMEGA will be programmed.

First example for XMEGA-A3BU board:

$regfile = "XM256A3BUDEF.DAT"
$crystal = 32000000 '32MHz
$hwstack = 64
$swstack = 40
$framesize = 80

Config Osc = Enabled , 32mhzosc = Enabled '32MHz


'configure the systemclock
Config Sysclock = 32mhz , Prescalea = 1 , Prescalebc = 1_1

© 2021 MCS Electronics


BASCOM IDE 179

Config P o r t e. 4 = Output
B a c k l i g h t A l i a s P o r t e. 4 'LCD Backlight
Config P o r t r. 0 = Output
Led0 A l i a s P o r t r. 0 'LED 0

Config P o r t r. 1 = Output
Led1 A l i a s P o r t r. 1 'LED 1

Do

Waitms 500
Reset Led0
S e t Led1

Waitms 500
S e t Led0
Reset Led1

Loop
End 'end program

FAQ - FLIP with BASCOM-IDE


On former versions like FLIP 3.3.1 there was on VISTA a problem with loading some
of the FLIP DLL's.
In case you get an error, copy the FLIP DLL's to the BASCOM application directory.
You need to copy the following files :
· atjniisp.dll
· AtLibUsbDfu.dll
· msvcp60.dll
· msvcrt.dll

You can also create a command file for that task like: flipDLLcopy.cmd to copy these
files.
The content of the command file :

copy "c:\program files\atmel\flip 3.3.1\bin\atjniisp.dll" .


copy "c:\program files\atmel\flip 3.3.1\bin\AtLibUsbDfu.dll" .
copy "c:\program files\atmel\flip 3.3.1\bin\msvcp60.dll" .
copy "c:\program files\atmel\flip 3.3.1\bin\msvcrt.dll" .
pause

The last line pauses so you can view the result. Notice the . (dot) that will copy the
file to the current directory, which is the reason that you need to run this file from the
BASCOM application directory.
You also need to adapt the version of FLIP in the command file.

In order to use BASCOM's FLIP support, you must have running FLIP successfully first
!
Here is a good tip from a user :

IMO he Flip 3.3.1 Installer is a little bit stupid.


The dll´s are located in the Path ...\Atmel\Flip 3.3.1\bin .
The Installer has set a correct Path-Variable in Windows for this path.
But, the libusb0.dll isn´t in that location. It is in ...\Atmel\Flip 3.3.1\USB !
So I moved the libusb0.dll into the \bin dir and Flip runs without the errors. (GRRRR)

In the ...\Atmel\Flip 3.3.1\USB dir I have also detected the missing .inf File.
After installing this, Windows detects the AT90USB162 and Flip can connect the

© 2021 MCS Electronics


180 BASCOM-AVR

device.

3.59.1.13 USBprog Programmer / AVR ISP mkII


The USBprog programmer is a neat small USB programmer which is fully compatible
with the AVR ISP mkII programmer.
When you select this programmer, you will get the same interface as for the STK500
native 160 programmer.
F4 will launch the programmer. For more details read the help section for the STK500
programmer.

When programming XMEGA chips the interface for the fuse bits will be different. See
STK600 184 programmer for a description.

The default clock is 125 KHz. This because most/all chips ship with a clock frequency
of 1 MHz. And since the clock frequency maximum is a quarter of the oscillator
frequency, the default is 125 KHz, low enough to be able to program all chips. Once
your chip runs at say 8 MHz, you can select 2 MHz as the maximum.

You must have the LIBSUSB 195 drivers installed on your PC. Without it, it will not
work.

Options
In the Configuration options you can adjust the clock speed and the timeout of the
USB.
When you are using USB 1.1 and a lot of devices that generate a lot of USB traffic,
you might need to increase the default timeout of 100 (msec).

XMEGA
When used in PDI mode, take care about the following for some of the processors:
JTAG is activated by default which preventing from using the PDI because both interfaced
share the same pins. In this case :
1 - Disable the JTAG before using the PDI. > You need a JTAG programmer
2 - Use a 47Kohm resistor to Pull down the clock pin to ground which allow you to have
both JTAG and PDI working simultaneously.

3.59.1.14 KamProg for AVR


KamProg for AVR is an USB programmer from Kamami.
You need to install the software that comes with the KamProg.
You can download the software from the web site of the manufacturer or from MCS
Electronics web shop Kamprog product page.
KamProg can be used with BASCOM but also with AVR Studio.

BASCOM will use the KamProg software to either automatic or manual program the
chip.
The Kamprog programmer works on Vista32 and Vista64 and requires no special
drivers. It has also been tested with Win7 and Win8 and Win8.1

© 2021 MCS Electronics


BASCOM IDE 181

The KamProg programmer is available from MCS Electronics webshop.

When you use Auto program, you will see a small progress window while the
processor is programmed.
When you chose manual program, you will see a familiar window, known from USB-
ISP.

When the source code is compiled and the BIN file exists, it is loaded automatic into
the buffer.
When an EEPROM image file exists (EEP), it is loaded too into the EEPROM buffer.
When it does not exist you will see a warning which you can ignore.
When the target device is not read yet, the CHIP will be unidentified which is marked
as ???.
In the status bar you can see the loaded file, and the size of the file. Notice that
16000 will be shown as 16 KB.

You can select the EEPROM-TAB to view the EEPROM image. Memory locations can be
altered. Select a cell, and type a new value. Then press ENTER to confirm. You can
immediately see the new value.
When you select the Lock and Fusebits-TAB the lock and fuse bits will be read.

© 2021 MCS Electronics


182 BASCOM-AVR

As soon the target chip is determined, the chip name is shown under the tool bar.
The FLASH size and EEPROM size are shown too.
When you alter a lock or fuse bit, the corresponding Write-button will be enabled. You
need to click it to write the new value. The lock and fuse bits are read again so you
can see if it worked out.
The lock and fuse bits shown will depend on the used chip. Every chip has different
fuse bits. Some fuse bits can not be altered via the serial programming method. For
example the fuse bit 'enable serial downloading' can not be changed using the serial
programming method.

Fuse bits of interest are : the clock divider and the oscillator fuse bits. When you
select a wrong oscillator fuse bit (for example you select an external oscillator) the
chip can not programmed anymore until you connect such an external oscillator! Of
course a simple 555 chip can generate a clock signal you can use to 'wake' a locked
chip.

Once you have all settings right, you can press the 'Write PRG' button which will
insert some code into your program at the current cursor position. This is the $PROG
directive.
For example : $prog &HFF , &HED , &HD0 , &HFF
When you compile your program with the $PROG 594 directive it will generate a PRG
file with the lock and fuse bit settings.
If you then auto program(see later) a chip, it will use these settings.
$PROG is great to load the right lock and fuse bits into a new chip. But be careful : do
not enable $PROG till you are done with development. Otherwise programming will be
slow because of the extra reading and writing steps.

The following menu options are available:

© 2021 MCS Electronics


BASCOM IDE 183

Option Description
File
Exit Close programmer.

Buffer
Clear Clear buffer. Will put a value of 255 (FF hex) into each memory
location. When the FLASH-TAB has the focus, the FLASH buffer
will be cleared. When the EEPROM-TAB has the focus, the
EEPROM buffer will be cleared. 255 is the value of an empty
memory location.
Load from File This will shown an open file dialog so you can select a binary
file (BIN)
The file is loaded into the buffer.
Save to File Will save the current buffer to a file.
Reload Reloads the buffer from the file image.

Chip
Identify Will attempt to read the signature of the chip. When the
signature is unknown(no DAT file available) or there is no chip
or other error, you will get an error. Otherwise the chip name
will be shown.
Write buffer to chip This will write the active buffer(FLASH or EEPROM) into the
chip.
Read chipcode When the chip lock bit is not set you can read the FLASH or
EEPROM into the buffer.
Blank check Check if the chip FLASH or EEPROM is empty.
Erase Erases the chip FLASH. It depends on the fusebits if the
EEPROM is erased too. Normally the EEPROM is erased too but
some chip have a fuse bit to preserve EEPROM when erasing
the chip.
A chip MUST be erased before it can be programmed.
Verify Checks if the buffer matches the chip FLASH or EEPROM.
Auto program This will eraser, and program the FLASH and EEPROM and
if $PROG is used, it will set the lock and fusebits too.

In the toolbar you can also alter the ISP clock frequency.

The clock frequency should not be higher then a quarter of the oscillator
frequency.
This means that a chip with an internal 8 MHz oscillator which has the 8-divider fuse
enabled, will have a clock frequency of 1 Mhz.
The programming clock may not exceed 250 KHz in that case.

3.59.1.15 USBASP
The USBASP is a popular USB programmer created by Thomas Fischl
The programmer uses a Mega8 or other AVR chip as an USB device.
You can find the programmer at Thomas website : http://www.fischl.de/usbasp

Make sure when programming the fuse and lock bits that the selected clock frequency
is not too high. The clock frequency of the ISP programmer should be less then one
quarter of the oscillator frequency. When your micro is running at 8 MHz, you can

© 2021 MCS Electronics


184 BASCOM-AVR

select up to 2 MHz. On the safe size, 125 KHz is always ok.


By default most AVR processors run at 8 MHz with an 8-divider resulting in 1 MHz
clock frequency. So 250 KHz is a safe value for most processors.

You can select various clock frequencies.

See also LIBUSB 195 for installation of LIBUSB

3.59.1.16 STK600
The STK600 is a development board from Atmel. It uses a similar protocol as the
STK500 and has an integrated USB programmer on board.
The programmer can be connected with a cable to the STK600 board itself, but also
to an external board.

The STK600 replaces the STK500 and is advised for XMEGA development. For regular
AVR chips we would recommend the STK500.

The STK600 has actual 3 different programmers on board : ISP, PDI and JTAG. the
ISP/PDI protocols are combined and placed on one connector.

When programming XMEGA chips, the BASCOM programmers will automatic switch to
the PDI protocol. The ISP protocol can not be used with XMEGA chips.
For other chips, (non-xmega), the ISP protocol will be used.
There are affordable PDI programmers available.

The following description is also true for the AVRISP/mkII programmer which also
supports the PDI protocol.

In order to use the STK600 protocol you need to have LIBSUSB 195 installed.

Identification

© 2021 MCS Electronics


BASCOM IDE 185

The BASCOM programmers always try to identify the chip before an action is
performed. This is needed to check the size and to check if your program is intended
for the selected chip.
It would not be a good idea for example to program an attiny13 with xmega128a1
code.

When you chose manual programming, you will get the following window:

As you can see, the binary image is loaded and if an EEPROM EEP binary image was
available it would have been loaded too.

When you click the Identify button, the programmer will read the device id. The same
will happen for any other action you chose.

© 2021 MCS Electronics


186 BASCOM-AVR

The Device ID is now read and you can see the ATXMEGA128A1 is detected.

The programmer has the same options as the STK500 programmer. Only the lock and
fuse byte differ for the Xmega.
When you select the Lock and Fuse bits, you will get a similar screen:

The XMEGA has one lock byte and 6 fuse byes named FUSE0-FUSE5.
Not all fuse bytes are used. The options depend on the XMEGA chip you use.

© 2021 MCS Electronics


BASCOM IDE 187

In the screen shot from above you can see that under the FUSE1 section, the
'Watchdog Window Configuration' is colored red.
When you change an option and move focus or enter, a change will result in the
option to be shown in red.

When you have selected all values you can select the WRITE button to write the lock
and fuse bytes.
After this the values will be read again and updated.

The WRITE PRG button will insert a $PROG directive into your code with all lock and
fuse bytes.

A description of the fuse bytes you can find in the PDF of the processor.

3.59.1.17 ARDUINO
The ARDUINO is a hardware platform based on AVR processors. ARDUINO boards/
chips are programmed with a bootloader. This bootloader is the old STK500 protocol,
not longer supported by Atmel in Studio. There are various programmers for
ARDUINO, AVRDUDE is probably the most versatile.

BASCOM also supports the ARDUINO/STK500 v1 protocol. the DTR/RTS lines are used
to reset the board.
You can program/read flash/EEPROM but you can not read/write fuse/lock bytes. The
STK500 bootloader for ARDUINO does not support this.

Under options you only need to select the programmer, and the COM port. Since an
FTDI chip is used on most ARDUINO boards, this is a virtual COM port. Only present
when the USB cable is connected to your PC.
Select 57600 baud for the baud rate. Older ARDUINO boards work with 19200 baud.

ARDUINO V2
The developers of the ARDUINO finally implemented the STK500V2 protocol. This
protocol is supported by Atmel and of course by BASCOM.
Select the ARDUINO STK500V2 programmer in BASCOM programmer options to use
this protocol.
A board like the MEGA2560 R3 uses this protocol and probably all newer AVR based
ARDUINO boards will support this protocol. The baud rate should be 115200 but could
be different for your board.

ARDUINO Leonardo
For some reason each arduino board seems to use a different bootloader method. The
leonardo implements a virtual COM port. When opened at 1200 baud, the board
resets into another virtual COM device with a different COM port number.
In BASCOM you need to chose the myAVR MK2 / AVR910 programmer since
Leonardo uses the AVR910 loader from Atmel.
You need to select the COM port that you get at Boot time. The baud is 115200.
To program, press the reset button, wait till the USB is enumerated and the Virtual
COM port is ready, then press F4 to program the processor.

© 2021 MCS Electronics


188 BASCOM-AVR

Using Bascom-AVR with Arduino Optiboot Bootloader


(under Windows 7)

For more information on Optiboot visit following website: http://code.google.com/p/optiboot/

1. Download AVRDUDE from http://www.nongnu.org/avrdude/


2. Latest Windows Version (April 2012): avrdude-5.11-Patch7610-win32.zip
Complete link:
http://download.savannah.gnu.org/releases/avrdude/avrdude-5.11-Patch7610-win32.zip
3. Create a folder like c:\AVRDUDE
4. Copy the content of avrdude-5.11-Patch7610-win32.zip in this new folder
5. Open Bascom-AVR
6. Click on Options >>> Programmer
7. Choose External programmer
8. Checkmark Use HEX file
9. Include the path to avrdude.exe
10. User Parameter:
-C c:\avrdude\avrdude.conf -p m328p -P com19 -c arduino -b 115200 -U flash:w:{FILE}:i

Explanation of Parameter:
-C
c:\avrdude\avrdude.conf The config file tells avrdude about all the different ways it can talk to
the programmer.

© 2021 MCS Electronics


BASCOM IDE 189

-p
m328p This is just to tell it what microcontroller its programming. For example, if you are
programming an Atmega328p, use m328p as the partnumber

-P
com19 This is the communication port to use to talk to the programmer (COM19) in this case.
Change it to your COM port.
-c
arduino
Here is where we specify the programmer type, if you're using an STK500 use stk500, use
arduino for Optiboot
-b
115200
Set serial baudrate for programmer. Use 115200 baud for Optiboot.
-U
flash:w:{FILE}:i
You define here:
· the memory type: flash or eeprom (this could be also hfuse, lfuse or effuse if you want
to verfiy this)
· r (read), w (write) or v (verify)
· Use {FILE} to insert the filename {EEPROM} to insert the filename of the generated EEP
file.
· i = Intel Hex File

After clicking on the F4 (Program Chip) Button in Bascom-AVR you see the CMD window of
Windows 7 until AVRDUDE is ready flashing the Arduino.

Complete documentation of AVRDUDE parameters:


http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions

© 2021 MCS Electronics


190 BASCOM-AVR

3.59.1.18 BIPOM MINI-MAX/C


The BiPOM MINI-MAX/AVR-C board from www.bipom.com can be set into PROGRAM
and RUN modes.
In programming mode, the board uses the STK500V2 protocol for program
downloads.
Selecting the BiPOM MINI-MAX/AVR-C programmer and the COM port is sufficient.
Baud rate is fixed at 115200 baud.
The IDE automatically handles switching between PROGRAM and RUN modes.
If you press F4, the board will be put in PROGRAM mode, the firmware will be
uploaded, and the board will be set back to RUN mode.

3.59.1.19 mySmartUSB Light


The mySmartUSB Light programmer is an affordable and versatile ISP programmer. It
supports the AVR911 and STK500V2 protocols.
The mySmartUSB Light programmer is available form the MCS Webshop. It is an USB
programmer that requires a virtual COM port driver. When your PC is connected to
the internet, the driver will be installed automatically by Windows.

The programmer is either shipped with the AVR911 protocol or the STK500V2
protocol.
The support in BASCOM is for the STK500V2 mode.
MyAVR has a simple utility that you can use to check and/or change the firmware.
Download it here

When you run the tool you get a window similar to this one:

© 2021 MCS Electronics


BASCOM IDE 191

The window above shows that the current firmware is STK500 which is OK.
When the version is AVR911, you can change it by selecting the STK500 1.11.xxxx in
the list and click 'BRENNEN' (burning)

The tool also allows to set the voltage of the programmer to 3V or 5V.
And you can turn on the power while burning (this will use internal USB power)

The above options are available from BASCOM as well.


When you press manual program, the following window will be shown:

© 2021 MCS Electronics


192 BASCOM-AVR

The usual options are available. Please read STK500 Programmer 160 for more info.

The MyAVR programmer has a special menu accessible from the Board menu.
Board, MyAVR, Voltage, 3V or 5V. This selects the output voltage of the programmer
Board, MyAVR, Power On Program. This option can be set and cleared. When set, the
programmer will route power to the target circuit during programming.
Board, MyAVR, Board Power, turn on/off. These options can be used to power the
target board while not programming.

When using the options to power the circuit, you should notice that this power is
taken from the USB bus. You should take care that your circuit does not draw too
much current.

For the manual see : http://www.myavr.info/download/produkte/mysmartusb_light/


techb_mySmartUSB-light_de_en.pdf

3.59.1.20 UPDI Programmer


The UPDI programmer is a serial based programmer.
You need to select 115200 BAUD and the COM port which is connected to the UPDI
interface.
In version 2084 you can select up to 225000 baud. This is the maximum

© 2021 MCS Electronics


BASCOM IDE 193

recommended baud from microchip with the default clock.

The UPDI interface is very simple : all you need is a TX, RX and a resistor.
Connect TX from the PC UART to a 4K7 resistor. The other side of the resistor is
connected to the PC RX and to the UPDI pin of the processor.
We use DTR to switch the TX and RX from the PC to the processor. This allows to use
the PC COM port to be used for serial communication and as a UPDI programmer.

Note : some modules will not give proper signals. A 1K resistor will bring better
results.

Please notice that you need a MAX232 or other level converter between the PC
communication pins to create the proper voltage level! Like the circuit shown below.

The programmer works similar as the other supported programmers : you can
program the FLASH, EEPROM and the fuse/lock bytes

In version 2083 you can also write the fuse bytes.

When you change the values of a fuse the WRITE-FUSES button will be enabled.
When you change the value of the LOCK fuse, the WRITE-LOCK bits button will be
enabled.
When you change the value of the user fuses, the WRITE USER ROW button will be

© 2021 MCS Electronics


194 BASCOM-AVR

enabled.

When you write the fuses, the fuse values will be re-read (refreshed). And the same
for the other fuses.

A typical connection for the UPDI programmer :

A MAX232 level converter will convert the RS232 levels to 5V.


The TX from the PC/max232 is connected with a 4K7(or 1K) resistor to the UPDI pin.
The RX from the PC/max232 is connected directly to the UPDI pin.

you can also use an USB virtual com port chip such as the FT232 or CP2102.

Using a serial port just for programming is a bit of a waste. Often you also like to
have serial communications.
So a more practical programmer will switch the TX/RX lines between the UPDI pin
and the TX-RX USART pins of the processor.

Notice that the USB circuit shown is not complete, you should check it with the chip of
your choice like FT232RL, CP2102, etc. The main purpose of the USB part is to show
the TX/RX and DTR pins.

The TX pin and RX pins are connected to a 4053 switch. This is an analog switch. The
DTR line selects the XYZ-0 or XYZ-1 side of the switch.
The UPDI pin is also connected to a MUX switch. This simple circuit now switches
between the UPDI mode and the TX and RX pins of the processor.
The BASCOM-UPDI programmer will automatically switch the DTR line.

© 2021 MCS Electronics


BASCOM IDE 195

3.59.2 LIBUSB

Using USB programmers in BASCOM-AVR


Please read this document completely before starting to install software.

Like every other USB device, an USB programmer requires a windows driver. Some
programmers use drivers that are provided (built into) by windows. For example the
KamProg uses the HID class and does not require an additional third party driver.

A programmer like the AVRISP mkII does need an additional driver. This device driver
is installed when you install AVR Studio.
Studio is using device drivers from JUNGO.
When you plug in the programmer and Windows informs you that it requires a driver
you know that you need to install a third party driver.
When Windows does not complain it will use a driver already available on your PC.

Most USB devices need software installed before you plug them in for the first time.
In many cases there is a warning sticker that you should first install the software.

BASCOM uses LIBUSB to access USB devices. LIBUSB is available as a device driver
or as a filter driver.
When your device is using a device driver you must access the device with a filter
driver.
Some devices do not have a vendor supplied driver (USBASP programmer) and those
require a device driver.

Scenario one : you have a 32 bit or 64 bit OS and have


a product that uses a device driver.
In this example we use the AVRISP mkII that is supported by AVR Studio. When you
do not have AVR Studio installed you can download it from Atmels website for free.
The original programmer comes with a CD-ROM too. But many imitation/self build
devices exist that do not come with a CD. For those you need to download and install
AVR Studio.

The next step is to plug your programmer, and see if it works with AVR Studio.
Windows will recognize it, and install the device driver.
When windows is ready, press the connect button in Studio.

© 2021 MCS Electronics


196 BASCOM-AVR

If you open Studio, and press the CON(nection) button, the window shown above will
open.
Now select your programmer, in this sample AVRISP mkII and press Connect

When it functions, a new window will open

© 2021 MCS Electronics


BASCOM IDE 197

You can select the device, the programming mode and ISP frequency. This frequency
should be 125 KHz (or better said, should not exceed a quarter of the chip oscillator
frequency).

When you do not get this window but you return to the connection window, it means
your programmer is not working.
You have to solve this first before you can continue.
The programmer will only work in BASCOM when it functions with the original
software!

In the windows device manager, you can find this info: (right click Computer, select
manage, and chose device manager)

© 2021 MCS Electronics


198 BASCOM-AVR

The screen above shows the JUNGO usb driver which Atmel AVR Studio uses and the
AVRISP mkII driver for the AVRISP mkII.
If you install AVR Studio with the USB drivers, it will install JUNGO and the WinDriver.
The AVRISP mkII entry you only get when you plug the programmer.

To make it work with BASCOM, you need to install LIBUSB. LIBUSB is used by many
different programs. Atmels FLIP is using it too. So there is a big change that it is
available on your system already.
You can install LIBUSB as a FILTER driver or a DEVICE driver.
We install the FILTER driver, so we can use the programmer with Studio AND bascom.

Before you install LIBUSB it is a good idea to make a restore point.

When installing the USB driver, disconnect ALL USB devices. Obvious, you can
not install from an USB flash drive since this is an USB device as well.

You can read about LIBUSB and download it from :


http://sourceforge.net/apps/trac/libusb-win32/wiki
The last version is :
http://sourceforge.net/projects/libusb-win32/files/libusb-win32-releases/1.2.4.0/libus
b-win32-devel-filter-1.2.4.0.exe/download

Notice that this an executable you can install. You MUST have ADMIN rights when you
install this executable.

After LIBUSB has been installed you can test if it is functional.

- Look in the Program Files\LibUSB-Win32 folder (also named on Windows-7 64 bit


!!!)
You will find a sub folder named bin which contains a number of executables.

© 2021 MCS Electronics


BASCOM IDE 199

- Run the testlibusb-win.exe application. When LIBUSB is functional you will see a
screen with all USB devices.
When it does not work, try to install again with compatibility mode set to XP SP2.
Do this by selecting the the setup exe file properties, and select 'Compatibility'.

Click Apply and/or OK. And run setup again.

On Windows 7 - 64 bit, this was NOT required.

Once the testlibusb-win.exe works, you can continue to the next step.

Install the filter driver for the device


You need to install a filter driver for your programmer. Each different programmer
requires it's own filter driver. So you must repeat these steps if you have different
programmers.
- Plug in your programmer if it was not plugged in yet
- Run the install-filter-win.exe application from the BIN folder.
- You will see this window:

© 2021 MCS Electronics


200 BASCOM-AVR

Select 'Install a device filter' and press Next.

Select the programmer and press Install.

After some moments, you will get a confirmation:

© 2021 MCS Electronics


BASCOM IDE 201

Now the programmer will work in BASCOM. Just select the proper programmer, and
timeout of 100 ms. You can try lower time outs too to make it quicker. When you get
errors, increase the time out. 100 ms should do for all programmers.

Scenario two: you do not have a device driver.


In this case you can follow scenario one till the filter driver installation.
Instead of running install-filter-win.exe , you will run inf-wizard.exe.

Press Next. And the following window will be shown.

© 2021 MCS Electronics


202 BASCOM-AVR

As you can see, the USBASP was inserted in this sample. Select it (or your
programmer) and press Next.

Press Next again and select a folder to store the device driver files.
These files are required to install the device.

© 2021 MCS Electronics


BASCOM IDE 203

After you have saved the files, you have the option to install the driver. Press Install
Now.. button to do so.

When ready :

Final note
The USB-ISP programmer form EMBUD, uses drivers from FTDI. It does not require
LIBUSB.
The Kamprog programmer from KAMAMI uses a HID class and does not require
LIBUSB.

Some devices gave a problem in 1.2.3.0. This problem is solved in 1.2.4.0.


http://sourceforge.net/projects/libusb-win32/files/libusb-win32-releases
/1.2.4.0/libusb-win32-devel-filter-1.2.4.0.exe/download

© 2021 MCS Electronics


204 BASCOM-AVR

3.60 Options Monitor


With this option you can modify the monitor settings.

OPTION DESCRIPTION
Upload Selects the baud rate used for uploading
speed
Monitor String that will be send to the monitor before the upload starts
prefix
Monitor String that us sent to the monitor after the download is completed.
suffix
Monitor Time in milliseconds to wait after a line has been sent to the monitor.
delay
Prefix delay Time in milliseconds to wait after a prefix has been sent to the
monitor.

3.61 Options Printer


With this option you can modify the printer settings.

OPTION DESCRIPTION
Font Printer font to use when printing
Setup Click to change the printer setup
Color Will print in color. Use this only for color printers.
Wrap lines Wrap long lines. When not enabled, long lines will be partial shown.
Print Print a header with the filename.

© 2021 MCS Electronics


BASCOM IDE 205

header
Line Will be the line number before each line.
numbers
Syntax Enable this to use the same syntax highlighting as the editor
Left margin The left margin of the paper.
Right The right margin of the paper.
margin
Top margin The top margin of the paper.
Bottom The bottom margin of the paper.
margin

3.62 Options Select Settings File


The options are stored in a file named bascom-avrxxxx.xml
The xxxx represent the version. For example 2083.
When you click Help, About, you can click the XML data link that will show you where
the file is stored.

In order to make it possible to use different settings file, you can rename these files.
You can select the actual settings file using this menu option.
When you select this option, the status bar will show the current selected file.
This file will also be loaded when you run bascom.

A File Dialog will open and show all XML files. You need to select a bascom-avr xml
file.

You can use this option after you have performed an update. Each update will have
its own settings file. That way you can use multiple versions that each have their own
settings file.

The following dialog window is shown :

The current option file is show : d:\users\mark\AppData\Roaming\MCS

© 2021 MCS Electronics


206 BASCOM-AVR

Electronics\bascom-avr2082.xml
This location is also shown when you click the XML data folder link in the Help, About
window

At the left you can view all the xml files.


When you select a file, the COPY and SELECT buttons will be enabled.
By using the COPY button you can make a backup of the selected option file.

You must give the file a different name. When the file is created, it will be shown in
the list.

When you use the SELECT button, you select the new option file. This is reflected at
the CURRENT OPTION FILE value in the top of the window.

The CUSTOM location can be used to store your option file at a custom location. You
can enter a file and location or use the button to browse to the file.
You need to click the SELECT CUSTOM button to select this file as the new custom
option file.

Click the CLOSE button to close the window.

3.63 Window Cascade


Cascade all open editor windows.

© 2021 MCS Electronics


BASCOM IDE 207

3.64 Window Tile


Tile all open editor windows horizontally.

© 2021 MCS Electronics


208 BASCOM-AVR

3.65 Window Tile Vertically


Tile all open editor windows vertically.

3.66 Window Arrange Icons


Arrange the icons of the minimized editor windows.

3.67 Windows Maximize All


Maximize all open editor windows.

3.68 Window Minimize All


Minimize all open editor windows.

© 2021 MCS Electronics


BASCOM IDE 209

3.69 Help About


This option shows an about box as shown below.

Your serial number is shown on the third line of the about box.
You will need this when you have questions about the product.

The compiler and IDE version numbers are also shown.

When you click the App data dir link, the folder which contains the BASCOM settings
will be opened:

It contains the bascom-avr.xml file with all settings and the bascavr.log file. When
you need support, you might be asked to email these files.

© 2021 MCS Electronics


210 BASCOM-AVR

When you need support, also click the Copy-button. It will copy the following info to
the clipboard, which you can paste in your email :

Dont forget that Serial numbers should not be sent to the user list.
Make sure you sent your email to support and not a public list !

Compiler version :1.11.8.3


IDE version :1.11.8.5
Serial number :XX-XXXX-XXXXX
Windows OS :Microsoft Windows XP
Windows SP :Service Pack 2
Explorer :7.0.5730.11
Company :MCS
Owner :Mark Alberts
Windows dir :C:\WINNT
App data dir :C:\Documents and Settings
System dir :C:\WINNT\system32

When you click the support link, your email client will be started and an email to
[email protected] will be created.

Click on Ok to return to the editor.

3.70 Help Index


Shows the BASCOM help file.

When you are in the editor window, the current word selected or by the cursor will be
used as a keyword.
Notice that when the help window is small, you might need to make the help window
bigger to show the whole content.

The help contains complete sample code and partial sample code.
In all cases the samples are shown to give you an idea of the operation. When trying
a program you should always use the samples from the SAMPLES directory. These are
updated and tested when new versions are published. The (partial) samples are not
all updates, only when they contain errors. So the samples from the help might need
some small adjustments while the samples form the SAMPLES dir will work at least on
the used chip.

3.71 Help MCS Forum


This option will start your default Web browser and direct it to http://www.mcselec.
com/index2.php?option=com_forum&Itemid=59

This forum is hosted by MCS Electronics. There are various forums available. You can
post your questions there. Do not cross post your questions on multiple forums and to
support.

The forum is available for all users : demo or commercial users.


Note that everything you write might be on line for ever. So mind your language.

Users of the commercial version can email MCS support.

© 2021 MCS Electronics


BASCOM IDE 211

The forum allows uploads for code examples, circuits etc.


If you try to abuse the forum or any other part of the MCS web, you will be banned
from the site.

3.72 Help MCS Shop


This option will start your default web browser and direct it to :http://www.mcselec.
com/index.php?option=com_phpshop&Itemid=1

You can order items and pay with PayPal. PayPal will accept most credit cards.

Before you order, it is best to check the resellers 1710 page to find a reseller near you.
Resellers can help you in your own language, have all MCS items on stock, and are in
the same time zone.

© 2021 MCS Electronics


212 BASCOM-AVR

Before you can order items, you need to create an account.


Read the following about the new website : http://www.mcselec.com/index.php?
option=com_content&task=view&id=133&Itemid=1

3.73 Help Support


This option will start your default browser with the following URL :

http://www.mcselec.com/support-center/

It depends from your browser settings if a new window or TAB will be created.
At the support site you can browse articles. You can also search on keywords.

3.74 Help Knowledge Base


This option will ask you to enter a search string.

This search string will be passed to the MCS support site.


The above example that searches for "FUSEBIT" will result in the following :

© 2021 MCS Electronics


BASCOM IDE 213

You can click one of the found articles to read it.

3.75 Help Credits


BASCOM was "invented" in 1995. Many users gave feedback and helped with tips,
code, suggestions, support, a user list, and of course with buying the software.
The software improved a lot during the last 25 years and will so during the next
decade.

While it is impossible to thank everybody there are some people that deserve credits :

· Peter Maroudas. He wrote and tested the FT80x FTDI display support. FT800
support would not exist without him.
·
· Josef Franz Vögel. He wrote a significant part of the libraries in BASCOM-AVR.
He is also author of AVR-DOS.

· Dr.-Ing. Claus Kuehnel for his book 'AVR RISC' , that helped me a lot when I
began to study the AVR chips. Check his website at http://www.ckuehnel.ch

· Atmel, who gave permission to use the AVR picture in the start up screen. And
for the great tech support. Check their website at http://www.atmel.com

· Brian Dickens, who did most of the Beta testing. He also checked the
documentation on grammar and spelling errors. (he is not responsible for the
spelling errors i added later :-) )

· Jack Tidwell. I used his FP unit for singles. It is the best one available.

© 2021 MCS Electronics


214 BASCOM-AVR

3.76 Help Update


The manual update process is explained here 55 .
The Help Update is an automated version.

The DEMO version can not be updated. You can however install the full version into
the DEMO folder.

In order to do a successful update you need the following :


- license validated in the register (https://register.mcselec.com)
- working internet connection.
- firewall and anti virus software must allow BASCOM to connect to the internet

When you click Help, Update, the following window will be shown:

You can select if you want to update BasCom or the Add-On's.


By default BasCom is selected.

BasCom Update
You need to click the START button to start the actual update process.

When there are unsaved files, you will get an error message :

© 2021 MCS Electronics


BASCOM IDE 215

Your work/project must be saved since as soon the update download is finished, the
setup will be executed and BASCOM is closed.

When there are no unsaved files, the current version will be checked.

Checking for update...


Current version : 2.0.8.0
Latest version : 2.0.7.8
No newer version found

In this case, there is no newer file and nothing happens. You need to click the CLOSE
button to close the Update window. The IDE will not be closed in this case.

If however a newer version exists, it will be downloaded and unzipped in your


windows TEMP folder.
After that setup.exe will be executed with admin rights. So you might get a windows
security message that setup requires admin rights.
BASCOM will close automatically so the new version can be installed in the same
folder. We recommend however to install each version into a different folder.
There is no need to uninstall an older version first.

This setup is the same as you used when you installed the software. But of course the
latest version.
You can install into the same folder, but you may also install into a new folder.
When installing into a new folder you must manual install/copy the license file
bscavrl.dll into the new folder yourself.
The bscavrl.dll file you get when you purchase bascom. It is either on CD-ROM or in
the bascom-avr application folder.
Please notice that this license file is offered during purchase. We do not offer it again
in the event you lost it.

Add On Update
When you chose to update Add On, you can also specify that libraries will be copied
after the update. You do this by checking the 'Copy Libs After Update' check box.
The Add on update will check if you have an add on installed. It will then check if
there is an update available. Notice that not all add ons you purchased are supported
yet. So those you have to manual download/install.
The supported Add Ons :
- AVRDOS.
- I2CSLAVE
- XTINY

The add on is always ZIPPED and this ZIP file is downloaded to a new SUB folder
named ADDONS.
This ADDONS subfolder is created in the BasCom-AVR application folder.
Each Add On is installed into its own sub folder. So for AVRDOS it is installed into
ADDONS\AVRDOS
Older versions that might exist are overwritten.

When an Add-On contains a LIB or LBX file, the option 'Copy Libs after update' will be
copied to the BasCom-AVR Library folder. The original file will be renamed so you
always have a backup.
You do need write access in the BasCom-AVR application folder and sub folder.

© 2021 MCS Electronics


216 BASCOM-AVR

3.77 Help Wiki


This option will open the browser at wiki.mcselec.com
The wiki contains the help file, projects and is partial translated into German as well.

When you want to contribute you need to create an account and send an email to
[email protected] to get the proper access rights.

3.78 BASCOM Editor Keys

Key Action
LEFT ARROW One character to the left
RIGHT ARROW One character to the right
UP ARROW One line up
DOWN ARROW One line down
HOME To the beginning of a line
END To the end of a line
PAGE UP Up one window
PAGE DOWN Down one window
CTRL+LEFT One word to the left
CTRL+RIGHT One word to the right
CTRL+HOME To the start of the text
CTRL+END To the end of the text
CTRL+ Y Delete current line
INS Toggles insert/over strike mode
F1 Help (context sensitive)
F2 Run simulator
F3 Find next text
F4 Send to chip (run flash programmer)
F5 Run
F7 Compile File
F8 Step
F9 Set breakpoint
F10 Run to
F11 Collapse Code Toggle Sub/Function
SHIFT+F11 or Collapse Code Toggle current block
CTRL+ENTER
CTRL+F7 Syntax Check
CTRL+F Find text
CTRL+G Go to line
CTRL+K+x Toggle bookmark. X can be 1-8
CTRL+L LCD Designer
CTRL+M File Simulation
CTRL+N New File
CTRL+O Load File
CTRL+P Print File
CTRL+Q+x Go to Bookmark. X can be 1-8
CTRL+R Replace text

© 2021 MCS Electronics


BASCOM IDE 217

CTRL+S Save File


CTRL+T Terminal emulator
CTRL+P Compiler Options
CTRL+W Show result of compilation
CTRL+X Cut selected text to clipboard
CTRL+Z Undo last modification
SHIFT+CTRL+Z Redo last undo
CTRL+INS Copy selected text to clipboard
SHIFT+INS Copy text from clipboard to editor
CTRL+SHIFT+J Indent Block
CTRL+SHIFT+U Unindent Block
Select text Hold the SHIFT key down and use the cursor keys to select text.
or keep the left mouse key pressed and drag the cursor over the
text to select.
CTRL+SPACE Code help.
SHIFT + MOUSE Hover on indention lines to see to which group they belong.
Hover on an element in your code to get info about that element.
CTRL+BACKSPAC Jump back
E
CTRL+CLICK Hold the CTRL key down and hover with the mouse till an
element is underlined like an URL. Click the left mouse to jump to
the implementation.

3.79 Program Development Order


· Start BASCOM
· Open a file or create a new one
· ! Important ! Check the chip settings, baud rate and frequency settings for the
target system
· Save the file
· Compile the file (this will also save the file !!!)
· If an error occurs fix it and recompile (F7)
· Run the simulator(F2)
· Program the chip(F4)

3.80 PlugIns
3.80.1 Font Editor
In version 2079 the Font Editor plugin is replaced by the integrated Font Editor from
the Tools menu 133 . It has the same options.

The Font Editor is a Plug in that is intended to create Fonts that can be used with
Graphical display such as SED1521, KS108, color displays, etc.

When you have installed the Font Editor , a menu option becomes available under the
Tools menu : Font Editor.

When you choose this option the following window will appear:

© 2021 MCS Electronics


218 BASCOM-AVR

You can open an existing Font file, or Save a modified file.

The supplied font files are installed in the Samples directory.


You can copy an image from the clipboard, and you can then move the image up ,
down, left and right.

When you select a new character, the current character is saved. The suggest button
will draw an image of the current selected character.

When you keep the left mouse button pressed, you can set the pixels in the grid.
When you keep the right mouse button pressed, you can clear the pixels in the grid.

When you choose the option to create a new Font, you must provide the name of the
font, the height of the font in pixels and the width of the font in pixels.

The Max ASCII is the last ASCII character value you want to use. Each character will
occupy space. So it is important that you do not choose a value that is too high and
will not be used.

When you display normal text, the maximum number is 127 so it does not make
sense to specify a value of 255.

A font file is a plain text file.


Lets have a look at the first few lines of the 8x8 font:

Font8x8:
$asm

© 2021 MCS Electronics


BASCOM IDE 219

.db 1,8,8,0
.db 0,0,0,0,0,0,0,0 ;
.db 0,0,6,95,6,0,0,0 ; !

The first line contains the name of the font. With the SETFONT 1219 statement you can
select the font. Essential, this sets a data pointer to the location of the font data.

The second line ($ASM) is a directive for the internal assembler that asm code will
follow.
All other lines are data lines.

The third line contains 4 bytes: 1 (height in bytes of the font) , 8 (width in pixels of
the font), 8 (block size of the font) and a 0 which was not used before the 'truetype'
support, but used for aligning the data in memory. This because AVR object code is a
word long.

This last position is 0 by default. Except for 'TrueType' fonts. In BASCOM a TrueType
font is a font where every character can have it's own width. The letter 'i' for example
takes less space then the letter 'w'. The EADOG128 library demonstrates the
TrueType option.
In order to display TT, the code need to determine the space at the left and right of
the character. This space is then skipped and a fixed space is used between the
characters. You can replace the 0 by the width you want to use. The value 2 seems a
good one for small fonts.

All other lines are bytes that represent the character.

© 2021 MCS Electronics


Part

IV
BASCOM HARDWARE 221

4 BASCOM HARDWARE
4.1 Additional Hardware
Of course just running a program on the chip is not enough. You will probably connect
many types of electronic devices to the processor ports.
BASCOM supports a lot of hardware and so it has lots of hardware related statements.
Before explaining about programming the additional hardware, it might be better to
talk about the chip.

The AVR internal hardware 221

Attaching an LCD display 245

Using the I2C protocol 266

Using the 1WIRE protocol 278

Using the SPI protocol 282

You can connect additional hardware to the ports of the microprocessor.


The following are hardware related:

I2CSEND 1173 and I2CRECEIVE 1172 and other I2C related statements.

CLS, 1190 LCD, 1204 DISPLAY 1197 and other related LCD-statements.

1WRESET 622 , 1WWRITE 633 and 1WREAD 624

There are many more hardware specific statements and functions.

Adding XRAM 230

Adding XRAM to XMEGA using EBI 234

Adding SRAM 4-port Non Multiplexed 236

4.2 AVR Internal Hardware


The AVR chips all have internal hardware that can be used.

For this description of the hardware the 90S8515 was used. Newer chips like the
Mega8515 may differ and have more or less internal hardware.

You will need to read the manufacturers data sheet for the processor you are using to
learn about the special internal hardware available.

Timer / Counters
The AT90S8515 provides two general purpose Timer/Counters - one 8-bit T/C and
one 16-bit T/C. The Timer/Counters have individual pre-scaling selection from the
same 10-bit pre-scaling timer. Both Timer/Counters can either be used as a timer
with an internal clock time base or as a counter with an external pin connection which
triggers the counting.

© 2021 MCS Electronics


222 BASCOM-AVR

More about TIMERO 224

More about TIMER1 225

The WATCHDOG Timer 227

Almost all AVR chips have the ports B and D. The 40 or more pin devices also have
ports A and C that also can be used for addressing an external RAM chip (XRAM 230 ).
Since all ports are similar except that PORT B and PORT D have alternative functions,
only these ports are described.

PORT B 227
PORT D 229

4.3 AVR Internal Registers


You can manipulate the internal register values directly from BASCOM. They are also
reserved words. Each register acts like a memory location or program variable, except
that the bits of each byte have a special meaning. The bits control how the internal
hardware functions, or report the status of internal hardware functions. Read the
data sheet to determine what each bit function is for.

The internal registers for the AVR90S8515 are : (other processors are similar,
but vary)
Addr. Register
$3F SREG I T H S V N Z C
$3E SPH SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8
$3D SPL SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0
$3C Reserved

© 2021 MCS Electronics


BASCOM HARDWARE 223

$3B GIMSK INT1 INT0 - - - - - -


$3A GIFR INTF1 INTF0
$39 TIMSK TOIE1 OCIE1A OCIE1B - TICIE1 - TOIE0 -
$38 TIFR TOV1 OCF1A OCF1B -ICF1 -TOV0 -
$37 Reserved
$36 Reserved
$35 MCUCR SRE SRW SE SM ISC11 ISC10 ISC01 ISC00
$34 Reserved
$33 TCCR0 - - - - - CS02 CS01 CS00
$32 TCNT0 Timer/Counter0 (8 Bit)
$31 Reserved
$30 Reserved
$2F TCCR1A COM1A1 COM1A0 COM1B1 COM1B0 - -PWM11 PWM10
$2E TCCR1B ICNC1 ICES1 - - CTC1 CS12 CS11 CS10
$2D TCNT1H Timer/Counter1 - Counter Register High Byte
$2C TCNT1L Timer/Counter1 - Counter Register Low Byte
$2B OCR1AH Timer/Counter1 - Output Compare Register A High Byte
$2A OCR1AL Timer/Counter1 - Output Compare Register A Low Byte
$29 OCR1BH Timer/Counter1 - Output Compare Register B High Byte
$28 OCR1BL Timer/Counter1 - Output Compare Register B Low Byte
$27 Reserved
$26 Reserved
$25 ICR1H Timer/Counter1 - Input Capture Register High Byte
$24 ICR1L Timer/Counter1 - Input Capture Register Low Byte
$23 Reserved
$22 Reserved
$21 WDTCR - - - WDTOE WDE WDP2 WDP1 WDP0
$20 Reserved
$1F Reserved - - - - - - - EEAR8
$1E EEARL EEPROM Address Register Low Byte
$1D EEDR EEPROM Data Register
$1C EECR - - - - - EEMWE EEWE EERE
$1B PORTA PORTA7 PORTA6 PORTA5 PORTA4 PORTA3 PORTA2 PORTA1
PORTA0
$1A DDRA DDA7 DDA6 DDA5 DDA4 DDA3 DDA2 DDA1 DDA0
$19 PINA PINA7 PINA6 PINA5 PINA4 PINA3 PINA2 PINA1 PINA0
$18 PORTB PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1
PORTB0
$17 DDRB DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0
$16 PINB PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0
$15 PORTC PORTC7 PORTC6 PORTC5 PORTC4 PORTC3 PORTC2 PORTC1
PORTC0
$14 DDRC DDC7 DDC6 DDC5 DDC4 DDC3 DDC2 DDC1 DDC0
$13 PINC PINC7 PINC6 PINC5 PINC4 PINC3 PINC2 PINC1 PINC0
$12 PORTD PORTD7 PORTD6 PORTD5 PORTD4 PORTD3 PORTD2 PORTD1
PORTD0
$11 DDRD DDD7 DDD6 DDD5 DDD4 DDD3 DDD2 DDD1 DDD0
$10 PIND PIND7 PIND6 PIND5 PIND4 PIND3 PIND2 PIND1 PIND0
$0F SPDR SPI Data Register

© 2021 MCS Electronics


224 BASCOM-AVR

$0E SPSR SPIF WCOL - - - - - -


$0D SPCR SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
$0C UDR UART I/O Data Register
$0B USR RXC TXC UDRE FE OR - - -
$0A UCR RXCIE TXCIE UDRIE RXEN TXEN CHR9 RXB8 TXB8
$09 UBRR UART Baud Rate Register
$08 ACSR ACD - ACO ACI ACIE ACIC ACIS1 ACIS0
$00 Reserved

The registers and their addresses are defined in the xxx.DAT files which are placed in
the BASCOM-AVR application directory.

The registers can be used as normal byte variables.

PORTB = 40 will place a value of 40 into port B.

Note that internal registers are reserved words. This means that they can't be
dimensioned as BASCOM variables!

So you can't use the statement DIM SREG As Byte because SREG is an internal
register.

You can however manipulate the register with the SREG = value statement, or var =
SREG statement.

4.4 AVR Internal Hardware TIMER0


The 8-Bit Timer/Counter0

The 90S8515 was used for this example. Other chips might have a somewhat
different timer.
The 8-bit Timer/Counter0 can select its clock source from CK, pre-scaled CK, or an
external pin. In addition it can be stopped (no clock).

The overflow status flag is found in the Timer/Counter Interrupt Flag Register - TIFR.
Control signals are found in the Timer/Counter0 Control Register - TCCR0. The
interrupt enable/disable settings for Timer/Counter0 are found in the Timer/Counter
Interrupt Mask Register - TIMSK.

When Timer/Counter0 is externally clocked, the external signal is synchronized with


the oscillator frequency of the CPU. To assure proper sampling of the external clock,
the minimum time between two external clock transitions must be at least one
internal CPU clock period. The external clock signal is sampled on the rising edge of
the internal CPU clock.

© 2021 MCS Electronics


BASCOM HARDWARE 225

The 8-bit Timer/Counter0 features both a high resolution and a high accuracy mode
with lower pre-scaling values. Similarly, high pre-scaling values make the Timer/
Counter0 useful for lower speed functions or exact timing functions with infrequent
actions.

4.5 AVR Internal Hardware TIMER1


The 16-Bit Timer/Counter1

The 90S8515 was used for the documentation. Other chips might have a
somewhat different timer.

The 16-bit Timer/Counter1 can select its clock source from CK, pre-scaled CK, or an
external pin. In addition it can be stopped (no clock).

The different status flags (overflow, compare match and capture event) and control
signals are found in the Timer/Counter1 Control Registers - TCCR1A and TCCR1B.

The interrupt enable/disable settings for Timer/Counter1 are found in the Timer/
Counter Interrupt Mask Register - TIMSK.

When Timer/Counter1 is externally clocked, the external signal is synchronized with


the oscillator frequency of the CPU. To assure proper sampling of the external clock,
the minimum time between two external clock transitions must be at least one

© 2021 MCS Electronics


226 BASCOM-AVR

internal CPU clock period.

The external clock signal is sampled on the rising edge of the internal CPU clock.

The 16-bit Timer/Counter1 features both a high resolution and a high accuracy usage
with lower pre-scaling values.

Similarly, high pre-scaling values make the Timer/Counter1 useful for lower speed
functions or exact timing functions with infrequent actions.

The Timer/Counter1 supports two Output Compare functions using the Output
Compare Register 1 A and B -OCR1A and OCR1B as the data values to be compared
to the Timer/Counter1 contents.

The Output Compare functions include optional clearing of the counter on compareA
match, and can change the logic levels on the Output Compare pins on both compare
matches.

Timer/Counter1 can also be used as a 8, 9 or 10-bit Pulse Width Modulator (PWM). In


this mode the counter and the OCR1A/OCR1B registers serve as a dual glitch-free
stand-alone PWM with centered pulses.

The Input Capture function of Timer/Counter1 provides a capture of the Timer/


Counter1 value to the Input Capture Register - ICR1, triggered by an external event
on the Input Capture Pin - ICP. The actual capture event settings are defined by the
Timer/Counter1 Control Register -TCCR1B.

In addition, the Analog Comparator can be set to trigger the Capture.

© 2021 MCS Electronics


BASCOM HARDWARE 227

4.6 AVR Internal Hardware Watchdog timer


The Watchdog Timer
The Watchdog Timer is clocked from a separate on-chip oscillator which runs at
approximately 1MHz. This is the typical value at VCC = 5V.

By controlling the Watchdog Timer pre-scaler, the Watchdog reset interval can be
adjusted from 16K to 2,048K cycles (nominally 16 - 2048 ms). The BASCOM RESET
WATCHDOG - instruction resets the Watchdog Timer.

Eight different clock cycle periods can be selected to determine the reset period.

If the reset period expires without another Watchdog reset, the AT90Sxxxx resets and
program execution starts at the reset vector address.

4.7 AVR Internal Hardware Port B


Port B
Port B is an 8-bit bi-directional I/O port. Three data memory address locations are
allocated for the Port B, one each for the Data Register - PORTB, $18($38), Data

© 2021 MCS Electronics


228 BASCOM-AVR

Direction Register - DDRB, $17($37) and the Port B Input Pins - PINB, $16($36). The
Port B Input Pins address is read only, while the Data Register and the Data Direction
Register are read/write.

All port pins have individually selectable pull-up resistors. The Port B output buffers
can sink 20mA and thus drive LED displays directly. When pins PB0 to PB7 are used
as inputs and are externally pulled low, they will source current if the internal pull-up
resistors are activated.

The Port B pins with alternate functions are shown in the following table:

When the pins are used for the alternate function the DDRB and PORTB register has
to be set according to the alternate function description.

Port B Pins Alternate Functions


Port Pin Alternate Functions
PORTB.0 T0 (Timer/Counter 0 external
counter input)
PORTB.1 T1 (Timer/Counter 1 external
counter input)
PORTB.2 AIN0 (Analog comparator positive
input)
PORTB.3 AIN1 (Analog comparator negative
input)
PORTB.4 SS (SPI Slave Select input)
PORTB.5 MOSI (SPI Bus Master Output/Slave
Input)
PORTB.6 MISO (SPI Bus Master Input/Slave
Output)
PORTB.7 SCK (SPI Bus Serial Clock)

The Port B Input Pins address - PINB - is not a register, and this address enables
access to the physical value on each Port B pin. When reading PORTB, the PORTB
Data Latch is read, and when reading PINB, the logical values present on the pins are
read.

PortB As General Digital I/O


All 8 bits in port B are equal when used as digital I/O pins. PORTB.X, General I/O pin:
The DDBn bit in the DDRB register selects the direction of this pin, if DDBn is set
(one), PBn is configured as an output pin. If DDBn is cleared (zero), PBn is configured
as an input pin. If PORTBn is set (one) when the pin configured as an input pin, the
MOS pull up resistor is activated.

To switch the pull up resistor off, the PORTBn has to be cleared (zero) or the pin has
to be configured as an output pin.

DDBn Effects on Port B Pins


DDBn PORTBn I/O Pull up Comment
0 0 Input No Tri-state (Hi-Z)

© 2021 MCS Electronics


BASCOM HARDWARE 229

0 1 Input Yes PBn will source


current if ext.
pulled low.
1 0 Output No Push-Pull Zero
Output
1 1 Output No Push-Pull One
Output

By default, the DDR and PORT registers are 0. CONFIG PORTx=OUTPUT will set the
entire DDR register. CONFIG PINX.Y will also set the DDR register for a single bit/pin.
When you need the pull up to be activated, you have to write to the PORT register.

4.8 AVR Internal Hardware Port D


Port D

Port D Pins Alternate Functions


Port Pin Alternate Function
PORTD.0 RDX (UART Input line )
PORTD.1 TDX (UART Output line)
PORTD.2 INT0 (External interrupt 0 input)
PORTD.3 INT1 (External interrupt 1 input)
PORTD.5 OC1A (Timer/Counter1 Output compareA match
output)
PORTD.6 WR (Write strobe to external memory)
PORTD.7 RD (Read strobe to external memory)

RD - PORTD, Bit 7
RD is the external data memory read control strobe.

WR - PORTD, Bit 6
WR is the external data memory write control strobe.

OC1- PORTD, Bit 5


Output compare match output: The PD5 pin can serve as an external output when the
Timer/Counter1 com-pare matches.

The PD5 pin has to be configured as an out-put (DDD5 set (one)) to serve this f
unction. See the Timer/Counter1 description for further details, and how to enable the
output. The OC1 pin is also the output pin for the PWM mode timer function.

INT1 - PORTD, Bit 3


External Interrupt source 1: The PD3 pin can serve as an external interrupt source to
the MCU. See the interrupt description for further details, and how to enable the
source

INT0 - PORTD, Bit 2


INT0, External Interrupt source 0: The PD2 pin can serve as an external interrupt

© 2021 MCS Electronics


230 BASCOM-AVR

source to the MCU. See the interrupt description for further details, and how to enable
the source.

TXD - PORTD, Bit 1


Transmit Data (Data output pin for the UART). When the UART transmitter is enabled,
this pin is configured as an output regardless of the value of DDRD1.

RXD - PORTD, Bit 0


Receive Data (Data input pin for the UART). When the UART receiver is enabled this
pin is configured as an output regardless of the value of DDRD0. When the UART
forces this pin to be an input, a logical one in PORTD0 will turn on the internal pull-
up.

When pins TXD and RXD are not used for RS-232 they can be used as an input or
output pin.

No PRINT, INPUT or other RS-232 statement may be used in that case.

The UCR register will by default not set bits 3 and 4 that enable the TXD and RXD
pins for RS-232 communication. It is however reported that this not works for all
chips. In this case you must clear the bits in the UCR register with the following
statements:

RESET UCR.3
RESET UCR.4
or as an alernative : UCR=0

4.9 Adding XRAM with External Memory Interface


With ATMEGA AVR like ATMEGA128, ATMEGA1280 or older types like 90S8515 you
can access external RAM (SRAM) or other peripherals through its External Memory
Interface. Search in the Atmel ATMEGA datasheets for "External Memory Interface"

For ATXMEGA devices see App Note: AVR1312: Using the XMEGA External Bus
Interface for details.

For example for an ATMEGA1280 the external memory interface consist of PORTA
(multiplexed data and address low byte), PORTC (address high byte), and
PORTG[2:0] (RD, WR and ALE).

ATMEGA1280 pin connections to SRAM device:


Port A = Multiplexed Address low byte (A0....A7) / Data (D0....D7) <--------> Direct
connection to SRAM (D0...D7) and connected to Input D of octal latch (typically “74 x
573” or equivalent) to (A0.....A7) of SRAM chip
Port C = Address high byte (A8....A15) <--------> direct connection to for example
SRM (A8....A15)
Port G Pin 0 = WR (Write strobe to external memory) <--------> direct connection to
for example SRAM WR
Port G Pin 1 = RD (Read strobe to external memory) <--------> direct connection to
for example SRAM RD
Port G Pin 2 = ALE (Address Latch Enable to external memory) <-------->
Connected to G Input of octal latch (typically “74 x 573” like 74 x 573)

Example for 74HTC573 (TTL variant):

© 2021 MCS Electronics


BASCOM HARDWARE 231

http://www.nxp.com/documents/data_sheet/74HC_HCT573.pdf

Address latch with octal latch:


The data bus and the low byte of the address bus is multiplexed on Port A. The ALE
signal indicates when the address is present. This low byte must be stored by a latch
until the memory access cycle is completed.

Schematics for connecting the ATMEGA with octal latch and sram can be found in:
· Atmel AVR Studio Help File (AVR tools user guide) search for: "external memory
interface" and scroll down to APPENDIX. There you also find a list of 3.3 or 5V
compatible SRAM's that can be used with ATMEGA's and there is a link to
STK503.pdf which is part of the help file.
· The list of compatible SRAM devices can be also found here:
http://www.atmel.com/images/stk503_ug.pdf (page 16)
· The datasheet of for example ATMEGA1280 also include a picture which show the
connections between AVR, Octal Latch external SRAM device.

The data memory map for example for ATmega640/1280/1281/2560/2561:


Hex-Address:
&H00 .... &H1F 32 Registers
&H20 .... &H5F 64 I/O Registers
&H60 .... &H1FF 416 external I/O Registers
&H200 .... &H21FF Internal SRAM (8K in this case)
&H2200 .... &HFFFF External SRAM (XRAM)

XRAM will use an area in the remaining address locations in the 64K address space
(&HFFFF). This starts at the address following the internal SRAM.
Internal SRAM use the lowest 4,608/8,704 bytes, so when using 64KB (65,536 bytes)
of XRAM, 60,478/56,832 Bytes of XRAM are available.
See datasheet of ATMEGA device for a way to use the complete 64KByte.

XRAM will be enabled by CONFIG XRAM 1036 (config XRAM is setting SRE bit of the
atmega 1280 XMCRA Register)
The Pins of Port A, Port C and Port G from ATMEGA1280 are automatically enabled for
XRAM and can not be used for other tasks by default if XRAM is enabled. The external
memory address space can be divided in two sectors (upper and lower sector) with
different wait-state bits. You can also release some Port C pins for other tasks (in the
XMCRB Register) . See atmega 1280 datasheet for details.

See also: $XRAMSIZE 617 and $XRAMSTART 617

You can clear the XRAM for example with:


For N = Ramstart To Ramend 'replace RamStart and RamEnd
with the real values
Out N , 0 'zero or any value you like
Next

With XRAM, you should dim all your global variables with XRAM. Example: Dim Var As
Xram Byte
This will leave the internal memory for the stacks and local created variables.
You can also use $ d e f a u l t Xram when you do not want to add the XRAM to each DIM.

Example 1:
A real Example for using SRAM and another Bus-mode device is WIZ200WEB from
Wiznet.

© 2021 MCS Electronics


232 BASCOM-AVR

Here an ATMEGA128L, an external 32K SRAM and a W5300 Ethernet Chip is used. See
also CONFIG TCPIP 980

The data memory map for ATMEGA128:


Hex-Address:
&H00 .... &H1F 32 Registers
&H20 .... &H5F 64 I/O Registers
&H60 .... &HFF 160 external I/O Registers
&H100 .... &H10FF Internal SRAM (4K in this case)
&H1100 Start of External SRAM (XRAM)

So the config is following ( &H8000 = 32kByte):

$xramstart = &H1100
$xramsize = &H8000
Config Xram = Enabled

The W5300 Chip from Wiznet is setup to use Base Address &H8000.

So the data memory map for ATMEGA128 is:


Hex-Address:
&H00 .... &H1F 32 Registers
&H20 .... &H5F 64 I/O Registers
&H60 .... &HFF 160 external I/O Registers
&H100 .... &H10FF Internal SRAM (4K in this case)
&H1100 Start of External SRAM (XRAM)
&H8000 Base Address of W5300 Chip from WIZNET
&H8400 .... &HFFFF Not in use

See also CONFIG TCPIP 980 for further details on W5300 Chip from Wiznet.

Example 2:
We use now an WIZ830mj module (which uses a W5300 Chip from Wiznet) on a board with
an 64/128KByte SRAM in combination with ATMEGA1280:

Hex-Address:
&H00 .... &H1F 32 Registers
&H20 .... &H5F 64 I/O Registers
&H60 .... &H1FF 416 external I/O Registers
&H200 .... &H21FF Internal SRAM (8K in this case)
&H2200 .... &HFBFF External SRAM (XRAM) upper and lower
&HFC00 Base Address of W5300 Chip over memory address selector

XRAM configuration here is:


$xramstart = &H2200
$xramsize = &HFBFF
Config Xram = Enabled

Writing to the first XRAM address is done by:


Out &H2200 , &H01

Reading from first XRAM is done by:


Var = I n p( &H2200)

The datasheet of W5300 say: "In the case of using an 8bit data bus width, ADDR[9:0] is used
" so we have Address 0.......Address 9 but the SRAM need Address 0.....15.

© 2021 MCS Electronics


BASCOM HARDWARE 233

Here an example of additional circuit between ATMEGA and W5300 and SRAM to solve the
difference of address (A0...A15) for SRAM and (A0...A9) for W5300:

The Base Address for W5300 (WIZ830mj) in this case is &HFC00

Address Bit A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0


Binary: 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
Hex: FC00

For older 90S8515 chips for example the maximum size of XRAM can be 64 Kbytes.
Example: The STK200 has a 62256 ram chip (32K x 8 bit).

Here is some info from the BASCOM user list :


If you do go with the external ram , be careful of the clock speed.
Using a 4 MHz crystal , will require a SRAM with 70 nS access time or less. Also the
data latch (74HC573) will have to be from a faster
family such as a 74FHC573 if you go beyond 4 MHz.

You can also program an extra wait state, to use slower memory.

Here you will find a pdf file showing the STK200 schematics:
See Stk200_schematic.pdf for more information.

© 2021 MCS Electronics


234 BASCOM-AVR

If you use a 32 KB SRAM, then connect the /CS signal to A15 which give to the range
of &H0000 to &H7FFF, if you use a 64 KB SRAM, then
tie /CS to GND, so the RAM is selected all the time.

4.10 Adding XRAM to XMEGA using EBI


This information has been provided by Electronic Design Bitzer.
Some XMEGA processors have an EBI. The following circuit shows how to set up the
EBI for 8 bit bus mode where the SRAM can be selected with a jumper.
128 KB SM621008VLLP70T : SRAM LLPow 3,3V 128Kx8 70ns TSOP32(I)
512 KB SM624008VLLP70M : SRAM LLPow 3,3V 512Kx8 70ns SOP32

The BASCOM setup code :


' All EBI-Ports must be set to OUTPUT
' All Ports, ACTIVE-LOW , must be set to 1 !!!
' All Ports, ACTIVE-HIGH, must be set to 0 !!!

Porth_dirset = &B1111_1111 : Porth = &B1111_0011 'WR, RD, ALE1, ALE2, CS


Portj_dirset = &B1111_1111 : Portj = &B1111_1111
Portk_dirset = &B1111_1111 : Portk = &B1111_1111

Config Xram = 3port , Ale = Ale12 , Sdbus = 8 , Modesel0 = Sram , Adrsize0 = 256b ,
Modesel1 = Sram , Adrsize1 = 128k , Waitstate1 = 1 , Baseadr1 = &H20

See also : CONFIG XRAM 1036

© 2021 MCS Electronics


BASCOM HARDWARE 235

© 2021 MCS Electronics


236 BASCOM-AVR

4.11 Adding SRAM 4-port Non Multiplexed


The following information was contributed by Juergen Bitzer.

The EBI allows to use an SRAM in 4-port non multiplexed mode. This means that you
need little parts but you loose 4 ports.

Example
$regfile = "xm128a1def.dat"
$crystal = 32000000
$hwstack = &H32
$swstack = &H32
$framesize = &H32
$xramstart = &H100000
$xramsize = &H080000

'------------------
' CPU:
' ATXMEGA128A1U-AU : 2,23/100 Mouser Muss -->A1U-AU<--

© 2021 MCS Electronics


BASCOM HARDWARE 237

sein !!!
' ATXMEGA64A1U-AU
'------------------
' SRam:
' 512 KB AS6C4008-55PCN : SRAM 4MB 2.7V-5.5V, 512KX8, PDIP32

' 512 KB AS6C4008-55SIN : SRAM 4MB 2.7V-5.5V, 512KX8, SOP32


' 512 KB AS6C4008-55SIN : SRAM 4MB 2.7V-5.5V, 512KX8, SOP32
'----------------------------------------------------------------
---------------
'----------------------------------------------------------------
---------------

' #### Four Port SRAM ####


' MODE SRAM 4Port direkt

' PortH.0 - Pin 55 /WR


' PortH.1 - Pin 56 /RD

' PortE.4 - Pin 39 /CS0 / A16 -> CS0: SRAM 512 KB


' PortE.5 - Pin 40 /CS1 / A17 -> CS1: unbenutzt
' PortE.6 - Pin 41 /CS2 / A18 -> CS2: unbenutzt
' PortE.7 - Pin 42 /CS3 / A19 -> CS3: unbenutzt

' PortJ.0 - Pin 65 D0 -> SRam


' PortJ.1 - Pin 66 D1 -> SRam
' PortJ.2 - Pin 67 D2 -> SRam
' PortJ.3 - Pin 68 D3 -> SRam
' PortJ.4 - Pin 69 D4 -> SRam
' PortJ.5 - Pin 70 D5 -> SRam
' PortJ.6 - Pin 71 D6 -> SRam
' PortJ.7 - Pin 72 D7 -> SRam

' PortK.0 - Pin 75 A0 -> SRam


' PortK.1 - Pin 76 A1 -> SRam
' PortK.2 - Pin 77 A2 -> SRam
' PortK.3 - Pin 78 A3 -> SRam
' PortK.4 - Pin 79 A4 -> SRam
' PortK.5 - Pin 80 A5 -> SRam
' PortK.6 - Pin 81 A6 -> SRam
' PortK.7 - Pin 82 A7 -> SRam

' PortF.0 - Pin 45 A8 -> SRam


' PortF.1 - Pin 46 A9 -> SRam
' PortF.2 - Pin 47 A10 -> SRam
' PortF.3 - Pin 48 A11 -> SRam
' PortF.4 - Pin 49 A12 -> SRam
' PortF.5 - Pin 40 A13 -> SRam
' PortF.6 - Pin 41 A14 -> SRam

© 2021 MCS Electronics


238 BASCOM-AVR

' PortF.7 - Pin 42 A15 -> SRam

' PortH.2 - Pin 57 A16 -> SRam


' PortH.3 - Pin 58 A17 -> SRam
' PortH.4 - Pin 59 A18 -> SRam
' PortH.5 - Pin 60 A19 - unbenutzt
' PortH.6 - Pin 61 A20 - unbenutzt
' PortH.7 - Pin 62 A21 - unbenutzt

'----------------------------------------------------------------
---------------
'----------generate a 32 MHz system clock by use of the PLL (2MHz
* 23 = 46MHz)

Config Osc = Disabled , Extosc = Enabled

'Set the Multiplication factor and select the clock Reference


for the PLL
'Osc_pllctrl = &B00_0_10100
'2MHz clock Source and Multiplication factor = 23
' 00 : 2 MHz internal OSC
' 01 : Reerved
' 10 : 32 MHz internal OSC
' 11 : External Clock Source
' 1 : 0=PLL-Output devided by 1
|1=PLL-Output devided by 2
' xxxxx: Multiplikation of PLL 1-31
Osc_pllctrl = &B11_0_01000 : Const Mhz = 32 ' 32
MHz

'enable PLL
Set Osc_ctrl.4 'PLL
enable

'configure the systemclock


Config Sysclock = Pll 'use
PLL

'----------------------------------------------------------------
---------------
'----------------------------------------------------------------
---------------
Config Com1 = 115200 , Mode = Asynchroneous , Parity = None ,
Stopbits = 1 , Databits = 8

Open "com1:" For Binary As #1

' Termninal initialisieren


Printbin #1 , &H1B ; &H5B ; &H30 ; &H6D ' All

© 2021 MCS Electronics


BASCOM HARDWARE 239

attributes off(normal)
Printbin #1 , &H1B ; &H5B ; &H32 ; &H4A '
Bildschirm löschen
Printbin #1 , &H1B ; &H5B ; &H48 ; '
Cursor Home
Printbin #1 , &H1B ; &H5B ; &H3F ; &H32 ; &H35 ; &H68 ; '
Cursor an

'----------------------------------------------------------------
---------------
' Einstellungen externer Speicher
' Alle EBI-Ports müssen auf OUTPUT
' ALLE Ports, die ATKIV-LOW sind müssen auf 1 gesetzt werden
!!!
' ALLE Ports, die ATKIV-HIGH sind müssen auf 0 gesetzt werden
!!!

Print #1 , "Config Ports for external Adress / Data-Bus with


no ALE... ";

Portj_dirset = &B1111_1111 : Portj = &B0000_0000 '


D0:7
Portj_pin0ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin1ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin2ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin3ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin4ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin5ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin6ctrl = &B0_0_000_000
'Totem (PushPull)
Portj_pin7ctrl = &B0_0_000_000
'Totem (PushPull)

Portk_dirset = &B1111_1111 : Portk = &B1111_1111 '


A0:7
Portk_pin0ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin1ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin2ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin3ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper

© 2021 MCS Electronics


240 BASCOM-AVR

Portk_pin4ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin5ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin6ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portk_pin7ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper

' PortX_pinYctrl = &B0_0_001_000 : X= Port A... Y= Bit Nr. 0-7


' X :7 : 0= SlewRate normal, 1=
SlewRate limited
' X :6 : 0= IO normal, 1= IO
inverted
' XXX :5:3: 000 = Totem (PushPull)
' XXX :5:3: 001 = Totem + Buskeeper
' XXX :5:3: 010 = Totem + Pulldown on
Input
' XXX :5:3: 011 = Totem + PullUp on
Input
' XXX :5:3: 100 = Wired or
' XXX :5:3: 101 = Wired and
' XXX :5:3: 110 = Wired Or + PullDown
' XXX :5:3: 111 = Wired And + PullUp
' XXX:2:0: 000 = Both edges trigger
port Interrupts / Events
' XXX:2:0: 001 = Rising edge trigger
port Interrupts / Events
' XXX:2:0: 010 = Falling edge trigger
port Interrupts / Events
' XXX:2:0: 011 = Low Level trigger
port Interrupts / Events
' XXX:2:0: 100 = Reserved
' XXX:2:0: 101 = Reserved
' XXX:2:0: 110 = Reserved
' XXX:2:0: 111 = Input Buffer
Disabled (Only Port A to F) for use with ADC or AC

Portf_dirset = &B1111_1111 : Portf = &B1111_1111 '


A8:15
Portf_pin0ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin1ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin2ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin3ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper

© 2021 MCS Electronics


BASCOM HARDWARE 241

Portf_pin4ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin5ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin6ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Portf_pin7ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper

Porth_dirset = &B1111_1111 : Porth = &B1111_1111 ' WR,


RD , A16, A17, A18, A19, A20, A21
Porth_pin0ctrl = &B0_0_000_000
'Totem (PushPull)
Porth_pin1ctrl = &B0_0_000_000
'Totem (PushPull)
Porth_pin2ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Porth_pin3ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Porth_pin4ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Porth_pin5ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Porth_pin6ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper
Porth_pin7ctrl = &B0_0_001_000
'Totem (PushPull) + Buskeeper

Porte_dirset = &B1111_1111 : Porte = &B1111_0000 '


CS3, CS2, CS1, CS0
Porte_pin0ctrl = &B0_0_000_000
'Totem (PushPull) CS3
Porte_pin1ctrl = &B0_0_000_000
'Totem (PushPull) CS2 SRAM
Porte_pin2ctrl = &B0_0_000_000
'Totem (PushPull) CS1 SRAM
Porte_pin3ctrl = &B0_0_000_000
'Totem (PushPull) CS0 TFT
Porte_pin4ctrl = &B0_0_000_000
'Totem (PushPull)
Porte_pin5ctrl = &B0_0_000_000
'Totem (PushPull)
Porte_pin6ctrl = &B0_0_000_000
'Totem (PushPull)
Porte_pin7ctrl = &B0_0_000_000
'Totem (PushPull)

' EBI-OUT legt die 4 ChipSelect's auf einen anderen Port,

© 2021 MCS Electronics


242 BASCOM-AVR

damit die Adressleitungen


' A16 bis A21 auf Port-H frei wird.
Portcfg_ebiout = &B0000_00_11
' XXXX : RESERVED
' -> 00 : EBI Port3 adress output on PORT-F
0..7: SD: 4'h0, A[11:8] - SR or SR-LPC with SD on CS3: A[23:16] -
SR NoAle or ALE1: A[15:8]
' 01 : EBI Port3 adress output on PORT-E
0..7: SD: 4'h0, A[11:8] - SR or SR-LPC with SD on CS3: A[23:16] -
SR NoAle or ALE1: A[15:8]
' 10 : EBI Port3 adress output on PORT-F
4..7: SD: A[11:8] - SR or SR-LPC with SD on CS3: A[19:16] -
SR NoAle or ALE1: ---
' 11 : EBI Port3 adress output on PORT-E
4..7: SD: A[11:8] - SR or SR-LPC with SD on CS3: A[19:16] -
SR NoAle or ALE1: ---

' 00 : EBI CS-output on PORT-H 4..7


' 01 : EBI CS-output on PORT-L 4..7
' 10 : EBI CS-output on PORT-F 4..7
' -> 11 : EBI CS-output on PORT-E 4..7

Ebi_ctrl = &B01_00_11_10 'SRAM


ALE12, 3Port
' XX : 00: 4 Bit Data Bus
' XX -> : 01: 8 Bit Data Bus
' XX : 10: RESERVED
' XX : 11: RESERVED

' XX -> : 00: LPC-Mode: ALE1


' XX : 01: LPC-Mode: RESERVED
' XX : 10: LPC-Mode: ALE12
' XX : 11: LPC-Mode: RESERVED

' XX : 00: ALE1 - Adressbyte 0 and 1


multiplexed
' XX : 01: ALE2 - Adressbyte 0 and 2
multiplexed
' XX : 10: ALE12- Adressbyte 0,1 and 2
multiplexed
' -> XX : 11: NOALE- No adress multiplexing

' XX: 00: Externer Bus disabled


' XX: 01: 3 Port
Control-Bus # Data-Bus # A0:A7 und A8:A15 über ALE1 gemuxt
' -> XX: 10: 4 Port
' XX: 11: 2 Port

© 2021 MCS Electronics


BASCOM HARDWARE 243

'----------------------------------------------------------------
---------------
'----------------------------------------------------------------
---------------
'----------------------------------------------------------------
---------------
'----------------------------------------------------------------
---------------
'ChipSelect0 für 512 KByte SRam

' xxxxxxxx xxxx----


' Bit: 23 bis 12 11 bis 0 nicht
verwendet
' | |
Ebi_cs0_baseaddr = &B00010000_00000000 '
Start &H100000 = 1M
' 00000000_00100000_00000000 = &H002000 =
8K
' 00000000_00110000_00000000 = &H003000 =
12K
' 00000000_01000000_00000000 = &H004000 =
16K
' 00000000_10000000_00000000 = &H008000 =
32K
' 00000001_00000000_00000000 = &H010000 =
64K
' 00000010_00000000_00000000 = &H020000 =
128K
' 00000100_00000000_00000000 = &H040000 =
256K
' 00001000_00000000_00000000 = &H080000 =
512K
' -> 00010000_00000000_00000000 = &H100000 =
1M
' 00100000_00000000_00000000 = &H800000 =
2M
' 01000000_00000000_00000000 = &H800000 =
4M
' 10000000_00000000_00000000 = &H800000 =
8M

Ebi_cs0_ctrla = &B0_01011_01 '


Size &H080000 = 512 KB
' X : RESERVED
' XXXXX : AdressBlockSize
' 00000 : 256 Byte
' 00001 : 512 Byte
' 00010 : 1 KByte
' 00011 : 2 KByte

© 2021 MCS Electronics


244 BASCOM-AVR

' 00100 : 4 KByte


' 00101 : 8 KByte
' 00110 : 16 KByte
' 00111 : 32 KByte
' 01000 : 64 KByte
' 01001 : 128 KByte
' 01010 : 256 KByte
' -> 01011 : 512 KByte
' 01100 : 1 MByte
' 01101 : 2 MByte
' 00110 : 4 MByte
' 01111 : 8 MByte
' 10000 : 16 MByte
' XX : ChipSelectMode
' 00 : disabled
' -> 01 : Enabled for SRAM
' 10 : Enabled for SRAM LPC
(LowPinCount)
' 11 : Enabled for SD-SRAM

Ebi_cs0_ctrlb = &B00000_100 ' je


nach Geschwindigkeit des SRam's
' XXXXX : RESERVED
' XXX : Waitstates
' 000 : 0 Waitstates
' 001 : 1 Waitstates
' 010 : 2 Waitstates
' 011 : 3 Waitstates
' -> 100 : 4 Waitstates
' 101 : 5 Waitstates
' 110 : 6 Waitstates
' 111 : 7 Waitstates

'----------------------------------------------------------------
---------------

' Nun kann das externe SRam genauso wie das interne SRam
angesprochen werden.
' Vorteil: erheblich schneller im Zugriff, wie DRam !!!
' So kann auch Hardware "memory-mapped" eingebunden werden
' oder ein ISA-Bus realisiert werden.

' Now you can use the external SRAM just like the internal SRAM.
' This is much faster like DRAM
' This way you can also map hardware and access registers as you
would do for SRAM

$xramstart = &H100000
$xramsize = &H080000

© 2021 MCS Electronics


BASCOM HARDWARE 245

4.12 Attaching an LCD Display


A LCD display can be connected with two methods.

· By wiring the LCD-pins to the processor port pins. This is the pin mode. The
advantage is that you can choose the pins and that they don't have to be on the
same port. This can make your PCB design simple. The disadvantage is that more
code is needed.

· By attaching the LCD-data pins to the data bus. This is convenient when you have
an external RAM chip and will add only a little extra code.

The LCD-display can be connected in PIN mode as follows:

LCD PORT PIN


DISPLAY
DB7 PORTB.7 14
DB6 PORTB.6 13
DB5 PORTB.5 12
DB4 PORTB.4 11
E PORTB.3 6
RS PORTB.2 4
RW Ground 5
Vss Ground 1
Vdd +5 Volt 2
Vo 0-5 Volt 3

This leaves PORTB.1 and PORTB.0 and PORTD for other purposes.

You can change these pin settings from the Options LCD 140 menu.

BASCOM supports many statements to control the LCD-display.

For those who want to have more control of the example below shows how to use the
internal BASCOM routines.

$ASM
Ldi _temp1, 5 'load register R24 with value
Rcall _Lcd_control 'it is a control value to control the display
Ldi _temp1,65 'load register with new value (letter A)
Rcall _Write_lcd 'write it to the LCD-display
$END ASM

Note that _lcd_control and _write_lcd are assembler subroutines which can be called
from BASCOM.

See the manufacturer's details from your LCD display for the correct pin assignment.

© 2021 MCS Electronics


246 BASCOM-AVR

4.13 Memory usage


SRAM
Every variable uses memory. Variables are stored in memory. This memory is also
called SRAM (static ram).

The available memory depends on the chip. When you double click on the chip pinout,
you can view the parameters of the used chip.

A special kind of memory are the registers in the AVR. Registers 0-31 have addresses
0-31.
Almost all registers are used by the compiler or might be used in the future.
Which registers are used depends on the program statements you use.

This brings us back to the SRAM.


No SRAM is used by the compiler other than the space needed for the software stack (
$SWSTACK 609 ) and frame
($FRAMESIZE 545 )
Some statements might use some SRAM. When this is the case it is mentioned in the
help topic of that statement.

For example, CONFIG CLOCK 798 in user mode requires variables to hold the time.
Variables like _sec , _min , _hour, _day , _month , _year.

Each 8 bits used occupy one byte. When you dimension 1 bit, you will also use 1
byte.
Each byte variable occupies one byte.
Each integer/word variable occupies two bytes.
Each Long, Dword or Single variable occupies four bytes.
Each double variable occupies 8 bytes.
Each string variable occupies at least 2 bytes.
A string with a length of 10 occupies 11 bytes.

Strings need an additional byte (Null termination) to indicate the end of the
string. That's why a string of 10 bytes occupies 11 bytes.

With dimension of a bit you will occupy one byte.

Use bits or byte variables wherever you can to save memory. (not allowed for
negative values)

See also DIM 1099

The software stack is used to store the addresses of LOCAL variables and for variables
that are passed to SUB routines.

Each LOCAL variable and passed variable to a SUB/FUNCTION, requires two bytes to
store the address (because it is a 16-Bit address = 2 bytes).
So when you have a SUB routine in your program that passes 10 variables, you need
10 * 2 = 20 bytes.
When you use 2 LOCAL variables in the SUB program that receives the 10 variables,
you need additional 2 * 2 = 4 bytes.

© 2021 MCS Electronics


BASCOM HARDWARE 247

See also DECLARE SUB 1093 , DECLARE FUNCTION 1090

The software stack ($SWSTACK 609 ) size can be calculated by taking the maximum
number of parameters in a SUB routine, adding the number of LOCAL variables and
multiplying the result by 2. To be safe, add 4 more bytes for internally used LOCAL
variables.

LOCAL variables are stored in a place that is named the Frame ($FRAMESIZE 545 )

When you have a LOCAL STRING with a size of 40 bytes, and a LOCAL LONG, you
need 41 + 4 bytes = 45 bytes of frame space.

When you use conversion routines such as STR 740 , VAL 743 , HEX 737 , INPUT 1359 etc. that
convert from numeric to string and vice versa, you also need a frame. Note that the
use of the INPUT 1359 statement with a numeric variable, or the use of the PRINT 1367 or
LCD 562 statement with a numeric variable, will also force you to reserve 24 bytes of
frame space. This because these routines use the internal numeric<>string
conversion routines.

In fact, the compiler creates a buffer of 24 bytes that serves as scratchpad for
temporary variables, and conversion buffer space. So the frame space should be 24
at minimum ($FRAMESIZE 545 = 24). This 24 Byte start at the beginning of the
Frame which act as the conversion buffer within the frame

For an ATXMEGA or ATMEGA you have usually enough SRAM so you can start with
higher values of Stack and Frame.

With an ATTINY13 and 64Byte SRAM it is a challenge but also start with all stack
defined and lower the Stack Values when your application program grows.

· Avoid to use SUB or FUNCTIONS (If you want to save SRAM space)
· If you use Functions like PRINT, LCD, INPUT and the FP num <> FORMAT(), String
conversion you need to define the 24 Byte conversion buffer (at least 24Byte for
Software Stack + FRAME together).

In this case just 9 Bytes are left for global variables !

See also: $HWSTACK 553 , $SWSTACK 609 , $FRAMESIZE 545

XRAM
Some processors have an external memory interface. For example the ATMEGA128
has such an interface.
The additional memory is named XRAM memory (extended or external memory).
When you add 32 KB RAM, the first address will be 0.
But because the XRAM can only start after the internal SRAM, the lower memory
locations of the XRAM will not be available for use. The processor will automatically
use the SRAM if an address is accessed that is in range of the SRAM memory.
Thus adding 32KB of XRAM, will result in a total of 32 KB RAM.

With ATXMEGA you can add XRAM with the EBI (External Bus Interface). There is no
problem to add for example
16 MByte of external SDRAM.
See CONFIG XRAM 1036

© 2021 MCS Electronics


248 BASCOM-AVR

ERAM
Most AVR chips have internal EEPROM on board.
This EEPROM can be used to store and retrieve data.
In BASCOM, this data space is called ERAM.

An important difference is that an ERAM variable can only be written to a maximum


of 100.000 times. So only assign an ERAM variable when it is required, and never
use it in a loop or the ERAM will become unusable.
Always use the Brown out detection of the processor to prevent EEPROM corruption.

See also DIM 1099


For ATXMEGA see also CONFIG EEPROM 851

Constant code usage


Constants are stored in a constant table.
Each used constant in your program will end up in the constant table.

For example:
P r i n t "ABCD"
P r i n t "ABCD"

This example will only store one constant (ABCD).


P r i n t "ABCD"
P r i n t "ABC"

In this example, two constants will be stored because the strings differ.

Stack

See also: $HWSTACK 553 , $SWSTACK 609 , $FRAMESIZE 545

The Stack is a part of SRAM (Static RAM). In SRAM the compiler stores user
dimensioned variables, as well as internal variables, but SRAM holds also Hardware
Stack, Software Stack and Frame. The Variables always start at the lowest SRAM
Address. After Reset all SRAM Bytes are 0 (and strings are "") so the SRAM memory is
cleared after reset. With the $noramclear option you can turn this behavior off which
means the SRAM is not cleared after reset.

The available SRAM depends on the Chip.

With ATTINY13 for example you have 64Byte of SRAM and you will find this
information beside the user manual in the *.DAT file. You can also double click the
chip in Chip Pinout to view the chip parameters.

The following you find in the attiny13.dat file: SRAM = 64 ; SRAM


size

Global Variables start with the lowest SRAM Address and the Hardware Stack start
with the highest SRAM Address.

© 2021 MCS Electronics


BASCOM HARDWARE 249

Example for using with Bascom-AVR Simulator:


$regfile = "attiny13.dat"
$crystal = 4000000
$hwstack = 30
$swstack = 0
$framesize = 24
Dim B As Byte
B = 5

Pcmsk = &B00000001 'PIN Change Int


ON PCINT0 pin_change_isr
S e t Gimsk. 5
Enable I n t e r r u p t s

Do
!NOP
Loop
End 'end program

p i n _ c h a n g e _ i s r:
B = 7
Return

With an ATTINY13 the SRAM is just 64Byte and it is easy to see which SRAM Bytes
will be overwritten with Bascom AVR Simulator Memory Window.

Click on M to display the memory window.

© 2021 MCS Electronics


250 BASCOM-AVR

Picture: SRAM of ATTINY13 when executing the above ATTINY13 example in Bascom
Simulator

You can see the Hardware Stack (32 Byte) , Frame (24 Byte) and the Variable B.
For this example you do not really need a Frame so it could be also $framesize = 0 for
this example.

With ATXMEGA128A1 there is 8K Byte of SRAM available and you can find in the DAT
file (SRAM = 8192 ; SRAM size )

The Values of Stack should be ALWAYS defined at the beginning of any


BASCOM-AVR Program in the main project file. The best place is right after the
$REGFILE 598 statement.

Example:
$hwstack = 32 ' default use 32 for the
hardware stack
$swstack = 32 ' default use 32 for the SW
stack
$framesize = 40 ' default use 40 for the frame
space

The following example show what can happen when


you define NO Stacks or Frame or when you define
not enough Stack or Frame.
In this example we use: $hwstack = 64, $swstack = 0, $framesize = 8

As we know now Software Stack and FRAME together must be as absolute minimum
24 Byte (for the conversion buffer) so we force the overwriting of Hardware Stack
which causes malfunction.

© 2021 MCS Electronics


BASCOM HARDWARE 251

(Reminder: Don’t start with the lowest values for Stack and Frame)

Picture : SRAM for example with$hwstack = 64, $swstack = 0, $framesize = 8

You can now imagine what could happen:

· Because of overwritten return address in Hardware Stack the micro is jumping to


somewhere else and malfunction if forced.
· Functions like PRINT overwrite addresses of LOCAL Variables and here also will the
micro jump to somewhere else and malfunction is forced.

© 2021 MCS Electronics


252 BASCOM-AVR

Picture: Simulator Memory Windows for example with $hwstack = 64, $swstack = 0,
$framesize = 8

Now an example for passing an Array to a SUB:

With this example we see the complete SRAM.


The SRAM start with the dimed variables. In this case it start with the variable I
followed by the Array Ar of 16 Byte and in the end the variable B.

Because it is easier with the memory window of Bascom Simulator I choose multiple
of 16 for Stack and Framesize.
We have here 2 Addresses stored in Software Stack. One address for the Array and
one address for the variable B.

So passing an Array to a SUB just need 2 Bytes for the address in Stack which is the
same size as for one Byte variable (here variable B).

© 2021 MCS Electronics


BASCOM HARDWARE 253

Picture: Simulator Memory Window for example passing an Array to a SUB

With this example you also see that especially with ATTINY and smaller ATMEGA it is
not that complicated to see if other SRAM bytes will be overwritten by something and
causes malfunction.
You have with the Simulator window the “big picture” of SRAM and STACK together.

As already written it is easier to use multiple of 16 for Hardware Stack, Software


Stack and FRAME as a starting point because one line in Simulator Memory window is
16 Bytes.

How to see which Variables are stored on which SRAM


Byte ?
You can find out the stored variable with the Bascom-AVR Simulator Memory Window

© 2021 MCS Electronics


254 BASCOM-AVR

by clicking on that byte.


Click on SRAM Bytes show the OCCUPIED BY in the footer of that window.
Only the first Byte of an Array will show the Name of the Array !

Picture: How to see which Variables are stored on which SRAM Byte

You can also find this information in the Compiler output report:
In this case under VARIABLES

© 2021 MCS Electronics


BASCOM HARDWARE 255

Picture: How to see which Variables are stored on which SRAM Address

The following small example is good for examining the Bascom-AVR internal variables
like _sec, _min or _hour in Bascom-AVR Simulator Memory Window.

Config Clock = User for example create the internal variables for seconds (_sec),
minutes (_min) ,hour (_hour) etc…. You can see this variables by clicking on the
SRAM Byte and watch the footer of that Bascom-AVR Simulator Memory Window
footer.

$regfile = "m88def.dat"
$hwstack = 48
$swstack = 80
$framesize = 80

Config Clock = User

End 'end program

© 2021 MCS Electronics


256 BASCOM-AVR

Picture: Internal Variables in the Bascom-AVR Simulator Memory Window

See also: $HWSTACK 553 , $SWSTACK 609 , $FRAMESIZE 545

© 2021 MCS Electronics


BASCOM HARDWARE 257

4.14 Statements and Hardware Resources


Some of the BASCOM statements and functions use a hardware resource.
This is a list of hardware resources and the statement/functions that use them.

USART0
$BAUD, BAUD

USART1
$BAUD1 , BAUD1,

USARTx
BUFSPACE, CLEAR, ECHO, WAITKEY, ISCHARWAITING, INKEY, INPUTBIN, INPUTHEX,
INPUT, PRINT, PRINTBIN

TIMER0
DCF77 , READHITAG , GETRC5 , CONFIG SERVOS , TIME$, DATE$

TIMER1
DTMFOUT , RC5SEND, RC6SEND , SONYSEND.

TIMER2
TIME$, DATE$

ADC
GETADC

EEPROM
READEEPROM, WRITEEPROM

TWI
I2CINIT, I2CRECEIVE, I2CSEND, I2START I2CSTOP I2CRBYTE I2CWBYTE

SPI
SPIIN, SPIINIT, SPIMOVE, SPIOUT - SPI

CAN
CONFIG CANBUS, CONFIG CANMOB, CANBAUD, CANRESET, CANCLEARMOB,
CANCLEARALLMOBS, CANSEND, CANRECEIVE, CANID, CANSELPAGE, CANGETINTS

4.15 Using the UART


UART
A Universal Asynchronous Receiver and Transmitter (UART) can be used to send and
receive data between two devices. More specific these devices can be PC-to-PC, PC-
to-micro controller and micro controller-to-micro controller. The UART communicates
using TTL voltages +5V and 0V or LVTTL depending on your micro controllers VCC
voltage.

If you wish to connect to a PC you need to use RS232 protocol specifications. This
means that the hardware communication is done with specific voltage levels. (+15V
and -15V) This can be achieved by using a MAX232 level shifter.

The hardware is explained in this schematic:

© 2021 MCS Electronics


258 BASCOM-AVR

The DB-9 connector has 9 pins but you only need to use 3 of them. Notice that the
drawing above shows the FRONT VIEW thus remember that you are soldering on the
other side. On most connectors the pin outs can also be found on the connector itself.

If your controller has no UART you can use a software UART see below. If your
controller has one UART you connect controller pins TxD and RxD to TxD and RxD in
the schematic above. If your controller has more than one UART you connect
controller pins TxD0 and RxD0 to TxD and RxD in the schematic above.
You now need to initialize the program in your micro controller, open a new .bas file
and add the following code in the beginning of your program.

$ r e g f i l e = "your micro here def.dat"


$ c r y s t a l = 8000000
$baud = 19200

Make sure to define your micro controller after $regfile for example if you use the ATMega32
$ r e g f i l e = "m32def.dat"

Some new chips can use an internal oscillator, also some chips are configured to use
the internal oscillator by default. Using an internal oscillator means you do not need
an external crystal.

Perform this step only if you have an internal oscillator.


Open the BASCOM-AVR programmer like this:

· Select the “Lock and Fuse Bits” tab and maximize the programmer window.
· Check if you see the following in the “Fusebit” section:
"1:Divide Clock by 8 Disabled"
and
"Int. RC Osc. 8 MHz; Start-up time: X CK + X ms; [CKSEL=XXXX SUT=XX]"

© 2021 MCS Electronics


BASCOM HARDWARE 259

These options are not available for all AVR’s, if you don’t have the option do not
change any fuse bits.

If these options are available, but in a wrong setting. Change the setting in the drop
down box and click another Fuse section. Finally click the "Program FS" button. Click
"Refresh" to see the actual setting.

Now connect a straight cable between the DB-9 connector, micro controller side and
the PC side.
Program a test program into your micro controller, it should look like this:

$ r e g f i l e = "m32def.dat" 'Define your own


$ c r y s t a l = 8000000
$baud = 19200

Do
Print "Hello World"
Waitms 25
Loop

End

Now open the BASCOM-AVR Terminal and set your connection settings by clicking
“Terminal” -> “Settings” Select your computers COM port and select baud 19200,
Parity none, Data bits 8, Stop bits 1, Handshake none, emulation none.

© 2021 MCS Electronics


260 BASCOM-AVR

If you see the Hello World displayed in the BASCOM-AVR Terminal emulator window,
your configuration is OK. Congratulations.

Example
You can also try this example with the BASCOM Terminal emulator, it shows you how to send and
receive with various commands.

$regfile = "m88def.dat"
$crystal = 8000000
$baud = 19200

Dim Akey As Byte 'Here we declare a byte variable

Print
Print "Hello, hit any alphanumerical key..."
Akey = Waitkey() 'Waitkey waits untill a char is received from the UART
Print Akey

Wait 1
Print
Print "Thanks!, as you could see the controller prints a number"
Print "but not the key you pressed."

Wait 1
Print
Print "Now try the enter key..."
Akey = Waitkey()
Akey = Waitkey()
Print Akey

Print
Print "The number you see is the ASCII value of the key you pressed."

© 2021 MCS Electronics


BASCOM HARDWARE 261

Print "We need to convert the number back to the key..."


Print 'Notice what this line does
Print "Please try an alphanumerical key again..."
Akey = Waitkey()
Print Chr(akey) 'Notice what this does
Print "That's fine!"

Wait 1
Print
Print "For a lot of functions, just one key is not enough..."
Print "Now type your name and hit enter to confirm"

Dim Inputstring As String * 12 'Declare a string variable here

Do
Akey = Waitkey()
If Akey = 13 Then Goto Thanks 'On enter key goto thanks
Inputstring = Inputstring + Chr(akey) 'Assign the string
Loop

Thanks:
Print "Thank you " ; Inputstring ; " !" 'Notice what ; does

Wait 1
Print
Print "Take a look at the program code and try to understand"
Print "how this program works. Also press F1 at the statements"
Print
Print "If you understand everything continue to the next experiment"

End

ASCII
As you could have seen in the previous example we use the PRINT statement to send
something to the UART. Actually we do not send just text. We send ASCII characters.
ASCII means American Standard Code for Information Interchange. Basically ASCII is
a list of 127 characters.

ASCII Table (Incomplete)

Decimal Hex Binary Value


------- --- ------ -----
000 000 00000000 NUL (Null char.)
008 008 00001000 BS (Backspace)
009 009 00001001 HT (Horizontal Tab)
010 00A 00001010 LF (Line Feed)
012 00C 00001100 FF (Form Feed)
013 00D 00001101 CR (Carriage Return)
048 030 00110000 0
049 031 00110001 1
052 034 00110100 4
065 041 01000001 A
066 042 01000010 B
067 043 01000011 C

You can find a complete ASCII table here 505

CARRIAGE RETURN (CR) AND LINE FEED (LF)


In the previous example you can also see that a second print statement always prints
the printed text to the following line. This is caused by the fact that the print
statement always adds the CR and LF characters.

© 2021 MCS Electronics


262 BASCOM-AVR

Basically if we state:
Print “ABC”
We send 65 66 67 13 10 to the UART. (In binary format)

The carriage return character (13) returns the cursor back to column position 0 of the
current line. The line feed (10) moves the cursor to the next line.

Print “ABC” ;
When we type a semicolon ( ; ) at the end of the line...
Bascom does not send a carriage return/line feed, so you can print another text after
the ABC on the same line.

Print “ABC” ; Chr(13) ;


This would send only ABC CR. The next print would overwrite the ABC.

OVERVIEW
Here are some other commands that you can use for UART communications:

Waitkey( )
Waitkey will until a character is received in the serial buffer.

I s c h a r w a i t i n g( )
Returns 1 when a character is waiting in the hardware UART buffer.

I n k e y( )
Inkey returns the ASCII value of the first character in the serial input buffer.

Print
Sends a variable or non-variable string to the UART

ANOTHER EXAMPLE
This example shows how to use Ischarwaiting to test if there is a key pressed. And if there is, read
to a variable.

'Print "Press B key to start"


Dim Serialcharwaiting As Byte, Serialchar As Byte

Serialcharwaiting = Ischarwaiting() 'Check if B or b pressed then goto


If Serialcharwaiting = 1 Then
Serialchar = Inkey()
If Serialchar = 66 Or Serialchar = 98 Then
Goto MyRoutine
End If
End If

Goto Main

Myroutine:
'Statements

Main:
'Statements
End

BUFFERING SERIAL DATA


If you wish to send and receive data at high speed, you need to use serial input and

© 2021 MCS Electronics


BASCOM HARDWARE 263

serial output buffers. This buffering is implemented in BASCOM-AVR and can only be
used for hardware UART’s.

To configure a UART to use buffers, you need to use the Config statement.

Config Serialout = Buffered , Size = 20


and/or
Config Serialin = Buffered , Size = 20

More information can be found in BASCOM-Help. Search topic = "config serialin" 939 .
There is also a sample program “RS232BUFFER.BAS” in the samples folder if you wish
a demonstration of the buffering.

SOFTWARE UART
The previous examples used the hardware UART. That means the compiler uses the
internal UART registers and internal hardware (RxD(0) and TxD(0)) of the AVR. If you
don’t have a hardware UART you can also use a software UART.

The Bascom compiler makes it easy to “create” additional UART’s. Bascom creates
software UART’s on virtually every port pin.

Remember that a software UART is not as robust as a hardware UART, thus you can
get timing problems if you have lots of interrupts in your program.

For this example we use micro controller pins portc.1 and portc.2.
Connect portc.1 to TxD and portc.2 to RxD see the schematic above.

Change the $regfile and program this example:

$regfile = "m88def.dat"
$crystal = 8000000
$baud = 19200

Dim B As Byte
Waitms 100

'Open a TRANSMIT channel for output


Open "comc.1:19200,8,n,1" For Output As #1
Print #1 , "serial output"

'Now open a RECEIVE channel for input


Open "comc.2:19200,8,n,1" For Input As #2
'Since there is no relation between the input and output pin
'there is NO ECHO while keys are typed

Print #1 , "Press any alpha numerical key"

'With INKEY() we can check if there is data available


'To use it with the software UART you must provide the channel
Do
'Store in byte
B = Inkey(#2)
'When the value > 0 we got something
If B > 0 Then
Print #1 , Chr(b) 'Print the character
End If
Loop
Close #2 'Close the channels
Close #1

© 2021 MCS Electronics


264 BASCOM-AVR

End

After you have programmed the controller and you connected the serial cable, open
the terminal emulator by clicking on in Bascom.
You should see the program asking for an alphanumerical input, and it should print
the input back to the terminal.

4.16 USING RS485


RS485
RS485 is used for serial communication and well suited for transmission over large
distances.
Similar to RS232 we need a level shifter.

The sample above uses a MEGA161 or MEGA162 which has 2 UARTS. This way you
can have both a RS232 and RS485 interface.
The RS232 is used for debugging.
In order to test you need 2 or more similar circuits. One circuit would be the master.
The other(s) would be a slave.

© 2021 MCS Electronics


BASCOM HARDWARE 265

The same hardware is used to test the MODBUS protocol. The bus need to be
terminated at both ends with a resistor. 100 ohm is a typical used value.
The GND of both circuits may not be connected ! Only connect point A and B from
both circuits. For industrial usage it is best to use an optical isolated level shifter.

Simple MASTER sample


$regfile = "m162def.dat" ' specify the used micro
$crystal = 8000000
$baud = 19200 ' use baud rate
$hwstack = 42 ' default use 32 for the hardware stack
$swstack = 40 ' default use 10 for the SW stack
$framesize = 40 ' default use 40 for the frame space

$lib "modbus.lbx"
Config Print1 = Portb.1 , Mode = Set ' use portb.1 for the direction
Rs485dir Alias Portb.1
Config Rs485dir = Output
Rs485dir = 0 ' go to receive mode
Portc.0 = 1 ' a switch is connected to pinc.0 so activate pull up resistor
' TX RX
' COM0 PD.1 PD.0 monitor
' COM1 PB.3 PB.2 rs485
' PB.1 data direction rs485

Config Com1 = Dummy , Synchrone = 0 , Parity = None , Stopbits = 1 , Databits =


8 , Clockpol = 0
Config Com2 = 9600 , Synchrone = 0 , Parity = Even , Stopbits = 1 , Databits = 8 ,
Clockpol = 0 ' MUST MATCH THE SLAVE

'use OPEN/CLOSE for using the second UART


Open "COM2:" For Binary As #1

'dimension some variables


Dim B As Byte
Dim W As Word
Dim L As Long

W = &H4567 ' set some values


L = &H12345678

Print "RS-485 MODBUS master"


Do
If Pinc.0 = 0 Then ' test button
Waitms 500 ' delay since we want to send just 1
frame
Print "send request to slave/server" ' to debug terminal
' Print #1 , Makemodbus(2 , 3 , 8 , 2); 'slave 2, function 3, start
address 8, 2 bytes
' Print #1 , Makemodbus(2 , 6 , 8 , W); 'slave 2, function 6, address
8 , value of w
Print #1 , Makemodbus(b , 16 , 8 , L); 'send a long
End If
If Ischarwaiting(#1) <> 0 Then 'did we got something back?
B = Waitkey(#1) ' yes so get it

© 2021 MCS Electronics


266 BASCOM-AVR

Print Hex(b) ; ","; ' print it


End If
Loop

A slave would simply listen to data, and once enough data received, send it back.

4.17 Using the I2C protocol


I²C bus
I²C bus is an abbreviation for Inter Integrated Circuit bus or "I-Squared-C".
Some manufacturer call it TWI (Two-Wire-Interface) which is technically the same as
I2C.

There is also SMBus. The I²C bus and the SMBus™ are essentially compatible with
each other. Normally devices, both masters and slaves, are freely interchangeable
between both buses. Both buses feature addressable slaves (although specific
address allocations can vary between the two).
The buses operate at the same speed, up to 100kHz, but the I²C bus has both
400kHz and 2MHz
versions. Complete compatibility between I2C and SMBus is ensured only below
100kHz.

I²C is a serial and synchronous bus protocol. In standard applications hardware and
timing are often the same. The way data is treated on the I²C bus is to be defined by
the manufacturer of the I²C master and slave chips.

In a simple I²C system there can only be one master, but multiple slaves. The
difference between master and slave is that the master generates the clock pulse.
The master also defines when communication should occur. For bus timing it is
important that the slowest slave should still be able to follow the master’s clock.
In other words the bus should be as fast as the slowest slave.

A typical hardware configuration is shown in the figure below:

Note that more slave chips can be connected to the SDA and SCL lines, normally Rp
has a value of 1kOHM.

© 2021 MCS Electronics


BASCOM HARDWARE 267

The clock generated by the master is called Serial Clock (SCL) and the data is called
Serial Data (SDA).

Always check if the pull-up resistors are connected !

In most applications the micro controller is the I²C Master. Slave chips can be Real
Time Clocks and Temperature sensors. For example the DS1307 and the DS1624
from http://www.maximintegrated.com .

Of course you can also create your own I2C slaves by programming an ATTINY or
ATMEGA . See CONFIG I2CSLAVE 875
In that case there is AVR Master to AVR Slave communication.

LOGIC BUS LEVELS AND CONDITIONS

Data can only occur after the master generates a start condition. A start condition is
a high-to-low transition of
the SDA line while SCL remains high. After each data transfer a stop condition is generated. A
stop condition is a low-to-high transition of the SDA line while SCL remains high.

As said a data transfer can occur after a start condition of the master. The length of
data sent over I²C is always 8 bit this includes a read/write direction bit, so you can
effectively send 7 bits every time.
The most significant bit MSB is always passed first on the bus.

If the master writes to the bus the R/W bit = 0 and if the master reads the R/W bit = 1.

After the R/W bit the master should generate one clock period for an acknowledgement ACK.

Each receiving chip that is addressed is obliged to generate an acknowledge after the
reception of each byte. A chip that acknowledges must pull down the SDA line during
the acknowledge clock pulse in such a way that the SDA line is stable LOW during the
HIGH period of the acknowledge related clock pulse.

© 2021 MCS Electronics


268 BASCOM-AVR

After an acknowledge there can be a stop condition, if the master wishes to leave the
bus idle. Or a repeated start condition. A repeated start is the same as a start
condition.

When the master reads from a slave it should acknowledge after each byte received.
There are two reasons for the master not to acknowledge. The master sends a not
acknowledge if data was not received correctly or if the master wishes the stop
receiving.

In other words if the master wishes to stop receiving, it sends a not


acknowledge after the last received byte.

The master can stop any communication on the bus at any time by sending a stop
condition.

BUS ADRESSING
Let’s say we have a slave chip with the address &B1101000 and that the master wishes
to write to that slave, the slave would then be in receiver mode, like this:

You can see here that the master always generates the start condition, then the
master sends the address of the slave and a “0” for R/W. After that the master sends
a command or word address. The function of that command or word address can be
found in the data sheet of the slave addressed.

After that the master can send the data desired and stop the transfer with a stop
condition.

Again the start condition and the slave address, only this time the master sends “1”
for the R/W bit. The slave can then begin to send after the acknowledge. If the
master wishes to stop receiving it should send a not acknowledge.

OVERVIEW of Routines
Config Sda = P o r t x . x
Configures a port pin for use as serial data SDA.

Config Scl = P o r t x . x
Configures a port pin for use as serial clock SCL.

© 2021 MCS Electronics


BASCOM HARDWARE 269

I2cinit
Initializes the SCL and SDA pins.

I2cstart
Sends the start condition.

I2cstop
Sends the stop condition.

I2cwbyte
Writes one byte to an I²Cslave.
I2crbyte
Reads one byte from an I²Cslave.

I2csend
Writes a number of bytes to an I²Cslave.

I2creceive
Reads a number of bytes from an I²Cslave.

I2C write and read:


A typical I2C write to send one byte of data looks like this:

I2cstart
I2cwbyte I2c_address_of_slave
I2cwbyte Byte_to_send
I2cstop

(I 2 c s t a r t generates the start condition on the I2C bus were all devices are listen to.
After this we send the Slave address of the device we want to send a byte to. The I2C
slave with this address will send out a Ack where all other do nothing. Now you can
start to send a byte (or more bytes) to this Slave address. After this an I 2 c s t o p
release the bus.)

A typical I2C read to read one byte of data looks like this:

I2cstart
I2cwbyte I2c_address_of_slave
I2crbyte Databyte_to_read , Nack
I2cstop

(Nack indicates that the master do not want to read more bytes)

A typical I2C read to read one byte of data looks like this:

I2cstart
I2cwbyte I2c_address_of_slave
I2crbyte Databyte_to_read , Ack
I2crbyte Databyte_to_read , Nack
I2cstop

(Ack indicates that the master want to read more bytes from the slave and with the
last byte to read the master indicate this with Nack)

I2C Software vs. Hardware Routines


By default BASCOM will use software routines when you use I2C statements. This
because when the first AVR chips were introduced, there was no TWI yet. Atmel
named it TWI because Philips is the inventor of I2C. But TWI is the same as I2C.

© 2021 MCS Electronics


270 BASCOM-AVR

So BASCOM allows you to use I2C on every AVR chip. Most newer AVR chips have
build in hardware support for I2C. With the I2C_TWI lib you can use the TWI which
has advantages as it require less code.

To force BASCOM to use the TWI, you need to insert the following statement into your
code:

$LIB "I2C_TWI.LBX"

You also need to choose the correct SCL and SDA pins with the CONFIG SCL and
CONFIG SDA statements.
The TWI will save code but the disadvantage is that you can only use the fixed SCL
and SDA pins.

When using XMEGA, there is a difference : here you are supposed to use the
hardware TWI. So that is a default. To force to the software solution, use
$FORCESOFTI2C 540

See also:
Using USI (Universal Serial Interface) 289 , Config TWI 999 , CONFIG TWISLAVE 1005 ,
I2C_TWI 1607 , $FORCESOFTI2C 540
I2CSEND 1173 , I2CSTART 1174 , I2CSTOP 1174 , I2CRBYTE 1174 , I2CWBYTE 1174 , I2C_TWI
Library for using TWI 1607

EXAMPLE with Software Routines


This example shows you how to setup and read the temperature from a DS1624
temperature sensor.
Connect the DS1624 like this:

Then program this sample into your micro controller and connect your micro
controller to the serial port of your PC.
$ r e g f i l e = "m88def.dat" 'Define the chip you use
$ c r y s t a l = 8000000 'Define speed
$hwstack = 40

© 2021 MCS Electronics


BASCOM HARDWARE 271

$swstack = 30
$framesize = 40

$baud = 19200 'Define UART BAUD rate

' Declare RAM for temperature storage


Dim I2ctemp As Byte 'Storage for the temperature
' We use here the software emulated I2C routines
' Configure pins we want to use for the I²C bus
Config Scl = P o r t d. 1 'Is serial clock SCL
Config Sda = P o r t d. 3 'Is serial data SDA
I2cinit

' Declare constants - I2C chip addresses


Const Ds1624wr = &B10010000 'DS1624 Sensor write
Const Ds1624rd = &B10010001 'DS1624 Sensor read
' This section initializes the DS1624
I2cstart 'Sends start condition
I2cwbyte Ds1624wr 'Sends the address
'byte with r/w 0
'Access the CONFIG register (&HAC address byte)
I2cwbyte &HAC
'Set continuous conversion (&H00 command byte)
I2cwbyte &H00
I2cstop 'Sends stop condition
Waitms 25 'We have to wait some time after a stop
I2cstart
I2cwbyte Ds1624wr
'Start conversion (&HEE command byte)
I2cwbyte &HEE
I2cstop
Waitms 25
'End of initialization
Print 'Print empty line

Do

'Get the current temperature


I2cstart
I2cwbyte Ds1624wr
I2cwbyte &HAA 'Read temperature (&HAA command byte)
I2cstart
I2cwbyte Ds1624rd 'The chip will give register contents
'Temperature is stored as 12,5 but the ,5 first
I 2 c r b y t e I2ctemp , Ack
'So you'll have to read twice... first the ,5
I 2 c r b y t e I2ctemp , Nack
'And then the 12... we don't store the ,5
I2cstop
'That's why we read twice.

'We give NACK if the last byte is read


'Finally we print
P r i n t "Temperature: " ; S t r( i 2 c t e m p) ; " degrees" ; Chr( 13) ;

Waitms 25

Loop
End

You should be able to read the temperature in your terminal emulator.


Note that the used command bytes in this example can be found in DS1624
temperature sensor data sheet.

Example which use I2C Master hardware in AVR


See here: CONFIG TWI 999

© 2021 MCS Electronics


272 BASCOM-AVR

I2C Practice (Tips&Tricks)


The design below shows how to implement an I2C-bus. The circuit is using a Mega88
as a master.
The TWI bus is used. While you can use any pin for software mode I2C, when a micro
has TWI hardware build in, it is advised to use the TWI hardware.

R1 and R2 are 4K7 pull up resistors.

There are many I2C slave chips available. The example shows the PCF8574. With the
additional TWI slave library you can make your own slave chips.

How to calculate Pull Up Resistor


The maximum of bus capacitance is 400pF (which is independent of bus speed
100KHz or 400KHz).
Here is a good article which describe how to calculate the Pull Up Resistor:
http://www.edn.com/design/analog/4371297/Design-calculations-for-robust-I2C-com
munications

Using AVR interal pull-up resistor (with Hardware


Routines)
It is recommended to use external pull-up resistors !
For testing you could use also the AVR interal pull-up resistors

See example where Portc.4 and Portc.5 is SDA and SCL (the pull-up needs to be set

© 2021 MCS Electronics


BASCOM HARDWARE 273

after i2cinit):

i2cinit
P o r t c. 4 = 1
P o r t c. 5 = 1

Active Termination of I2C


The following information was submitted by Detlef Queck:
Many people have problems over and over with I2C(TWI) Termination. Use 4,7k or 10
k pull up? How long can the SCL, SDA line be when used with pull ups etc, etc.
You can simplify this confusing problem. Here is a Schematic for an active
Termination of I2C and TWI. We have used this Schematic for over 10 years, and
have had no problems with it. The I2C (TWI) lines can be up to 80cm (400KHz)
without any problem when the Terminator is at the end of the lines.

How to handle longer cable length between I2C Master


and Slaves or Multi-drop Configurations
The I2C-bus capacitance limit of 400 pF restricts practical communication distances.
You can extend the use of the I2C in systems
with more devices and / or longer bus lengths with P82B715 or P82B96.

P82B96
· Isolates capacitance allowing 400 pF on Sx/Sy side and 4000 pF on Tx/Ty side
· 400 kHz operation over at least 20 meters of wire (see AN10148)
· Create Multi-drop configurations
· Supply voltage range of 2 V to 15 V with I2C-bus logic levels on Sx/Sy side
independent of supply voltage
· Splits I2C-bus signal into pairs of forward/reverse Tx/Rx, Ty/Ry signals for interface
with opto-electrical isolators and similar devices that need unidirectional input and
output signal paths.

© 2021 MCS Electronics


274 BASCOM-AVR

P82B715
· Increase the total connected capacitance of an I2C-bus system to around 3000 pF
and drive signals over long cables to approximately 50m
· Multi-drop distribution of I2C-bus signals using low cost twisted-pair cables

I2C Multiplexing, Switch and Voltage Level translation


between different I2C busses
Some specialized devices only have one I2C or SMBus address and sometimes
several identical devices are needed in the same system. The multiplexers and
switches split the I2C bus into several sub-branches and allow the I2C master to
select and address one of multiple identical devices, in order to resolve address
conflict issues. An example is PCA9544A or PCA9546A (which also llows voltage level
translation between 1.8 V, 2.5 V, 3.3 V and 5 V buses).

Your I2C (TWI) connection is not working


(Tips&Tricks):
Checklist:
- Is the configured I2C clock frequency matching the frequency of the connected
chip
- Check if you have pull-up resistors on SDA and SCL (and if the pull-up resistors
are working)
- Do you have the right SDA and SCL pins conected ?
- connect also GND to have the same potential
- You can use the E r r variable to check which I2C function is not working. When
an error occurs, the internal ERR variable will return 1. Otherwise it will be set to
0.
- How about the voltage levels on both chips (do not connect 3.3V systems to 5V
systems without voltage adapter)

- Is the system you are connecting the I2C to using a 7 Bit address or 8 Bit
address (8-bit addresses include the read/write bit) ?
Then you can try with shift left:
' you can simply do this; &HC4 is an example address
const someI2caddress= &H4C * 2
' this would shift the address to the left.

- It is important that you specify the proper crystal frequency. Otherwise it will
result in a wrong TWI clock frequency

- With following lib you do not use the software emulated TWI (I2C). You use the
hardware I2C (for the AVR's that have an hardware I2C)
$lib "i2c_twi.lbx" ' we do not use software
emulated I2C but the TWI
- By default BASCOM will use software routines for I2C.
- Do you have the right I2C read address ?
Here an example I2C write address which Bascom expects:
&B01000000 = &H40
Read address would be for this example:
&b01000001 = &h41

- In case of using TWI (I2C) Slave: Are you using the right library for your used
chip ?

With the I2C TWI Slave add-on library you get both libraries:
• i2cslave.lib and i2cslave.lbx : This library is used for AVR‘s which have no

© 2021 MCS Electronics


BASCOM HARDWARE 275

hardware TWI/I2C interface like for example ATTINY2313 or ATTINY13. In this


case TIMER0 and INT0 is used for SDA and SCL (Timer0 Pin = SCL, INT0 Pin =
SDA). Only AVR' with TIMER0 and INT0 on the same port can use this library
like for example ATTINY2313 or ATTINY13. The i2cslave.lib file contains the ASM
source. The i2cslave.lbx file contains the compiled ASM source. See CONFIG
I2CSLAVE below.

• i2c_TWI-slave.LBX : This library can be used when an AVR have an TWI/I2C


hardware interface like for example ATMEGA8, ATMEGA644P or ATMEGA128. In
this case the hardware SDA and SCL pin's of the AVR will be used (with
ATMEGA8: SCL is PORTC.5 and SDA is PORTC.4). This library will be used when
USERACK = OFF. When USERACK =ON then i2c_TWI-slave-acknack.LBX will
be used. See also Config TWISLAVE 1005

Operation at 400 kHz


Fast- mode devices can only be operated at 400 kHz clock frequency if no
standard-mode devices (100KHz) are on the bus.

You can use an I2C Scanner to find I2C devices:


You basically use the E r r variable. When an error occurs, the internal ERR variable
will return 1. Otherwise it will be set to 0.
So 0 means we have found a I2C Slave with that address.

'------------------------------------------------------------------
' (c) 1995-2021 MCS
' i2cscan.bas
'purpose : scan all i2c addresses to find slave chips
'use this sample in combination with twi-slave.bas
'Micro: Mega88
'------------------------------------------------------------------
$ r e g f i l e = "M88def.dat" ' the used chip
$ c r y s t a l = 8000000 ' frequency used
$baud = 19200 ' baud rate
$hwstack = 40
$swstack = 30
$framesize = 40
Dim B As Byte

'we use the TWI pins of the Mega88


$lib "i2c_twi.lbx" ' we do not use software
emulated I2C but the TWI

Config Scl = P o r t c. 5 ' we need to provide the SCL


pin name
Config Sda = P o r t c. 4 ' we need to provide the SDA
pin name
I2cinit
Config Twi = 100000 ' wanted clock frequency when
using $lib "i2c_twi.lbx"
'will set TWBR and TWSR
'Twbr = 12 'bit rate register
'Twsr = 0 'pre scaler bits

P r i n t "Scan start"
For B = 0 To 254 Step 2 'for all odd addresses
I2cstart 'send start
I2cwbyte B 'send address
I f E r r = 0 Then 'we got an ack
P r i n t "Slave at : " ; B ; " hex : " ; Hex( b) ; " bin : " ; Bin( b)
End I f
I2cstop 'free bus
Next
P r i n t "End Scan"
End

I2C Slave Library

© 2021 MCS Electronics


276 BASCOM-AVR

See I2C TWI Slave 1676

I2C Slave LIB - how to Send/Receive more than 1 Byte


for chips that do not have hardware I2C ?
Using following config:

Config I2cslave = &H34 , I n t = Int0 , Timer = Timer0

When you want to receive/send multiple bytes, you need to keep track of them.
You can do this with a byte counter. this counter you would need to reset when
the slave is addressed.
To do this the lib need to be altered:

- open i2cslave.lib with notepad


- look for label : I2c_adr_ack:
Then add this line :
rcall i2c_master_addressed

-then save and add this label to your code:

I2c_master_addressed:
Br = 0 'clear the byte counter
Bw = 0
return

in your code where the bytes are passed you can increase them.
The BR you increase when a byte is read, the BW you increase when a byte is
passed.
for example:

I2c_master_has_data:
I n c r Bw
Myarray( bw) = _a1
Return

Using ATXMEGA I2C with Software Routines (then you


can choose the SDA and SCL Pins)
ATXMEGA have usually enough I2C interfaces. But nevertheless there is a possibility to use
the I2C software routines and you can use any
Pin you want as SDA and SCL.

Following the ATXMEGA Master and below the ATMEGA328P I2C Slave which was tested with the
ATXMEGA Master in I2C Software Mode:

Master
' Using ATXMEGA with software I2C routines to use also pins which are no hardware SDA/SCL
pins
' Needed Library: $lib "i2c.lbx"
' The $forcesofti2c directive force the ATXMEGA to use software I2c/TWI Library

' The hardware for this example is XMEGA-A3BU XPlained board from Atmel
' Don't forget the pull-ups on SDA/SCL pin !
' Bascom Version 2.0.7.6 or higher needed

$regfile = "XM256A3BUDEF.DAT"
$crystal = 32000000 '32MHz
$hwstack = 64
$swstack = 40
$framesize = 80

$forcesofti2c ' with this the software


I2C/TWI commands are used when inlcuding i2c.lbx

© 2021 MCS Electronics


BASCOM HARDWARE 277

$lib "i2c.lbx" ' override the normal xmega


i2c lib

Config Osc = Enabled , 32mhzosc = Enabled


Config Sysclock = 32mhz , Prescalea = 1 , Prescalebc = 1_1

Config P o r t r. 0 = Output
Led0 A l i a s P o r t r. 0 'LED 0 (XMEGA-A3BU XPlained
board from Atmel )
Config P o r t r. 1 = Output
Led1 A l i a s P o r t r. 1 'LED 1 (XMEGA-A3BU XPlained
board from Atmel )

Dim B As Byte
'We use here Virtual port 0
Config Vport0 = B ' 'map portB to virtual port0

Config Scl = P o r t 0 . 1 ' Pin to use as SCL (The


hardware pin is Pinb.1)
Config Sda = P o r t 0 . 0 ' Pin to use as SDA (The
hardware pin is Pinb.0)
I2cinit ' Bring the Pin's in the
proper state

Do

Waitms 500
S e t Led1
Reset Led0
Waitms 500
Reset Led1
S e t Led0

Incr B
I2cstart
I2cwbyte &H24 ' address of I2C Slave
I2cwbyte B ' databyte to send to slave
I2cstop
Loop

End 'end program

Slave (for ATXMEGA using Soft I2C Master)

' I2C Slave Example for using with ATXMEGA


' ATMEGA328P running @ 3.3 Volt !

' Terminal output of this example when used with XMEGA_ise_soft_i2c.bas:

' (

ATXMEGA using Software TWI/I2C <------> ATMEGA 328P Bascom-AVR @ 3.3V...


>>> 180
>>> 181
>>> 182
>>> 183
>>> 184
>>> 185
>>> 186
>>> 187
>>> 188
>>> 189
>>> 190
>>> 191

' )
$ r e g f i l e = "m328pdef.dat"
$ c r y s t a l = 12e6 '16MHz

© 2021 MCS Electronics


278 BASCOM-AVR

$hwstack = 80
$swstack = 80
$framesize = 160

'CONFIG TWI SLAVE


Config Twislave = &H24 , Btr = 1 , Bitrate = 100000 , Gencall = 1
' With the CONFIG BTR, you specify how many bytes the master will read.

Dim Receive As Byte


Dim S As Byte

Enable I n t e r r u p t s

Config Com1 = 19200 , Synchrone = 0 , Parity = None , Stopbits = 1 , Databits = 8 ,


Clockpol = 0
Wait 3
Print
P r i n t "ATXMEGA using Software TWI/I2C <------> ATMEGA 328P Bascom-AVR @ 3.3V..."
Do
nop
Loop

End 'end program


'--------------------------------I2C--------------------------------------------

'Master sent stop or repeated start


T w i _ s t o p _ r s t a r t _ r e c e i v e d:
Return

'We were addressed and master will send data


Twi_addressed_goread:

Return

'We were addressed and master will read data


Twi_addressed_gowrite:

Return
'this label is called when the master sends data and the slave has received the byte
'the variable TWI holds the received value
'Twi_btw is the BYTE NUMBER
T w i _ g o t d a t a:
Receive = Twi 'lesen
P r i n t ">>> " ; Twi 'Print what we have received
(ONLY FOR TESTING)
Return

'this label is called when the master receives data and needs a byte
'the variable twi_btr is a byte variable that holds the index of the needed byte
'so when sending multiple bytes from an array, twi_btr can be used for the index
'twi_btr is the BYTE NUMBER
Twi_master_needs_byte:
Return

'when the mast has all bytes received this label will be called
Twi_master_need_nomore_byte:
Return
'-------------------------------------------------------------------------------

4.18 Using the 1 WIRE protocol


The 1-wire protocol was invented by Dallas Semiconductors and needs only 1 wire for
two-way communication. You also need power and ground of course.

This topic is written by Göte Haluza. He tested the new 1-wire search routines and is
building a weather station.

Dallas Semiconductor (DS) 1-wire. This is a brief description of DS 1-wire bus when

© 2021 MCS Electronics


BASCOM HARDWARE 279

used in combination with BASCOM. For more detailed explanations about the 1-wire
bus, please go to http://www.maxim-ic.com. Using BASCOM makes the world a lot
easier. This paper will approach the subject from a "BASCOM-user-point-of-view".

1-wire-net is a serial communication protocol, used by DS devices. The bus could be


implemented in two basic ways :

With 2 wires, then DQ and ground is used on the device. Power is supplied on the DQ
line, which is +5V, and used to charge a capacitor in the DS device. This power is
used by the device for its internal needs during communication, which makes DQ go
low for short periods of time. This bus is called the 1-wire bus.

With 3 wires, when +5V is supplied to the VDD line of the device, and DQ + ground
as above. This bus is called the 2-wire bus.

So, the ground line is "not counted" by DS. But hereafter we use DS naming
conventions.

How it works. (1-wire)


The normal state of the bus is DQ=high. Through DQ the device gets its power, and
performs the tasks it is designed for.

When the host (your micro controller (uC)) wants something to happen with the 1-
wire bus, it issues a reset-command. That is a very simple electric function that
happens then; the DQ goes active low for a time (480uS on original DS 1-wire bus).
This put the DS-devices in reset mode; then (they) send a presence pulse, and then
(they) listen to the host.

The presence pulse is simply an active low, this time issued by the device(s).

Now, the host cannot know what is on the bus, it is only aware of that at least 1 DS
device is attached on the bus.

All communication on the 1-wire bus is initialized by the host, and issued by time-
slots of active-low on a normally high line (DQ), issued by the device, which is
sending at the moment. The devices(s) internal capacitor supplies its power needs
during the low-time.

How do you work with 1-wire-bus


Thereafter, you can read a device, and write to it. If you know you only have 1 sensor
attached, or if you want to address all sensors, you can start with a "Skip Rom" -
command. This means; take no notice about the IDs of the sensors - skip that part of
the communication.

When you made a 1-wire-reset, all devices of the bus are listening. If you chose to
address only one of them, the rest of them will not listen again before you have made
a new 1-wire-reset on the bus.

I do not describe BASCOM commands in this text - they are pretty much self-
explanatory. But the uC has to write the commands to the bus - and thereafter read
the answer. What you have to write as a command depends on devices you are using
- and what you want to do with it. Every DS chip has a data sheet, which you can find
at http://www.dalsemi.com/datasheets/pdfindex.html. There you can find out all
about the actual devices command structure.

© 2021 MCS Electronics


280 BASCOM-AVR

There are some things to have in mind when deciding which of the bus-types to use.

The commands, from BASCOM, are the same in both cases. So this is not a problem.

The +5V power-supply on the VDD when using a 2-wire bus has to be from a
separate power supply, according to DS. But it still works with taking the power from
the same source as for the processor, directly on the stabilizing transistor. I have not
got it to work taking power directly from the processor pin.

Some devices consume some more power during special operations. The DS1820
consumes a lot of power during the operation "Convert Temperature". Because the
sensors knows how they are powered (it is also possible to get this information from
the devices) some operations, as "Convert T" takes different amount of time for the
sensor to execute. The command "Convert T" as example, takes ~200mS on 2-wire,
but ~700mS on 1-wire. This has to be considered during programming.

And that power also has to be supplied somehow.

If you use 2-wire, you don't have to read further in this part. You can do
simultaneously "Convert T" on all the devices you attach on the bus. And save time.
This command is the most power-consuming command, possible to execute on
several devices, I am aware of.

If you use 1-wire, there are things to think about. It is about not consuming more
power than you feed. And how to feed power? That depends on the devices (their
consumption) and what you are doing with them (their consumption in a specific
operation).

Short, not-so-accurate description of power needs, not reflecting on cable lengths.

Only the processor pin as power supplier, will work < 5 sensors. (AVR, 1-wire-
functions use an internal pull-up. 8051 not yet tested). Don't even think of
simultaneous commands on multiple sensors.

With +5V through a 4K7 resistor, to the DQ-line, 70 sensors are tested. But, take
care, cause issuing "Convert T" simultaneously, would cause that to give false
readings. About ~15 sensors is the maximum amount of usable devices, which
simultaneously performs some action. This approach DS refers to as "pull-up
resistor".

With this in mind, a bus with up to 70 devices has been successfully powered this
way.

The resistor mentioned, 4K7, could be of smaller value. DS says minimum 1K5, I
have tested down to 500 ohm - below that the bus is not usable any more. (AVR).
Lowering the resistor feeds more power - and makes the bus more noise resistant.
But, the resistor minimum value is naturally also depending on the uC-pin electric
capabilities. Stay at 4K7 - which is standard recommendation.

DS recommends yet another approach, called "strong pull-up" which (short) works via
a MOS-FET transistor, feeding the DQ lines with enough power, still on 1-wire, during
power-consuming tasks. This is not tested, but should naturally work. Because this
functionality is really a limited one; BASCOM has no special support for that. But
anyway, we tell you about it, just in case you wonder. Strong pull-up has to use one
uC pin extra - to drive the MOS-FET.

© 2021 MCS Electronics


BASCOM HARDWARE 281

Cable lengths (this section is only for some limitation understanding)


For short runs up to 30 meters, cable selection for use on the 1-Wire bus is less
critical. Even flat modular phone cable works with limited numbers of 1-Wire devices.
However, the longer the 1-Wire bus, the more pronounced cable effects become, and
therefore greater importance is placed on cable selection.

For longer distances, DS recommends twisted-pair-cable (CAT5).

DS standard examples show 100 meters cable lengths, so they say, that's no
problem. They also show examples with 300m cabling, and I think I have seen
something with 600-meter bus (but I cant find it again).

Noise and CRC


The longer cable and the noisier environment, the more false readings will be made.
The devices are equipped with a CRC-generator - the LSByte of the sending is always
a checksum. Look in program examples to learn how to re-calculate this checksum in
your uC. AND, if you notice that there are false readings - do something about your
cables. (Shield, lower resistor)

Transfer speed
On the original 1-wire bus, DS says the transfer speed is about 14Kbits /second. And,
if that was not enough, some devices has an overdrive option. That multiplies the
speed by 10. This is issued by making the communication-time-slots smaller (from 60
uS to 6uS ) which naturally will make the devices more sensitive, and CRC-error will
probably occur more often. But, if that is not an issue, ~140Kbit is a reachable speed
to the devices. So, whatever you thought before, it is FAST.

The BASCOM scanning of the bus is finds about 50 devices / second , and reading a
specific sensors value to a uC should be about 13 devices / second.

Topology
Of the 1w-net - that is an issue we will not cover so much. Star-net, bus-net? It
seems like you can mix that. It is a bus-net, but not so sensitive about that.

The benefit of the 1-wire bus


Each device is individual - and you can communicate with it over the media of 2
wires. Still, you can address one individual device, if you like. Get its value. There are
64 ^ 2 unique identifications-numbers.

Naturally, if lot of cables are unwanted, this is a big benefit. And you only occupy 1
processor pin.

DS supplies with different types of devices, which all are made for interfacing an uC -
directly. No extra hardware. There are sensors, so you can get knowledge about the
real world, and there are also potentiometers and relays, so you can do something
about it. On the very same bus.

And the Ibutton approach from DS (ever heard of it?) is based on 1wire technology.
Maybe something to pick up.

BASCOM let you use an uC with 1wire-devices so easy, that (since now) that also has
to count as a benefit - maybe one of the largest. ;-)

© 2021 MCS Electronics


282 BASCOM-AVR

The disadvantages of the 1-wire bus


So far as I know, DS is the only manufacturer of sensors for the bus. Some people
think their devices are expensive. And, until now, it was really difficult to
communicate with the devices. Particularly when using the benefit of several devices
on one bus. Still some people say that the 1w-bus is slow - but I don't think so.

Göte Haluza
System engineer

4.19 Using the SPI protocol


General description of the SPI
The SPI allows high-speed synchronous data transfer between the AVR and peripheral
devices or between several AVR devices. On most parts the SPI has a second purpose
where it is used for In System Programming (ISP).

The interconnection between two SPI devices always happens between a master
device and a slave device. Compared to some peripheral devices like sensors which
can only run in slave mode, the SPI of the AVR can be configured for both master and
slave mode.

The mode the AVR is running in is specified by the settings of the master bit (MSTR)
in the SPI control register (SPCR).

Special considerations about the /SS pin have to be taken into account. This will be
described later in the section "Multi Slave Systems - /SS pin Functionality".

The master is the active part in this system and has to provide the clock signal a
serial data transmission is based on. The slave is not capable of generating the clock
signal and thus can not get active on its own.

The slave just sends and receives data if the master generates the necessary clock
signal. The master however generates the clock signal only while sending data. That
means that the master has to send data to the slave to read data from the slave.

Data transmission between Master and Slave


The interaction between a master and a slave AVR is shown in Figure 1. Two identical
SPI units are displayed. The left unit is configured as master while the right unit is

© 2021 MCS Electronics


BASCOM HARDWARE 283

configured as slave. The MISO, MOSI and SCK lines are connected with the
corresponding lines of the other part.

The mode in which a part is running determines if they are input or output signal
lines. Because a bit is shifted from the master to the slave and from the slave to the
master simultaneously in one clock cycle both 8-bit shift registers can be considered
as one 16-bit circular shift register. This means that after eight SCK clock pulses the
data between master and slave will be exchanged.

The system is single buffered in the transmit direction and double buffered in the
receive direction. This influences the data handling in the following ways:

1. New bytes to be sent can not be written to the data register (SPDR) / shift register
before the entire shift cycle is completed.
2. Received bytes are written to the Receive Buffer immediately after the
transmission is completed.
3. The Receive Buffer has to be read before the next transmission is completed or
data will be lost.
4. Reading the SPDR will return the data of the Receive Buffer.

After a transfer is completed the SPI Interrupt Flag (SPIF) will be set in the SPI Status
Register (SPSR). This will cause the corresponding interrupt to be executed if this
interrupt and the global interrupts are enabled. Setting the SPI Interrupt Enable
(SPIE) bit in the SPCR enables the interrupt of the SPI while setting the I bit in the
SREG enables the global interrupts.

Pins of the SPI


The SPI consists of four different signal lines. These lines are the shift clock (SCK),
the Master Out Slave In line (MOSI), the Master In Slave Out line (MISO) and th