PDF Avr workshop: a hands-on introduction with 60 projects (not genuine pdf) 1st edition john boxall

Page 1


AVRWorkshop:AHands-OnIntroductionwith60 Projects(NOTgenuinepdf)1stEditionJohnBoxall

https://ebookmass.com/product/avr-workshop-a-hands-onintroduction-with-60-projects-not-genuine-pdf-1st-edition-

Instant digital products (PDF, ePub, MOBI) ready for you

Download now and discover formats that fit your needs...

Programming for Game Design: A Hands-On Guide with Godot 1st Edition Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-onguide-with-godot-1st-edition-wang/

ebookmass.com

Essentials of Marketing Research: A Hands On Orientation 1st Edition, (Ebook PDF)

https://ebookmass.com/product/essentials-of-marketing-research-ahands-on-orientation-1st-edition-ebook-pdf/

ebookmass.com

Programming for Game Design: A Hands-On Guide with Godot 1st Edition Wallace Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-onguide-with-godot-1st-edition-wallace-wang/

ebookmass.com

The Ultimate Guide to Python Programming for Beginners: Your 7-Day Gateway to Solve Problems & Express Creativity with Hands-On Exercises to Unlock Career Opportunities

Megabyte Publishing https://ebookmass.com/product/the-ultimate-guide-to-pythonprogramming-for-beginners-your-7-day-gateway-to-solve-problemsexpress-creativity-with-hands-on-exercises-to-unlock-careeropportunities-megabyte-publishing/ ebookmass.com

https://ebookmass.com/product/health-promotion-throughout-thelifespan-ebook/

ebookmass.com

Corporate Governance and Diversity in Boardrooms: Empirical Insights into the Impact on Firm Performance 1st ed. Edition Barbara Sveva Magnanelli

https://ebookmass.com/product/corporate-governance-and-diversity-inboardrooms-empirical-insights-into-the-impact-on-firm-performance-1sted-edition-barbara-sveva-magnanelli/ ebookmass.com

Exceptional Learners: An Introduction to Special Education 12th Edition Daniel P. Hallahan

https://ebookmass.com/product/exceptional-learners-an-introduction-tospecial-education-12th-edition-daniel-p-hallahan/

ebookmass.com

Challenges and Opportunities for Chinese Agriculture: Feeding Many While Protecting the Environment 1st ed. Edition Wensheng Chen

https://ebookmass.com/product/challenges-and-opportunities-forchinese-agriculture-feeding-many-while-protecting-the-environment-1sted-edition-wensheng-chen/ ebookmass.com

Coding Clean, Reliable, and Safe REST APIs with ASP.NET Core 8 1st Edition Anthony Giretti

https://ebookmass.com/product/coding-clean-reliable-and-safe-restapis-with-asp-net-core-8-1st-edition-anthony-giretti/

ebookmass.com

Education Reform in the Twenty-First Century: The Marketization of Teaching and Learning at a No-Excuses

https://ebookmass.com/product/education-reform-in-the-twenty-firstcentury-the-marketization-of-teaching-and-learning-at-a-no-excusescharter-school-erinn-brooks/

ebookmass.com

AVRWORKSHOP

AVRWORKSHOP

AHands-onIntroductionwith60Projects

SanFrancisco

AVRWORKSHOP.Copyright©2023byJohnBoxall.

Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyany means,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorage orretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher

Firstprinting

2625242322 12345

ISBN-13:978-1-7185-0258-1(print)

ISBN-13:978-1-7185-0259-8(ebook)

Publisher:WilliamPollock

ManagingEditor:JillFranklin

ProductionManager:RachelMonaghan

DevelopmentalEditor:AbigailSchott-Rosenfield

ProductionEditor:RachelMonaghan

CoverandInteriorDesign:OctopodStudios

TechnicalReviewer:XanderSoldaat

Copyeditor:RachelHead

ProductionServices:ScribeInc.

Forinformationondistribution,bulksales,corporatesales,ortranslations,pleasecontactNo StarchPress,Inc.directlyatinfo@nostarch.comor:

NoStarchPress,Inc.

2458thStreet,SanFrancisco,CA94103 phone:1.415.863.9900 www.nostarch.com

LibraryofCongressControlNumber2022020563

NoStarchPressandtheNoStarchPresslogoareregisteredtrademarksofNoStarchPress,Inc. Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespective owners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weare usingthenamesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withno intentionofinfringementofthetrademark.

Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileevery precautionhasbeentakeninthepreparationofthiswork,neithertheauthornorNoStarchPress, Inc.shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedor allegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.

ToCyril,John,David,andallthepeoplewhoenjoymakingsomethingout ofnothing.

AbouttheAuthor

John Boxall has been an electronics enthusiast for over 30 years, spending much of that time in the electronics retail, wholesale, and consulting fields. He also spent several years writing Arduino tutorials, projects, and reviews of kits and accessories at https://tronixstuff.com. Arduino Workshop (No StarchPress,2013)washisfirstbook.

AbouttheTechnicalReviewer

Xander Soldaat is a former Mindstorms Community Partner for LEGO® MINDSTORMS. He has a deep background in IT infrastructure architecture, aswellasembeddedsystems,compiler,andSTEMcurriculum development. He is currently an OpenShift Cloud Success Architect at Red Hat. In his spare time he likes to tinker with robots, electronics, retro computers,andtable-topgames.

BRIEFCONTENTS

Acknowledgments

Introduction

Chapter1:GettingStarted

Chapter2:FirstSteps

Chapter3:GettingandDisplayingInput

Chapter4:CommunicatingwiththeOutsideWorldusingtheUSART

Chapter5:TakingControlwithHardwareInterrupts

Chapter6:UsingHardwareTimers

Chapter7:UsingPulse-WidthModulation

Chapter8:ControllingMotorswithMosfets

Chapter9:UsingtheInternalEEPROM

Chapter10:WritingYourOwnAVRLibraries

Chapter11:AVRandtheSPIBus

Chapter12:AVRandtheI2CBus

Chapter13:AVRandCharacterLiquidCrystalDisplays

Chapter14:ControllingServos

CONTENTSINDETAIL

Acknowledgments

Introduction

1:GettingStarted

ThePossibilitiesAreEndless

TheMicrochipAVRMicrocontrollers

RequiredPartsandAccessories

ElectronicComponents

ChoosinganAVRProgrammer

RequiredSoftware

macOS10.6orLater

UbuntuLinux20.04LTSorLater

Windows7Through11

Current,Voltage,andPower

ElectronicComponents

Resistors

Light-EmittingDiodes

PowerDiodes

Capacitors

IntegratedCircuits

SolderlessBreadboards

PoweringYourProjects

2:FirstSteps

TestingtheHardwareandToolchain

BuildtheCircuit

ConnectandRuntheProgrammer

WhatIfItDidn’tWork?

Project0:BlinkinganLED

UploadingYourFirstAVRCode

WhatIfItDidn’tWork?

ControllingDigitalOutputs

HardwareRegisters

Project1:ExperimentingwithATtiny85DigitalOutputs

TheHardware

TheCode

UsingSchematicDiagrams

ComponentsinSchematics

WiresinSchematics

DissectingaSchematic

Project2:ExperimentingwithATmega328P-PUDigitalOutputs

TheHardware

TheCode

Project3:Bit-ShiftingDigitalOutputs

Project4:ExperimentingwithNOT

Project5:ExperimentingwithAND

Project6:ExperimentingwithOR

Project7:ExperimentingwithXOR

3:GettingandDisplayingInput

DigitalInputs

IntroducingthePushbutton

ReadingtheStatusofDigitalInputPins

Project8:BlinkinganLEDonCommand

TheHardware

TheCode

MakingDecisionsinCode ifStatements if...elseStatements

MakingTwoorMoreComparisons

switch...caseStatements

CreatingYourOwnFunctions

Project9:ASimpleCustomFunction

Project10:CustomFunctionswithInternalVariables

Project11:CustomFunctionsThatReturnValues

SwitchBounce

ProtectingYourAVRfromFluctuatingVoltages

PullupResistors

PulldownResistors

IntroducingSeven-SegmentLEDDisplays

Project12:BuildingaSingle-DigitNumericalCounter

TheHardware

TheCode

AnalogInputs

UsingATtiny85ADCs

Project13:MakingaSingle-CellBatteryTester

TheHardware

TheCode

UsingtheATmega328P-PUADCs

IntroducingtheVariableResistor

Project14:ExperimentingwithanATmega328P-PUADC

TheHardware

TheCode DoingArithmeticwithanAVR

UsingExternalPower

TheTMP36TemperatureSensor

Project15:CreatingaDigitalThermometer

TheHardware

TheCode

4:CommunicatingwiththeOutsideWorldusingtheUSART

IntroducingtheUSART

HardwareandSoftwareforUSARTCommunication

Project16:TestingtheUSART

TheHardware

TheCode

Project17:SendingTextwiththeUSART

Project18:SendingNumberswiththeUSART

Project19:CreatingaTemperatureDataLogger

TheHardware

TheCode

Project20:ReceivingDatafromYourComputer

Project21:BuildingaFour-FunctionCalculator

5:TakingControlwithHardwareInterrupts

ExternalInterrupts

SettingUpInterruptsinCode

Project22:ExperimentingwithRisingEdgeInterrupts

TheHardware

TheCode

Project23:ExperimentingwithFallingEdgeInterrupts

TheHardware

TheCode

Project24:ExperimentingwithTwoInterrupts

TheHardware

TheCode

Pin-ChangeInterrupts

Project25:ExperimentingwithPin-ChangeInterrupts

TheHardware

TheCode

Project26:CreatinganUp/DownCounterUsingInterrupts

TheHardware

TheCode

FinalNotesonInterrupts

6:UsingHardwareTimers

IntroducingTimers

Project27:ExperimentingwithTimerOverflowandInterrupts

TheHardware

TheCode

Project28:UsingaCTCTimerforRepetitiveActions

Project29:UsingCTCTimersforRepetitiveActionswithLongerDelays

ExaminingtheAccuracyoftheInternalTimer

AddressingRegisterswithBitwiseOperations

AddressingIndividualBitsinaRegister

AddressingMultipleBitsinaRegister

Project30:ExperimentingwithOverflowTimersUsingBitwiseOperations

7:UsingPulse-WidthModulation

Pulse-WidthModulationandDutyCycles

Project31:DemonstratingPWMwiththeATtiny85

TheHardware

TheCode

IndividualPWMPinControlfortheATtiny85

Project32:ExperimentingwithPiezoandPWM

TheHardware

TheCode

IndividualPWMPinControlfortheATmega328P-PU

TheRGBLED

Project33:ExperimentingwithRGBLEDsandPWM

TheHardware

8:ControllingMotorswithMosfets

TheMOSFET

Project34:DCMotorControlwithPWMandMOSFET

TheHardware

TheCode

Project35:Temperature-ControlledFan

TheHardware

TheCode

TheL293DMotorDriverIC

Project36:DCMotorControlwithL293D

TheHardware

TheCode

Project37:ControllingaTwo-Wheel-DriveRobotVehicle

TheHardware

TheCode

9:UsingtheInternalEEPROM

StoringBytesinEEPROM

Project38:ExperimentingwiththeATtiny85’sEEPROM

StoringWords

Project39:ASimpleEEPROMDatalogger

TheHardware

TheCode

StoringFloating-PointVariables

Project40:TemperatureLoggerwithEEPROM

TheHardware

10:WritingYourOwnAVRLibraries

CreatingYourFirstLibrary

AnatomyofaLibrary

InstallingtheLibrary

Project41:YourFirstLibrary

CreatingaLibraryThatAcceptsValuestoPerformaFunction

Project42:Usingtheblinko2.cLibrary

CreatingaLibraryThatProcessesDataandReturnsValues

Project43:CreatingaDigitalThermometerwiththethermometer.cLibrary

11:AVRandtheSPIBus

HowBusesWork

PinConnectionsandVoltages

ImplementingtheSPIBus

SendingData

Project44:Usingthe74HC595ShiftRegister

TheHardware

TheCode

Project45:UsingTwo74HC595ShiftRegisters

TheHardware

TheCode

Project46:UsingtheMAX7219LEDDriverIC

TheHardware

TheCode

Project47:AddingaResetButton

MultipleSPIDevicesontheSameBus

ReceivingDatafromtheSPIBus

Project48:UsingtheMCP3008ADCIC

TheHardware

TheCode

12:AVRandtheI2CBus

IncreasingAVRSpeed

IntroducingtheI2CBus

PinConnectionsandVoltages

WritingtoI2CDevices

Project49:UsingtheMCP2301716-BitI/OExpander

TheHardware

TheCode

ReadingDatafromI2CDevices

Project50:UsinganExternalICEEPROM

TheHardware

TheCode

Project51:UsingtheDS3231Real-TimeClock

TheHardware

TheCode

13:AVRandCharacterLiquidCrystalDisplays

IntroducingLCDs

SendCommandstotheLCD

InitializetheLCDforUse

CleartheLCD

SettheCursor PrinttotheLCD

Project52:UsingaCharacterLCDwithYourAVR

TheHardware

TheCode

Project53:BuildinganAVR-BasedLCDDigitalClock

TheHardware

TheCode

DisplayingFloating-PointNumbersontheLCD

Project54:LCDDigitalThermometerwithMin/MaxDisplay

TheHardware

TheCode

DisplayingCustomCharactersontheLCD

WriteDatatoCGRAM

SendCustomCharacterDatatoLCD

DisplayCustomCharactersonLCD

Project55:DisplayingCustomLCDCharacters

14:ControllingServos

SettingUpYourServo

ConnectingaServo

ControllingaServo

Project56:ExperimentingwithServos

TheHardware

TheCode

Project57:CreatinganAnalogThermometer

TheHardware

TheCode

Project58:ControllingTwoServos

TheHardware

TheCode

Project59:BuildinganAnalogClockwithServoHands

TheHardware

TheCode

Epilogue

Index

ACKNOWLEDGMENTS

Thank you to Brian S. Dean for starting the AVRDUDE project, followed by Jörg Wunsch and the various contributors. Kudos and thanks to the KiCad team for their open source electronics design automation suite, whichI’veusedthroughoutthisbookforcircuitschematics.

Many thanks to my technical reviewer, Xander Soldaat, for his contributions and for once again having the tenacity to follow through with suchalargeproject.

Thanks also to the following people (in no particular order) from whom I’ve received encouragement, inspiration, and support: Elizabeth Pryce, Mr. Richard Smith AC, the late Sir Clive Sinclair, and my wife, Kathleen, forherendlesspatience.

Finally, thank you to everyone at No Starch Press for their efforts, including Abigail Schott-Rosenfield for her editorial input; Rachel Monaghan for guiding the book through the production process; Rachel Head for copyediting; Scribe Inc. for composition, proofreading, and indexing; and of course Bill Pollock for his support and guidance and for convincingmethatsometimesthereisabetterwaytoexplainsomething.

INTRODUCTION

A microcontroller (or MCU for short) is a small, complete computer that fits on a single integrated circuit. Just like your desktop computer, a microcontrollercontainsaprocessor,memory,devicestoreceiveinputfrom various sources, and outputs that can be used to control or communicate withexternaldevices.

Thanks to the success of development platforms like Arduino and PICAXE, microcontrollers are being used increasingly often in the electronics field and among hobbyists and hackers. Such platforms simplify projects for beginners, but they can be costly; they also put a layer of abstraction between the user and the microcontroller, which decreases the microcontroller’s performance and often prevents the user from accessing its full set of features. More experienced users may want to control the microcontroller directly or use less expensive parts in their projects. Or, if you’re a beginner, you may want to start your microcontroller journey withoutanyartificiallyimposedoverheads.

That’swherethisbookcomesin.Whether you’reanabsolute beginneror a longtime electronics enthusiast, AVR Workshop shows you how to take advantage of two chips from the inexpensive range of Microchip AVR 8-bit microcontrollers made famous in the Arduino and compatible boards. Once you master these chips, you’ll be able to maximize their performance to create powerful projects with cheaper hardware. Along the way you’ll learn aboutelectronics,Cprogramming,andmuchmore.

I’ll walk you through over 55 projects of increasing difficulty based around the ATtiny85 and ATmega328P-PU microcontrollers from Microchip, and I’ll explain and demonstrate everything you need to know

for each project. You’ll start off blinking a small light, then move on to keepingtime,capturingandanalyzingreal-worlddatasuchastemperatures, and even controlling small motorized devices. This book doesn’t cover AVR for IoT, as that’s a more advanced topic, but after completing the projects here, you’ll be able to harness a wide variety of devices, sensors, motors, displays, and more with your AVR microcontroller to bring your dreamsandideastolife.

I’ve written this book for a wide variety of people. You might be a student wanting to get a head start with microcontrollers, an electronics hobbyist with no prior experience in digital or microcontroller circuitry, an employee who wants to increase their knowledge base for work, or just someone who enjoys making things. This book is for anyone interested in learning more about AVR technology and harnessing it to create their own projects.

My goal is that you’ll leave this book with lasting knowledge and the confidence to keep learning and making. Chapter 1 will get you started by introducing a few cool real-world projects that use AVR microcontrollers, thenshowingyouhowtosetupyourownworkstation.

1

GETTINGSTARTED

Welcome to the beginning of your AVR microcontroller journey! In this chapter I’ll introduce you to the microcontrollers used in this book, as well as a few exciting examples of real-world AVR-based projects, then teach yousomefundamentalsaboutelectronics.

Youwilllearn:

•Wheretogettherequiredpartsfortheprojectsinthisbook

• How to install the required software for Windows, macOS, and Linux

•Thebasicpropertiesofelectricityandelectroniccomponents

• About electronic components, including resistors, light-emitting diodes(LEDs),powerdiodes,capacitors,andmore

•Howtouseasolderlessbreadboardtoconstructcircuits

•Waystosafelypoweryourexperiments

Bytheendofthechapter,you’llbereadytouseyourAVRworkstationto buildyourfirstproject.

A quick scan through this book will show you that you can use AVR microcontrollers as the heart of an incredibly wide range of devices. You’ll go from blinking LEDs to creating a thermostat, a GPS logger, and more— butdon’tlimityourselftotherangeofprojectscoveredhere!Afterworking through this book, you’ll be well prepared to explore more advanced projectslikethoseI’lldescribeinthissection.

For example, computer scientist Vassilis Serasidis built a piece of electronics test equipment called a logic analyzer, which can measure the values of four electrical currents at the same time and display the results. His design uses an inexpensive LCD typically found in cheap cellular phonestoshowthesignalsinagraphicalform,asshowninFigure1-1.

Figure 1-1: An inexpensive logic analyzer

You can use logic analyzers to run a huge variety of displays with an AVR microcontroller, from inexpensive black and white versions like the one in Figure 1-1 to realistic color displays. For more information on the project, visit

https://www.serasidis.gr/circuits/mini_logic_analyzer/miniLogicAnalyzer.ht m.

You can also use AVRs to build tiny projects like wearable electronics, but you need an incredibly small development board to do so. Electronics enthusiast Erik Kettenburg dreamed of such a board based on the smallest AVRinexistence.HetranslatedthisideaintotheDigisparkboard,shownin Figure 1-2, which measures only 17.5 × 19 mm, and built a thriving businessviaasuccessfulKickstarterpromotionin2017.

Figure 1-2: An example of the Digispark board

The size of the Digispark board means the AVR microcontroller it uses doesn’t have quite as many features as some larger chips—for example, it has less program memory space. However, the Digispark allows you to

program the microcontroller directly via USB, whereas you’d normally have to purchase a separate programming device. For more information on theDigisparkboard,visit http://digistump.com/.

In addition to using AVRs professionally, plenty of people build AVRbased projects purely for fun! One example is the AVR TV Game software engineerBenRyvesbuiltin2009,showninFigure1-3.Benusedverybasic electronics and an AVR to make a device that plugs into a television and letsyouplaytheclassicgames Snake and Tetris.

The AVR can generate the video signals to communicate with a television without any extra hardware, and with some imagination, you can

Figure 1-3: Playing Tetris on the AVR TV Game

program your own games into the microcontroller. For more information, visit http://benryves.com/products/avrtvgame/.

Engineer Adam Heinrich even built his own cellular telephone in 2017 based on an AVR, complete with a color touchscreen interface. Adam’s “AvrPhone,” which is portable for mobile use, is shown in Figure 1-4. For moreinformation,visit http://projects.adamh.cz/avrphone/.

Just like these makers, with some effort, you can bridge the gap between hobbyist tinkering and full product development! But for now, let’s start withamoredetaileddiscussionofthepartsyou’lluseinthisbook.

TheMicrochipAVRMicrocontrollers

Figure 1-4: The AvrPhone

Throughout this book, you’ll use the two microcontrollers shown in Figure 1-5, which Microchip Technology produces as part of its AVR product line. The smaller one, called an ATtiny85, has 8 pins, which are the pieces ofmetal sticking outonthesidesoftheblackchipsthatallowyouto sendandreceivedataandpowerfromandtothemicrocontroller.Thelarger AVRisanATmega328P-PU,whichhas28pins.

NOTE In this book and when purchasing your own parts, you may see microcontrollers labeled “Atmel.” Microchip acquired Atmel in 2016, but at the time of writing some suppliers still have Atmel-branded units; either label is fine.

Apart from size, there are several important differences between the ATtiny85andATmega328P-PUmicrocontrollers,aslistedinTable1-1.

Figure 1-5: Our AVR microcontrollers, the ATtiny85 and ATmega328P-PU

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
PDF Avr workshop: a hands-on introduction with 60 projects (not genuine pdf) 1st edition john boxall by Education Libraries - Issuu