Introduction: Learn About Microcontrollers

This Instructable was designed to answer the question: how do I get started in microcontrollers? Now, in clear, simple English, you can learn what a microcontroller is, and how to use one. You will learn how to make everything that you need to get started. This does require a Windows PC with at least one USB port.

In eighteen easy steps, you will learn what a microcontroller is, how to put one together, how to program it and how to interface the microcontroller to simple input and output devices. All of the components, including the microcontroller itself, are are easily obtained from many different sources, or you may purchase a complete kit from GranzTronix (https://www.tindie.com/products/granztronix/introduction-to-microcontrollers/.) You will get all of the parts that you need in the kit, but you do not need the kit - all of the experiments may be completed with the information provided in this 'ible.

Your introduction text ebook, including the assembly instructions for the purchased kit (skip this part if you build your own following this Instructable,) all quizzes and answers and the sample programs, may be downloaded from our web site at: http://files.granzeier.com/Downloads/2313ES.pdf. The steps in this 'ible are like a Reader's Digest version of the ebook.

Required Parts:

You will need a few parts for this project. You can get most of these from your local Radio Shack, or you may mail order them from any of many different supply houses.

  1. a breadboard - you will need at least an 800-terminal breadboard, but that will give you limited expansion space. The breadboard I show in these pictures provides two 800-terminal breadboards with dual power rails for each one.
  2. an AVR programmer - we use the USBASP programmer here. I routinely find these on eBay for well under $5.00 delivered. If you choose a different model, you will need to modify the directions in this 'ible accordingly.
  3. a way to connect the programmer to your breadboard. In step 4, I mention two ways to accomplish this.
  4. 3 low-voltage, low-current LEDs (plus one more if you would like a pilot light to indicate when your dev kit is powered.
  5. 3 (or 4 if you use the pilot light) 360 ohm, 1/4 to 1/8 watt resistors to limit the current through the LED.
    (You can get a pack of 6 LEDs and resistors from https://www.tindie.com/products/granztronix/led-prototyping-pack/.)
  6. 3 small NO, SPST, Momentary action pushbutton switches - one for the reset circuit, and two for experiments. (https://www.tindie.com/products/granztronix/pushbutton-switch-pack/)

  7. a small speaker. (included in: https://www.tindie.com/products/granztronix/digital-interface-pack/)

  8. An Atmel AVR ATtiny2313 microcontroller (this is also included in the GranzTronix kit.)
  9. optional - a 5V power source. Your dev kit can be totally powered by the programmer, this is only needed if you would like to disconnect your computer and take your experiments out to show them off. The kit comes with a battery box, using 4 AA-cells for a total of 4.8V or 6V, depending upon the type of cells used.

As mentioned earlier, you may build this system, and go through all of the experiments shown here (and the others in the book,) or you may purchase a complete set of all parts, including a professionally developed PCB (printed circuit board,) from GranzTronix (https://www.tindie.com/products/granztronix/introduction-to-microcontrollers/.)

Step 1: What Is a Microcontroller?

Before you can design with a microcontroller, you really need to know what one is. Microcontrollers are all around you, although you may not even realize it. Many people seem overawed by the thought of a microcontroller. A while ago, I spoke to a woman who, when I told her that I work with microcontrollers, replied that those things were far beyond her. I responded that maybe she could not design with them yet, but that she uses those small computers all the time. She appeared to think that I was nuts to suggest that she could even be involved, in any way, with that kind of “high tech” stuff. These microcontrollers are the brains in many products around the home and office. These microcontrollers can be found in watches, microwave ovens, telephones, cars and trucks, DVD players and robots, in fact almost every product that has a display will use at least one of these microcontrollers. So, most people in industrialized nations are already microcontroller users, even though they don’t think of themselves that way.

What is a computer?

A microcontroller is a type of computer, so what is a computer? All computers are made up of four major units. These include the Input unit, the Output unit, the Central Processing unit and the Memory unit. The Input unit is the way that the computer gets the data on which it will do it’s work. Most people know about input devices attached to their desktop computers, devices like their keyboard and their mouse. The Central Processing unit performs the work of running the computer’s programs. This is made up of a Control Unit and an Arithmetic/Logic Unit (also called an ALU). Together these two units make up the Central Processor Unit, or CPU. While working, the CPU keeps it’s instructions, or the program, along with the data on which it is working, in the Memory unit. After the computer does it’s computing, it will present the results of that work thru the output unit. Some of the output devices attached to your desktop computer would be the video display and the printer. A microprocessor combines the two parts of a computer’s CPU (the Control Unit and the ALU) into one single integrated circuit (IC) or chip.

A computer can do a vast number of different jobs. The computers with which you may be most familiar are the ones that sit on or next to your desk and run Windows or Linux or maybe MacOS. These general-purpose computers will help you type a letter or term paper, balance your checkbook or your accounting books, or maybe research different topics by letting you browse the Web. A whole other type of job is for the computer to run (or control) a piece of equipment. By connecting the electrical lines in a computer’s input unit to different switches or sensors, and connecting the electrical lines in that computer’s output unit to lights, motors and other such devices, a computer can control things like an assembly line, a microwave oven, a stereo, or even something like a plane or space ship. In fact, anything that can be operated by one or more switches can be connected to an output line and controlled by a computer. These computers, which are dedicated to the control of equipment, are called Control Computers, or simply Controllers.

In the same way that a Microprocessor combines the two parts of a Control Unit into one IC, a Microcontroller combines the four parts of a computer onto one single IC – these ICs are specially crafted to include things useful for controlling equipment. Thus, they are called microcontrollers.

As you can see, there is nothing inherently complex about microcontrollers; they are simply small control computers integrated onto a single chip. The microcontroller on your Tiny2313 Experimenter System is an IC (or chip) from Atmel, called the AVR ATtiny2313A.

Step 2: Tell Me What You Want Me to Do.

A computer is only as useful as a doorstop between uses, without a program to tell it what to do. The process of giving the computer instructions to perform a task is called programming. A program is pretty much just a list of instructions to the computer. Since a computer only knows about the presence or absence of voltage levels, the Tiny2313 chip uses voltage levels to tell it what to do. All of the instructions and data inside the Tiny2313 are actually voltage levels of either (about) 5 volts or 0 volts. We represent these voltage levels as ones and zeros for our convenience, not for the computer’s convenience. However, as good as those representations are, they are still not very easy for humans. Shortly after computers started coming on the scene, humans wrote tools to help with programming these machines. Some of the first tools were language translators, which took a more human-like language, and translated that into ones and zeros for the computer. Higher level languages, or languages which are closer to human languages, make it easier for a programmer to tell the computer what to do. The process of translating these “high” level languages into the computer’s machine language is called compiling.

MCS Electronics produces a language compiler called BASCOM-AVR for Atmel’s AVR family. BASCOM is a variant of the BASIC programming language. This language was invented by two professors, at Dartmouth College in the 1960s, specifically for beginners. In fact, the name BASIC is an acronym, which stands for Beginners All-purpose Symbolic Instruction Code; in other words, it is a general (All-purpose) Code, for Beginners to give the computer Symbolic Instructions to perform a job. It was designed to be easy to learn and to allow non-computer students to quickly be able to write programs for the university’s computer system. The free trial version, of this BASIC, is limited only in the size of the program. This limit is 4K bytes, which makes BASCOM-AVR an easy match for learning about microcontrollers with the Tiny-2313. You can download this language from MCS’s web site.

Getting the Latest Version
In this book, we will be installing and using BASCOM-AVR. You will need to get the newest version from MCS Electronics, the publisher:

1. Go on the web to http://www.mcselec.com and click on Downloads on the left side of the screen.

2. On the Downloads page, click on the BASCOM link at the bottom of the Downloads list on the right side of the page.

3. On the BASCOM page, click on the BASCOM-AVR link at the top of the list of downloads.

4. On this page, click on the link to download the BASCOM-AVR Demo version.

5. On the Terms and Conditions page, click the radio button for “I agree” and then click the button to proceed. This will open the download dialog box, make sure that the “Save file” radio button is selected and click the OK button.

6. In the Save to dialog box, select your desktop and click the Save button.

7. Click on the back button on your browser to return to the BASCOM AVR download page and also download the manual. This has lots of information and is very well organized. 8. Also, on the BASCOM-AVR page, you will find more information about BASCOM-AVR, including articles written about this compiler.

9. Close, or minimize, your browser.

10. Follow the directions to install BASCOM-AVR (you may follow the directions from MCS Electronics, or those in the ebook.)

Step 3: You're Driving Me Nuts.

While you will be writing your programs for the Tiny2313 on your PC, you will need to transfer that program to the Tiny2313 chip, itself, in order to let the controller run the program. To put the program into your microcontroller, you must have some way to get the program from your PC into the chip. The way engineers used to do this was by taking the chip and placing it into a special device called a programmer. There is a picture of my old Fun Card AVR programmer for ATtiny2313 controllers above. After running the programming software, you would take the chip with the program in it and place it into your circuit. If, or rather when, you discovered an error in your program, you would take the chip out of the circuit, put it into a special device to erase the program (often taking hours), put it back into the programmer, and start the whole process again. This would happen over and over until either you got the program correct, or (often) you just got tired and quit.

We will be using what is called an ISP Downloader Cable. The ISP abbreviation stands for In System Programmer; this is a way that engineers have developed to get around that old way of using a dedicated programmer. We have a special ISP connector on the microcontroller board, and will just connect the programming cable to the board in order to download the program. All of the programming activity is accomplished on the circuit board and the microcontroller chip itself. No need to pull the chip out and move it around.

The ISP that you ordered with your kit is called a USBASP Programmer. We mentioned that programmer earlier, when talking about how to set up BASCOM-AVR.(If you purchased a different model, you will need to modify this Instructable appropriately.)

In order for your computer to be able to use a piece of hardware, you will need to tell it how. The way that you do this is to load a program, called a driver. A driver is just a program that tells your computer how to talk to an attached device. There are drivers, built in to Windows, to tell your computer how to use the mouse, how to read the keyboard, how to display pictures and text on the screen. The USBASP Programmer is not something that everyone uses, though and so, we need to install the driver for that Programmer.

As you did with the BASCOM compiler itself, you will need to download the driver for your USBASP Programmer. To do this, follow the directions in the ebook, or at: http://www.protostack.com/blog/2011/05/usbasp-driver-for-windows-7-and-windows-vista-x64/.

Step 4: Let's Build This Thing.

Start off with a breadboard.

If you do not want to get a kit, you will need to build your own Development Kit (dev kit.) The best start for your dev kit is to use a solderless breadboard. If you do not know what a breadboard is, take a look at my breadboard page: http://projects.granzeier.com/what-is-a-breadboar... (page is being updated - please check back soon.) You will want to use the pictorial diagram above to see where to place the jumper wires. You will only need three components: the programmer connector, the ATtiny2313 itself, and an SPST, normally-open, momentary pushbutton switch for the reset button. I used one of the AVR Breadboard Adaptors (https://www.tindie.com/products/granztronix/breadboard-avr-isp-adapter-kit/,) but you could also use The Real Eliot's USB Ghetto Development Environment (original 'ible was deleted, wayback machine link: https://web.archive.org/web/20130122122222/https://www.instructables.com/id/E5H5UDWB5UEUKIKV8V/, Eliot's updated article is: https://www.instructables.com/Ghetto-Development-Environment/) or any other AVR programming system.

Once you place the components on the breadboard, it's just a matter of connect the dots. You may want to double-check your connections using the AVR ATtiny2313 datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/doc8246.pdf - the 2313 and the 2313A are very similar, there will be no difference in the wiring. You will just need to make tiny changes to your program (every place that the program mentions Tiny2313A, you will just use Tiny2313 if you use the older chip.)

Step 5: Connect Your 2313 to the World - Pt. 1.

Let's shine a little light on the subject.

An LED is a device which allows electricity to flow in only one direction, and when electricity does flow, it gives off light. You can learn more about LEDs and how they work, at my store: (https://www.tindie.com/products/granztronix/led-prototyping-pack/.)

Take your LEDs and trim the leads to about 1/4" (or about 1 cm.) It's a good idea to mark the cathode (negative lead) of your LED with a black marker pen, or a drop of fingernail polish - this can help you to identify the cathode after you cut the leads. You will be placing the LEDs' leads into the breadboard spanning two different rows. Place a 360 ohm (anywhere between about 220 ohms and about 470 ohms will work fine) resistor in one of the holes in the row with the LEDs cathode, and the ground power rail. The anode (or positive lead of the LED) will be left free so that you can connect the LED to your Tiny2313 microcontroller.Take a look at the photo of the LED/resistor pair in the breadboard to see what I am describing.

Next, move down the board (away from the Tiny2313 circuitry,) about one inch, and add a second LED/resistor pair. Now, add one more LED/resistor pair, about one more inch down the board. This will give you three LEDs that your microcontroller can turn on and off.

While I have used all green LEDs in my dev kit, and in the Tiny2313 Experimenter System in my store, there is no reason that you could not use another color LED. In fact, you could even use three different color LEDs.

Step 6: Connect Your 2313 to the World - Pt. 2.

You really know how to push my buttons.

To provide input to your Tiny2313, we will use simple pushbutton switches. These are called Normally Opened (NO,) SPST, momentary, pushbutton switches. If you take a look at the schematic diagram of the switch above, you will see that the switch consists of two terminals and a small conductor; when you push the button, the small conductor is pressed against the two terminals allowing electricity to flow. Later on, we will see how this allows the Tiny2313 to tell when the button is pressed.,

Take a look at the photo above, and you will see that the pushbutton is placed on the breadboard very much like the LED. Use a short jumper wire to connect one terminal of the switch to ground, and leave the other terminal free for connecting to the Tiny2313. Place this switch circuit just down from the last LED/resistor pair, on the breadboard.

Repeat this one more time so that you have two pushbutton switch circuits.

Step 7: Connect Your 2313 to the World - Pt. 3.

It's music to my ears (or at least noise.)

This is the last step in building the development kit. Take your speaker, and mount it on the breadboard, just down a bit from the last pushbutton switch. Like the switch, you will need to use a short jumper wire to connect one of the terminals to ground. You cannot see it in the picture, but it is there, underneath the speaker - connecting the left terminal of the speaker to ground. You will use the row of breadboard connections for the other terminal to connect the speaker to the Tiny2313.

Your dev kit is now completed. If you would like to make it more stable, and permanent, you may use tiny drops of glue to hold the components down to the breadboard. If you choose this option, be careful to avoid getting any glue inside any of the breadboard holes. This could block the flow of electricity, messing up your experiments.

One final, optional, step (if you are going for the permanent version,) is that you may take a magic marker, and highlight the breadboard rows for the unconnected leads of the LEDs, the switches and the speaker. This will make it much easier for you to see where you will be inserting your jumper wires, when building the circuits for your experiments.

Step 8: This Little Light of Mine...

Most programmers, when they are learning a new programming language, will start with a program called the “Hello World” program. This is nearly the simplest program that may be written in a language for any given computer. All it does it to output the phrase: Hello World onto the output device. It’s only purpose is to provide a very quick success and show the new programmer that the language does indeed work. In the controller world, it turns out that there are far simpler things to do than output some text. In fact, sometimes it can be downright complex to output text, so we do something much simpler.

The Hello World equivalent in the microcontroller world is simply lighting up an LED. For this Hello World experiment, first study the schematic diagram above. A schematic diagram is simply a picture representing an electronic circuit. At the top of the schematic, we have an arrow pointing to the right. This symbol represents an input (to the circuit) from the Tiny2313’s output pin. From there, we have a line going to the right a bit and then turning down. This simply represents a wire connecting that input to the next component. That component looks like a triangle with a bar across the bottom point, and a couple of small arrows to the left. This symbol represents a light emitting diode (LED); this device, as we mentioned above, gives off light when current flows through it from the bottom (with the bar) to the top. There is another wire from the bottom of the LED to the top of a zig-zag symbol. This zig-zag symbol represents a resistor; the resistor protects the LED and the Tiny2313 from too much current. Finally, there is another wire going to the symbol of 3 horizontal lines; this represents ground, or the negative terminal of the battery.

Now, using the pinout diagram of the Tiny2313 above, you need to connect a jumper wire from Pin PB.0 on the Tiny2313 (top row, second from right,) to anode of the left-most LED. The pictorial diagram above shows the LED wired up with a blue wire. Now, don't laugh too hard - after all, I am an engineering professional, not an artist. Anyway, go ahead and plug the short jumper wire into the breadboard. This is all that you need to do to prepare for your first microcontroller program.

Step 9: Starting Programming.

Now that we have the components wired up, we will work on the program. Make sure that you do not have any battery, or other power source, connected to the breadoard, this will make your Experimenter System obtain it’s power from the ISP plug. Plug the USB programmer in to the USB jack on your computer and the cable end into the 10-pin male header on your Tiny2313 breadboard.

Start BASCOM-AVR by double-clicking its icon. In the editing window (the largest white window in BASCOM-AVR) type the following:

' Title:
' Author: Art Granzeier, GranzTronix
' Date:
' Description:

' Configuration Section
$regfile = "ATtiny2313a.dat" ' Specify the micro
$crystal = 1000000 ' Frequency for internal RC clock
$hwstack = 32 ' Default - Use 32 for the hardware stack
$swstack = 10 ' Default - Use 10 for the SW stack
$framesize = 40 ' Default - Use 40 for the frame space

' Main Program

End

Use your name, instead of mine, in the Author line, of course.

(This is in the Template.bas file attached below. You may copy and paste the contents from Template.bas into the programming window of BASCOM.)

This is called a template; it is simply a skeleton, upon which we can build our real program. We will start each new program with this template, and then we don't have to worry about the basic “housekeeping.” Save your template by clicking on File and then clicking on Save as. In the Save as dialog box, give it the name “template”. From now on, whenever you want to create a new program for your Tiny2313 Experimenter System, you will start by loading the template and then changing the name. If you ever, accidentally, delete or overwrite your template, you may recreate it, just by following the above steps again.

A computer, like the Tiny2313A will normally, execute a program starting at the top, and working it’s way down through the program. This is called “top down” program execution. It’s really pretty easy, it’s just like when you follow someone’s written directions; you start at the top, and work you way through the directions, just like normal reading.

Let's take a closer look at what is going on here. Notice that the first four lines all begin with the apostrophe (single quote, or '), this tells the BASCOM compiler that everything on that line is a comment, and to ignore it. Comments are added to programs so that you, the programmer, can tell what the program is doing. At the beginning, we are just giving identifying information about the program. In fact, this is called the identification section of the program.

The next section, which begins with another comment line, contains what are called directives. These lines, which each start with the dollar sign ($,) are directing the BASCOM compiler how to set itself up. As the comment line indicates, this is the beginning of the configuration section. These first five lines are really beyond the scope of this introduction, but if you look at the lines you just entered, you can already tell a little bit about these directives. The first directive, sort of contains the name of the microcontroller on your Tiny2313 Experimenter System. Since BASCOM can convert your BASIC program for many different microcontrollers in Atmel's AVR family, it needs to know exactly which chip to target; this command directs BASCOM to convert your program to the ATtiny2313. For now, you can just keep the directives lines of the configuration section as they are above.

The final line in our template is the End statement. Every program must end with an End statement to prevent the program from starting over by built-in resets.

Now that we have this framework, the template, set up, we can get on with writing our own programs – and, with the framework done, it will be a pretty simple job. With the template (as shown above – remember, use your name as the author, not mine,) in your editing screen, start a new program by clicking on the File menu and then clicking on the Save As... entry. When the Save As dialog box appears, give the program a name by typing LED Test 01 in the file name field, and then click the Save button at the bottom of the dialog box. Notice, at the top of the BASCOM window – in the blue title bar, that BASCOM is showing the name of your new program. You are now ready to start entering your new program.

Begin by updating the identification section of the program like this:

' Title: LED Test 01
' Author: Art Granzeier, GranzTronix (again, use your name)
' Date: 13 Oct 13 (use today's date)
' Description: Turning an LED on

Next, go to the bottom of the configuration section (right below the $framesize directive) and add the following line:

Config PortB = Output

And after the Main Program comment line, add the line:

set

PortB.0 ‘ Turn LED on

So, your whole program should look like this:

' Title: LED Test
' Author: Art Granzeier, GranzTronix (again, use your name)
' Date: 13 Oct 13 (again, use today's date)
' Description: Turning an LED on

' Configuration Section
$regfile = "ATtiny2313a.dat" ' Specify the micro
$crystal = 1000000 ' Frequency for internal RC clock
$hwstack = 32 ' Default - Use 32 for the hardware stack
$swstack = 10 ' Default - Use 10 for the SW stack
$framesize = 40 ' Default - Use 40 for the frame space

Config PortB = Output

' Main Program

set PortB.0 ‘ Turn LED on

End

Before we download this into the Tiny2313, let’s take a closer look at these lines. The identification section is just as we discussed. It is just a series of comments, to you, to let you know what the program is supposed to be doing. The beginning of the configuration section, at least the directive statements, is the same as we described earlier. The only thing new in the configuration section is a statement that is new to us. That line (Config PortB = Output) tells the controller to set Port B up as an output port. Port pins can be set to either read the voltage level on the pin (0V, or 5V,) called input, or to place a voltage (0V or 5V) on the pin, this is called output. For this program, we want to have the pin be an output; so we set the port to output. We can have control over individual pins of a port, but for this example, it is easier to just set the entire port to output.

Finally, we get to the meat of the issue. The latest line of this program (set PortB.0) is actually the part that does the work. The set statement tells the controller to make a pin high, or set it to plus 5 volts. The remainder of this statement tells the Tiny2313 controller which pin to set to high, PortB.0. Take a look at the diagram of the Tiny2313 chip; notice that pin number 12 on the chip is labelled as PB0. The P part of the tells us that it is a Port – that is a series of pins, each of which can be set up to either sense a voltage (0V or 5V) and react to it (the pin is called an input when it does this) or it can output a voltage (0V or 5V) which can control lights, relays, motors or other things (the pin is then called an output.) As the comment, on that line, mentions, this will light the LED on that pin. Port B is one of the four ports available on the Tiny2313.

Now that we have written our program, we need to convert it into machine code, and then send the program to the controller (or download it.) Remember from earlier, that the process of converting a program from a human-like language, such as BASIC, into a machine language is called compiling. In order to compile the program, you will need to click on the Program menu, and then click Compile. This will start the compiler and that will convert your program into something that the ‘2313 chip can understand, and the machine program is stored in BASCOM’s buffer area, ready to send to the Tiny2313 chip.

Now that your machine language program has been stored in the buffer, you need to send the buffer to the microcontroller chip. Click on the Program menu again, and then click on Send to chip, near the bottom of the menu. This will open a new Programmer window. You can see the buffer in the main window of the Programmer window. To send the buffer to the microcontroller, click on the Chip menu and then click on Autoprogram. Your program will be sent to the Tiny2313 and then the Programmer window will disappear.

Take a look at your Tiny2313 Experimenter System; notice that the right-most LED is now lit. Congratulations are in order. Things are going nicely, huh?

Step 10: What Just Happened?

Refer to the schematic diagram above, once more. Notice that, following this diagram, we are going to take an output from our Tiny2313 and connect it to an LED, which is then connected through a resistor, and to ground. The arrow, at the top of the schematic, represents the I/O (Input/Output) pin on the microcontroller. When we have the Tiny2313 apply positive voltage on this pin, the current will flow from ground, up through the resistor and then through the LED by being attracted to the positive charge on the output pin (remember that the only things moving in an electrical circuit are electrons, and with the electron's negative (-) charge, they will only move towards a more positive (+) charge – opposites attract.) When the current flows through the LED, it will give off light, saying “Hello World”. Likewise, when we have the controller apply ground to the output pin, the electrons will not be attracted to any positive charge and will not flow from ground. Without any current flow, the LED will not light up. This is the basis for turning a LED on and/or off under control of the Tiny2313, and why the LED lit up when we ran the "Hello World" program.

Step 11: Lights Out Up There.

Now, we have gotten the LED to light, but so what? My flashlight, when I was a kid, could do that! Well, we need to learn to crawl before we can learn to run, these are our baby steps. We need to have more control over that LED, so we should be able to have the Tiny2313 turn the light out. Let’s revisit that set statement… If the statement, as you typed it in earlier, set the port PB0 to +5 volts (or high, or 1) then how would you reset the port to back to low (or 0)?

Before you make any changes, save the working program and start a new one. Click on the File menu in BASCOM, and then click on Save. This will save your LED Test 01 program. Now, Click on the File menu again, and this time click on Save as… Change the name of your program to LED Test 02, and then click Save. Also, update the first line, in the identification, with the new title for your program.

Change the set statement in your program to reset, like so:

reset PortB.0 ‘ Turn LED off

Now, compile your new program by pressing the F7 function key on your keyboard. Make sure that there are no errors shown at the bottom of your BASCOM window, and then open the Programmer window by pressing the F4 function key.

Send your compiled program to the ‘2313 by clicking on the Autoprogram option on the Chip menu. The LED on your Experimenter Board will go out. Yep, that reset at the beginning of the line told the computer to put port PB0 to ground, or low voltage. There is no positive point in the circuit, so electrons are not attracted to anything and current does not flow anywhere. Thus the LED does not light up.

(I’ll let you in on a small secret: when BASCOM sends the program to the controller, it resets the ‘2313. So, the LED would have gone out, even without the reset statement. That said, the reset statement does work as advertised, and we will be using it more properly pretty soon.)

Step 12: Blinky, Blinky.

Now that we have gotten the Tiny2313 to be able to turn the LED on and off, on command, how about more advanced things? Since we have not really entered a real program here (that secret that I mentioned,) we do not need to give BASCOM a new program name.

Re-enter that set statement above the reset statement in your program:

' Main Program
set PortB.0 ‘ Turn LED on
reset PortB.0 ‘ Turn LED off

This seems to be right, correct? The ‘2313 chip will put a high (+5V) signal on the PB0 pin and then immediately bring that pin back to ground. The +5V will cause electrons to flow through the LED, making it light, and then the low, or ground, on PB0 will cause the LED to go out, right?

Compile your new program by pressing the F7 function key on your keyboard. Make sure that there are no errors shown at the bottom of your BASCOM window, and then open the Programmer window by pressing the F4 function key. Again, send your compiled program to the ‘2313 by clicking on the Autoprogram option on the Chip menu.

Your Tiny2313 chip will immediately run the new program, lighting the LED and then immediately turning it back off. Right?

What? Wait a minute – What happened here? It appears that there is something wrong with the program, doesn’t it? The LED didn’t light at all. If you want to see the Tiny2313 run the program again, just press the reset button beneath and to the left of the Tiny2313 chip itself. The program is stored in the ‘2313 chip and the reset will cause the chip to run the program each time that it is pressed. Still nothing, though, right?

Well, actually, the LED did light. It’s just that computers work extremely quickly, and the Tiny2313 turned the LED on and then immediately turned it back off. This happened in only a few millionths of a second, far too fast for your eye to notice the flash.

If you look through the BASCOM-AVR manual, you will run across a statement called wait. This statement tells the computer to do exactly what it says. The parameter, or number, that you type after the wait statement is the number of seconds that you want the Tiny2313 to pause, before continuing with the program.

Let’s fix up our program. In between the set and the reset statement, enter a wait statement with a delay of 1, like this:

' Main Program
set PortB.0 ‘ Turn LED on
wait 1 ‘ Pause for 1 second
reset PortB.0 ‘ Turn LED off

Compile your new program by pressing the F7 function key on your keyboard. Make sure that there are no errors shown at the bottom of your BASCOM window, and then open the Programmer window by pressing the F4 function key. Again, send your compiled program to the ‘2313 by clicking on the Autoprogram option on the Chip menu.

Your Tiny2313 chip will immediately run the new program, lighting the LED and then after about one second, turning it back off. This time the program works, right? Remember, the computer does EXACTLY what you tell it to. If you tell it to do something too quickly, then that is exactly what it will do. When you told the Tiny2313 to turn the LED on and then off, it did just that; only it was so quick that it was pretty much useless to you. Again, if you want to see the Tiny2313 run your program again, just press the reset button on your Tiny2313 Experimenter System.

Now that your program works correctly, save your program, before going on. (One more reminder, click on File and then click on Save.)

Begin a new program by clicking on File and then clicking on Save As… and name the program LED Test 03. Change the wait line to: wait 2, what do you think this will do? Try compiling this program and downloading it to your Experimenter Board (press the F7 key and then the F4 key and then click on Autoprogram) – did it do what you thought? The number, after the wait statement, tells the controller how long (in seconds) to wait before continuing with the next statement (the reset statement.) This new program should leave the LED lit for about two seconds before turning it back off.

While it is useful to have your controller wait for full seconds, computers really shine at doing things quickly. Sometimes you need to have your controller pause for a shorter period of time. A statement, which is related to the wait statement, that allows you much finer control over the delay times, is: waitms. You can find a description of the waitms statement in the manual, but this stands for “wait for a specified number of milliseconds (or 1/1000ths of a second.”) You would use it exactly as you would the wait statement, except that the time is given in thousandths of a second (waitms 1000 is the same as wait 1.)

Play around with the program, substituting the waitms statement for the wait statement. See what happens with your LED flashing. Try lowering the delay time; try to find the shortest delay that you can actually notice. The average human eye can notice things happening at about 30 times per second (or Hertz, which means “per second”). If a light blinks faster than that, your eye will not notice the blinking, and will tell your brain that the light is steadily off, or on. This 30 Hertz (or 30 Hz) flashing equals out to be about 33 ms, or about 16 ms on and then off. See how close you can get to 16 ms before the LED appears to remain off. Your eye will notice and respond better if the room light is lowered or the LED light is raised; try turning the room lights out while performing this experiment.

Try lengthening the pause statement. Enter numbers around 2000 or 4000, and try using a stopwatch to see how accurate you can get in starting the timer and then stopping it. You will not be able to get perfectly, exactly accurate, because human response time is measured in milliseconds. In other words, from the time that your eye sees the LED turn on, until your brain tells your finger to press start on the stopwatch, until your finger actually does the work, will take several hundreds of milliseconds. It can be kind of entertaining to see how close you can get to the time you entered in the pause statement.

Having the Tiny2313 flash the LED can be kind of fun, but still, a flashlight can do that – again, “baby steps.”

Step 13: Loop-the-Loop

Another thing that computers are good at is doing things over and over. A computer does not get bored, nor does it tire out (unless the battery charge starts getting low, but that is another issue.) In this step, we will see one way to make the '2313 repeat itself.

Save your program from the last step, and start a new program by clicking on File, and then Save as... Give your new program a new name ("LED Test Flash", perhaps.) Now immediately after the Main routine comment line, add:

do ' Introducing the DO loop

Now after the body of your program add another line:

loop

So that the main body of your program will look like this:

' Main Program
Do
set PortB.0
waitms 500
reset PortB.0
Loop

This is called a loop, because the lines in between the Do and the Loop statement are executed over and over, in a loop fashion. By tradition, we indent, or place blank spaces in front of, the lines inside the loop. This makes it easier for us to see at a glance which lines are being repeated. The BASCOM compiler does not care one way, or the other; it compiles these line the same with, or without, the indents (blank spaces at the front of the line.)

As you can see, the program will make the Tiny2313 chip set Port B.0 high, lighting the LED, and then low again. The the program will hit the Loop statement and go back up to the Do statement to run through the loop again. This should make the controller turn the light on, and off, repeatedly, right?

Compile, and download, this new program to your '2313. The program will immediately start running. Did this work as expected? Umm, no? Well, time to get out your thinking hat - this is called debugging, or looking for the errors in a program.

Think back to when you first had your ATtiny2313 turn the LED on and then right back off. Remember that the microcontroller runs a program extremely fast (at least as compared to our human speeds.) Do you remember that you needed to insert a wait statement in between turning the LED on, and then back off, so that you had enough time to see the light? Well, the same bug (or trouble) is plaguing us here. Follow along as we examine the program above. The first line, in the loop, turns the LED on; next the program pauses for a half a second so that we can see the LED light up. Next, the program turns the LED back off, and then returns to the top of the loop to start all over again. Notice, that, while the program pauses to let us see that the LED is tuned on, it never pauses to let us see that the LED has turned back off - it just goes ahead and turns the LED on again, within a few millionths of a second. Oops, we need to add another pause (wait, or waitms, statement) after turning the LED off, and before repeating the loop.

Add the second wait statement in, so that your program looks like this:

' Main Program
Do
set PortB.0
waitms 500
reset PortB.0
waitms 500
Loop

Now, compile and download your program again. Everything looks good this time, right?

The way that this program is written, your Experimenter System will flash the LED on, and then off, about once per second. Play with the time values in the waitms statements to make the flashing faster and slower. See if you can get your LED flashing at the same speed as the turn signal light on your car. Notice that the two values for the waitms statements are exactly the same. This causes the LED to turn on, and then off for exactly the same amount of time, in each loop. What happens if you change the times, using different values for the two different waitms statements?

Make sure to save your program before you go on to the next step.

Step 14: Switch Things Up a Bit.

For these next programs, you will need to add in one of the pushbutton switches. Since there are two switches already placed on your breadboard (remember this is the advantage of having a development system,) you only need to add one jumper wire from pin 9 (PD5) of the Tiny2313 chip to the left lead of the left-most pushbutton switch. The diagram above shows that new wire in yellow. Now, aren't you glad that you have a development system? Adding all of the circuitry for a whole new switch took only one piece of wire, and a few seconds.

Now, what is a switch?

A switch is basically like two pieces of wire which, when the switch is off (or the button is not pressed, with these buttons – that is what the “normally open” means) then the wires are held apart from each other. This prevents electricity from flowing through the switch. When the switch is turned on (or the button is pressed), the wires inside the switch are connected together and electricity is able to flow.

There is another type of pushbutton switch called a normally-closed switch; this switch normally has the leads connected together inside and breaks them apart when you push the button. You can see a good example of one of these types of switches here: https://www.instructables.com/id/simple-normally-closed-switch/ We won’t be using any of those here, but keep this in the back of your mind.

Take a look at the 'Ible that I referenced above, the one for the normally-closed switch. This is a good illustration of any switch. If the spring were on the other side of the clothes-pin fulcrum, then the two metal tacks would be kept separate until you pushed on the clothes-pin. This is how the pushbutton switches in your 2313 Experimenter System work - they are normally-opened, and the two pieces of metal come into contact when you push the button. This is represented by the first schematic diagram above.

Tiny2313 ports, when they have been configured as inputs, may have a small resistor tied between the port pin and +V. This is called a “pull-up” resistor and “pulls up” the pin to +5V. This avoids what is called a floating input, or an input, which is neither high nor low, and could be seen as either (or even worse, keep changing.)

In the schematic second diagram above, you can see that there is a partial path for electrons to flow from the ground to the arrow at the top of the schematic diagram (the input pin of the controller.) Notice, that there is a break in the line from ground up to the arrow representing the input port of the ‘2313. The switch (looks like the top hat in the schematic) has a piece of metal, that when you press the button, touches the two electrical contacts, making the path complete, very much like the opposite of Stan1ey's 'ible. The switch between ground and port PD5 will allow electricity to flow from ground through the internal pull-up resistor ONLY when it is pressed. When the button is not pressed, PortD.5 will “see” a high signal (through the pull-up resistor) and when you press the button, PD5 will be connected to (or “see”) the low from the ground. Another important purpose of the pull-up resistor is to prevent a short circuit between the +5V of high and the 0V of ground when you connect a port pin to ground.

Step 15: To See the Light, Press 1.

Now that we have a way for the Tiny2313 to detect a button being pressed, how do we get the program to respond?

Take the LED flashing program from the last step, and add in these two lines to the configuration section, just after the config port b output, line:

Config PortD = Input
Set PinD.5 ‘ Activate Pull-up Resistor

These lines will have the Tiny2313 set port D to an input port, so that it can sense whether there is a high (+5V), or a low (0V) on that pin. The second line is needed to activate the internal pull-up resistor that we discussed in the previous step.

Now that the controller chip is set up to read an input, we will make the program react to that input. Add a single loop just after the beginning of the main program, like this:

Do
If Pind.5 = 0 Then Goto Start
Loop

And add a single line after the new loop. The main body of your new program should look like this:

' Main Program

Do
If Pind.5 = 0 Then Goto Start
Loop

:Start
Do
set PortB.0
waitms 500
reset PortB.0
waitms 500
Loop

The :Start line begins with a colon (:), this tells BASCOM that the line is a label. BASCOM will mark the location of this line in the Tiny2313's memory, so that other program statements may refer to that line. This feature is used in the new loop. The if statement in the first loop above will make the '2313 examine the voltage level on pin D.5. If the voltage is high (+5V) then the if part of the statement is read as false (in other words, the high voltage on pin D.5 is NOT equal to 0.) In that case, the if statement will ignore the then part of the statement, and will proceed to the next statement. Only when the if part of the statement is true, in other words, the pushbutton has been pressed, allowing current to flow, and the input pin to see a 0V (or low,) will the if...then statement execute the then part of the statement, thus going to the Start label.

This all sounds kind of complicated, but it is really simple. As we discussed in the last step, when you have the pushbutton un-pressed, there is no current flowing, and the input line "sees" a high (+5V) through the pull-up resistor. But when you press the button, current flows through the switch and then through the internal pull-up resistor, and the input "sees" a low (0V.) So the first loop just waits, constantly checking the input line, until the pushbutton is pressed. When the input pin shows a 0, then the if statement is true, and the program jumps down to the :Start line, and continues with the second loop.

Thus the 2313 Experimenter System will wait until you press the button and then will proceed to flash the LED until you turn the system off, or reset the '2313. If you just reset the system, the program will start all over again, waiting until you press the button.

Now, how would you change this to make use of Stan1ey's 'Ible (from the last step)? Since his button is a normally closed switch, meaning that the contacts are closed until you push the "handle" of the clothes-pin, you could just change the number for which the if statement is looking. Try changing that in the if statement, and hook up one of Stan1ey's switches. Now, take a piece of paper, and place it between the pins. like the second photo in Stan1ey's step 7. When the trip wire pulls the paper out of the clothes-pin switch, your 2313 Experimenter System will flash the LED, alerting you to the break-in.

Look through other Instructables to try to find other projects that you can connect to your 2313 Experimenter System. Remember, that right now, you can only use a project line making a simple switch. Take a look at MightyMouse's Morse Code keyer (https://www.instructables.com/id/Morse-Code-Buzzer/.) The paper clip, screws, washers and nuts, and the loop connectors make up another normally-opened switch, like the ones on your 2313 Experimenter System - how would you modify the program so that you could use the keyer for Morse code? (Hint, have your program use a single loop, and have the program check to see if the NO switch is closed, and if so, then light the LED, otherwise, turn the LED off.) You may also be interested in Liam's 'Ible (https://www.instructables.com/id/How-To-Make-A-Low-Tech-Timer-Switch/) and hook that up to your 2313 Experimenter System.

This is another beautiful aspect of development systems; it is easy to add circuits and devices from other projects.

Step 16: Make a Joyful Sound.

For our next set of experiments, we will need to connect the speaker. Following the diagram above, add one more jumper wire from port B.3. The diagram shows this new wire in purple. Again, the beauty of a development kit is that most of the speaker circuitry is already there; to add the entire speaker circuit, all you need is a single jumper wire.

Consider, for a minute, the electromagnet that you made when you were a kid (if you don't remember that, the magnet is made by wrapping a wire around a nail. Look at the diagram above. When you connect the ends of the wire to a battery, the nail becomes magnetized, and you can pick up things like paper-clips.) A speaker is much like an electromagnet; when you make current flow, and stop flowing through the coil of a speaker, it causes a membrane to vibrate, making sound.

Now, take a look at the schematic diagram of the speaker circuit. Now, keeping with our precedent of using Port B for output and Port D for input, Port B.3 will control the speaker. Take a look at the schematic, above. When Port B.3 is set to high, current will flow from ground through the speaker and to the output pin. This will act the same as when you connected the wire ends in your electro-magnet to a battery, and will activate the electro- magnet inside the speaker. When you output a low on Pin B.3, there will be no positive point in the circuit, so no current will flow, and the electro-magnet will be turned off.

In the same way that we used loops to turn the LEDs on and off repeatedly, we will again use loops to magnetize and de-magnetize the electro-magnet inside the speaker. The main difference will be that we will use much shorter delay times within our loops. Using your template, add the following program and then save it with a name like Speaker Test.

Config PortB = Output

' Main Program
Do ‘ Toggle speaker line
set PortB.3
waitms 1
reset PortB.3
waitms 1
Loop

Again, take a look at this program: we see a standard loop, nothing new here. Also, we see that, inside the loop, we set port B.4 (the speaker pin) to high, wait 1millisecond and then reset it back to low and wait for another 1 millisecond. Because these statements are within a loop, this will repeat, turning the magnet in the speaker on and off at 500 times per second – two milliseconds on and off, and repeated.

Compile your program and download it to the ‘2313. What happens? With the speaker activating at 500 Hz (Hertz, or times per second) you should hear a tone coming from the speaker. Try changing the delay times, what happens? See how large you can get the delay time before it no longer sounds like a tone, but rather a series of clicks. Try using different values for the two delay times; what does that do to the tones?

There is one more statement set that I want to introduce; the for...next loop. This loop includes the ability for the controller to keep count of how many times it executes the loop. In it’s basic format, the loop starts with a for statement, and then it ends with a next statement. You can best understand this loop with an example:

For cntr = 1 to 100
set PortB.4
waitms 1
reset PortB.4
waitms 1
Next cntr ‘ Toggle speaker line 100 times

Notice the similarity with other loops that we have already covered; there is a beginning to the loop (the for statement) and an end (the next statement) and everything inside gets repeated a certain number of times. At the beginning of the loop, the for statement uses a special area of memory, called a variable, to hold a number. The variable is given the name “cntr”, and it is first set equal to the first number in the for statement (in this case 1). The commands inside the for...next loop are then executed. At the end of the loop, with the next statement, two things happen: first the variable is compared to the highest number in the for statement (in this case 100), if the number is equal (or higher) then the next statement exits the loop, and the program continues after the loop. Secondly, if the variable, “cntr”, is less than the limit number (100,) then “cntr” is incremented, and program flow loops back to the for statement.

In order to use a variable, you must set up the special area of memory. To do this you will need to add a new configuration statement. After the output config statement, add the following line:

Dim cntr as byte

This will set aside one byte of memory (one memory location) to hold the number that we call cntr. One byte can hold any integer between 0 and 255. We use this strange spelling of counter because the word counter itself is reserved for BASIC to use. So we just change it’s name and everything works fine. If, during your experimenting, you wish to use more than 255 in your for...next loop, remember to change the byte parameter – try using long. (Look at the BASCOM manual for more information on variables, and the byte and long types.)

So, the first time through the loop, the variable “cntr” will hold the number one. At the end of the loop, the next statement will check and see that “cntr” is less than 100 (the limit, as set up by the for statement,) will increment “cntr” to 2, and then have the program loop back to the for statement.

The next time through the loop, everything is repeated, except that “cntr” contains the number 2. This is repeated, with the variable “cntr” being incremented each time, until it reaches 100. When “cntr” is equal to 100, then the next statement will say “that’s enough times through the loop, go on to the next statement.”

As you can see, this is a way to repeat some steps a certain number of times. How does that help us here? How about if we write a loop to toggle the speaker magnet on and off a specific number of times? Since we know how long we leave the magnet on and how long we leave the magnet off, we can calculate how long the tone will last. Take another look at the above loop; how long will that last? If we consider that the magnet is on for 1 millisecond and then turns off for another 1 millisecond, and then it loops for 100 times, we find that the tone should last for 200 milliseconds, or 1/5 th of a second. Actually, it will last for just over 200 milliseconds because each of the other statements, including the loop statements themselves, will take a small amount of time. However, for the purposes of this class, we can ignore the overhead time – just keep it in the back of your mind, in case you need better timing later on.

Hint: for higher-pitched frequencies, take a look at the BASCOM-AVR manual under the waitus statement.

I think that my old flashlight just ran away with embarrassment!

Step 17: And in Conclusion, I Would Like to Say...

By the way, in the same way that you can use the output port to control an electro-magnet in a speaker, you can also use this basic set-up to control an electro-magnet directly. This could be useful if you were to need to build an electro-magnetic crane device into your system. What you will need to do is to make sure that your electro-magnet circuit does not draw more current than your Tiny2313 (or whatever control system you use) can provide. If the magnet does draw more current than the controller can provide, you could use a driver circuit, or a relay, to boost the signal strength.

In the same way, you can control motors, electric heater elements, pumps, coffee makers, and just about any other type device. Now that I think about it, one way that you could switch a track for a train (model railroading here, this would be too small for a real train) would be to use an electro-magnet to switch the track to redirect the train. Just use a signal booster circuit, of some kind, and write programs similar to what you have done here.

For input devices, you already know about having the computer read a simple switch. As you have seen in a previous step, the switch could be a regular pushbutton switch, or a clothes-pin switch, or a Morse Code keyer, but it could also be a magnetic train-sensor. Standard toggle switches (the kind that you use to turn your bedroom light on and off) work in a similar way, but the contacts remain opened or closed, depending on the position of your switch. Push button switches are often used as limit switches, to let a control computer know when a motor has moved something to it’s farthest position. A thermostat, like the one used to control your furnace and/or air conditioner, is nothing more than a simple switch (that changes the point at which is opened or closed based on the temperature) – you can connect a thermostat to an input pin, and ground, and your Tiny2313 Experimenter System can tell when the temperature is above, or below, the set temperature.

One other type of input (among millions of types in the world of control systems) would be an operator input. For example, if you were to set up five switches, going to five different input pins, you could use those pushbuttons to have your program know what options the human operator selects. Perhaps you could use one button for each of several different songs, or light pattern displays. The possibilities are, literally, endless.

You would need to do a bit more research on basic electronics before undertaking jobs like these – but you already have an understanding of the controller, and programming, end of the tasks. Search Instructables, and your favorite search engine (Google, Yahoo, etc.) Above all, play, experiment, learn...

Step 18: Where Do We Go From Here?

Congratulations, you now have a basic understanding of what a microcontroller is, and what it can do. You have built your own development system, and set up several circuits. You have started learning a beginners programming language, although it is a real language, and many professionally developed products are written in BASCOM-AVR. You learned to teach your Atmel AVR ATtiny2313A microcontroller many new tricks, and hopefully, you had fun doing so.

So, where can you go from here? As Buzz says: "to infinity and beyond!"

If you are interested in continuing with this new hobby, there are a few things that you will want to do. First, spend some time going through the BASCOM manual that you downloaded earlier in this 'Ible. Next, play! Playing is the best way to learn about new things. Take the experiments that were presented in this book, and follow the suggestions for changes. Then make more changes to the program and watch what happens. Connect the second and third LEDs and then see if you can make the LEDs flash in sequence, from left to right, then try to make them flash from right to left. Connect the other button and try to have the LEDs flash in sequence on command – if you press the left button, have the LEDs flash from right to left, and vice-a-verse. How about making a miniature KITT scanner (from the TV series Knight Rider,) or a mini Cylon scanner (from the TV series Battlestar Galactica) - both of these projects are called Larson scanners, after Glen Larson, the producer of those TV shows.

In addition, there are lots of projects on the Internet; do a search for “simple tiny2313 projects.” You will be able to duplicate many of these, right on your Tiny2313 Experimenter System. For some of these projects, you may need to expand the board. The system shown here has an additional breadboard below the one used for the Experimenter System, or you may add additional breadboards, just connect the power rails to the power rails of your 2313ES, and you may add on whatever you need.

As mentioned earlier, you may build this system, and go through all of the experiments shown here (and the others in the book.) If you would rather, you may purchase a complete set of all parts, including a professionally developed PCB (printed circuit board,) from GranzTronix (https://www.tindie.com/products/granztronix/introduction-to-microcontrollers/.)

The heart of the prudent acquires knowledge,
and the ear of the wise seeks knowledge.

Proverbs 18:15 - New King James Version (NKJV)

Please also visit our Faith page (http://faith.granzeier.com/.)