533 135 19MB
English Pages 376 [377] Year 2021
books
Explore ATtiny Microcontrollers using C and Assembly Language An in-depth look at the 8-bit AVR architecture found in ATtiny and ATmega microcontrollers, mainly from a software and programming point of view. Explore the AVR architecture using C and assembly language in Microchip Studio (formerly Atmel Studio) with ATtiny microcontrollers.
> > > > > > > > > >
Learn the details of how AVR microcontrollers work internally, including the internal registers and memory map of ATtiny devices. Program ATtiny microcontrollers using an Atmel-ICE programmer/ debugger, or use a cheap hobby programmer, or even an Arduino Uno as a programmer. Most code examples can be run using the Microchip Studio AVR simulator. Learn to write programs for ATtiny microcontrollers in assembly language. See how assembly language is converted to machine code instructions by the assembler program. Find out how programs written in the C programming language end up as assembly language and finally as machine code instructions. Use the Microchip Studio debugger in combination with a hardware USB programmer/debugger to test assembly and C language programs, or use the Microchip Studio AVR simulator. DIP packaged ATtiny microcontrollers are used in this volume for easy use on electronic breadboards, targeting mainly the ATtiny13(A) and ATtiny25/45/85. Learn about instruction timing and clocks in AVR microcontrollers using ATtiny devices. Be on your way to becoming an AVR expert with advanced debugging and programming skills.
Warwick A. Smith is an electronics engineer and embedded programmer from South Africa with experience in industrial, commercial and aerospace related industries. Warwick has a wide interest in various fields of technology, including embedded systems hardware, software, and information technology. His writing style has been described as "clear and concise" as well as "conversational and friendly".
Elektor International Media BV www.elektor.com
Explore ATtiny Microcontrollers using C and Assembly Language • Warwick A. Smith
AVR Architecture and Programming
AVR Architecture and Programming
Explore ATtiny Microcontrollers using C and Assembly Language
Warwick A. Smith
TH
EP
-D
IN
books books
●
This is an Elektor Publication.
Elektor is the media brand of Elektor International Media B.V. PO Box 11, NL-6114-ZG Susteren, The Netherlands Phone: +31 46 4389444
●
All rights reserved. No part of this book may be reproduced in any material form,
including photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication, without the written permission of the copyright holder except in accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be addressed to the publishers. Trademarks are property of their respective owners and are used in an editorial fashion with no intention of infringement of the trademark.
●
Declaration
The Author and the Publisher have used their best efforts in ensuring the correctness of the information contained in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from negligence, accident or any other cause.
●
British Library Cataloguing in Publication Data
A catalogue record for this book is available from the British Library
●
ISBN: 978-3-89576-479-0 (print)
●
© Copyright 2021: Elektor International Media B.V.
ISBN: 978-3-89576-480-6 (e-book)
Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com
Table of Contents Introduction
17
Broad Overview of this Book..........................................................................................18 About the Targeted AVR Microcontrollers....................................................................18 Primary Programming Software.....................................................................................19 Why Learn Assembly Language?...................................................................................19 The Many Reasons for Learning Assembly Language...............................................19 C Programming.................................................................................................................. 21 Intended Audience.............................................................................................................21 Prerequisites......................................................................................................................21 Software Requirements.................................................................................................22 Hardware Requirements...............................................................................................22 A DIP Packaged ATtiny............................................................................................23 An Electronic Breadboard.......................................................................................23 Programmer/Debugger............................................................................................23 Atmel-ICE Basic Kit............................................................................................24 Atmel-ICE Full Kit...............................................................................................24 AVR Dragon.........................................................................................................25 AVRISP mkII........................................................................................................25 Hobbyist USB Programmers..............................................................................25 Power Supply............................................................................................................26 Jumper Links and Wires..........................................................................................27 Electronic Components............................................................................................28 Optional Test Equipment.........................................................................................28 Microchip, Atmel, Microchip Studio and Atmel Studio..............................................28 Accompanying Resources...............................................................................................29 Let’s Get Started................................................................................................................29
Chapter 1 • Overview of ATtiny Microcontrollers
31
1.1 ATtiny Microcontrollers.............................................................................................32 1.1.1 8-Pin Devices........................................................................................................33 1.1.1.1 ATtiny13 and ATtiny13A..............................................................................33 1.1.1.2 ATtiny25, ATtiny45 and ATtiny85...............................................................33 1.1.2 14-Pin ATtiny24, ATtiny44 and ATtiny84............................................................34
3
1.1.3 20-Pin Devices.....................................................................................................34 1.1.3.1 ATtiny26........................................................................................................34 1.1.3.2 ATtiny261, ATtiny461 and ATtiny861.........................................................35 1.1.3.3 ATtiny2313 and ATtiny4313........................................................................35 1.1.4 28-Pin Devices.....................................................................................................36 1.1.4.1 ATtiny48 and ATtiny88................................................................................36 1.1.4.2 ATtiny28L and ATtiny28V............................................................................36 1.2 Which ATtiny to Use...................................................................................................36 1.3 Comparison of ATtiny Devices.................................................................................37 1.4 Summary....................................................................................................................... 38
Chapter 2 • Hardware and Software Setup
39
2.1 Install Microchip Studio.............................................................................................40 2.1.1 Download Page and Software Version...............................................................40 2.1.2 Newest Software Version....................................................................................40 2.1.3 Start the Installation.............................................................................................40 2.1.4 Installation Steps..................................................................................................40 2.2 8-Pin ATtiny Microcontroller LED Circuit...............................................................41 2.2.1 Circuit Power Supply...........................................................................................44 2.2.2 Decoupling Capacitor..........................................................................................45 2.3 A First Assembly Language Program.....................................................................45 2.3.1 Start a New AVR Assembler Project in Microchip Studio.................................45 2.3.2 LED Blink Assembly Code...................................................................................47 2.3.3 Build the Project...................................................................................................48 2.3.4 Fix Any Build Errors.............................................................................................49 2.3.5 Load the Program to the AVR Microcontroller...................................................49 2.3.6 Fault Finding.........................................................................................................50 2.4 A First C Program........................................................................................................50 2.4.1 Start a New GCC C Executable Project in Microchip Studio...........................50 2.4.2 LED Blink C Code................................................................................................51 2.4.3 Build the Project...................................................................................................53 2.4.4 Fix Any Build Errors.............................................................................................53 2.4.5 Load the Program to the AVR Microcontroller...................................................53 2.4.6 Fault Finding.........................................................................................................53 2.5 Summary....................................................................................................................... 54
4
Chapter 3 • Basics of Assembly Language
55
3.1 Mnemonics...................................................................................................................56 3.2 AVR Instruction Set....................................................................................................56 3.3 Opcodes and Operands.............................................................................................58 3.4 Assembly Language Comments...............................................................................58 3.5 LED Blink Program Operation..................................................................................59 3.6 Using the Debugger and Simulator.........................................................................61 3.6.1 Using the AVR Simulator and Debugger............................................................62 3.6.2 Using a Physical AVR Microcontroller and Debugger......................................64 3.6.3 Putting an AVR Back into ISP mode...................................................................67 3.7 Summary.......................................................................................................................67
Chapter 4 • Binary Numbers and Memory
69
4.1 Bits and Bytes.............................................................................................................70 4.1.1 Counting in Binary................................................................................................70 4.1.2 Bytes and Nibbles................................................................................................73 4.2 Weighted Number Systems.......................................................................................73 4.2.1 Weighted Decimal Numbers................................................................................73 4.2.2 Weighted Binary Numbers...................................................................................75 4.3 Hexadecimal Numbers...............................................................................................76 4.3.1 Counting in Hexadecimal....................................................................................76 4.3.2 Using Hexadecimal to Represent Binary...........................................................76 4.4 Calculating Number Sizes.........................................................................................79 4.4.1 Calculating the Maximum Value of a Binary Number.......................................79 4.4.2 Calculating Memory Size.....................................................................................79 4.4.3 Converting Between Bytes and Kilobytes..........................................................81 4.5 Numbers in Assembly Programs.............................................................................81 4.6 Numbers in C Programs............................................................................................82 4.6 Summary.......................................................................................................................83
Chapter 5 • AVR Registers and Memory Map
85
5.1 AVR Registers..............................................................................................................86 5.1.1 General Purpose Working Registers..................................................................86 5.1.2 I/O Registers.........................................................................................................86 5.2 Using General Purpose Registers...........................................................................86 5.2.1 Adding Two Registers..........................................................................................87 5
5.2.2 Incrementing a Register......................................................................................90 5.3 AVR Memory Map........................................................................................................91 5.3.1 Program Memory..................................................................................................92 5.3.2 Data Memory........................................................................................................93 5.3.3 EEPROM...............................................................................................................94 5.4 Accessing SRAM in Assembler Programs.............................................................94 5.4.1 SRAM Store and Load Example.........................................................................95 5.4.2 Store and Load Example in the Simulator.........................................................96 5.4.3 SRAM Start Addresses........................................................................................97 5.5 Summary....................................................................................................................... 98
Chapter 6 • AVR Internal Architecture
99
6.1 Clock Pulses and Program Counter......................................................................100 6.1.1 Clock Pulses.......................................................................................................100 6.1.2 Clock Pulse Period and Frequency..................................................................101 6.1.2.1 ATtiny13(A) Default Clock Frequency.....................................................101 6.1.2.2 ATtiny25/45/85 Default Clock Frequency...............................................101 6.1.2.3 RC Oscillator Accuracy.............................................................................102 6.1.2.4 Clock Sources and Improving Accuracy.................................................102 6.1.2.5 Calculating Clock Period from Frequency..............................................102 6.1.2.6 Calculating Clock Frequency from Period..............................................103 6.1.3 The Program Counter........................................................................................103 6.2 Microcontroller Buses..............................................................................................105 6.3 Harvard and von Neumann Architectures............................................................106 6.4 Fetching and Executing Instructions....................................................................107 6.5 Status Register..........................................................................................................109 6.5.1 Zero Flag.............................................................................................................109 6.5.2 Negative Flag......................................................................................................111 6.6 Stack and Stack Pointer..........................................................................................112 6.6.1 How the Stack Works.........................................................................................113 6.6.2 Accessing the Stack with PUSH and POP.......................................................114 6.6.3 Calling a Subroutine...........................................................................................117 6.7 LED Blink Program Fully Explained......................................................................121 6.8 AVR Instruction Encoding.......................................................................................124 6.9 Addressing Modes....................................................................................................129 6.9.1 Register Direct Addressing...............................................................................130
6
6.9.2 I/O Direct Addressing.........................................................................................131 6.9.3 Other Addressing Modes...................................................................................132 6.10 Summary................................................................................................................... 132
Chapter 7 • Arithmetic and Logic Instructions
135
7.1 Positive and Negative Numbers.............................................................................136 7.1.1 1’s Compliment Numbers..................................................................................136 7.1.2 2’s Compliment Numbers..................................................................................136 7.2 Addition....................................................................................................................... 139 7.2.1 ADD – Add without Carry...................................................................................139 7.2.2 ADC – Add with Carry........................................................................................140 7.3 Subtraction.................................................................................................................142 7.4 Logic Instructions.....................................................................................................143 7.4.1 Logical AND........................................................................................................143 7.4.2 Logical OR..........................................................................................................145 7.4.3 Logical Exclusive OR.........................................................................................147 7.5 Other Arithmetic and Logic Instructions.............................................................148 7.6 Summary..................................................................................................................... 148
Chapter 8 • Programming AVR I/O Ports
149
8.1 Instructions for Accessing I/O Registers.............................................................150 8.1.1 Reading and Writing I/O Registers with IN and OUT.....................................150 8.1.1.1 The IN Instruction......................................................................................150 8.1.1.2 The OUT Instruction..................................................................................151 8.1.2 I/O Register Bit Manipulation and Testing.......................................................152 8.1.3 Accessing I/O Registers as Data Space..........................................................152 8.2 I/O Ports...................................................................................................................... 153 8.2.1 Configuring I/O Pins as Outputs in Assembler................................................154 8.2.1.1 Five LED 8-pin ATtiny Circuit...................................................................154 8.2.1.2 Using debugWIRE or ISP/SPI to Program an ATtiny AVR....................154 Program-only Programmers............................................................................155 Peripheral Hardware Devices Interfering with Programming.......................155 Putting the AVR into debugWIRE Mode.........................................................156 8.2.1.3 Build the 5 LED ATtiny Circuit on Breadboard.......................................156 8.2.1.4 Assembly Code for the 5 LED Count Circuit..........................................157 8.2.1.5 Select the Debugger or Simulator...........................................................157
7
8.2.1.6 What the LED Count Assembler Code Does..........................................157 8.2.1.7 Build and Run the Program......................................................................158 8.2.1.8 How the LED Count Assembler Program Works....................................158 8.2.1.9 Using a Breakpoint in the Debugger.......................................................161 8.2.2 Configuring I/O Pins as Outputs in C...............................................................162 8.2.2.1 LED Count C Code...................................................................................162 8.2.2.2 How the LED Count C Code Works........................................................163 8.2.2.3 Running the LED Count C Code..............................................................163 8.2.2.4 LED Count C Code Disassembly.............................................................163 8.2.3 Limiting a Count Value.......................................................................................171 8.2.4 Three Ways to Toggle an LED with an AVR....................................................173 8.2.4.1 Toggling an LED by Value........................................................................173 8.2.4.2 Toggling an LED by Exclusive OR...........................................................173 8.2.4.3 Toggling an LED with the PINB Register................................................175 8.2.5 Configuring I/O Pins as Inputs..........................................................................177 8.3 Summary..................................................................................................................... 182
Chapter 9 • Assembly Language Elements
183
9.1 Instructions and Labels...........................................................................................184 9.2 The Preprocessor and Include Files.....................................................................185 9.3 Assembler Directives...............................................................................................187 9.3.1 Specifying Code and Data Locations...............................................................188 9.3.1.1 ORG Assembler Directive........................................................................188 9.3.1.2 CSEG Code Segment Directive...............................................................189 9.3.1.3 DSEG Data Segment and BYTE Directives...........................................190 9.3.1.4 ESEG EEPROM Segment Directive........................................................191 9.3.2 Reserving Memory.............................................................................................192 9.3.2.1 BYTE..........................................................................................................192 9.3.2.2 DB – Define Constant Byte......................................................................192 Modified Harvard Architecture.........................................................................192 Example Code using the DB Assembler Directive........................................192 CSEG Directive and First RJMP Instruction..................................................192 Usage of the DB Assembler Directive............................................................193 Data Formats and Null Terminating Strings...................................................193 Location of DB Data in Program Memory and Alignment.............................194 16-bit Address Pointer Registers....................................................................194
8
Loading the Z Register....................................................................................195 Reading Bytes from Program Memory...........................................................195 Running the Example Code.............................................................................196 9.3.2.3 DW – Define Constant Word....................................................................199 9.3.2.4 DD – Define Constant Double-word........................................................199 9.3.2.5 DQ – Define Constant Quad-word...........................................................199 9.3.3 Defining Names for Registers with DEF..........................................................200 9.3.4 Equating Names to Expressions using EQU and SET...................................200 9.3.5 Conditional Assembly........................................................................................201 9.4 Other Assembly Language Elements....................................................................203 9.5 Further Reading........................................................................................................204 9.6 Summary..................................................................................................................... 204
Chapter 10 • AVR Timing, Timers and Interrupts
205
10.1 Instruction Timing..................................................................................................206 10.1.1 AVR CPU Versions...........................................................................................206 10.1.2 Instruction Timing Examples...........................................................................206 10.1.2.1 The NOP Instruction...............................................................................206 10.1.2.2 16-bit and 32-bit Instruction Timing.......................................................208 10.1.2.3 Timing of Branch Instructions................................................................208 The Simulator Cycle Counter and Stop Watch..............................................210 Simulator Cycle Counter Bug..........................................................................211 10.2 Assembly Language Time Delay..........................................................................213 10.2.1 Calculating a Software Delay Subroutine Time Delay.................................213 10.2.1.1 Delay Subroutine Cycle Counter Measurement...................................214 10.2.1.2 Delay Subroutine Mathematical Formula.............................................215 10.2.2 A Better Software Delay Subroutine..............................................................226 10.2.2.1 Principle of Operation.............................................................................227 10.2.2.2 32-bit Subtraction with 8-bit Registers..................................................227 10.2.2.3 Timing of the Code..................................................................................229 10.2.2.4 Testing the Code in Microchip Studio...................................................230 10.2.3 A Changeable Software Time Delay Subroutine...........................................231 10.2.3.1 Splitting an Assembly Language Project into Files.............................234 10.2.3.2 How the wait_ms Subroutine Works.....................................................235 10.2.3.3 Limits of the wait_ms Subroutine..........................................................237 Simplifying the Formula...................................................................................238
9
Calculating the Maximum Delay Time of the Subroutine.............................238 Posing Value Limits in Assembly Language..................................................240 Number Size Limits in the Assembler Program.............................................243 Solution to Flagging Out of Range Upper Values.........................................246 Flagging Out of Range High and Low Values................................................247 10.2.4 Passing a Value to a Subroutine....................................................................251 10.2.4.1 Simplest Way to Pass a Value...............................................................251 10.2.4.2 Improved Way to Pass a Value..............................................................253 10.3 Calling an Assembly Subroutine from C Code.................................................261 10.3.1 Passing a Value to an Assembly Subroutine from C....................................261 10.3.1.1 Testing the wait_ms_c Project Code.....................................................263 10.3.1.2 How the wait_ms_c Project Code Works..............................................264 10.3.2 Returning a Value from an Assembly Subroutine in C.................................266 10.4 Polled Timer Delay..................................................................................................268 10.4.1 Timer/Counter0 Registers...............................................................................268 10.4.1.1 Timer/Counter0 Register Addresses.....................................................269 10.4.1.2 Using Counter/Timer0 as a Timer.........................................................270 10.4.2 Polled Timer Assembly Program....................................................................271 10.4.2.1 The IFNDEF Directive.............................................................................271 10.4.2.2 Left Shift Operator..................................................................................272 10.4.2.3 Register Write or Read-Modify-Write....................................................273 10.4.2.4 Initializing Timer 0...................................................................................273 10.4.2.5 Polling Timer 0........................................................................................275 10.4.2.6 Running the Code in the Simulator.......................................................276 10.4.3 Polled Timer C Program..................................................................................276 10.5 Timer Interrupt Delay.............................................................................................277 10.5.1 How Interrupts Work........................................................................................278 10.5.2 The Interrupt Vector Table...............................................................................278 10.5.3 Assembly Program Timer Interrupt.................................................................279 10.5.3.1 ATtiny13(A) Timer Interrupt Project.......................................................279 The Interrupt Vector Table...............................................................................280 Main Program Code.........................................................................................282 Interrupt Service Routine Code.......................................................................282 Running the Timer Interrupt Code..................................................................283 10.5.3.2 ATtiny25/45/85 Timer Interrupt Project.................................................283 10.5.3.3 Universal Timer Interrupt Project...........................................................285
10
10.5.4 C Program Timer Interrupt..............................................................................286 10.6 Summary................................................................................................................... 288
Chapter 11 • The AVR Instruction Set
289
11.1 AVR Instruction Set Overview and Categories..................................................290 11.2 A Guided Tour through the ATtiny AVR Instruction Set..................................290 11.2.1 Arithmetic and Logic Instructions...................................................................290 11.2.1.1 Add and Subtract Instructions................................................................290 Addition Instructions.........................................................................................290 Subtraction Instructions...................................................................................293 11.2.1.2 Logical Instructions.................................................................................294 Logical AND......................................................................................................294 Logical OR.........................................................................................................294 Logical Exclusive OR.......................................................................................294 11.2.1.3 Increment and Decrement Instructions.................................................294 11.2.1.4 Sign Change Instructions.......................................................................294 11.2.1.5 Bit Set and Clear Instructions................................................................295 11.2.1.6 Register Set, Clear and Test Instructions.............................................296 11.2.2 Branch Instructions..........................................................................................297 11.2.2.1 Jump Instructions....................................................................................297 11.2.2.2 Subroutine Call Instructions...................................................................299 11.2.2.3 Return from Subroutine and Interrupt Instructions..............................300 11.2.2.4 Compare Instructions..............................................................................300 11.2.2.5 Skip Instructions......................................................................................301 11.2.2.6 Branch Instructions.................................................................................302 Branch if Bit in SREG Set or Cleared.............................................................302 Branch if Equal or Not Equal – SREG Z Flag................................................303 Branch if Carry Set or Cleared – SREG C Flag............................................303 Branch if Same or Higher, or Lower – SREG C Flag....................................303 Branch if Minus or Plus – SREG N Flag........................................................304 Branch if Greater or Equal, or Less Than Signed – SREG S Flag..............304 Branch if Half Carry Flag Set or Cleared – SREG H Flag............................304 Branch if T Bit Set or Cleared – SREG T Flag..............................................304 Branch if Overflow Flag Set or Cleared – SREG V Flag..............................304 Branch if Interrupt Enabled or Disabled – SREG I Flag...............................304 11.2.3 Bit and Bit-test Instructions.............................................................................305
11
11.2.3.1 Bit Set and Clear Instructions................................................................305 11.2.3.2 Shift, Rotate and Swap Instructions......................................................305 Logical Shift Instructions.................................................................................305 Rotate through Carry Instructions...................................................................305 Logical Shift and Rotate Code Example........................................................305 Led Chaser Logical Shift Code Example.......................................................306 Arithmetic Shift and Swap Instructions..........................................................310 11.2.3.3 Status Register Bit Set and Clear Instructions.....................................310 Set or Clear SREG Bit.....................................................................................310 Store or Load SREG T Bit to/from Register...................................................310 Set or Clear Carry Flag – SREG C Bit...........................................................311 Set or Clear Negative Flag – SREG N Bit......................................................311 Set or Clear Zero Flag – SREG Z Bit.............................................................311 Set or Clear Global Interrupt Flag Bit – SREG I Bit......................................311 Set or Clear Sign Flag – SREG S Bit.............................................................312 Set or Clear Two’s Compliment Overflow Flag – SREG V Bit.....................312 Set or Clear T Bit in SREG – SREG T Bit......................................................312 Set and Clear Half Carry Flag – SREG H bit.................................................312 11.2.4 Data Transfer Instructions...............................................................................312 11.2.4.1 Move/Copy Instructions..........................................................................312 11.2.4.2 Load Immediate Instruction....................................................................313 11.2.4.3 Load Indirect Instructions.......................................................................313 11.2.4.4 Store Indirect Instructions......................................................................314 11.2.4.5 Load Indirect with Displacement............................................................315 11.2.4.6 Store Indirect with Displacement...........................................................315 11.2.4.7 Load Direct from SRAM..........................................................................315 11.2.4.8 Store Direct to SRAM..............................................................................316 11.2.4.9 Load Program Memory Instructions......................................................316 11.2.4.10 Store Program Memory........................................................................316 11.2.4.11 Port IN and OUT Instructions...............................................................316 11.2.4.12 PUSH and POP Instructions................................................................317 11.2.5 MCU Control Instructions................................................................................317 11.3 Entire AVR Instruction Set....................................................................................318 11.3.1 Number of AVR Instructions............................................................................318 11.3.1.1 Total Number of AVR Instructions..........................................................318 11.3.1.2 Number of ATtiny AVR Instructions........................................................318
12
11.3.1.3 Discrepancies in Documentation...........................................................318 11.3.2 Other AVR Instructions....................................................................................319 11.3.2.1 Arithmetic and Logic Instructions...........................................................319 11.3.2.2 Branch Instructions.................................................................................319 11.3.2.3 Data Transfer Instructions......................................................................320 11.3.3 Putting Instructions into Perspective..............................................................321 11.3.3.1 The Full AVR Instruction Set..................................................................321 11.3.3.2 The Plain AVR CPU.................................................................................321 11.3.3.3 Reduced AVRrc Core..............................................................................321 11.3.3.4 AVRe and AVRxt Cores...........................................................................321 11.3.3.5 AVRe+ CPU..............................................................................................322 11.3.3.6 AVRxm CPU.............................................................................................322
Chapter 12 • Software Tools and Settings
323
12.1 AVR Assembler Programs.....................................................................................324 12.1.1 The AVRASM2 Assembler...............................................................................324 12.1.1.1 Building a Project with AVRASM2.........................................................324 12.1.1.2 AVRASM2 on the Command Line..........................................................326 12.1.1.3 AVRASM2 Options in Microchip Studio................................................327 12.1.1.4 List File Options......................................................................................328 12.1.2 The AVR-AS Assembler...................................................................................329 12.1.3 The AVRA Assembler.......................................................................................329 12.2 The GNU C Toolchain.............................................................................................329 12.3 Where to from Here?..............................................................................................330 12.3.1 Objectives Achieved........................................................................................330 12.3.2 What was Not Covered....................................................................................332 12.3.3 Other AVR Microcontrollers.............................................................................332 12.3.4 Assembly Language Resources.....................................................................332
Appendix A • External Programmer Setup
333
A.1 Hobby USB Programmer Capabilities..................................................................334 A.1.1 Differences Between Hobby Programmers and the Atmel-ICE.....................334 A.1.2 Programming Interfaces....................................................................................335 A.1.3 Using Hobby USB Programmers with this Book.............................................335 A.2 Overview of External Programmer Setup............................................................336 A.3 External Programmer Setup...................................................................................336
13
A.3.1 Install a Driver....................................................................................................336 A.3.1.1 USBasp Driver..........................................................................................336 A.3.1.2 USBtinyISP Driver....................................................................................339 A.3.1.3 Arduino Uno Sketch..................................................................................341 A.3.2 Download and Install avrdude..........................................................................342 A.3.3 Build an AVR Circuit and Connect a Programmer..........................................343 A.3.3.1 Connecting a USBasp..............................................................................344 10-pin Male Header..........................................................................................344 10-pin Female Connector on Ribbon Cable..................................................344 6-pin Adapter (ISP/SPI)...................................................................................345 A.3.3.2 Connecting a USBtinyISP........................................................................345 6-pin Male Header............................................................................................345 6-pin Female Connector on Ribbon Cable.....................................................345 A.3.3.3 Connecting an Arduino Uno ArduinoISP................................................345 A.3.4 Programming Parameters.................................................................................346 A.3.4.1 Documentation for avrdude.....................................................................346 A.3.4.2 Parameters for avrdude Explained.........................................................346 A.3.4.3 Parameters for a USBasp........................................................................349 A.3.4.4 Parameters for a USBtinyISP..................................................................350 A.3.4.5 Parameters for an ArduinoISP.................................................................350 A.3.5 Microchip Studio External Tool Setup..............................................................350 A.3.5.1 Open an Assembly or C Project..............................................................351 A.3.5.2 Add an External Tool in Microchip Studio...............................................351 USBasp..............................................................................................................352 USBtinyISP........................................................................................................352 ArduinoISP (Arduino Uno with ArduinoISP sketch loaded)..........................352 A.3.5.3 Add a Toolbar Button for the External Tool............................................353 A.3.6 Testing the Programmer....................................................................................355 A.3.7 Programming Problems and Solutions............................................................355
Appendix B • Alternate Circuits and Programs
357
B.1 8-Pin PDIP ATtiny13/25/45/85.................................................................................358 B.2 14-Pin PDIP ATtiny24/44/84....................................................................................359 B.3 20-Pin PDIP ATtiny26/261/461/861 and ATtiny2313/4313..................................360 B.4 28-Pin PDIP ATtiny48/88..........................................................................................361 B.5 Alternate Programs..................................................................................................362
14
B.5.1 Alternate LED Blink Assembly Program..........................................................363 B.5.2 Alternate LED Blink C Program........................................................................363
Appendix C • The ASCII Table
365
C.1 Printable Characters................................................................................................365 C.2 ASCII Table.................................................................................................................365
Index
367
15
16
Introduction
This book provides an in-depth look at the 8-bit AVR architecture found in ATtiny and ATmega microcontrollers, mainly from a software and programming point of view. It explores the AVR architecture using Microchip Studio (formerly Atmel Studio) and ATtiny microcontrollers with a hardware programmer/debugger and/or using the AVR simulator found in Microchip Studio. By initially targeting the simpler smaller ATtiny range of microcontrollers, such as those shown at the left and middle of Figure 0.1, learning the AVR architecture is made easy. Going on to learn ATmega devices after this, for example the microcontroller found on the Arduino Uno seen at the right of Figure 0.1, is simplified as these devices add enhancements to, and are basically extensions of the ATtiny range. ATtiny microcontrollers are very useful devices that can be used in many small electronics projects.
Figure 0.1: Microcontrollers in the Form of DIP ATtiny Devices (left), Boards with SMD ATtiny Devices (middle) and an ATmega Device on an Arduino Uno (right) all Contain the 8-bit AVR Architecture
17
Explore ATtiny Microcontrollers using C and Assembly Language As this is a practical book, it is filled with examples that can be run on real hardware and/or the AVR simulator. It includes circuits that can be built and tested on an electronic breadboard. The rest of this introductory chapter has more information on the contents of this book, the intended audience, as well as software and hardware requirements.
Broad Overview of this Book By studying the AVR architecture, we learn how machine code instructions are executed. In order to properly understand the AVR architecture, assembly language programming is taught. By the end of the book, you will be able to program AVR microcontrollers using assembly language, understand how assembly language converts to machine code understood by microcontrollers, as well as how the C programming language eventually ends up as machine code instructions. Programming examples are given in both assembly language, and in the C programming language where applicable.
About the Targeted AVR Microcontrollers Low pin count ATtiny microcontrollers are the primary devices used in this book, with the 8-pin ATtiny13, ATtiny13A, ATtiny25, ATtiny45 and ATtiny85 microcontrollers being the primary devices used. The reason for this is that these devices are cheap, and are simpler with fewer built-in peripherals, which simplifies learning. They are also more likely to benefit from assembly language programming because of their small program memory sizes. Principles learned on the simpler ATtiny AVR devices also apply to higher end AVR devices, for example the ATmega AVR microcontroller range, which are just extensions of the simpler devices that add more functionality and resources. These differences are extensions of the basic AVR architecture and instruction set, increased memory sizes, and the inclusion of more advanced peripherals. ATtiny microcontrollers that are available in DIP packages are used in the book as these devices are easy to use with an electronic breadboard. These are the 8-pin devices already mentioned. Appendix B includes alternate circuits that use DIP packaged ATtiny microcontrollers that have 14 pins, 20 pins and 28 pins. These devices can be used instead of the 8-pin devices if desired, but anyone using these alternate devices must be prepared to make changes to the code where necessary to run on these devices. 18
Introduction
Primary Programming Software Microchip Studio, formerly known as Atmel Studio, for Windows is the primary software package used in this text, but programming principles and techniques taught using this software can be adapted for use with other programming tools, software, and operating systems. Microchip Studio is a full-featured Integrated Development Environment ( IDE) for AVR C and assembly language software development, and is available for download free of charge and unrestricted.
Why Learn Assembly Language? As pointed out in the previous paragraphs of this chapter, studying the AVR architecture automatically exposes us to the instruction set of the AVR. It also exposes us to the internal registers and memory areas of the AVR. The instruction set consists of every binary machine code instruction that the AVR can run or execute. This instruction set acts on the internal registers and various memories of the AVR. The primary reason for learning assembly language in this book is to properly understand how the AVR works internally. By writing assembly language programs, we can see how instructions operate and affect internal registers and memory.
The Many Reasons for Learning Assembly Language There are several advantages to learning assembly language programming. A list of these reasons follows, with the primary reason already explained at the top of the list, to make the list complete. 1.
To properly understand the architecture of a microcontroller
2.
To write smaller and more efficient code than a compiler can generate
3.
For targeting very small microcontrollers with limited memory resources
4.
For debugging optimized C programs
5.
To evaluate compiler code generation quality
6.
For academic purposes in schools and universities
7.
For programming tool development such as compilers and simulators
8.
For understanding application notes and other documentation that contains assembly language
19
Explore ATtiny Microcontrollers using C and Assembly Language The previous list of points requires additional explanation which follows for each point in the list. Point number 1, to properly understand the architecture of a microcontroller, has previously been discussed. Point number 2 – to write smaller and more efficient code than a compiler can generate: This is possible to do once the internal architecture and instruction set of a microcontroller are properly understood, and after a lot of assembly language programming practice. Assembly language programming is more suited to smaller programs, and therefore smaller microcontrollers. This is one of the reasons that ATtiny devices have been chosen as the primary devices for use with this text. As assembly language programs get bigger, they tend to get more difficult to comprehend and maintain than programs written using a higher level language such as C. Assembly language and C can also be mixed, where critical parts of a program that require precise timing can be written in assembly language, while the remainder of the program is written in C. Point number 3 – for targeting very small microcontrollers with limited memory resources: This goes hand-in-hand with point number 2. Very small microcontrollers can benefit from assembly language, as exact control can be maintained over all of the resources in the device. This book covers a number of microcontrollers from the ATtiny range, including some of the smaller devices that are available. Point number 4 – for debugging optimized C programs: When C programs are compiled with optimization enabled, some lines of code can’t be stepped over using a debugger, because they are optimized away or combined with other lines of code. Optimization can be switched off during debugging, but this changes the underlying machine code generated by the compiler and also uses more program memory. The only way to properly debug an optimized C program is to look at the disassembly – which means looking at and understanding assembly language instructions generated by the C compiler. Point number 5 – to evaluate compiler code generation quality: when choosing a compiler for use with a particular microcontroller architecture, the only way to truly evaluate the compiler is to look at the assembly language code that it generates. When choosing between different compilers, the output of the compilers can be compared as part of the evaluation process.
20
Introduction Point number 6 – for academic purposes in schools and universities: any academic course that teaches microcontrollers in-depth needs to teach assembly language to show how instructions on a microcontroller or microprocessor are executed internally. Point number 7 – for programming tool development such as compilers and simulators: an understanding of the architecture and assembly language of a particular microcontroller is needed when developing any code generation, debugging or simulation tools. Point number 8 – for understanding application notes and other documentation that contains assembly language: Assembly language frequently appears in application notes, data sheets and other microcontroller documentation.
C Programming Although this book includes code in the C programming language, it does not teach the C programming language. Despite including C code, it is not necessary to understand the C language to benefit from this book. Programs appear in assembly language first, and the assembly language code is taught and explained. Those readers who have not yet learned the C programming language can still type the C programs, compile and run them to see what they do. Of course readers who have learned the C language will obtain extra benefits from this book.
Intended Audience This book has been written for anyone interested in AVR microcontrollers who wants to learn assembly language, how microcontrollers work internally, the internal architecture of 8-bit AVR microcontrollers, as well as get an advanced understanding of programming tools and software. The intended audience includes students, hobbyists, makers, hackers and engineers.
Prerequisites To follow this book it is necessary to be able to use a Windows computer and be able to download and install the necessary software tools. Although the use of physical hardware is encouraged, most of the book can be followed using an AVR simulator without the need for any physical hardware. To get the most out of the programs that manipulate hardware
21
Explore ATtiny Microcontrollers using C and Assembly Language devices such as LEDs and switches connected to a microcontroller, it is necessary to be able to read a circuit diagram and build circuits on an electronic breadboard. That being said, some of the programs that do access external hardware can still be run in the simulator. Assembly language programming is taught from scratch, so no programming experience is needed. Readers who have experience with other programming languages such as C will progress through the book quicker. C programmers will benefit from the included C code examples.
Software Requirements As already mentioned, Microchip Studio (formerly Atmel Studio) running on a Windows PC is used as the development platform. It includes an assembler program and AVR simulator. Microchip Studio also includes C programming tools – the GCC tools for AVR. AVR microcontrollers on physical hardware, such as a breadboard circuit or development board, can be programmed from Microchip Studio by using an external USB programming device such as an Atmel-ICE, or cheaper hobby USB programming devices.
Hardware Requirements Although this book can be followed using the AVR simulator in Microchip Studio, the simulator has its limitations. Building the microcontroller circuits on breadboard results in a more enhanced learning experience. A list of parts required for building the circuits follows, with an explanation for each item in the subsections following the list.
22
1.
A DIP packaged ATtiny13(A) or ATtiny25/45/85 or one of several other ATtiny devices discussed in more detail in Chapter 1
2.
An electronic breadboard
3.
Programmer / debugger, for example an Atmel-ICE
4.
5V DC power supply
5.
Jumper links and wires for building breadboard circuits
6.
Electronic components such as resistors, LEDs and switches
7.
Optional test equipment such as a multimeter and oscilloscope
Introduction A DIP Packaged ATtiny It is highly recommended to have some 8-pin DIP packaged ATtiny devices available when working through this book. These 8-pin DIP devices are the ATtiny13, ATtiny13A, ATtiny25, ATtiny45 and ATtiny85. The ATtiny25/45/85 range are really just enhanced versions of the ATtiny13(A). It would be better to have more than one of these devices, in case one gets damaged. Three or four of any of these devices are fine to get you through the book. Other ATtiny microcontrollers with more pins can be used instead of 8-pin devices if desired. An Electronic Breadboard A 400 tie point breadboard, is sufficient for all of the circuits built in this book. These breadboards are sometimes called half-size breadboards. It is not necessary to buy a halfsize breadboard if you already have a full-size breadboard, which can be used instead. Programmer/Debugger In order to load a program to an ATtiny or other AVR microcontroller, a USB programmer is needed. This allows in-system programming where the programmer is connected to an AVR microcontroller while it is in a circuit. Microchip Studio or other programming software is then used to load a program to the microcontroller using the USB programmer. A USB programmer that has debugging capabilities is preferable to a plain “program-only” programmer. The recommended USB programmer/debugger for use with this book is the Microchip Atmel-ICE which comes in two main kits, namely, the basic kit as shown in Figure 0.2 on the next page, and the full kit. This programmer/debugger can be used to program and debug both 8-bit AVR microcontrollers as well as ARM Cortex-M based SAM microcontrollers. For 8-bit AVR microcontrollers, the Atmel-ICE can program using the ISP/SPI interface and debugWIRE interface, both found on ATtiny25/45/85 and ATtiny13(A) ranges of microcontrollers. A USB programmer/debugger has debugging capabilities that allows single-step debugging when used with Microchip Studio. Internal registers and memory of the target AVR device can be examined, breakpoints inserted and register/memory values changed for a better debugging and learning experience when using a USB programmer/debugger. It is still possible to follow this book using a USB programmer that does not have debugging capabilities. In this case the simulator can be used to examine internal memories and registers. 23
Explore ATtiny Microcontrollers using C and Assembly Language
Figure 0.2: Atmel-ICE USB Programmer/Debugger Basic Kit
With a programmer/debugger, AVRs from the ATtiny25/45/85 and ATtiny13(A) ranges of microcontrollers can be put into debugWIRE mode. Once in debugWIRE mode, a single pin of the AVR is used for programming and debugging, which is great for these low pincount devices, as it frees up the other pins of the microcontroller. A description of various USB programmer/debugger and programmer only devices follows. In short, get an Atmel-ICE programmer/debugger, but if you can’t justify the expense use one of the older Atmel tools (AVR Dragon or AVRISP mkII), alternatively use a hobbyist programmer such as a USBasp, USBtinyISP or even an Arduino Uno. Atmel-ICE Basic Kit
The Atmel-ICE basic kit, shown in Figure 0.2, is ideal for use with this book and has the part number ATATMEL-ICE-BASIC. It has programming and debugging capabilities and comes with a single flat adapter cable as well as a USB cable. This kit is cheaper than the full kit. Atmel-ICE Full Kit
The Atmel-ICE full kit is exactly the same as the basic kit, but includes extra cables and adapters including a 10-lead squid cable. This kit has the part number ATATMEL-ICE. It is more expensive than the basic kit.
24
Introduction AVR Dragon
Those readers who already have an AVR Dragon can use it for programming and debugging instead of an Atmel-ICE. At the time of writing, the AVR Dragon has a status of “No Longer Available” on the Microchip website. The AVR Dragon supports the ISP/SPI and debugWIRE interfaces for ATtiny25/45/84 and ATtiny13(A) microcontrollers. AVRISP mkII
The Microchip AVRISP mkII is a “program-only” USB device that does not have any debugging capabilities and is now no longer available from Microchip. Microchip recommend the Atmel-ICE as a replacement. Those readers who already have an AVRISP mkII can still use it to program AVR microcontrollers in-circuit. This type of program-only USB programmer uses up four pins of the target AVR microcontroller to program it in ISP mode. Hobbyist USB Programmers
USB AVR hobby programmers, such as the USBasp shown in Figure 0.3, and others such as the USBtinyISP and even Arduino boards, can be used to program some AVR devices. Appendix A shows how to set up a USBasp, USBtinyISP, and Arduino Uno as an Arduino AVR ISP programmer in Microchip Studio. Hobby programmers can usually only program AVR microcontrollers that use the ISP/SPI interface. This means that they can be used with the ATtiny25/45/85 and ATtiny13(A) ranges of 8-bit AVR microcontrollers.
Figure 0.3: Although a USBasp can Program an AVR, it can't be used for Debugging
As with other program-only programmers, the USBasp can’t put an AVR into debugWIRE mode and then be used to program the AVR using one wire, but rather uses up four pins in ISP/SPI mode. The circuits in this book work just fine with external hardware and a programmer connected to the same pins. With no debugging capabilities on the USBasp, USBtinyISP and Arduino Uno as a programmer, the AVR simulator can be used for singlestepping through code and to examine registers and memory instead of hardware debugging. Of course not having the physical external hardware attached to the simulator does present some limitations. 25
Explore ATtiny Microcontrollers using C and Assembly Language Power Supply A 5V DC (Direct Current) power supply capable of delivering 100mA or more is needed to power AVR breadboard circuits. Many different power supplies are available, such as the breadboard power supply shown in Figure 0.4. An external power supply may not be needed if using a hobby programmer, as they usually supply 5V from USB. There are many different breadboard power supplies available. The one shown in Figure 0.4 is just one example and is manufactured by RobotDyn. It can supply 1A of current at 5V and 800mA of current at 3.3V. The two voltages are individually selectable by jumpers on the board. This means that one rail can be set to 5V and the other to 3.3V for circuits that use both 5V and 3.3V, but only 5V is needed with this book. This breadboard power supply requires an external DC supply of 6V to 12V supplied on the barrel connector. A mains voltage to 12V DC power supply is shown in Figure 0.4 supplying 12V DC to the breadboard power supply via a 2.1mm centre positive barrel connector. If you are using a different make or model of breadboard power supply, be sure to check its specifications and configuration from the manufacturer.
Figure 0.4: 5V/3.3V Breadboard Power Supply Powered by an External DC Supply
On most of these breadboard power supplies, the USB connector is intended as a 5V output for USB powered devices. Some of them allow 5V to be fed into this connector to
26
Introduction supply 5V to the breadboard. This, however, is not intended by design – it just so happens that they work this way without being destroyed. The type of USB connector seen in the figure is a USB host connector and intended to supply 5V, rather than be supplied with 5V. It is better to always use an external power supply attached to the barrel connector. Jumper Links and Wires Jumper wires are needed to connect from a USB programmer/debugger to the AVR microcontroller in a breadboard circuit, as can be seen in Figure 0.5 that follows. Jumper wires with single pin male connectors on each end are an excellent choice for this purpose. These wires are usually sold as a ribbon cable of wires that can individually be peeled off. They are typically called “Dupont” cables, for example “10cm male to male Dupont jumper cable”. Other single core jumper wires are useful for building circuits on a breadboard. Dupont cables with one male and one female connector can be used to connect from some hobby programmers to a breadboard circuit.
Figure 0.5: An Atmel-ICE Connected to an ATtiny Breadboard Circuit
27
Explore ATtiny Microcontrollers using C and Assembly Language Electronic Components Basic electronic components, such as LEDs, resistors and switches are needed for interfacing with ATtiny microcontrollers when following along with this book. For example, LEDs with series resistors are the most basic requirement when using pins as outputs, as they show when a pin is switched high or low. Other components such as 100n decoupling capacitors may be needed in the circuits. As this book deals mostly with the internal architecture of ATtiny AVR microcontrollers, only a minimum of components are needed. 5 through-hole LEDs with series resistors of around 470Ω each, a push-button switch and an optional 100n ceramic capacitor are all the components needed. Optional Test Equipment A multimeter is very useful for verifying voltages of power supplies before connecting them to circuits, as well as for general fault finding on circuits. Although not essential, an oscilloscope may be needed for testing of circuits and fault finding.
Microchip, Atmel, Microchip Studio and Atmel Studio There can be some confusion when dealing with AVR microcontrollers if one does not know the history of Atmel and Microchip, so an explanation is in order. Originally a company called Atmel was the designer and manufacturer of AVR microcontrollers including the ATtiny and ATmega ranges. In 2016, Microchip (www.microchip.com) bought Atmel and is now the owner and manufacturer of AVR microcontrollers. At the time of writing, some of the AVR documentation still has the Atmel name on it. Many AVR microcontrollers still bear the Atmel name and have not been changed to Microchip yet. Microchip Studio is the free development software used with this book to program ATtiny AVR microcontrollers using assembly language and C. Microchip Studio is the same as the previously available Atmel Studio, it is simply a brand name change. Although Microchip acquired Atmel back in 2016, Atmel Studio was only rebranded to Microchip Studio in 2020. The first release of Microchip Studio was available in November 2020, and continued with the version numbering left by Atmel Studio. Thus the first release of Microchip Studio is version 7.0.2542, rather than version 1.0. It follows on from the last release of Atmel Studio which was version 7.0.2389. Everything in Microchip Studio is identical to Atmel Studio, so those readers who have previously used Atmel Studio will immediately be able to use Microchip Studio.
28
Introduction
Accompanying Resources Accompanying resources, such as the source code from this book, is available for download from the publisher’s website www.elektor.com where the book can be searched for by name or ISBN number to find its web page containing the downloadable resources. Additional resources can be found on the author’s website at wspublishing.net where the book name can be clicked to find its page and resources.
Let’s Get Started I hope that you enjoy this fantastic adventure as we look at the 8-bit AVR architecture and how to program AVR microcontrollers in assembly language and C.
29
Explore ATtiny Microcontrollers using C and Assembly Language
30
Chapter 1 • Overview of ATtiny Microcontrollers
This chapter takes a look at ATtiny microcontrollers that are available in DIP packages and can be programmed using an ISP programmer. ISP programming can
In this Chapter
be done using any of the Microchip AVR USB programmers as well as most hobby programmers built for 8-bit AVRs. Basics of 8-pin, 14-pin, 20-pin and 28-pin ATtiny microcontrollers are covered.
▫ An overview of DIP packaged ATtiny AVR microcontrollers that can be programmed in-circuit ▫ A parametric table for easily comparing different ATtiny parts
31
Explore ATtiny Microcontrollers using C and Assembly Language
1.1 ATtiny Microcontrollers Before we start programming, it is best to get a general understanding of what exactly we will be programming. Various ATtiny devices are listed under the sub-headings that follow. Each sub-heading lists ATtiny devices by number of pins. These sections are followed by a table of all of the devices discussed, to help assimilate the information. All devices listed are available as Dual-Inline Package (DIP) chips. In the Microchip/Atmel documentation for ATtiny devices, DIP ICs are known as Plastic Dual-Inline Package, or PDIP devices. Although the text uses 8-pin ATtiny devices, it is possible to use devices that have more pins. Devices with more pins are discussed for readers who may be interested in them. The motivation for specifying DIP or PDIP ATtiny microcontrollers is that they are much easier to use on an electronic breadboard, and programming is supported by many different USB programming devices via the ISP/SPI programming interface. ATtiny surface mount device (SMD) parts can also be used with a breadboard, but need to be mounted on a breakout board, or similar printed circuit board (PCB). Each PDIP device is also available in a surface mount package, so using a breakout board with an SMD equivalent of a DIP ATtiny is fine too. Basic pinout diagrams of various ATtiny microcontrollers are shown in the figures in each subsection that follows. ATtiny and ATmega microcontrollers all have one or more internal 8-bit ports that are attached to the pins of each microcontroller, one port bit per pin. These ports are named Port A, Port B, Port C and so on, or with a shorter notation PA, PB, PC, etc. Ports allow microcontroller pins to be configured and manipulated in software. On devices that have few pins, only a certain number of port bits are available on the pins of the devices, and not the full 8-bits of a port. When looking at the figures that follow, notice that the pins for a port are labeled with the shorter notation. For example, pins labeled PB0, PB1, PB2, etc. are pins from port B or PB of the microcontroller. These pins are input/output (I/O) pins that can be individually configured as either inputs or outputs in software. Port pins are also multiplexed with various internal peripherals, such as analog to digital converters (ADCs), or timer outputs. This means that a pin can be configured as either an input, or an output, or as a special function pin connected to an internal peripheral. The actual function of the pin is configurable in software. In the figures that follow, only the basic port pin numbers are shown, and not the alternate functionality. 32
Chapter 1 • Overview of ATtiny Microcontrollers
1.1.1 8-Pin Devices There are two ranges of 8-pin ATtiny microcontrollers available in DIP packages, namely ATtiny13 and ATtiny25/45/85. These two ranges are pin compatible (Figure 1.1), but additional peripherals and memory are available in the ATtiny25/45/85 range.
Figure 1.1: Basic Pinout of 8-pin DIP ATtiny Devices
1.1.1.1 ATtiny13 and ATtiny13A ATtiny13 and ATtiny13A microcontrollers have only 1K byte of Flash memory, 64 bytes of SRAM and 64 bytes of EEPROM. ATtiny13A devices are a low power version of the original ATtiny13, and are a newer device. For this reason ATtiny13A devices are preferred, given a choice between the two. ATtiny13(A) refers to both devices. ATtiny13 and ATtiny13V devices share a datasheet. ATtiny13 devices operate from a voltage of between 2.7V to 5.5V, while ATtiny13V devices operate from 1.8V to 5.5V, but at a lower clock speed. ATtiny13A devices have their own datasheet, separate from the ATtiny13, and operate from a voltage of between 1.8V and 5.5V. 1.1.1.2 ATtiny25, ATtiny45 and ATtiny85 ATtiny25, ATtiny45 and ATtiny85 microcontrollers are basically the same device, but with each one in the series having more memory than the previous. These three devices all share the same datasheet, and also have a ‘V’ version in the same datasheet – the ATtiny25V, ATtiny45V and ATtiny85V. Parts with the V suffix operate at voltages between 1.8V and 5.5V, but at lower clock speeds, while parts without the V suffix operate at voltages between 2.7V and 5.5V, but at higher clock speeds. ATtiny25, ATtiny45 and ATtiny85 devices are collectively referred to as ATtiny25/45/85. ATtiny25 devices have 2K bytes of Flash program memory, 128 bytes of SRAM and 128 bytes of EEPROM. The ‘2’ in ATtiny25 indicates 2K bytes of Flash memory, ATtiny45 devices have 4K bytes of Flash memory and ATtiny85 devices have 8K bytes of Flash memory. Flash, SRAM and EEPROM sizes double for each device in the series.
33
Explore ATtiny Microcontrollers using C and Assembly Language
1.1.2 14-Pin ATtiny24, ATtiny44 and ATtiny84 ATtiny24, ATtiny44 and ATtiny84 devices are 14-pin microcontrollers, as shown in Figure 1.2. and all share the same datasheet which includes the ‘V’ variants of these devices – the ATtiny24V, ATtiny44V and ATtiny84V. As seen with the 8-pin devices, parts with a V suffix can operate at lower voltages, but also operate at lower clock frequencies than the parts without the V suffix. Newer devices that feature low power operation are now available in this group of microcontrollers. These newer devices have an ‘A’ suffix – the ATtiny24A, ATtiny44A and ATtiny84A, and share their own datasheet separate from the older devices. It is preferable to use these newer ‘A’ devices than the older devices.
Figure 1.2: Basic Pinout of 14-pin DIP ATtiny Devices
Memory sizes of 14-pin ATtiny24, ATtiny44 and ATtiny84 devices are the same as for 8-pin ATtiny25, ATtiny45 and ATtiny85 devices, with the first number in the part name specifying the Flash memory size in kilobytes.
1.1.3 20-Pin Devices In 20-pin DIP packages, there are two main ATtiny groups, the ATtiny26/261/461/861 and ATtiny2313/4313. As can be seen in Figure 1.3 and Figure 1.4, the two groups have different pinouts. 1.1.3.1 ATtiny26 The ATtiny26 has really been replaced by the ATtiny261A, although the ATtiny26 is still in production at the time of writing. ATtiny26 and ATtiny26L devices share a datasheet. The ATtiny26 operates from a voltage between 4.5V and 5.5V and up to 16MHz, while the ATtiny26L operates from 2.7V to 5.5V and up to 8MHz. ATtiny26 microcontrollers have 2K bytes of Flash program memory, 128 bytes of SRAM and 128 bytes of EEPROM. It is preferable to use the newer ATtiny261A rather than the ATtiny26 if possible.
34
Chapter 1 • Overview of ATtiny Microcontrollers 1.1.3.2 ATtiny261, ATtiny461 and ATtiny861 ATtiny261, ATtiny461 and ATtiny861 share a datasheet with their lower voltage, and lower clock speed ‘V’ variants (ATtiny261V, ATtiny461V and ATtiny861V). In this datasheet the ATtiny261 and ATtiny261V are marked as mature devices, so are not recommended for new designs. The ATtiny261A is the replacement for these two parts.
Figure 1.3: Basic Pinout of 20-pin DIP ATtiny26/261/461/861 Devices
It is preferable to use the newer low power ATtiny261A, ATtiny461A and ATtiny861A devices, which share a separate datasheet from the older devices. As with the previous 8pin and 14-pin devices, the first number in the part name of these devices denotes the size of Flash memory in kilobytes. Memory sizes for Flash, SRAM and EEPROM are the same for the ATtiny261/461/861 20-pin devices, as for the ATtiny25/45/85 8-pin devices and ATtiny24/44/84 14-pin devices. Each member of these groups has double the memory capacity of the preceding device. 1.1.3.3 ATtiny2313 and ATtiny4313 The main feature of ATtiny2313 and ATtiny4313 devices is that they have a hardware USART peripheral. ATtiny4313 devices have double the memory capacity of the 2K bytes of Flash, 128 bytes of SRAM and 128 bytes of EEPROM of ATtiny2313 devices.
Figure 1.4: Basic Pinout of 20-pin DIP ATtiny2313/4313 Devices
ATtiny2313 and ATtiny2313V devices share a datasheet. It is preferable to use the newer ATtiny2313A instead of these older devices. ATtiny2313A and ATtiny4313 devices share a datasheet and are both low power devices. These devices have basic pin compatibility with the older AT90S2313 8-bit AVR, and older AT89C2051 and AT89C4051 microcontrollers that have an 8-bit MCS51 architecture. MCS51 is a completely different 8-bit architecture to AVR. 35
Explore ATtiny Microcontrollers using C and Assembly Language
1.1.4 28-Pin Devices There are two groups of 28-pin DIP ATtiny microcontrollers available. The ATtiny48/88 and ATtiny28. Of these two ranges it is practical to only use the ATtiny48/88 devices as they, like all of the previous devices discussed, are in-system programmable. 1.1.4.1 ATtiny48 and ATtiny88 ATtiny48 and ATtiny88 devices share a datasheet and are both low power 28-pin devices. The ATtiny48 has 4K bytes of Flash, 256 bytes of SRAM and 64 bytes of EEPROM, while the ATtiny88 has 8K bytes of Flash, 512 bytes of SRAM and also 64 bytes of EEPROM.
Figure 1.5: Basic Pinout of 28-pin DIP ATtiny48/88 Devices
1.1.4.2 ATtiny28L and ATtiny28V ATtiny28L and ATtiny28V devices are not recommended for most applications, primarily because they are not in-system programmable. High voltage programming must be used to program these devices, such as HVPP, or High Voltage Parallel Programming. These devices also have no SRAM or EEPROM. Because these devices require high voltage programming, they won’t be considered further in this book.
1.2 Which ATtiny to Use Any of the 8-pin devices discussed in this chapter are good choices to have available when following this book. Having a few 8-pin ATtiny devices from the ATtiny25/45/85 range is a good start, this includes the ‘V’ variants. It is also fine to use an ATtiny13, ATtiny13A, or ATtiny13V which are also 8-pin devices. Although specific ATtiny devices have been chosen for this book, assembly and C programs in this book apply to all ATtiny devices and even devices from the ATmega range, although some changes to programs may be needed in certain cases. Circuits and software presented for 8-pin devices can easily be adapted to run on higher pin count devices.
36
Chapter 1 • Overview of ATtiny Microcontrollers
1.3 Comparison of ATtiny Devices Table 1.1 that follows compares the ATtiny microcontrollers that have been discussed in the previous sections of this chapter. The table gives a better view of everything discussed so far. Devices are grouped by number of pins, starting with 8-pin ATtiny microcontrollers, and ending with 28-pin devices. 28-pin ATtiny28 devices have been left off the table for reasons already explained. The preferred column suggests newer low-power enhanced versions of ATtiny microcontrollers to use in place of older parts, for example it is preferable to use the ATtiny13A instead of the older ATtiny13 in new designs.
Table 1.1: Comparison of ATtiny PDIP Devices Part
Preferred
Low Max Flash SRAM EEPROM ADC ADC UART SPI I2C 8-Bit 16-Bit PWM Power Clock KB Bytes Bytes In Res. Timers Timers Out Speed Bits
8-Pin PDIP No
20 MHz
1
64
64
4
10
0
0
0
1
0
2
ATtiny13A
Yes
20 MHz
1
64
64
4
10
0
0
0
1
0
2
ATtiny25
No
20 MHz
2
128
128
4
10
0
1
1
2
0
6
ATtiny45
No
20 MHz
4
256
256
4
10
0
1
1
2
0
6
ATtiny85
No
20 MHz
8
512
512
4
10
0
1
1
2
0
6
ATtiny13
ATtiny13A
14-Pin PDIP ATtiny24
ATtiny24A
ATtiny24A ATtiny44
ATtiny44A
ATtiny44A ATtiny84
ATtiny84A
ATtiny84A
No
20 MHz
2
128
128
8
10
0
1
1
1
1
4
Yes
20 MHz
2
128
128
8
10
0
1
1
1
1
4
No
20 MHz
4
256
256
8
10
0
1
1
1
1
4
Yes
20 MHz
4
256
256
8
10
0
1
1
1
1
4
No
20 MHz
8
512
512
8
10
0
1
1
1
1
4
Yes
20 MHz
8
512
512
8
10
0
1
1
1
1
4
20-Pin PDIP ATtiny26
ATtiny261A
ATtiny261A ATtiny461
ATtiny461A
ATtiny461A ATtiny861
ATtiny861A
ATtiny861A
No
16 MHz
2
128
128
11
10
0
1
1
2
0
4
Yes
20 MHz
2
128
128
11
10
0
1
1
1
1
6
No
20 MHz
4
256
256
11
10
0
1
1
1
1
6
Yes
20 MHz
4
256
256
11
10
0
1
1
1
1
6
No
20 MHz
8
512
512
11
10
0
1
1
1
1
6
Yes
20 MHz
8
512
512
11
10
0
1
1
1
1
6
No
20 MHz
2
128
128
0
0
1
2
1
1
1
4
ATtiny2313A
Yes
20 MHz
2
128
128
0
0
1
2
1
1
1
4
ATtiny4313
Yes
20 MHz
4
256
256
0
0
1
2
1
1
1
4
ATtiny48
Yes
12 MHz
4
256
64
8
10
0
1
1
1
1
2
ATtiny88
Yes
12 MHz
8
512
64
8
10
0
1
1
1
1
2
ATtiny2313
ATtiny2313A
28-Pin PDIP
37
Explore ATtiny Microcontrollers using C and Assembly Language
1.4 Summary Any DIP ATtiny AVR microcontroller from 8-pin to 28-pin that are in-system programmable are fine to use when following this book, although 8-pin devices are mainly targeted. Be sure to read the introduction chapter, to get an overview of this book and information on the hardware and software needed when reading this book. In Chapter 2 we install Microchip Studio and use it to program an ATtiny microcontroller in order to get the necessary tools and hardware set up for use in the chapters that follow.
38
Chapter 2 • Hardware and Software Setup
The objective of this chapter is to install Microchip Studio, build a circuit using an ATtiny25/45/85 or ATtiny13(A), then write a program and load it to the microcontroller. Microchip Studio is used to write assembly language and C programs when following this book. Those readers who do not have hardware yet can still install Microchip Studio, read through the rest of this chapter and create the first assembly
In this Chapter ▫ Install Microchip Studio ▫ Build an ATtiny microcontroller circuit ▫ Write a simple assembly language program and load it to an ATtiny
language and C language programs. Chapter 3 shows how to use the simulator found in Microchip Studio.
▫ Write a simple C program for an ATtiny microcontroller
39
Explore ATtiny Microcontrollers using C and Assembly Language
2.1 Install Microchip Studio Microchip Studio (formerly Atmel Studio) can be downloaded as a web installer, or as an offline installer. Downloading the offline installer allows Microchip Studio to be installed on many computers without the need to download the software from the internet with each installation as the web installer does. For a single computer it does not matter which installation method is used.
2.1.1 Download Page and Software Version A brief description of the installation using the offline installer follows. If you are using the web installer, the steps are basically the same but you must be connected to the internet when doing the installation. Download Microchip Studio from: www.microchip.com/en-us/development-tools-tools-and-software/microchip-studio-for-avrand-sam-devices The exact version of Microchip Studio used at the time of writing was: Microchip Studio for AVR and SAM Devices 7.0.2542 Offline Installer 934 MB, date published November 2020
2.1.2 Newest Software Version There should be no problem using the newest version of Microchip Studio when it becomes available, but if there are any issues or incompatibilities, the above version of Microchip Studio can be used. After the above version of Microchip Studio is replaced by a newer version, it will be available from the Downloads Archive for AVR and SAM: www.microchip.com/en-us/development-tools-tools-and-software/avr-and-sam-downloadsarchive
2.1.3 Start the Installation Navigate to the folder that the Microchip Studio file was downloaded to and double-click the file to run it and start the installation, for example the file as-installer-7.0.2542-full.exe. A basic default installation is all that is needed. Some of the components of the installation are optional, but no harm is done by installing them.
2.1.4 Installation Steps You will need to agree to the license terms and conditions in the first installation dialog box. Click Next to continue. All of the architectures can be left at their default in the next dialog box, unless you need to conserve disk space (or download data if doing the web 40
Chapter 2 • Hardware and Software Setup install), in which case only AVR need be selected. Click Next to continue. Advanced Software Framework and Example Projects in the next dialog box are not needed for assembly language programming, so installing it is optional again. Click Next to continue. A list of items that must be valid for installation to proceed are displayed in the next dialog box. In some cases the installer may report that a video card driver needs to be upgraded, although the newest driver is already installed. It is usually possible to continue with the installation even if this is the case. Continue with the installation by clicking the Next button. Click Install to start the installation in the Release Notes dialog box. When Windows asks if you would like the application to make changes to the computer, click Yes to continue. After installation starts, a dialog box opens for setting up the MPLAB XC8 compiler. This optional compiler can be set up by clicking the Next button, or skipped by clicking the Cancel button. It is not necessary to set up this compiler. It will take some time for the installation to complete, depending on the speed of the host computer. During installation you will be prompted several times with dialog boxes asking if you would like to install device driver software. Click the Install button in the dialog box each time. The installation will continue and then complete.
2.2 8-Pin ATtiny Microcontroller LED Circuit An initial circuit is used to blink a single LED on and off, and is shown in Figure 2.1. If you have a Microchip Studio compatible programmer, such as the Atmel-ICE, AVR Dragon, or AVRISP mkII, build this circuit on a breadboard and connect the programmer as shown in Figure 2.1, Figure 2.2 and Figure 2.3. Read to the end of section 2.2.2 for details on connecting the programmer and then come back and build the circuit. Appendix B has alternate circuits that use 14-pin, 20-pin, and 28-pin ATtiny devices. Build a circuit from this appendix if you are using an alternate ATtiny. Although the Atmel-ICE is specified in two of the figures that follow, any USB programming device that has ISP/SPI programming capabilities can be used. Readers using hobby programmers do not need to build the circuit now, but must continue reading and create the first assembly language program in section 2.3. It is only necessary to build the circuit and connect the hobby programmer when prompted to in section 2.3.5, but do read all of the following paragraphs and sections as they contain some information on connecting hobby programmers. Information on connecting power is important. For those using a programmer that is directly supported in Microchip Studio, such as the Atmel-ICE, AVR Dragon and AVRISP mkII, connect the programmer to the USB port of the PC. When the programmer is plugged into a USB port 41
Explore ATtiny Microcontrollers using C and Assembly Language of the host PC for the first time, drivers are installed automatically, provided that Microchip Studio has already been installed. SPI header J1 in Figure 2.1 is just to show how a programmer is connected to the circuit. The inset in the figure shows a bottom view of the 6-pin connector at the end of the ribbon cable of a USB programmer, for example the 6pin connector on the Atmel-ICE, to aid wiring. The paragraphs that follow explain how to connect a programmer to the circuit.
Figure 2.1: 8-Pin ATtiny LED Circuit and ISP/SPI Header Pinout
Figure 2.2 shows the pinout of the Atmel-ICE programming cable. Be sure to plug the small 10-pin connector at the end of this cable into the port marked AVR on the AtmelICE, as shown in Figure 2.3. The pinout of the 6-pin connector also applies to the AVRISP mkII and AVR Dragon, using the raised plastic key as a reference to find pin 1. This same pinout applies to any programmer that uses the 6-pin ISP/SPI connection, including hobby programmers that use this connector. Figure 2.3 shows a photo of the circuit of Figure 2.1 built on a breadboard and connected to an Atmel-ICE.
Figure 2.2: Atmel-ICE Cable Pinout
42
Chapter 2 • Hardware and Software Setup Single strand wire, or Dupont wires with a pin on each end, can be used to connect from the bottom of the 6-pin connector of the Atmel-ICE, or other programmer with 6-pin ISP/SPI header, to the breadboard circuit.
Figure 2.3: ATtiny Circuit Built on Breadboard with Atmel-ICE Connected
To connect the programmer to the breadboard circuit, turn the 6-pin header over so that it is facing you – so that you can see the holes in the connector. Make sure that the raised plastic key on the connector is at the left when looking at Figure 2.1 and Figure 2.2. Find pin 1 using Figure 2.2 or the inset in Figure 2.1. Insert a wire into the pin 1 hole of the connector. Look at Figure 2.1 to see where pin 1 connects to – as can be seen, pin 1 from the connector goes to pin 6 of the 8-pin ATtiny, and is named MISO. Make the connection. Pin 2 of the connector connects to +5V from the 5V power supply. When using a Microchip Studio compatible programmer, connect pin 2 of the connector to +5V of the power supply, which is usually connected to one of the horizontal rails of the breadboard. This means that pin 2 can be connected to the 5V rail of the breadboard. Pin 2 is used by the USB 43
Explore ATtiny Microcontrollers using C and Assembly Language programmer to detect the voltage that the circuit is powered from. Hobby programmers usually supply 5V on this pin, rather than detect the voltage that the circuit is powered from. This pin can therefore be used to power the circuit from 5V when using a hobby programmer. If using a hobby programmer and an external power supply, then leave this pin disconnected, otherwise it will result in 5V from the computer USB being connected to 5V of the external power supply. Continue wiring the remaining pins of the 6-pin ISP/SPI connector as shown in Figure 2.1. Pin 6 is the final pin that needs to be connected, which connects to GND or 0V of the power supply, which is usually connected to one of the horizontal breadboard rails.
2.2.1 Circuit Power Supply Any power supply that provides stable and smooth 5V DC can be used to power the circuit. A breadboard power supply is used in Figure 2.3. The breadboard power supply shown in the figure has a 5V regulator and is powered by an external 6V to 12V DC power supply via a barrel connector. This particular breadboard power supply can also supply the circuit with 3.3V by using jumpers to set the voltage on the board. The Power Supply section of the introduction chapter of this book already describes this power supply. Refer back to Figure 0.4 in the introduction for an image of the breadboard power supply powered from an external mains to DC power supply unit. Figure 0.5 in the introduction shows the same circuit as seen in Figure 2.3, but with the Atmel-ICE connected using Dupont wires. Breadboard power supplies connect +5V (or +3.3V) to the horizontal breadboard rails marked with a red line and + sign. These rails are found on both sides of the breadboard. 0V or GND of a breadboard power supply connects to the horizontal rails that have a blue line next to them and are marked with a – sign. It is a good idea to attach a new breadboard power supply to an unused breadboard, and use a multimeter to check that the voltages that it is producing are at the correct levels before connecting the power supply to a circuit. Also make sure that the jumpers on the breadboard power supply are set correctly for the voltage that is to be used in a circuit. As already mentioned, if a hobby programmer is used, it can usually supply 5V to the circuit from the USB 5V of the host computer. All of the hobby programmers shown in Figure A.1 of Appendix A are able to supply 5V to power the target ATtiny. This includes the Arduino Uno when set up as an ISP programmer, where a connection can be made
44
Chapter 2 • Hardware and Software Setup from the Arduino 5V pin to the ATtiny circuit +5V point. If one of these hobby programmers is used in combination with a breadboard power supply, or other external power supply, then do not connect pin 2 of the ISP/SPI header to the circuit.
2.2.2 Decoupling Capacitor It is common practice to insert a 100n decoupling capacitor between +5V and GND on the breadboard near the microcontroller, but was left off this circuit, as it was found that there were no power problems when using the breadboard power supply shown. An electrolytic capacitor of around 1µF to 10µF and a 100n capacitor can be added to the circuit if there are any power problems, or if the power supply is located far from the ATtiny circuit.
2.3 A First Assembly Language Program Now that the ATtiny circuit is built, and programmer connected, we can write a first assembly language program that blinks or flashes the LED on and off. For a hobby USB programmer, build the circuit after creating the program when prompted in section 2.3.5 that follows, but first complete each subsection that follows. The subsections that follow show how to start a new AVR assembler project in Microchip Studio, write a simple LED blink program in assembly language, and finally build and load the program to the target AVR microcontroller.
2.3.1 Start a New AVR Assembler Project in Microchip Studio Open Microchip Studio and start a new AVR Assembler Project. There are four ways to start a new project in Microchip Studio that all open the New Project dialog box and are listed below. Choose one: 1.
Select File ► New ► Project... from the top menu.
2.
Use the New Project icon on the top toolbar (hover the mouse cursor over the toolbar icons to see the tool tips which identify the icons).
3.
Use the keyboard shortcut Ctrl + Shift + N
4.
Click New Project... on the Microchip Studio Start Page (Select View ► Start Page from the top menu if the Start Page is not showing. There is also a Start Page icon on one of the top toolbars. To identify any toolbar icon in Microchip Studio, either hover the mouse cursor over the icon to see the tool tip, or use the top menu to identify the icon – View ► Start Page shows the Start Page icon, which can also be seen on the toolbar.) 45
Explore ATtiny Microcontrollers using C and Assembly Language In the New Project dialog box, click Assembler on the left and AVR Assembler Project in the middle pane. Name the project led_blink_asm in the Name: field near the bottom of the dialog box and select the location that you would like to save it to using the Browse… button as can be seen in Figure 2.4. Click the OK button at the bottom right of the New Project dialog box to move to the Device Selection dialog box, as shown in Figure 2.5.
Figure 2.4: New AVR Assembler Project in Microchip Studio
Search for the microcontroller that you are using in the Device Selection dialog box by using the search box at the top right. Type the part number of the ATtiny microcontroller that you are using into the search box. After filtering the ATtiny part by using the search box, select the specific ATtiny part in the left pane by clicking it, and then click the OK button. Figure 2.5 shows an ATtiny13A selected. An alternative to using the search box in the Device Selection dialog box is to use the Device Family: drop-down list near the top left of the dialog box. Here ATtiny can be selected using the drop-down list which then displays only the ATtiny family devices in the left pane of the dialog box. The desired device can then be clicked to select it in the left pane. After clicking the OK button in the Device Selection dialog box, a new project is created in Microchip Studio with a default main.asm assembly language file that contains some skeleton code. In the next section, we delete the skeleton code and enter a new assembly language program.
46
Chapter 2 • Hardware and Software Setup
Figure 2.5: AVR Device Selection in Microchip Studio
2.3.2 LED Blink Assembly Code Replace the skeleton code in main.asm created in the previous section, with the code shown in the led_blink_asm : main.asm listing that follows. If using an alternate circuit from Appendix B that has the LED connected to pin PB0 of the ATtiny, then use the alternate code from section B.5.1 of Appendix B. When learning any new programming language, it is best to type the code in yourself, rather than to copy and paste it. It is not necessary to type the comments at this stage – comments start with a semicolon (;) and describe what is happening in the program. Use the Tab key to indent the code as shown in Figure 2.6. In some cases you may need to press Tab twice to align the text properly. Make sure that you type everything in exactly as shown in the code listing. It is a good idea to carefully check the code typed into the main.asm file line by line to make sure that there are no typing errors. Being diligent when typing and checking code is the mark of a good programmer. After typing the program into the main.asm file of the led_blink_asm project, save the file by using the Ctrl + S keyboard shortcut, File ► Save from the top menu, or by using the Save icon on the top toolbar.
47
Explore ATtiny Microcontrollers using C and Assembly Language
led_blink_asm : main.asm start: sbi
DDRB, DDB4
; Set pin PB4 as output
loop: sbi rcall cbi rcall rjmp
PORTB, PORTB4 delay PORTB, PORTB4 delay loop
; ; ; ;
; Delay subroutine delay: ldi r16, 0xff delloop1: ldi r17, 0xff delloop2: dec r17 brbc SREG_Z, delloop2 dec r16 brbc SREG_Z, delloop1 ret
Set LED pin high LED on delay Clear LED pin low LED off delay
; Delay by decrementing ; Delay by decrementing
Figure 2.6: Indenting Assembler Code
2.3.3 Build the Project The project must now be built to convert the assembly language text file to a file that can be loaded to the AVR microcontroller. Click the Build icon on the top toolbar or select Build ► Build led_blink_asm from the top menu. Output messages from the build process are shown in a pane that pops up at the bottom of Microchip Studio. If the build was successful, the text “Build succeeded.” appears in the bottom pane.
48
Chapter 2 • Hardware and Software Setup
2.3.4 Fix Any Build Errors If any errors occurred when building, a red circle with an X inside it appears in the bottom pane of Microchip Studio with a description of the error. If a build error does occur in your program, double-click the red circle to move the cursor to the position in the assembler file that contains the error. Check the line of code against the led_blink_asm code listing to find the error. Any problem with this program can only be a typing error. Make sure that your code is exactly the same as the code listing. All source code for this book is available for download from Elektor. If there are still problems, download the code and compare with your code, or copy and paste the source code to main.asm, save and build again.
2.3.5 Load the Program to the AVR Microcontroller At this stage, it is assumed that the programmer, such as the Atmel-ICE being used is connected to the AVR microcontroller as already described in this chapter and that the microcontroller circuit is powered from 5V. It is also assumed that the microcontroller is new and therefore has the internal fuses set to factory default values. Those readers who are using a USB hobby programmer must follow the instructions in Appendix A now. These instructions show how to set up and program the target AVR microcontroller using a hobby programmer. Hobby programmer users can then continue at section 2.3.6. To load the program that has just been built in Microchip Studio to the AVR chip using a USB programmer that is directly supported in Microchip Studio, such as the Atmel-ICE, AVR Dragon, or AVRISP mkII, first select the programming tool that you are using. In Microchip Studio, click the hammer icon named None on or “No tool” on the second horizontal toolbar; or select Project ► led_blink_asm Properties... from the top menu (keyboard shortcut Alt + F7) and then Tool in the left column of the page that opens. Click the box under Selected debugger/programmer and then click the tool that you are using in the list that opens – the tool must be plugged into the USB port for it to appear in the list. Under Interface:, select ISP for a new ATtiny13 or ATtiny25/45/85 device which use the ISP setting as the default. Save the changes using the keyboard shortcut Ctrl + S. Switch power to the ATtiny circuit on. Click the “Start Without Debugging” icon (the top green triangle icon) on the top toolbar in Microchip Studio to load the program to the microcontroller. Alternatively use the keyboard shortcut Ctrl + Alt + F5 or Debug ► Start Without Debugging from the top menu. If the program loads successfully, the LED will start blinking.
49
Explore ATtiny Microcontrollers using C and Assembly Language
2.3.6 Fault Finding If the program does not load, check for the obvious, such as the programmer not plugged in, or if the power supply is not on. Also check the wiring of the programmer ISP header to the microcontroller. If the LED does not start blinking, but the program loaded successfully, then there could be an error in the program that does not trigger an error message when the program is built. In this case check each line of the program against the code listing to make sure that everything is correct. Check that the LED and series resistor are wired correctly. If there is still a problem, copy and paste the code from the accompanying files into your project as there may be an error that you have not located. Rebuild the project and load the program to the microcontroller again.
2.4 A First C Program As this book includes C programming in addition to assembly language programming, a C program is created in this section that blinks or flashes an LED on and off. The objective of this exercise is to show readers how to create a C project for ATtiny microcontrollers in Microchip Studio. For those readers who have not learned the C programming language yet, it is still possible to follow these steps and create a C program without the need to know the C programming language. As explained in the introduction, this book does not teach the C programming language, but can be used by anyone to learn AVR assembly language and the architecture of AVR microcontrollers. Readers wishing to learn the C programming language on microcontrollers may enjoy the book C Programming with Arduino by the same author and published by Elektor – ISBN: 978-1-907920-46-2. The subsections that follow show how to start a new C project in Microchip Studio, write code to blink the LED of Figure 2.1, build the C project and load the program to an ATtiny device. Use the same circuit of Figure 2.1, with the programmer connected the same way, or the same alternate circuit from Appendix B.
2.4.1 Start a New GCC C Executable Project in Microchip Studio Open Microchip Studio and start a new project in the same way that was used in section 2.3.1 for the assembler project. This opens the New Project dialog box. Because the previous project created was an assembler project, Assembler is still selected in the left pane of the dialog box. It is necessary to first click the C/C++ item in the left pane of the dialog box. In the middle pane of the dialog box, click GCC C Executable Project.
50
Chapter 2 • Hardware and Software Setup
Figure 2.7: Starting a New C Project in Microchip Studio
Give the project a name of led_blink_c in the Name: field near the bottom of the dialog box, and change the location of the project if needed. The Location: field can be left unchanged if the project is to be created in the same location as the assembler program previously created. Figure 2.7 shows an image of the New Project dialog box. Click the OK button to continue. The next dialog box that opens after clicking the OK button in the previous step is the Device Selection dialog box. This dialog box is used in exactly the same way as it was used to select a microcontroller when creating the assembler project. Search for the device being used in the search field by typing the part number, which is either ATtiny13, ATtiny13A, ATtiny25, ATtiny45 or ATtiny85 for this exercise. Refer back to Figure 2.5 if needed. After filtering out the desired device using the search field, click it in the left pane of the dialog box to select it. Finally click the OK button. Microchip Studio creates the new project and opens the main.c file of the project which contains some skeleton C code.
2.4.2 LED Blink C Code Replace the skeleton C code in the main.c file with the code in the led_blink_c : main.c code listing that follows. If using an alternate circuit from Appendix B that has the LED attached to pin PB0, then use the alternate C program from section B.5.2 of Appendix B. Be sure to type in all of the code as it is shown in the listing. As with the assembler project, use the Tab key to indent the code as shown. In C programs, a semicolon (;) is not the 51
Explore ATtiny Microcontrollers using C and Assembly Language start of a comment, but is used to terminate C statements. It is therefore important not to leave off any semicolons, or the C compiler will report errors when it is run during the build process.
led_blink_c : main.c //#define F_CPU 1000000UL #define F_CPU 1200000UL #include #include int main(void) { DDRB |= (1