Introduction to microcontroller electronics .................................................................... 63
What is a computer? ................................................................................................................... 64 What does a computer system do? ............................................................................................. 64 What exactly is a microcontroller? ............................................................................................... 65 What does a microcontroller system do?..................................................................................... 66 Getting started with AVR Programming ....................................................................................... 67

1 Introduction to Practical Electronics
This book has a number of focus areas.               Electronic component recognition and correct handling Developing a solid set of conceptual understandings in basic electronics. Electronic breadboard use Hand soldering skills Use of Ohm's law for current limiting resistors The voltage divider CAD PCB design and manufacture Microcontroller programming and interfacing The transistor as a switch Power supply theory Motor driving principles and circuits Modelling solutions through testing and trialing Following codes of practice Safe workshop practices

13

1.1 Your learning in Technology
1.1.1 Technology Achievement Objectives from the NZ Curriculum
Technological Practice Brief –develop clear specifications for your technology projects. Planning – thinking about things before you start making them and using drawings such as flowcharts, circuit diagrams, pcb layouts, statecharts and sketchup plans while working. Outcome Development – trialling, testing and building electronic circuits, designing and making PCBs, writing programs for microcontrollers. Technological Knowledge Technological Modelling – before building an electronic device, it is important to find out how well it works first by modelling and/or trialling its hardware and software. Technological Products – getting to know about components and their characteristics. Technological Systems - an electronic device is more than a collection of components it is a functioning system with inputs, outputs and a controlling process. Nature of Technology Characteristics of Technological Outcomes – knowing about electronic components especially microcontrollers as the basis for modern technologies. Characteristics of Technology – electronic devices now play a central role in the infrastructure of our modern society; are we their masters, how have they changed our lives?

1.2 Key Competencies from The NZ Curriculum
Thinking – to me the subject of technology is all about thinking. My goal is to have students understand the technologies embedded within electronic devices. To achieve this students must actively enage with their work at the earliest stage so that they can construct their own understandings and go on to become good problem solvers. In the beginning of their learning in electronics this requires students to make sense of the instructions they have been given and search for clarity when they do not understand them. After that there are many new and different pieces of knowledge introduced in class and students are given problem solving exercises to help them think logically. The copying of someone elses answer is flawed but working together is encouraged. At the core of learning isbuilding correct conceptual models and to have things in the context of the ‘big picture’. Relating to others – working together in pairs and groups is as essential in the classroom as it is in any other situation in life; we all have to share and negotiate resources and equipment with others; it is essential therefore to actively communicate with each other and assist one other. Using language symbols and texts – At the heart of our subject is the language we use for communicating electronic circuits, concepts, algorithms and computer programming syntax; so the ability to recognise and using symbols and diagrams correctly for the work we do is vital. Managing self – This is about students taking personal responsibility for their own learning; it is about challenging students who expect to read answers in a book or have a teacher tell them what to do. It means that students need to engage with the material in front of them. Sometimes the answers will come easily, sometimes they will not; often our subject involves a lot of trial and error (mostly error). Students should know that it is in the tough times that the most is learnt. And not to give up keep searching for understanding. Participating and contributing – We live in a world that is incredibly dependent upon technology especially electronics, students need to develop an awareness of the importance of this area of human creativity to our daily lives and to recognise that our projects have a social function as well as a technical one.

14

2 An introductory electronic circuit
2.1 Where to buy stuff?

In New Zealand there are a number of reasonably priced and excellent suppliers for components including www.surplustronics.co.nz and www.activecomponents.com Overseas suppliers I use include www.digikey.co.nz, www.sparkfun.com ebay.com & aliexpress.com A breadboard is a plastic block with holes and metal connection strips inside it to make circuits. The holes are arranged so that components can be connected together to form circuits. The top and bottom rows are usually used for power, top for positive which is red and the bottom for negative which is black. This circuit could be built like this, note that the LED must go around the correct way. If you have the LED and resistor connected in a closed circuit the LED should light up. Schematic or circuit diagram Layout

The LED requires 2V the battery is 9V, if you put the LED across the battery it would stop working! So a 1k (1000ohm) resistor is used to reduce the voltage to the LED and the current through it, get a multimeter and measure the voltage across the resistor, is it close to 7V? If you disconnect any wire within the circuit it stops working, a circuit needs to be complete before electrons can flow. 15

2.2 Identifying resistors by their colour codes
When getting a resistor check its value! In our circuits each resistor has a special pupose, and the

1M ‘1 Meg’ 1 Million Ohms 1M Ω 1,000,000 ohms

10k 10 thousand ohms 10,000 ohms 10k Ω

1k 1 thousand ohms 1,000 ohms 1k Ω

390R 390 ohms 390Ω

100R 1000 ohms 100Ω

47R 47 ohms 47Ω

value is chosen depending on whether we want more or less current in that part of the circuit,The higher the value of the resistor the lower the currentThe lower the value of the resistor the higher the current.

16

2.3 LED's
Light Emitting Diodes are currently used in indicators and displays on equipment, however they are becoming used more and more as replacements for halogen and incandescent bulbs in many different applications. These include vehicle lights, traffic signals, outdoor large TV screens. Compared to incandescent bulbs (wires inside glass bulbs that glow), LEDs give almost no heat and are therefore highly efficient. They also have much longer lives e.g. 10 years compared to 10 months. So in some situations e.g. traffic signals, once LEDs are installed there can be significant cost savings made on both power and maintenance. There is a small problem with LED traffic lights though – they don’t melt snow that collects on them!!!

2.4 Some LED Specifications
    

Intensity: measured in mcd (millicandela) Viewing Angle: The angle from centre where intensity drops to 50% Forward Voltage: Voltage needed to get full brightness from the the LED Forward Current: Current that will give maximum brightness, Peak Wavelength: the brightest colour of light emitted

2.5 LED research task
From a supplier in New Zealand (e.g. Surplustronics, DSE, Jaycar, SICOM) find the information and the specifications / attributes for two LEDs, a normal RED 5mm LED and a 5mm high intensity LED.

2.7 Switch assignment
Find a small switch and carefully disassemble it (take it apart) draw how it works and explain its operation. Make sure you explain the purpose of the spring(s). Here are simplified drawings of a small slide switch when it is in both positions. When the switch is on electricity can flow, when it is open the circuit is broken.

18

2.8 Important circuit concepts
A circuit consists of a number of components and a power supply linked by wires. Electrons (often called charges) flow in a circuit; however unless there is a complete circuit (a closed loop) no electrons can flow. Voltage is the measure of energy in a circuit, it is used as a measure of the energy supplied from a battery or the energy (voltage) across a part of a circuit. Current (I) is the flow of electrons from the battery around the circuit and back to the battery again. Current is measured in Amps (usually we will use milliamps or mA). Note that current doesn't flow electrons or charges flow. Just like in a river the current doesn't flow the water flows.

Resistance works to reduce current , the resistors in the circuit offer resistance to the current. Conductors such as the wires connecting components together have (theoretically) no resistance to current. A really important concept to get clear in your mind is that: Voltage is across components and current is through components.

2.9 Changing the value of resistance
What is the effect of different resistor values on our circuit? The resistor controls the current flow, the higher the resistor value the lower the current. (what would a 10K resistor look like?

A FET is a control component that amplifies small signals. It has three legs or leads: D – Drain G – Gate S – Source Only a small signal is required on the gate to control a larger current through the source to the drain.

The collector current is the same current which lights the LED Breadboard layout diagram The 390 limits this current to an acceptable value for the LED.

20

force.11
Understanding circuits
Electronics is all about controlling the physical world. manipulate and modify information (the information is coded as different voltages).2. They have output circuits to convert differen coltgae levels back to the physical world where we can sense the outcome of the process ( light. motion.
21
. the physical world radio signal on the input is converted to an voltage level. sound/radio/light waves associated with them
Electronic devices have input circuits to convert the physical world (light sound etc) to different voltage levels. this is processed by the electronic circuit and converted to light which we see and sound which we can hear. sound etc)
Take an example such as a television. They have process circuits that transform. Physical objects have properties such as temperature.

As photons of light hit the atoms within the LDR. if too much current flows they may overheat and burn out. Thalliumoxid and Cadmiumsulfide.g. a battery and the circuit is a series one.
When it is bright the LDR has a low resistance and the voltage is low. The components are a resistor from 10K (10.
22
.
When it is dark the LDR has a high resistance and the output voltage is high.000) ohms. 5mA.2. LDRs are made from semiconductors such as Selenium. an LDR. resistance decreases. electrons can flow through the circuit. This means that as light level increases. Find an LDR and measure its resistance: in full daylight the LDRs resistance is approximately ____________ in darkness the LDRs resistance is approximately ______________
LDRs can only with stand a small current flow e.000) ohms to 1M (1. They are used in voltage divider circuits with a series resistor.000.12
The input circuit – an LDR
The LDR or Light Dependant Resistor is a common component used in circuits to sense light level. An LDR varies resistance with the level of light falling on it.

23
.13
Working darkness detector circuit
The resistor in series with the LDR can be experiments with to change the sensitivity of the circuit to different light levels.2.

The circuit is protected by a diode.2. this means if the battery is connected in reverse then there is no current because the diode blocks it (this is commonly used in the workshop to protect our circuits from a reverse polarity situation). In this modified circuit the power is supplied from the battery.14
Protecting circuits – using a diode
Diodes are very common components. this means the current would increase rapidly and it would burn up.
Of course no diode is perfect and should the voltage of the power supply exceed the voltage rating of the diode then the diode would breakdown. Description 1N4007 1N4148 Peak reverse voltage Maximum forward current
24
.15
Diode Research Task
Research the specifications for these two common diodes (ones we use often in class) and find out what each specification / attribute means. The 1N4004 has a maximum forward current of 1Amp.
The key characteristic of a diode is that there is current in only one direction so you cannot reverse it in the circuit and expect it to work. Diodes can only take a certain current in the forward direction before they overheat and burn up. The 1N4004 has a 400V rating.
2. they come in all shapes and sizes.

have positive and negative ends and therefore require wiring into the circuit the right way round or it will not work You can identify the LED polarity by the flat on the LED body(negative-cathide) or by the longer lead (positive or anode) You can identify the TRANSISTOR polarity by the shape of the bidy and the layout of the three leads Draw lines from the components to the symbols to help you remember them. when there is light present the LED is switched off. LED and TRANSISTOR are polarised.
25
. This circuit could be used to help a younger child orientate themselves at night and to find the door in a darkened room. The function of the process part of the circuit (the transistor) is to amplify the small change in voltage due to light changes.2. Remember the resistor in the output circuit was made a lower value (changed from 1k to 390ohms) to make the LED brighter in the final circuit.16
Final darkness detector circuit
The function of the input part of the circuit is to detect light level. The function of the power supply is to safely provide the energy for the circuit to work When it is dark the LED is switched on. The function of the output part of the circuit is to indicate something to the end user. The DIODE.

PCB making
3.1 Eagle Schematic and Layout Editor Tutorial
A circuit such as the darkeness detector is no good to us on a breadboard it needs a permanent solution and so we will build it onto a PCB ( printed circuit board).
26
.3
Introductory PCB contruction
We take a short break from electronics theory to introduce a further topic of construction .

the PCB size is limited to 100mm x 80mm and the board must be not for profit
3.2.2 An Introduction to Eagle
Eagle is a program from www.de that enables users to draw the circuit diagram for an electronic circuit and then layout the printed circuit board.13
3.1 Open Eagle Control Panel
Start .
27
.2 Create a new schematic
On the menu go to FILE then NEW then SCHEMATIC You will see the schematic editor
3. where you will be led step by step through creating a PCB for a TDA2822 circuit.  If this is the first time you have used Eagle create an Eagle folder within your folder on the server.Eagle 4.cadsoft.2.  Within the Eagle folder create a folder for the name of this project e. The version used is the freeware version which has the following limitations.g.Eagle . This is a very quick start tutorial.Programs .sch within the DarkDetector folder.3.3 Saving your schematic
 It is always best to save your data before you start work  Eagle creates many temporary files so you need to keep your folders tidy.2. DarkDetector  Save the schematic as DarkDetector verA.

3.1 The Toolbox
As you point to the tools in the TOOLBOX their names will appear in a popup and also their description will appear in the status bar at the bottom of the window Find the following tools        ADD A PART MOVE AN OBJECT DELETE AN OBJECT DEFINE THE NAME OF AN OBJECT DEFINE THE VALUE OF AN OBJECT DRAW NETS (connections) ERC (electrical rule check)
28
.3.3 The Schematic Editor
The first part of the process in creating a PCB is drawing the schematic. Parts will be added from libraries 2. 1. and joined together using ‘nets’ to make the circuit
3.

It will have a green dot next to it if it is selected At this time right click on the other lbr folder and select Use none.3. 6. The cls.
NOTE THE IMPORTANCE OF THE GREEN DOT NEXT TO THE LIBRARY. 10. Parts are stored within libraries and there are a large number of libraries in Eagle. To use a library right click on it from within the Control Panel Make sure Use is highlighted. In Eagle's control panel from the menu select options then directories In the new window that appears make sure the directories for the libraries are highlighted Click on browse and find your Eagle. From your internet browser save the file cls. 4. You might need to close EAGLE and restart it to make sure it reads the libraries ok. 5.2 Using parts libraries
Selecting parts libraries to use. 11. Choose OK. 2.lbr has many already modified components within it. 9. if its not there you will not see the library in the schematic editor!
29
.directory Next highlight the directories for Projects Click on browse and find your Eagle directory again. It is not hard to create your own library and modify the parts within it.lbr into your Eagle folder. 3. 1. 7.3. 8. If Eagle is not setup to use the cls library you will need to do it now.

8 (wirepads) 2 cls led 5MM 1 cls 1N4148 D41-10 1 cls 2N7000 1 cls GND 3 A wirepad allows us to connect wires to the PCB (such as wires to switches and batteries)
3.3 Using Components from within libraries. Select it and then click OK
Add 2 more resistors of the same type.3.
30
.4 Different component packages
There are several different types of resistors.
From your schematic Click the ADD button in the toolbox A new window will open (it may take a while)      Find the CLS library Open it by double clicking on it or by clicking the + sign Open the R-EU_ section (ResistorEuropean) Here you will find the 0204/10 resistor.The 0204/7 is suitable for us but any of the 4 smallest ones would be OK.3.3. they all have the same symbol however resistors come in different physicalpackages so we must choose an appropriate one. Add all of the following parts LIBRARY PART Qty cls REU-0204/10 3 cls LDR 1 cls 2.54/0.

Left click again to stop at a point and draw before drawing in another direction.Moving parts
Move the parts around within the schematic editor so that they are arranged as per the schematic below.
3. Double left click at another component to finish the wire. R2.5 Wiring parts together
These form the electrical connections that makeup the circuit. Select the net button from the toolbox. R3) in the same places as those below.
31
. Keep the component identifiers (numbers like R1. Left click on the very end of a component and draw in a straight line either up. down. left or right.3.

each has a unique name. When you want to connect a new net to an existing net. ground.3.3. V+. Nets Nets are the wire connections between the components..
Find these on the toolbar and identify what each does. Find the info button in the toolbox and check the names and details of the components and nets/wires.7 Junctions
Junctions are the dots at joins in the circuit.V-. otherwise choose the net with the smallest number
3. Eagle will prompt you as to which name to give the combined net. they are there to make sure that the wires are electrically connected. If one of the nets has a proper name i.3. use that name.6 Zoom Controls
There are a number of zoom controls that can be used to help you work in your circuit.. Generally you will NOT need to add these to your circuit as the net tool puts them in place automatically
32
.e. VCC.

find this button and answer yes to the question about creating the board.8 ERC
The ERC button causes Eagle to test the schematic for electrical errors. never work on one without the other open or you will get horrible errors which will require you to delete the . You must correct all errors before going on.
33
.3. often zooming in on that point and moving components around will help identify the error.brd file and restart the board from scratch. and components unconnected are very common.4 The Board Editor
The board editor is opened using a button in the toolbar.
3. The ERC gives a position on the circuit as to where the error is.3. Errors such as pins overlapping. The new window has a pile of parts and an area upon which to place them. WARNING: once you have started to create a board always have both the board and schematic open at the same time.

Eventually your picture will look like the one on the right. Good PCB design is more about placement of components than routing.3. these wires will shortly become tracks on the PCB.1 Airwires
The wires from the schematic have become connections called airwires. Progressively arrange the components so that there is the minimum number of crossovers.4. In the demo version you cannot place parts outside this area. Keep the components in the lower left corner near the origin (cross). As you place components press the Ratsnest button often to reorganize the Airwires.2 Moving Components
Move the components into the highlighted area.4. Then zoom to fit. Reduce the size of the highlighted area you are using for the components. You want to make track lengths as short as possible
34
. These connections can look very messy at times and at this stage it is called a RATSNEST. so spending most of your time (80%) doing this step is crucial to success.
3.

3 Hiding/Showing Layers
The DISPLAY button in the TOOLBOX is used to turn on and off different sets of screen information. This will keep the screen easier to read. Turn off the names. and values while you are placing components.
35
. Turn off the layer by selecting the display button and in the popup window pressing the number of the layer you no longer want to see.4.3.

Place tracks so that no track touches the leg of a component that it is not connected to on the schematic No track may touch another track that it is not connected to on the schematic Tracks may go underneath the body of a component as long as they meet the above rules
2. Route the track by moving the mouse and left clicking on corner points for your track as you go. DON'T CONNECT ANY OTHERS OR YOUR CIRCUIT WILL NOT WORK. You may even want to rip up all the tracks and move components around as you go. Tracks need to connect all the correct parts of the circuit together without connecting together other parts.4. nor can they go through the middle of components! Go to the Toolbar.
36
. This will be necessary as you go to solve problems where it is not possible to route the tracks.5 Ripping up Tracks
Ripping up a track is removing the track you have laid down and putting the airwire back in place. Double click on a pad to finish laying down the track. Left click on a component. Note that around your circuit all of the pads on the same net will be highlighted.4.
3. YOU ONLY WANT TO CONNECT THE PADS ON THE SAME NET.3.
Track layout Rules
1. 3. This means that tracks cannot go over the top of one another.04. Select the ROUTE button On the Toolbar make sure the Bottom layer is selected (blue) and that the track width is 0.4 Routing Tracks
Now is the time to replace the airwires with actual PCB tracks.

5.from http://www. * Open yourboard.3. All this software is shareware with no fees attached for its use by students. It will keep the board exactly the same and correct size for printing.com * Install GSView . Make sure you can see the drill holes!
37
.ps' (postscript file). * Install GhostScript .brd in Eagle * From within the Eagle Board Editor start the CAM Processor * select device as PS_INVERTED * Scale = 1 * file = ..
3.5 Making Negative Printouts
Eagle is straight forward at producing printouts for a positive photographic pcb making process. * Select process job * if you will use this process a lot save this cam setup as so that you can reuse it again Open the TDA2822verA.ghostgum. (NOTE THE TEXT ON THE PCB APPEARS REVERSED THIS IS CORRECT) If your photosensitive board requires a negative image such as this.17. another stage on the process is required.from http://www.1 Other software required
The following software is required to manipulate the special CAM (computer aided manufacturing) files created by Eagle (and other pcb CAD software) into the printed image you require.com.ps * make sure fill pads is NOT selected this makes small drill holes in the acetate which we use to line up the drill with when drilling * for layers select only 16. it is the best output from Eagle to use. * make sure ALL other layers are NOT selected.au/ Conversion process This process creates a '.ps file with Ghostview for printing and print it onto an over head transparency.18 and 20.ghostscript.

Cut: Photosensitive board is expensive.3.
38
. so it is important not to waste it and cut it to the right size.
Expose: This over head projector is a great source of UV – ultra violet light. It is also sensitive to ordinary light so when cutting it don’t leave it lying around. The text acts as a cue or indication of which way around the acetate and board should be. It will ruin your clothes so do not splash it around.6 PCB Making
PCB Board Layers
Measure. it takes three minutes on the OHP in my classroom.
Develop: The developer chemical we use is sodium metasillicate which is a clear base or alkali. The development process takes anywhere from 20 seconds to 2 minutes. The reason being that the chemical dilutes over time making the reaction slower. The overhead transparency produced earlier must have some text on it. The board should be removed twice during the process and washed gently in water to check the progress. it is a strong cleaning agent! It should be heated to speed up the process. We want the text on the board to be around the right way.

this speeds the process up radically so always use the pump. This may take about 15 minutes. dry it and store it in a dark place. At this stage if there is not time to etch the board. Thee asiest way to do this is to put the board back into the developer again. it is an acid and will stain your clothes.
Etch: The etching chemical we use if ferric chloride.
39
.Rinse: The developer must becompletely removed from the board. The tank heats the etching solution and there is a pump to blow bubbles through the liquid. Etching may take from 10 to 30 minutes depending upon the strength of the solution.
Remove Photosensitve Resist: The photosensitive layer left on the tracks after etching is complete must be removed.
Rinse: Thoroughly clean the board.

9mm drill in class. This suits almost all the components we use. so the tracks must be protected straight away.Laquer: The copper tracks on the board will oxidise very quickly (within minutes the board may be ruined). Also bend the wires just a little to hold the component in place (do not bend them flat onto the track as this makes them very hard to remove if you make a mistake). Take you time with drilling as the drill bit is very small and breaks easily.
Drilling & Safety: Generally we use a 0. they can be sprayed with a special solder through laquer (or tinned). As always wear safety glasses!
Use a third hand: When soldering use something to support the board.
40
.

Put the tinned iron onto the joint to heat the joint first. 8. 1.DO NOT . Keep the iron on the joint after the solder for an instant. So approach it from that way. 10. The materials must be clean. HOLD the iron onto the joint until both parts of it COMPLETELY heat through . The most important point is GOOD THINGS TAKE TIME. Wipe clean the iron on a moist sponge (the splnge must not be dripping wet!) 3.DO NOT repeatedly touch and remove the soldering iron on a joint this will never heat the joint properly. Soldering is best described therefore as a graceful process. 5. Remove the solder. SO TAKE YOUR TIME! Quick soldering jobs can become really big headaches in the future.s
When you are soldering properly you are following a code of practice
41
. The joint must be heated (be aware that excessive heat can ruin boards and components) 6.it takes time for the solder to siphon or capillary around all the gaps.4 Soldering. 2.DO NOT . Use enough solder so the solder flows thoroughly around the joint. and people learning to solder tend to be quick because either they believe the temperatures will damage the components or they think of the solder as glue. the solder left on it will protect it from oxidising 11. 4. 9. always slowwwwing down to get a good soldering joint. Apply the solder to the joint near the soldering iron but not onto the iron itself. The iron must be tinned with a small amount of solder. Support the joint while it cools (do not cool it by blowing on it) DO NOT . 7. Follow these simple steps to get the best results. Remove the soldering iron last – do not clean the iron. solder and soldering irons
Soldering is a process of forming an electrical connection between two metals.

When the solder flows smoothly onto surfaces it is know as "WETTING".4. then they can deteriorate your solder joint and cause it to fracture. Very small components through the holes in a PCB are fine. It is for this reason that we don't dab at a joint with a hot iron.it will burn you! Good solder joints  
42
. This is the state of risk for your joint. It also reduces surface tension so improves viscosity and wettability. in fact it could even damage them. some larger components may need other support.  The soldering iron needs to be hot to be useful around 360 degrees Celsius . Flux is a crucial element in soldering it cleans removing oxidisation and prevents reoxidisation of components by sealing the area of the joint as solder begins to flow. it is not gluing! The new alloy must have time to form. Reheating joints without fresh solder often doesn't do much good. the joint never really becomes hot enough to melt the solder hence no wetting takes place and the joint is going to be unreliable. if something moves during that time the solder will crack.1 Soldering facts
   Currently the solder we use is a mix of tin and lead with as many as 5 cores of flux. however be careful as to how much support you expect it to give. Soldering provides a certain amount of mechanical support to a joint. A new alloy of tin and copper must be formed for soldering to have taken place. often just bending the legs slightly before soldering is enough. Don’t use solder whichis too thick. If you apply the solder to the joint not the iron you will know the joint is hot enough because the solder will melt. it will only be around 4-6 um thick As solder goes from a solid to a liquid it goes through a plastic state. Our use of lead solder may change in the future with the trend to move to non lead based materials in electronics. If a solder joint is not heated properly before applying more solder or the solder is applied to the iron not the joint then the flux will all burn away or evaporate before it can do its proper job of cleaning and sealing the materials. Flux is useful for only about 5 seconds.2 Soldering Safety
Lead is a poison so don’t eat solder! Solder in a well ventilated area as the fumes coming form the solder are the burning flux and are a nuisance in that they can lead to asthma. Too much heat on components during soldering can destroy the component or lift the tracks from the PCB.
     
   
4. If components get very hot while your circuit is on.

cut.4.
Step 1:
Step 2:
GET YOUR SOLDERING CHECKED
Step 3: The solder should cover the joint fully.
Ztep 4:
Follow these recommended codes of practice with your work
43
. stripped and soldered. and after the joint has cooled the wire should not be able to move in the switch contact. These must be correctly measured.3 Soldering wires to switches
LED's and Switches are most often attached to the circuit board with wires.

Before a Concord takes off the runway was supposed to be inspected and cleared of all foreign objects. sparking a bigger fuel leak and fire that brought the plane down. The titanium strip caused the tire to burst. So how important are codes of practice? So how important is your soldering? 44
. sending rubber fragments up into the wing of aircraft. The Air France Concorde crashed in a ball of flames 10km passed the runway. so that it is safe for users and provides reliable operation. 2000.
The next aircraft to take off was an Air France Concorde. But how important are they?
This metal strip is a “wear strip”. The aircraft stores its fuel in tanks in the wing. and in July 2008 it was determined that 5 people would stand trial for the crash. The strip fell off the DC10 onto the runway at Charles de Gaulle airport.4. Since the incident all Concorde aircraft have been retired from service. north of Paris on July 25. The aircraft picked up the strip with one of its tires. the aircraft leaked fuel which ignited. A “wear strip” is a sacrificial metal strip that protects an edge on an aircraft.4 Codes of practice
Codes of practice are industry recognized ways of carrying out work on your project. It was also not properly installed. This titanium strip was a replacement part on a Continental Airways DC-10 aircraft. killing all 109 people aboard and four people at a hotel in an outer suburb of Paris. it is designed to be worn away with friction. The wing is not very thick material and the tank burst open. it should have been made from stainless steel but was however made from titanium which is much stronger. this was also not done.

it has flowed onto another trac k
Too little solder
Heated only the leg of the component
Only soldered on one side of the leg
A whisker of solder is touching another track
Forgot to solder it!!
45
.4.5 Good and bad solder joints
The finished solder joint should be cone shaped and bright in colour When a solder joint is correct there will be a new alloy od Sn-Cu formed between the solder and the track or component lead.
Too little solder. not enough heat
Too much solder
Heated only the pcb track
Too much solder.

6 Short circuits
Can you spot the short circuits in these pictures?
46
.4.

shorted batteries might actually burst into flame.Here the upper short circuit is between two of the tracks that connect to the programming pins.
Can you see the short between the battery connections here?
47
. The lower short was noticed at the same time. so the board wouldn’t program. but wouldn’t havebecome a problem until either B5 or B6 were used
Here there is a possible short at the top left as the wire hasn’t been trimmed and bent over onto ro nearly onto the other track. so the batteries were getting really hot!! Watch out. the right hand short is between positive and negative.

49
.1 Cells
A cell is a single chemical container.
Here is a tomato cell powering an LCD clock.2 Batteries
A battery is a collection of cells in series e. from light (photovoltaic cells).
     
from chemical reactions (cells. and can produce a voltage of 1.1 volts to 2 volts depending on its type. In the diagram on the copper side there are plenty of electrons(-). from pressure (piezoelectric).
Lemons make good cells too!
5. a 12 volt car battery is six 2 volt lead-acid cells in series.
5.1. from heat (a thermocouple). from magnets.1 Making electricity
Electronic circuits need energy.g. on the zinc side (+) there is an absence of electrons. the Van de Graaff generator).1. this energy is in the form of moving charges(electrons)
There are a number of ways that we can get charges moving around circuits. batteries and the newer fuel cells).g. from friction (electrostatics e. wires and motion (generators and alternators).5 Introductory Electronics Theory
5.

Car Painting.1.inexpensive AAA.This is often used in hearing-aids. o Nickel-cadmium . Laser Printers.5. Damage/reduce life of electronic components Danger around any flammable material (like at petrol stations)
50
.4 Electrostatics
When certain materials such as wool and a plastic ruler are rubbed against each other an electric charge is generated. with potassiumhydroxide as the electrolyte. This causes a slight positive charge on the paper. with an alkaline electrolyte. o Metal-chloride
5. The negative side effects of static electricity Lightning Sparks from car – they hurt. o Lithium-ion . AA. Photocopiers.The electrodes are nickel-hydroxide and cadmium. Air fresheners. The rubbing process causes electrons to be pulled from the surface of one material and relocated on the surface of the other material. o Alkaline . o Zinc-air .Used in common Duracell and Energizer batteries.3 Different types of cells


Primary cells (not rechargeable) o Zinc-carbon . This will mean that the negatively charged plastic will attract and pick up the positively charged paper (because opposite charges attract). The positive side effects of Static Electricity Smoke stack pollution control.Used in automobiles. with an acidic paste between them that serves as the electrolyte. The electrodes are zinc and carbon.lightweight. This is the principle of electrostatics. Secondary Cells (Rechargeable) o Lead-acid . C and D dry-cells and batteries.Lithium.This is used in aeronautical applications because the power-to-weight ratio is good. o Nickel-metal hydride (NiMh). the electrodes are made of lead and lead-oxide with a strong acidic electrolyte. lithium-iodide and lead-iodide are used in cameras because of their ability to supply high currents for short periods of time.Excellent power-to-weight ratio.1. the electrodes are zinc and manganese-oxide. o Lithium photo . o Zinc-mercury oxide . As the charged plastic moves over a piece of paper the electrons within the paper will be repelled (The paper is an insulator so the electrons cannot move far). o Silver-zinc .

51
.2 ESD electrostatic discharge
Ever got a shock getting out of a car? That is caused by a build up of static electronicty. Electronic components can be damaged by the high voltage of static electricity that we produce by waking around (we can easily generate several thousand volts). A large industry exists to provide anti-static devices to prevent static electricity from damaging electronic components.5.

sources are referenced.
52
. write the information in your own words. wires and motion
When a wire moves in a magnetic field electricity is produced. colours.3 Magnets. hazards. Turning the hand crack on the front of this radio will charge the internal rechargeable batteries. hazards. sources are referenced In your group you will need to agree on a common format for presentation: A2. NiCad. Power stations: Geothermal. 30minutes of cranking will fully charge the batteries for 15 hours of listening
5. layout. Solar.5. Cells and Batteries Zinc Carbon. You will have 2 periods in class to work on this together. energy to weight ratio. Wave Describe in detail its operation. fonts. advantages. Gas Fired. where it is used (if used) In New Zealand B. some attempt at description of operation in own words Diagram. explains mAH ratings. Battery / Cell Thorough explanations and Technology clear diagrams and pictures of working. Alkaline. advantages and disadvantages. choose one of the following each: A. NiMh Describe in detail its operation. Wind.
This mechanical torch has no batteries. Hydro. disadvantages Excellence Power Station Thorough explanations and technology clear diagrams and pictures of working. Please do not copy information straight from wikipedia or some other source. some attempt at description of operation in own words Merit Pictures and Diagrams with clear descriptions of operation. This picture shows the process of generating electricity from motion. typical uses. Achieved Diagram. this means that it will only generate electricity while the lever is being worked. location(s). A3 or Web. Lithium. typical uses. Lead Acid. A one minute crank will give 30 minutes of listening. location(s). Pictures and Diagrams with clear descriptions of operation. sourc.4 Group Power Assignment
In groups of six.

5.000 Volts (220kV) at thousands of amps.
53
.5 Electricity supply in New Zealand
In Auckland the mains power comes up from power stations in the south via over head lines that carry voltages of 220.

copper. these tightly bound valence electrons make the material better at insulating. protons and electrons determine what type of material something is. The atoms in the outer shell are known as Valence electrons
5. Materials that have high conductivity are silver. The sum of all charges in a normal atom is zero making the atom electrically neutral. Electrons have a negative charge. Atoms themselves are made of a nucleus of protons and neutrons surrounded by numbers of electrons. protons a positive charge. Everything is made up of atoms or structures of atoms. Insulators are used in electronics just as much as conductors to control where current flows and where it doesn't. Insulators are materials that do not allow charges to move freely. steel and iron.
Less electrons in the outer shell means that a material is better at conducting. To understand why these are good conductors some knowledge about atoms is required. neutrons no charge.e.7 Insulators
When the outer shell of an atom is full there are no free electrons. This is shown in the copper atom. An insulating material can break down however if enough voltage is applied.
The numbers of different neutrons. no current can flow.6 Conductors
When a difference in energy exists in a circuit electrons (charges) want to flow from the negative to the positive. Materials that allow charges to flow freely are called conductors. and the electrons are arranged in layers or shells.5. aluminium. i. With larger atoms the nucleus contains more protons and neutrons.
54
. gold. The electrons spin around the nucleus. A single electron in an outer shell on its own tends to be held weakly or loosely bound by the nucleus and is very free to move.

single or multi-stranded.
55
.5. giving a total area of 0.8 Choosing the right wire
We use different types of wire for different jobs. NOTE: we use red for 5V. Wires can be categorised by the number and diameter of the strands and whether they are tinned or not.25mm
Solid core wire is really useful for breadboard use.
Tinned single strand 0.2mm in diameter. black for ground (0V/negative) and Yellow for voltages over 5V in the workshop.
Multistranded wire is great for anytime the wire is moved. Collect samples of the different types of wire used in class. but really bad for anytime the wire will be moved a lot as it breaks easily.g.2 wire we use a lot in classroom means 7 strands each 0. choose a thicker wire for high power. This can carry currents upto 1amp.22mm2 . tinned or un-tinned and number and thickness of the strands. We have thicker wire with more strands for higher current use. label each with the wires by its characteristics: e.
7/0.Tinned wire (looks like it has solder on it already) is great as it doesn’t corrode/oxidise and so it is easier to solder.

insulation for wires
Resisitivity is the measure of how a material opposes electrical current.11
Silver 1.5. resists oxidation Electrical hookup wire.68 10-8 2.9 Resistors
Resistors reduce the current (flow of electrons/charges) in a circuit. light dimmers.
5.10
Resistor Assignment
Write a description of how a metal film resistor is constructed.
5.
Gold
Copper Aluminium
Tungsten Iron Tin Lead Mercury Nichrome Carbon Germanium Seawater Silicon pure water Glass & porcelain Rubber Quartz (SiO4) PTFE (Teflon)
640 Ω-m
56
. The unit of resistance is ohms and the symbol is the Greek symbol omega.4 x 102 2.5 x 155 1 x 1010 1 x 1013 7. Write description of how a carbon film resistor is constructed. it is measured in ohm-meters. printed circuit boards Used in high voltage power cables. (Note that we often use the letter R on computers because an omega is harder to insert.5 x 10-5 4. it has 65% of the conductivity by volume of copper but 200% by weight High melting point so good for lightbulbs Used to make steel Used in Solder Used in solder Used in tilt switches.2 x 10-7 9.) Resistors can be variable in value (used in volume controls.09 x 10-7 2. resists oxidation Used in sliding contacts on circuit boards.8 x 10-7 1 x 10-6 3.000000016 Ω-m
Resistivity
Silver cadmium oxide is used in high voltage contacts because it can withstand arcing. Common fixed resistor types are Metal Film and Carbon Film.44 x 10-8 1. house wiring. Include pictures with both.6 x 10 -8 Ω/m 2.82 x 10-8 5. more corrosion resistant than silver.6 x 10-8 1 x 10-7 1.5 x 1017 1 x 1024 0. etc) or fixed in value.6 x 10-5 2 x 10-1 6. because it is liquid at room temperature Used in heating elements Used in resistors Was used in making diodes and transistors Used as the main material for semiconductors Doesn’t conduct! Used in power line insulators Insulating boots for electrical workers silicon–oxygen tetrahedral -used for its piexo electric properties Polytetrafluoroethylene.

13
Resistor Values Exercises
Resistor values are normally shown on the body of the resistor using colour codes There are 2 schemes.
58
.5. one with 4 bands of colour and one with 5 bands of colour
The colour code is
You will need some practice at using this table.

1uF = 100nF = 100.000 pF (means 10 + 4 more zeros) The main one of these we use in the workshop will be the 0. all capacitors are rated up to a particular voltage.000pF
There are polyester types as well
Values will be written on these capacitors.
60
.14
Capacitors
There are two different symbols for the two main categories of capacitors and many several types within each category Polarised non polarised
such as an electrolytic
such as ceramic
Note the 25V voltage rating on the above electrolytic and the 16V rating on the one below. exceeding this may cause the capacitor to overheat leak and even explode!
and tantalum
Values will be written on these capacitors. generally in picofarads and in code 104 = 100. generally in microfarads (uF) They are polarised (have a positive and a negative legs) – the positive leg is the longer one and there is a line on the body of the capacitor to show whcihc side is negative.5.

Draw a breadboard with a resistor.16
Year 10/11 . When a switch is turning a circuit on and off what is it actually doing? 10. What components make up the power supply part of the circuit? Soldering 15.Typical test questions so far
Darkness Detector 1. Why must the sponge be damp but not wet? 21. Does current flow in a circuit? (trick question!) 29. What is flux for? 17. Draw and name the first 11 symbols in the symbol table . What is the voltage of a AA cell? 27. Where does electricity come from in NZ? 26. What are some different types of wire and where do we use each one? 32. Describe three types of bad solder joints 22. What components make up the output part of the circuit? 13. What is a code of practice? 19. What temperature is a soldering iron? 18.5. What does LED stand for? 8. Describe a good solder joint 23. What is the LDR for? 11. What is your electronics teachers favourite type of chocolate? 7.
62
. switch and battery connected so that the LED lights up? 5. How can you tell the right way to put in an LED? 6. What is current? 25. When is static electricity bad? 28. 31. Why do we put heatshrink over wires? General electronic theory 24. LED. Draw the circuit for the darkness detector 3. 33. Think of at least one terrible thing that could go wrong due to poor soldering 20. Why do some things conduct and others not? 30. What components make up the input part of the circuit? 12. What is the diode for? 4. What does LDR stand for? 9. What components make up the process part of the circuit? 14. Use a resistor colour code table to find the values of 3 different resistors used in the workshop. Name three conductors used in electronics. What are the color codes for all the resistors used in the darkness detector? 2. What is solder made of? 16.

They are used extensively within cellular phones. commerce and everyday life.
They are found inside aircraft instruments.6 Introduction to microcontroller electronics
Microcontrollers are a fundamental electronic building block used for many solutions to needs throughout industry. modern cars.
domestic appliances such as stereos and washing machines
and in automated processes through out industry
63
.

hard drives. a motherboard which has a CPU.
6. and a bunch of I/O devices connected to it. RAM and other things on it.2 What does a computer system do?
A computer carries out simple maths on data.
64
. But don’t computers do complex things? Yes.6. the art of computer science is to break big complex tasks down into a lot of simple tasks. but as you will learn. Data is information which is input from I/O devices and stored inside the computers memory devices in the form of binary numbers.1 What is a computer?
A computer system that we are familiar with includes components such as DVD writers.

washing machines. remote controls. stereos. You will find them inside cars. I/O control circuits and a CPU (cental processing unit) however it is inside a single IC package.
However don't think that because a microcontroller is smaller than a PC that it is the same comparison as between a real car and a toy car. industrial equipment and so on.
The purpose of the parts of a microcontroller are exactly the same as in a larger computer. And there are billions of these controllers out there in the world doing just that. Data and programs are stored in memory and a CPU carries out simple maths on the data. calculators. data and program storage.3 What exactly is a microcontroller?
A microcontroller has the same things in it that bigger computers have. radios. microwaves. The microcontroller is capable of carrying out millions of instructions every second.
65
.6. airplanes.

sound etc to voltages and currents. The programmer writes programs (program code) which are made up of input instructions (convert electrical signals from input circuits to data). light etc)
In a microcontroller there is a second conversion.6. 5. heat.: INPUT. sound etc In a microcontroller circuit that creates light patterns based upon sounds the control process is SOUND to ELECTRICITY to DATA Processing of the DATA (numbers) DATA to ELECTRICITY to LIGHT 66
. Input circuits convert physical world properties to electrical signals (current/ voltage) which are processed and converted back to physical properties (heat. The processor runs a program which carries out mathematical operations on data or makes decisions about the data 4. 3. 2. Input instructions convert the electronic signals to data (numbers) and store them in its data memory (RAM) – A variable is the name for a RAM location. Output circuits convert electronic signals to light. where the electrical properties of voltage and current are changed to data and stored in memory. PROCESS (or CONTROL) and OUTPUT. control instructions (which work on data) and output instructions (convert data to electrical signals)
1.4 What does a microcontroller system do?
As with any electronic circuit the microcontroller circuit is a system with three parts. heat. Input circuits convert light. The output code converts the data (numbers) to electronic signals (voltage and current).

such as the ATMEL AVR. The AVR programs are written on a PC using BASCOM-AVR.6.mcselec.6 Breadboard
Often in electronics some experimentation is required to prototype (trial) specific circuits.
67
.
6. are controlled by software and they can do nothing until they have a program inside them. A prototype circuit is needed before a PCB is designed for the final circuit. The AVR is connected to the PC with a 5 wire cable. It comes in a freeware version so students may download it and use it at home. A breadboard can be used to prototype the circuit. It has holes into which components can be inserted and has electrical connections between the holes as per the diagram below.5 Getting started with AVR Programming
Microcontrollers. Using a breadboard means no soldering and a circuit can be constructed quickly and modified easily before a final solution is decided upon. it comes from www.com. This software is a type of computer program called a compiler.

6.
68
.7 Breadboard+Prototyping board circuit
This prototyping board along with a breadboard works well for trialling circuits.

69
. with the standard ATMEL 10 pin programming connector.This is the latest version of the PCB.

70
.On this breadboard a single LED has been setup along with the ground wire to complete the circuit.

the battery pack red wire is in VCC.B. the Electrolytic capacitor is in the rght way.D). you don’t want to damagee the board while trying to fixing it. the IC is in the right way. Check all the following: The value of the resistor is 10K.
Us the soldering good enough? Are there long wires left uncut (A. the black wire is in GND.C)? Any solder joints that don’t look like volcanoes(C. the 8 way and 10 way sockets are in the rows of holes closest to the IC.8 Checking your workmanship
Check your workmanship. the two links are in. if you fins any problems it is a good idea to ask the teacher what to do to fix it.6. Any solder between tracks causing short circuits(E)?
71
. the diode is the right way around.

10
AVR programming cable
A cable is needed to connect the AVR circuit to a PC.3.LED
There is an LED with a 1k ‘current limit’ resistor.9 Output Circuit .6. the wiring and orientation is critical so make sure it is around the right way and you use exactly the 5 wires as per the drawing (wires 2.
6.00 including free postage). One end has a DB25M connector on it (as in this picture) theother end a 10pin IDC connector. Only 5 of the 10 conductors are used. With 2V across the LED. The alternative is to buy an AVR USBASP programming cable from EBAY (about $5. there will be 3V across the resistor.4. and the current will be limited to (V/R) 3/1000 = 3mA. It connects the PC’s parallel port to the AVR circuit.6 & 8 are not used). An LED needs only 2V to operate so if connected without a resistor in series too much current would flow and destroy the LED. This is enough current to make the LED clearly visible but not too much for the micro to provide. The cable is typically a flat or ribbon cable.
72
.

OPTIONS – PROGRAMMER and select Sample Electronics programmer.11
Getting started with Bascom & AVR
BASCOM-AVR is four programs in one package. Double click on the error to get to the line which has the problem. it includes the Program Editor. Choose the parallel tab and select LPT-address of 378 for LPT1 (if you only have 1 parallel port on the computer choose this). also select autoflash.00 10.00 OPTIONS – ENVIRONMENT – EDITOR change the Comment Position to 040.
6.6. the Programmer and the Simulator all together.
After installing the program there are some set-up options that you might want to change. If its not already setup from the menu select. The following are not absolutely necessary but will help you get better printouts. it is known as an IDE (integrated development environment). If no microcontroller is connected an error will pop up.
73
. OPTIONS – PRINTER change the margins to 15. If the IC s connected then the BASCOM completes the programming process and automatically resets your microcontroller to start execution of your program. the Compiler. If your program is in error then a compilation will not complete and an error box will appear.00 10. This will change your high-level BASIC program into low-level machine code.13
The programmer
When you have successfully compiled a program pressing F4 or the green IC picture in the toolbar starts the programmer.12
The compiler
The command to start the compiler is F7 or the black IC picture in the toolbar.00 10.
6.

74
. where procedures are carried out
This is an Input or Output process step where
Here we test to see if something is true or false.6. Flowchart Symbols Daily Routine FlowChart
This is a process step.14
An introduction to flowcharts
Flowcharts are an incredibly important planning tool in use not just by software designers but by many professionals who communicate sequences and actions for systems of all types.

7 = 1 ‘ LED 7 on Waitms Flashdelay ‘wait a preset time PortA. it really helps make your code more readable and easier to debug! Use the TAB key in Bascom to do it.bas '-----------------------------------------------' Compiler Setup (tell Bascom about our micro) $regfile = "attiny461. this makes it easy 'to change things quickly later) Const Flashdelay = 250 ‘ preset how long a wait will be '-----------------------------------------------Do ‘start of a loop PortA.15
Bascom output commands
Flash1LEDv1.bas Type the code below into BASCOM.6. save it. then F7 to compile and then F4 to program ‘ Flash1LEDv1.7 = 0 ‘LED 7 off Waitms Flashdelay ‘wait a preset time Loop ‘return to do and start again End YOU NEED TO INDENT CODE BETWEEN ALL CONTROL STRUCTURES SUCH AS WITH THIS DO-LOOP.dat" 'wgich micro $crystal = 1000000 'its speed '-----------------------------------------------' Hardware Setups ' (these tell bascom how to setup our micro) Config Porta = Output 'LEDs on port '-----------------------------------------------' Declare Constants ' (these tell bascom names we will use for numbers ' in our program.
75
.

7 high (which will turn on the LED connected to that port) PortA. DO .7 = 0 make porta. This line tells Bascom the speed at which our microcontroller is executing operations 1 million per second)so that Bascom can calculate delays such as waitms properly Config porta=output. Sometimes thisis a permanently on LED sometimes it is a slow flashing one Find the value of Flashdelay so that the LED is on for 2 seconds and off for 2 seconds 2. it is easier to remember names and it is useful to keep them all together in one place in the program (this is a code of practice). this is the name of a file in the Bascom program folder with every detail about the ATTiny461. Find the value of Flashdelay so that the LED is on for ½ a second and off for ½ a second 3. so if there is no pause between turning an LED on and turning it off the led will not be seen flashing Output Code PortA. ‘constants’ are used in a program. When a computer monitor is in standbay mode often an LED is going to alert the user that the power is left on but ther ei s no signal to the monitor. each I/O must be configured to be either an input or output.7 low (which will turn off the LED connected to that port)
6. Bascom needs to know which micro is being used as each micro has different features.dat”.16
Exercises
1.This is a typical first program to test your hardware Every line of the code is important. a microcontroller carries out operations sequentially. Find the value of Flashdelay so that the LED is on for 5 seconds and off for 5 seconds
76
. $crystal=1000000.LOOP statements enclose code which is to repeat forever. $regfile=”attiny461. Waitms flashdelay wait a bit. when programming it is important to indent (tab) code within loops. (it cannot be both at once) Const Flashdelay=150.7 =1 make porta. this makes your code easier to follow (this is a code of practice).

this makes it easy 'to change things quickly later) Const Ondelay = 150 ‘how long an LED will be on for Const Offdelay = 1000 ‘how long an LED will be off for '-----------------------------------------------Do ‘start of a loop PortA. Change the on and off time to match your heart beat.bas This program has TWO delays one for the on time and one for the off time ‘ Flash1LEDv1. A piece of equipment that has a flashing LED like this is sometimes referred to as having a ‘heatbeat’ indicator to show it is ‘alive’ or on.15Seconds (150mSec) and off for a second (1000mSec) Flash1LEDv2. E.g.
77
.7 = 1 ‘ LED 7 on Waitms Ondelay ‘wait a preset time PortA.6.bas '-----------------------------------------------' Compiler Setup (this tell Bascom things about our micro) $regfile = "attiny461.7 = 0 ‘LED 7 off Waitms Offdelay ‘wait a preset time Loop ‘return to do and start again End REMEMBER YOU NEED TO INDENT CODE BETWEEN ALL CONTROL STRUCTURES SUCH AS WITH THIS DO-LOOP. on for 0. Use the TAB key
4.dat" 'bascom must know the micro $crystal = 1000000 'bascom must know its speed '-----------------------------------------------' Hardware Setups ' (these tell bascom how to setup our micro) Config Porta = Output 'LEDs on port '-----------------------------------------------' Declare Constants ' (these tell bascom names we will use for numbers ' in our program. Change the on time to the smallest possible length you can see 5.17
Two delays
Often pieces of equipment have a flashing LED that is on very briefly then off for a long time.

g. It needs three delays: Const Ondelay1 = 50 Const Ondelay2 = 500 Const OFFdelay = 200 Write this program then modify it to make what you think is a good heartbeat. It’s like having a conversation with a person whose first language is different to your own and they get the order of words in a sentence jumbled or use the worng word. We can generally get the meaning of the sentence but computers cannot understand the small mistakes that a programmer makes. carry out AT LEAST these to see what happens  What happens if you change Const Flashdelay to Const faslhdelay? (deliberate spelling error)  What happens if $crystal = 10000000 or 100000 instead of 1000000?  What happens if your change the $regfile to "attin26.
6. Double flashes are common ands some equipment might have a short then a long flash like this program.dat”? (deliberate spelling eror)  What happens if one of the waitms flashdelay statements is deleted (look closely at the LED)?  What happens when the two waitms flashdelay statements are deleted (look closely at the LED)? In programming we call these syntax errors.
78
.All sorts of ‘heartbeat’ indicators can be used in equipment to show it is on. Cup tea make me you or time when lunch is or stop bus where is we can make meaning fo these but a computer cannot make sense between flasshdelay and flashdelay.18
Syntax errors -‘bugs’
Playing around will develop your understanding. The syntax has to be 100%. E.

6..19
Microcontroller ports: write a Knightrider program using LED’s
Learn about controlling ports. Ports are groups of 8 I/O pins.
we should use the commands to control the whole port at once
79
.
If we have 8 LEDs connected to portA we could control them individually HOWEVER…there is a better way.

Keep a record of BOTH the schematic and layout changes in your notebook Remember that using a constant is meeting good programming codes of practice. 5. LED234. see the picture below) .20
Knightrider v2
As a second exercise rewrite the program so that three LEDs turn on at as in the Knightrider car. LED567… Success criteria to work on in your program 2. 4. If you didn’t use Const then you would have to go through your 80
. 3. 8. LED345. 2. LED67. 2. Sequence = LED0. 6. Use spaces to help layout your program so it looks good 3..g. 7. Use constants with good names e. 'led1. waitms flashdelay not waitms 150 5.. LED01. 2. 1.0 (each needs an individual 1k current limit resistor. LED567.You already have 1 LED connected to portA.7 now connect another 7 LEDs to your microcontroller from ports A. 3. 3. Use the following code to get started Porta=&B10000000 Waitms flashdelay Porta=&B01000000 Waitms flashdelay Porta=&B00100000 Waitms flashdelay … Using the above command to control the whole port at once is quicker and easier for some applications than individually controlling each pin.
6. LED67. LED123. LED456. Comment your program with short clear descriptions 4. Write a program to flash all 8 LEDs in a repeating sequence e. it means that when you want to change the speed all you have to do is change it in one place in the program. 4. You need to choose the best way when thinking about readability and understandability. LED012. 6.6 through to A. 7. LED7.g. 5.

In your studies we often distinquish between describe=Achieved.5 =1  porta.0 = 1 6.– it is showing the reader which LED is coming on and explains the special case of hand over of the LED control from one port to the other.2 = 0  port a. Comments make your program more readable  and especially explain how/why you did something 8. Before we use a pin or port we must set it up as either an input or an output  Config porta=output OR  we can configure each pin separately config pina.3 = 0  port a.2.22
Commenting your programs
Comments in your program code are used to explain (not just describe) to others what your program is doing or how your program is doing it. porta.7 = 1  porta. The code above is an excellence for commenting because it justifies why it works the way it does! If you can write good comments that explain thoroughly and where necessary discuss your code you are an excellent programmer!
6. PORTA. We can make each pin individually high or low  e.1. porta.  e.4 = 0  porta.g.0 4. The 8 pins in a port are numbered from 7 down to 0  porta.g. porta. Discuss would be where you explain and justify why you did it one way rather than another.6 = 0  porta.1 = 1  porta. … porta.6.7 = 1 or porta. porta. We can delay a microcontroller using program code  Waitms 50 Or better still use a constant  Const timedelay=50  Waitms timedelay 7.23
Learning review
1. or PORTB 2. Take note of the commenting in the code above.3=output 3. explain=Merit and justify=Excellence. We can control all 8 pins at once  Porta= &B10100011 This is the same as  porta. Microcontrollers input and output pins are grouped into 8 and called ports.7.7 = 0 5. Programs are sequential and run forever within a  Do-Loop
83
.6.

it moves in one direction. 500.6.
The piezo can be attached directly between a microcontrollers output pin and ground. Modern ceramic type piezos are much more efficient than natural quartz ones.6 Sound piezo. This command is not easy to use to get accurate tones from your AVR.
Bascom’s sound command can be used to directly make a tone. Piezo Alias Portb. The opposite occurs too. these are generally ceramic nowadays although the principle was originally discovered in naturally occuring quartz (and other) crystals. We make use of this property to produce sound and also in ultrasonic cleaning and other things. but they do make useful sounds. When a crystal has an electrical charge applied to it. Experiment with the sound command and make a series of tones suitable for an alarm
84
. 300 ‘that’s all that’s required The Bascom sound command has three parameters (values) attached ot it. if a crystal is moved or stressed a voltage potential can be created. This property is put to work in piezo lighters (such as in a bbq) and in ceramic microphones.  The port or pin of the microcontroller used  The duration of the sound (number of pulses)  The time the pin is high and low for.24
What is a piezo and how does it make sound?
A piezo is made from a nonsymmetrical crystal.

25
Sounding Off
.6.6. the piezo is connected to PortB. then see the layout pic on the next page
85
. Add a piezo to your project.

The datasheet gives the following information
88
.25Watts output.27
Amp it up
If the piezo is not loud enough then you might like to add an amplifier to the output of your project.
The LM386 is an audio amplifier IC that is capable of upto 1.6.

the diagram is not clear to beginners exactly what to do with the connection so this is how you connect it. what has been added and where and which way around to increase the amplification from 20 to 200.Can you see the difference between the two circuits. You will need a potentiometer. We can build one of these circuits easily and quickly on breadboard to test it.
89
.

Can you add that to your circuit?
90
.To boost the power of this circuit the schematic from the datasheet on the previous page shows an extra capacitor in the circuit.

. if the resistor was not there then the input pin would be ‘floating’ and give unreliable readings.7 Microcontroller input circuits
A computer is not much use to us if it only has outputs we must have some inputs for the user or the world to tell the computer what to do.
7.1 Single push button switch
A ‘pullup’ resistor is essential in this circuit. as when the switch is not pressed it connects the input pin to a known voltage.
91
.

Next put in the Switch
Get a mulitimeter and check the voltage goes up and down when the switch is pressed and released 92
.A lot of students get the switch wiring incorrect. here it has been broken down into two stages. first put in the 10k resistor from the pin to 5V.

2 Pullup resistor theory
In this circuit the switch is connected without a pull-up resistor. the resistor from the port to 5V
93
.7.
When the switch is pressed the voltage goes low (0V).3 Switch in a breadboard circuit
In this circuit make sure the schematic is followed very closely. the microcontroller input voltage will drift. sometimes be high (5V). sometimes low (0V) and is sensitive to touch and static leading to very unreliable results. The switch goes from the port to ground.
7.
In this circuit the 10k resistor pulls the microcontroller input pin high (to 5V) making the input reliable when the switch is not pressed. The input pin of the microcontroller has no voltage source applied to it and is said to be ‘floating’.

4 Checking switches in your program
There are two main methods of checking for switch activity. we can wait until a switch is pressed before we continue or we can test the switch and if not pressed move on to do the rest of our program
' check if switch pressed – main method If Redsw = 0 then 'do this only if pressed do_something end if … … ' check if switch pressed – method 2 Do Loop Until Redsw = 0 ' wait here until pressed … …
94
.7.

Without the delay we cannot see the LED toggle because the micro can toggle the LED really fast.when the switch is released the LED will always turn off .5 = Input 'switch on portB ' Hardware Aliases ' tell bascom names for I/O devices ' attached to the Micro ' names are easier to remember than ports ' when writing big programs RedSw Alias Pinb. too fast for our eyes to see.5 ' hardware alias Led Alias PortA.5 Program Logic – the ‘If-Then’ Switch Test
In this first program we would like the LED to change from off to on every time the switch is pressed.7.dat" ' the micro $crystal = 1000000 ' its speed '----------------------------------------' Hardware Setups ' tell bascom how to setup our micro ' setup direction of all ports Config Porta = Output 'LEDs on portA Config Portb.
95
. “When the switch is pressed toggle the LED” '-----------------------------------------' Compiler Setup (tell Bascom about our micro) $regfile = "attiny461.7 ' hardware alias Const waitdelay = 500 '---------------------------------------' Program starts here Do If Redsw = 0 Then ' wait for switch press Led = 1 Waitms waitdelay Led = 0 Waitms waitdelay End If Loop End
When the switch is pressed and held down. Notes: . the LED will flash on and off at the rate determined by the waitdelay value.

7 ' hardware alias Const waitdelay = 500 '---------------------------------------' Program starts here Do If Redsw = 0 Then ' wait for switch press Toggle Led Waitms waitdelay End If Loop End
This program also toggle the LED when you hold the switch down.5 = Input 'switches on portB ' Hardware Aliases ' tell bascom names for I/O devices ' attached to the Micro ' names are easier to remember than ports ' when writing big programs RedSw Alias Pinb.6 If-then exercises
1.dat" ' the micro $crystal = 1000000 ' its speed '----------------------------------------' Hardware Setups ' tell bascom how to setup our micro ' setup direction of all ports ' setup direction of all ports Config Porta = Output 'LEDs on portA Config Portb.“When the switch is pressed toggle the LED” '-----------------------------------------'Compiler Setup (tell Bascom about our micro) $regfile = "attiny461. HOWEVER when you release the switch. Extension excerise for quick students – get another 2 switches and use them to do different things like play different tunes.5 ' hardware alias Led Alias PortA.
7. Modify your progam so that inside the IF-THEN you have your knightrider 3. sometimes it will be on and sometimes it will be off and the LED will stay that way. Modify the program so that inside the IF-THEN you have your tune played 2.
96
.

7 Switch contact bounce
We have another problem but this one is quite hidden from us. This would be OK if the micro was as slow as we are. however a switch bounce might last 2 or more millseconds. When someone presses a push button switch the contacts inside the switch move together very fast. it is called contact bounce.
97
. sometimes when you turn the light on or off there is a little glow tihin the switch that is sparking caused by the high voltage as the switch contacts bounce.
In this circuit the voltage is being measured and you can see that the switch contacts have bounced 4 times. and our microcontroller can detect things as fast as 1microsecond so it might actually think the switch has been opened and closed many times when we pressed it only once! Similarly it might think the switch has been pressed several times when we release it too! (sometimes you might see this at home with an old lightswitch.7. In the next program we will add some delays to fix this issue. our micro could easily sense all these bounces as you opening and closing the switch really fast. and they actually bounce several times together before staying closed.

7
Const debouncetime = 30
'---------------------------------------' Program starts here Do If Redsw = 0 Then Waitms debouncetime Do Loop until Redsw = 1 Waitms debouncetime Toggle Led End If Loop End
We now have a debounce switch program. then we wait a short bit (for the switch to stop any contact bouncing) then we wait for the switch to be released then we wait for a short bit (for the switch to stop any contact bouncing) then we toggle the LED '---------------------------------------' Compiler Setup (these tell Bascom things about our micro) $regfile = "attiny461.dat" 'bascom needs to know the micro $crystal = 1000000 'bascom needs to know its speed '---------------------------------------' Hardware Setups (these tell bascom how to setup our micro) ' setup direction of all ports Config Porta = Output 'LEDs on portA Config Portb.    
“If the switch is pressed. only toggle the LED once To do this we check to see if the switch is pressed.5 = Input 'switches on portB ' Hardware Aliases (these tell bascom names we will use for I/O devices ' attached to the Micro.5 ' hardware alias Led Alias PortA.
98
. names are easier to remember that ports) RedSw Alias Pinb.

to indicate if a window is open or to the landing gear of a jet aircraft to indicate its position...
Do If Sw0 = 0 Then Waitms debouncetime Do Loop until Sw0 = 1 Waitms debouncetime Toggle Led0 End If If Sw1 = 0 Then Waitms debouncetime Do Loop until Sw1 = 1 Waitms debouncetime Toggle Led1 End If . These switches might be connected to an assembly line to indicate the presence of an item... End If Loop End 99
.8 Reading multiple switches
Often the microcontroller is required to read multiple input switches and then control something based upon the switch inputs.. . A common method of using switches within a program is to poll the switch (check it regularly to see if it has been pressed)..7. If Sw4 = 0 Then Waitms debouncetime Do Loop until Sw4 = 1 Waitms debouncetime Toggle Led4 .

10
Different types of switches you can use
Various types of switches can be connected to microcontrollers for various purposes: Find another type of switch and use it in your program.on doors and cupboards
Useful for parts or doors that open and close Tilt or Mercury Switch
Useful to sense movement or something falling over Rotary Switch Tact switch
Can be used to select one of several different values
Directly soldered to a circuit board.7. Use it for the next programs. Key switches Micro switches
So that only authorised people can operate a device Magnetic or Reed switch
Used inside moving machinery . better quality that the cheap push button switch 101
. write it up in your notebook.

7. it has an LED and a phototransistor built into it. note that one corner is cut on an angle. Have a close look at the shape.
Looking at the device from underneath (from the pins end NOT the top) this is the layout
102
.11
Reflective opto switch
The RPR220 is a reflective photosensor. This is to help you identify which connection is which.

this could be changed to adjust the sensitivity of the unit.To connect it into a circuit we need two resistors A current limit resistor for the LED and a pullup resistor for the microcontroller input pin.
It can be used in a program just like a switch
Opto_sensor alias pin B. ‘do something here End if
103
. For testing purposes a 150 was used. The current limit resistor can be calculated suing the data from the datasheet
The LED will drop 1.34)/0. So using ohms law R=V/I = (5-1.34V and is more powerful than a normal LED as it can handle 50mA.05 = 73 ohms minimum resistance. maybe a lower value would mean the reflective surface could be further away.6 … If Opto_sensor = 0 then….

8. 3.3 Organisation is everything
As with structuring and organising your folders you also need to structure and organise your program code.1 Three steps to help you write good programs
1. so use a different folder for each program:      it keeps the files that BASCOM generates for your program in one place this helps you find programs quickly when you want to it is less confusing it is good practice Save your program at the beginning when you start it. Break the code up into the following sections.
104
. and then when you want to refer to it in the future you find that you cannot understand what you have written! The use of a template or pattern to follow will help discipline your code writing.2 Saving Programs
When saving programs you need a good quality directory / folder structure. Messy code is hard to understand and it is surprising how fast you forget what you did. Interrupt routines
You will really need to be organised with what is coming up. this helps guard against teachers that like to turn the computers off unexpectedly. 2.8 Programming Review
8.             title block program description compiler directives hardware setups hardware aliases initialise hardware declare variables initialise variables initialise constants main program code subroutines. Name each program with a meaningful name and save it into its own directory Use a template to setup your program from the start Add lots and lots and lots of comments as you go
You must layout programs properly and comment them well to gain achievement 8.

While-Wend. pin d. Use constants instead of numbers in the code (e. Determine the state of all the I/O when the program begins e. F4. Use subroutines to organise complex code so that logic code is separate from I/O code h. Draw Flowcharts or Statecharts (visual diagram for the process the program must carry out) a. const. word.g. Determine variables and constants required in the program d. Write the algorithm – Identify.g. Identify the blocks/states that will be used b. Processing and manipulating data which is stored in variables 2.
106
. Learn how to configure pins as either input or output d. In your electronics courses at school the aim is not to make you an expert in all the above (expertise comes after about 10 years working in an area). Learn to comment code so that it explains what is happening (not just describes) g. Plan your I/O by drawing a system block diagram c. Develop Algorithms (written plans for the process the program must carry out) a. Learn to access the helpfile (e. Learn common I/O functions: set. Get to know about the hardware you are using a. Find out about the different types of memory and amount of each f. Understand the limitations of and use variables: byte. long. order and describe the major processes the micro must do. For-Next. The IDE (Integrated Development Environment) has special commands and built in functions you must know and use: F7. 5. Develop code from the flowcharts a. Trial different ways of solving the problem and keep records of you experiments This is not a step by step process. Switches. Use arrows to link the blocks and visualise control processes and program flow 6. The key to gaining depth in your knowledge and understanding comes from LOTS OF EXPERIMENTATION! That means making mistakes and above all having fun. write a few simple programs using the simulator) 4. the aim is to introduce you to microcontroller electronics and programming. The outer looping line is replaced with a do-loop b. Input and output conversion at the voltage level b. single. $regfile. Learn about the power supply required c. Backwards loops are replaced with do-loop do-loop-until. LDR… e. Find out about the speed of processing 3. while-wend c. The language has syntax (specific grammar/word rules) you must use correctly c. waitms timedelay) g. double f. Get to know the control functions: Do-Loop (Until). Layout the code with correct indentations(tabs) to improve readability f. Get to know the language and the IDE you are using a. Get to know about text and math functions (read help file. Get a copy of the datasheet b. as when you get to know about one area you get to know about others at the same time. GetADC e. Learn how to interface common I/O circuits: LED’s. locate. $crystal. Piezo. If-Then (Else) h.5 What you do when learning to program
1. reset. Conversion of input and output voltages into data c. you need to know that good decisions come from experience and experience comes from bad decisions!!! So experimenting is ok. and to understand some of what is happening in the world around you and to feel able to see that you can control it and not have it control you. for-next. highlight a word and press F1) b. LCD. port. alias. Replace the blocks with actual commands e. config.8. Forward loops are generally replaced with If-Then-EndIf d. Have a goal in mind for the program – use specifications and write a simple brief b. Develop an understanding of what a computer is and build a correct mental model for one a.

128 bytes of Ram and 128 bytes of EEPROM for long term data storage. A commercial range of microcontrollers called ‘AVR’ is available from ATMEL (www.5V
107
. (You cannot use RESET as an I/O pin. voltages in excess of these will destroy the micro.  I/O ports are a group of 8 I/O pins which can be controlled together  MOSI. the TDA2822M amplifier or LM358 opamp. ATTiny461
Important pins:  VCC & GND are dedicated for power. MISO. an infrared remote control or whatever. MISO.5V to 5. Check the datasheet to see what the range is for your micro.7 Power supplies
Most microcontrollers work off low voltages from 4. it can all be done with a microcontroller. SCK and RESET are pins used to upload the programs.5 to 5. If you want an egg timer. you decide:  what the function of the IC is  what most of the pins are used for (inputs or outputs)  and what external input/output devices these pins are connected to.atmel. a car alarm. Often ICs have fixed functions e. With a microcontroller however you are in control. Or you could start with the ATMega48. SCK can be used with care)
8.5V. so yours can be run off batteries or a dc power pack.com). 512 bytes of RAM and 256 bytes of EEPROM. they only do one job and their input and output pins have fixed roles. it has 4kbytes of Flash.8. You could start with the ATTiny461. it is a full computer inside a single integrated circuit (IC or chip). the ATTINY461-16PI will work from 4.6 AVR microcontroller hardware
A microcontroller is a general purpose electronic circuit.g. VCC is positive voltage and GND is negative  AVCC and AREF are special pins for measuring analog voltages (connect to VCC). but MOSI. and therefore limited control over how to connect them. it has 4kbytes of Flash for program storage. so you have limited control over what they do.

The Programmable Memory size is ______ The SRAM size is _______The EEPROM size is _______ The number of I/O lines is __________ and they are arranged in _______ports
BASCOM-AVR is a compiler from _____________________ The URL for their website is: ________________________ Download the latest version of the BASCOM AVR demo and install it on your PC. There are a number of application notes on the website for the AVR Describe what AN128 is about __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________
There are a number of other great resource websites for the AVR and BASCOM Find 3 websites on the internet that have useful resource information on BASCOM List the websites URL and what you found there __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________
108
.BASCOM and AVR assignment Learning goal: Students should become independent learners able to find support to help their own learning
The AVR is a microcontroller from which manufacturer________________ The URL for their website is: ________________________ Download the specific datasheet for our microcontroller (the summary version not the full version) and print the first 2 pages and put them in your journal.

8V.The ATTiny461 datasheet is full of useful information here is what some of it means
2/4/8k of progam memory (the 461 has 4k) 128/256/512 bytes of SRAM (the 461 has 256 bytes) Nore the power and frequency table.
109
. we wil generally use the micro at 1MHz. so we could run it as low as 1.

What is const used for? Write a few lines of program that uses const. Draw this on a bread board diagram as well.8.9 Year10/11 typical test questions so far
What have you learned about connecting power to a microcontroller? What is a typical power supply voltage? What range of voltages is acceptable? Which pin(s) are positive and which are negative? What are the names for these pins? What batteries would you use? What have you learned about programming a microcontroller? What is the software we are using called? Where does it come from? What does IDE stand for? What are the names for the 4 different parts of the IDE software? How many wires are there in the programming cable? What happens if $regfile is wrong? What happens if $crystal is wrong? What does compiling mean? What have you learned about interfacing LEDs to a microcontroller? Draw the connection for an LED and resistor to a microcontroller. Are these series or parallel? What is a typical value of resistor? What would be a minimum value? What would be a maximum value? What does the toggle command do? What have you learned about programming the pins of a microcontroller? How many I/O pins does an ATTiny461 have? With an LED on A.7 write the config statements for both What are the different commands for driving a single output pin? What command can you use to drive multiple output pins all at once? What have you learned about program style? We ‘tab’ or indent code for what reason? Why do we comment programs? Write comments for a simple flashing LED program.5 and a switch on A. What have you learned about making sound? How is a piezo connected? What is the command used to make sound? Write a line of code to show how it the command used? What have you learned about interfacing switches? What is the resistor in the circuit called? Why is it necessary? What value is typically used? Draw the circuit for a switch connected to a microcontroller? Explain the code used to test a switch to see if it pressed? What is the problem with switch contact bounce for software? . What is alias used for? Write a few lines of program that uses alias.
111
.

Cross and DontCross lights work as expected. System Block Diagram: (include all input and output devices)
112
. pedestrians are at considerable risk
Conceptual Statement: Design and construct a set of traffic lights for a pedestrian crossing Functional attributes: When the button is pressed the lights change from green to orange. need or opportunity (diagrams may be required): Vehicles travel at high speeds on this road and although there is a pedestrian crossing. there is a delay of 25 seconds Then the lights go red There is a delay for 1 minute Then the lights go back to green.9 Introduction to program flow
9. customer or end-user: … Description of the problem.1 Pedestrian crossing lights controller
Client. issue.

2 Pedestrian Crossing Lights schematic
113
.9.

3 Pedestrian Crossing Lights PCB Layout
114
.9.

orangelight. the orange light goes on Then after 25 seconds the orangelight goes off the redlight goes on the don’t cross goes off the cross now goes on Then after 1 minute the red light goes off the cross now goes off the don’t cross comes on the green light comes on REDLIGHT
Inputs Device Description Large buttons on each pole for pedestrians to press to cross
Starting State
CROSSBUTTON
OFF
ORANGELIGHT GREENLIGHT
OFF ON
BUZZER
OFF
CROSSNOW
OFF
DONTCROSS
On
115
.4 Algorithm planning example – pedestrian crossing lights
(define the operation of the system) Name: _______________ Project: _______________ Date: _____ Define all the input and output devices Outputs Name Device Name Description RED traffic lights for cars on pole Orange traffic lights for cars Green traffic lights for cars Buzzer to indicate to pedestrians to cross now CROSS NOW light on each pole DON’T CROSS light on each pole The algorithm Initially the Redlight . buzzer and cross are off.9. Greenlight. dontcross are on For each input describe what happens to any output devices Use “if __________ then _________” or “ do___________ until ___________” statements If the pedestrian presses the crossbutton then The greenlight goes off.

116
.9.5 Flowchart planning example – pedestrian crossing lights
Programs flow in sequence and can be represented well with flowcharts
Note how the planning for this program includes a graphic detailing the colour of the lights. this helps visualise the program and is an excellent example of choosing a planning tool that will help your thinking.

Generally the dontcross light is off until the pedestrian presses the button 2. Implement a short beep into the system when the cross now light comes on
Achieved Implements 1 above into the algorithm AND the program AND adds useful describing comments in the program
Merit Also impliments 2 above in both the algorithm AND the program AND uses comments to explain the program
Excellence Implements 3 above in both the algorithm AND program AND with good explanatory comments in the program.7 Orangelight Alias Porta.6 Getting started code
' PedestrianCrossingsVer1. After the redlight comes on there be a short delay before the crossnow 3.6 'we need different delays for different purposes Const Orangedelay = 10 Const Crossdelay = 20 Const Dontcrossdelay = 5 'initial state of lights for cars Greenlight = 1 Orangelight = 0 Redlight = 0 'initial state of lights for pedestrians Dontcrosslight = 1 Crossnowlight = 0 Do 'wait for pedestrian to press button Do Loop Until Crossbutton = 0 Greenlight = 0 Orangelight = 1 Wait Orangedelay 'you finish the rest of this code Loop End 'on 'off 'off 'on 'off
9.4 Crossnowlight Alias Porta. Put a 5 second delay into the system after the pedestrian pushes the button and before the light goes red.bas ' B.7 Modification exercise for the pedestrian crossing
1.5 'lights for pedestrians Dontcrosslight Alias Porta.
Can you see that achievement criteria are actually algorithms? SO MAKE SURE YOU UNDERSTAND THEM! 117
.9.3 Crossbutton Alias Pinb.Collis 1 Aug 2008 ' reads a switch to check if pedestrian wants to cross $crystal = 1000000 $regfile = "attiny461. 4.6 = Input 'here we use aliases to make the code easy to write and easy to read 'lights for cars Greenlight Alias Porta.6 Redlight Alias Porta.dat" Config Porta = Output Config Portb = Output Config Portb.

9. Learning about the Bascom commands ALIAS 1. The traffic light sequence process is actually very confusing and a planning tool such as a sequence diagram will help you plan the program. Complete this sequence which shows which lights come on in the sequence
How long should the delays between LED changes be for real traffic lights? In our model we only need to test that the sequence is correct so we will choose shorted delays 118
. Understand the situation by drawing a planning diagram that explains the road layout
2. tables & flowcharts. block diagrams.8 Traffic lights program flow
Learning to develop useful planning tools to help solve problems such as drawings.

Take special note that you will have to use at least one of the output pins on portb.
119
. but is not a full circuit diagram (complete the schematic below with the pin connections for Set B and Set C. Draw a system block diagram – which shows important connections within the system.Real lights Green is on for 1 minute Orange 30 seconds? Delay after one road goes red before the green for the next road goes on
Our Model for testing purposes will be Grn_delay = 8 Or_delay = 3 Red_delay = 1
3. Label the rst of this diagram with the pins on the micro you will use for the other 2 sets of lights. I chose portB.4.

Do the physical wiring of the 3 sets of LEDs to the microcontroller.4.
Here are some photos of the process Wiring stage one: all the LEDs and resistors are mounted
120
.  Layout the physical LEDs to follow the real physical layout  Use appropriate coloured LEDs  Keep it tidy. use short wires.

here I have chosen portA. A.4 and A.5.5 are used Also note that the G(ground) and V(positive voltage) pins are not connec ted to I/O devices but to the power supply!
Can you complete the last stage of the LED wiring? You will have to put one of the LEDs on portB.3. I chose portB.
122
.Wiring stage 3: B set of LEDs are wired to three ports of the microcontroller.4 If you need more help search the rest of the book for the last picture.portA. portA.4.
Note thatportsA.3.

Collis 123
. CAN you see thepattern emerging
start
all reds on all others off
Having the flowchart will help you debug (correct errors in your program) later on
A_red off A_grn on grn_delay A_grn off A_or on or_delay A_or off A_red on red_delay A_red off B_grn on grn_delay B_grn off B_or on or_delay
6.5.bas 'B. There are 9 LEDs so there will need to be 9 stages inside the loop. Complete this flowchart in your workbook with the rest of the sequence. Write your
'TrafficLightsVer1.

by hiding detail Reuse .using subroutines
Once a program gets large we need to learn how to manage it properly.10 Introductory programming . however they can be used well or used poorly. understand and maintain. Reusing & Recycling    Reduce the complexity of your programs. Subroutines have been seen already when we have used the debounce command but here is a list of what they can do for you: Refine you code by Reducing.reuse the program code multiple times within the same program Recycle – you can use the same program code easily in other programs
Here is an example of calling some subroutines Do Gosub test_sensor If sensor_output = 0 then gosub got_it Else gosub tell_the_user_again End if Loop End
And another example DO Gosub test_sensor If sensor_output =10 then gosub do_a If sensor_output =11 then gosub do_b If sensor_output =12 then gosub do_c If sensor_output =13 then gosub do_d If sensor_output =14 then gosub do_e … Loop End
You can see that they really can de-complicate code (make it easy to read and understand) by removing a lot of I/O code Subroutines are used to make code easier to read. The clue to using subroutines well is to keep the logic for the program in the main loop and the input and output detail in the subroutines.
126
. As above and in the next example.

A program like this though could be very very long so we will break it up into sections called subroutines by putting the I/O code into subroutines 127
. It was also used between ships using lights.” It is crucial that you get the gaps between letters . Draw a flowchart and write a program to send your name using Morse code.1
Sending Morse code
Morse code is a form of communication used in the early days of telegraph and radio communication when voice could not be sent just short messages using codes. Using the program Excel as a planning tool we can draw up a chart that shows the correct timing for the sequence for ‘whats up’. A B C D E F G ●▬ H ●●●● O ▬▬▬ U ●● ▬ ▬●●● I ●● P ●▬▬● V ●●● ▬ ▬●▬● J ●▬ ▬ ▬ Q ▬▬●▬ W ●▬▬ ▬●● K ▬●▬ R ●▬● X ▬ ●● ▬ ● L ●▬●● S ●●● Y ▬●▬▬ ●● ▬ ● M ▬▬ T ▬ Z ▬ ▬ ●● ▬▬● N ▬● To make sense timing is important so we will follow these rules  A dash is equal to three dots  The space between the parts of the same letter is equal to one dot  The space between letters is equal to three dots  The space between two words is equal to seven dots 1 2 3 4 5 ●▬▬▬▬ ●● ▬ ▬ ▬ ●●● ▬ ▬ ●●●● ▬ ●●●●● 6 7 8 9 0 ▬ ●●●● ▬ ▬ ●●● ▬ ▬ ▬ ●● ▬▬▬▬● ▬▬▬▬▬
If you wanted to send a short sentence like “ whats up.  the gap between parts of a letter is 1 cell.
Check that:  the width of 1 dot it is 1 cell in excel  the width of 1 dash is 3 cells.10.  the gap between letters is 3 cells  the gap between words is 7 cells. parts of letters and parts of words correct or the message willl not be understandable by the person receiving it.

indenting code. subroutines and comments properly in programs is an essential code of practice and worth credits to
129
. the use of alias and const make your code easier for you to read and debug. comments.the sequence is 3 dots For Count = 1 To 3 'send it 3 times Gosub Dot Next Waitms Dashdelay 'longer delay between letters Return '------------------------------------------------------------Dot: Morseled = 1 ' on Waitms Dotdelay ' wait 1 dot time Morseled = 0 'off Waitms Dotdelay 'short delay between dots & dashes Return Dash: Morseled = 1 Waitms Dashdelay Morseled = 0 Waitms Dotdelay Return ' on ' wait 1 dash time 'off 'short delay between dots & dashes
Not only do things like subroutines.Send_s: 'letter s . imagine going to a job interview and being asked to bring in some code you had written to show your prospective boss – which would you show him? Using const. alias.

the 10uF capacitor C3 has been added to increase the gain.10. however a couple of practical changes need to be made ot the schematic before it can be used. First it needs a filter capacitor on the DC supply.2
LM386 audio amplifier PCB
Stage 1 of the LM386 audio amplifier schematic
This is more or less from the datasheet.
130
. otherwise the speaker output will be extremely noisy.

131
.Next the audio input has only a signal conection niot a ground connection and cables that come from the device you want to amplify generally have a signal plus ground wire. so that has been added in the next diagram.
The labels in blue have been added to the schematic are to help you choose which components to use from the CLS library inEagle.It is important to choose the right size components otherwise they may not fit on the PCB when you make it.

3.3
LM386 PCB Layout
The layout progresses through several stages 1.layout the tracks 132
.turn off the layers you don’t need so that you can focus clarly on the layout
4.10..move all the components onto the working area of the layout
4. try to layout the components with the minimum number of crossing airwires.

8. Add some stress relief holes for wires that come on and off the board
133
. Add some mounting holes fr the board.5. so that it can be attached inside a case. Add labels for the wires you will have to connect to the board
7.Add your name and the board name
6.

g. alter and even create data while they are running.
134
. width is a variable it contains the number 3. it has more meaning if we store it in a variable called weight but it has information when we know that it is the weight of a particular pen in grams. it is the same in a computer. Variable Data RAM Address (name for address) (actual number in the RAM) 1 Orangedelay 10 2 Crossdelay 20 3 Num_flashes 0 4 Flashedelay 500 Programs use. We often use the different terms information. 
A variable is the unique name we give to a location in the microcontroller’s RAM to store data. o Addresses are sequential.  Address: this is the physical location of a byte of RAM in the microcontroller (e. 0 to 1023). This data varies as the program executes so we name it variables. address or variable without really understanding their separate meanings.g. o data is numbers e. These numbers may change a lot while a programis running. it is where we store and work on information.11 Introductory programming – using variables
Inside our brain is our memory.  Information: data such as ‘13’ has little meaning to us.g. RAM. When data is stored in ram we say we are storing it in a variable. E. height is a variable. it contains the number 6. data. In a computer it is arranged in ‘bytes’ -groups of 8 individual bits (8 bits = 1 byte)
We can think of it like a series of numbered storage containers or pigeon holes Data is what is stored in the RAM. 5 or &B00000101 in binary.  RAM is the physical place (like our brain cells/synapses). it is useful to clarfify a meaning for each one.  Variable is the name we give to the place in RAM . it is a useful way to keep track of what we stored there.

135
.11.
Dim Num_flashes As Byte
Dim Orangedelay As Byte Dim Crossdelay As Byte Dim Flashdelay As Byte Orangedelay = 10 Crossdelay = 20 Flashdelay = 500
‘Here is the wrong way to do it
Do Do Loop Until Crossbutton = 0 Reset Greenlight Set Orangelight Wait Orangedelay Reset Orangelight Set Redlight Reset Dontcrosslight Set Crossnowlight Wait Crossdelay Reset Crossnowlight 'wait for ped cross button 'stop the traffic
'allow pedestrian to cross
'flash the don't cross light 10 times to tell pedestrians to stop crossing Set Dontcrosslight 'flash1 Waitms Flashdelay Reset Dontcrosslight Waitms Flashdelay Set Dontcrosslight Waitms Flashdelay Reset Dontcrosslight Waitms Flashdelay Set Dontcrosslight Waitms Flashdelay Reset Dontcrosslight Waitms Flashdelay Set Dontcrosslight Waitms Flashdelay Reset Dontcrosslight Waitms Flashdelay '.1
Stepping or counting using variables
Have you noticed that at a pedestrian crossing that after the Crossnow light goes off the Dontcross light actually flashes before staying on.. Reset Redlight Set Greenlight Loop End 'let traffic continue 'flash2
'flash3
'flash4
The above code wastes a lot of our program memory.. In this program we want the dontcross light to flash 10 times while the pedestrian is crossing.

The variable num_flashes starts at 1 and each time through the loop it increases by 1 until it has completed the loop 10 times.
136
.‘Here is the right way to do it
Set Greenlight Reset Orangelight Reset Redlight Set Dontcrosslight Reset Crossnowlight Do Do Loop Until Crossbutton = 0 Reset Greenlight Set Orangelight Wait Orangedelay Reset Orangelight Set Redlight Reset Dontcrosslight Set Crossnowlight Wait Crossdelay Reset Crossnowlight 'on 'off 'off 'on 'off 'wait for ped cross button 'stop the traffic
'allow pedestrian to cross
'flash the don't cross light 10 times -
For Num_flashes = 1 To 10 Set Dontcrosslight Waitms Flashdelay Reset Dontcrosslight Waitms Flashdelay Next
Reset Redlight Set Greenlight Loop 'let traffic continue
This is the for-next loop in programming – every programming language has it (in some form or another) and we use it when we want something to repeat or step a fixed number of times.

... one red and one green. We could write a program the goes: Red on Wait ½ sec Red off Wait 2½ sec Red on Wait ½ sec Red off Wait 2½ sec Red on Wait ½ sec Red off Wait 2½ sec Red on Wait ½ sec Red off Wait 2½ sec . when the green light is flashing the green group is on the machines. .. Example: when you join a gym they give you a workout card which has the exercises and the number of repetitions on it to do. E..11. but this is not really computer programming
We need a simple way of controlling how many times the lights flash and we can use a variable to count the flashes and a loop that repeats depending upon what number is stored in the variable. at a very busy gym everyone has to be split into one of two groups.. 137
. There are two big lights. when you see something that looks like it is repeating you replace it with a loop of some form (there are several choices).2
For-Next
Repetition is what computers do best here is another example of repetition using a for-next. . Each light flashes 20 times per minute(on for ½ second off for 2½ seconds).
The same with computer programming. When the red light is flashing the red group is on the machines. Every 60 seconds everyone changes from the mat to the machines. They don’t give you a list: Bench Max Bench Max Bench Max Bench Max Bench Max Bench Max Inline Max Inline Max Inline Max Inline Max Inline Max Inline Max .. those that exercise on the machines and those that work on the mats..g.

it only makes a sound when you turn it on and off rapidly.
First lets review what a tone is. It is a repeated turning on and off of our piezo. Bascom has a waitus command (it is not particularly accurate but its good enough for this exercise). We want the tone to last long enough to hear it so we need to repeat it 150 times. A piezo will not make a sound when you turn it on.15S).programming using variables
In this program we will use a variable to control the duration (length) of a tone. Then it will repeat. and we will increase it inside a do-loop.
139
. then turn it off and we repeat this for the duration of the tone.11. Remember to reset cycle count to 0 or it will overflow. In this program the tone period will be 1mS so the piezo must be on for 500uS (1/2 mS) and off for the same. The duration of the tone is the number of complete cycles. 150 times 1mS will give us a tone duration of 150mS (0. It will count upto the max number of cycles and then we will have a 2 second break.3
Siren sound . The frequency of the tone is 1/period. This program works similalrly to the Bascom SOUND command. To count the number of cycles we will dimension a variable called cyclecount. So to make a tone we must turn the piezo on then wait a bit.

bas '-----------------------------------------------------------------' Program Description: ' This program makes a simple tone using a piezo ' Program Features: ' makes use of Bascom waitus (microseconds) command ' introduces first use of a variable ' the variable cyclecount increases from 0 until it reaches the preset (constant) ' value maxcyclecount at which point there is a quiet time ' the led is on when the the tone is occuring ' Hardware Features ' a pezo can be directly connected to the micro port ' the led has a 1k resistor in series to limit the current '-----------------------------------------------------------------' Compiler Directives (these tell Bascom things about our hardware) $regfile = "attiny461.3 'use useful name PIEZO not PORTb.4 '-----------------------------------------------------------------'Declare Constants Const Halfperioddelay = 500 ' delay for 1/2 period Const Maxcyclecount = 150 'number of cycles to do '-----------------------------------------------------------------' Declare Variables Dim Cyclecount As Byte '-----------------------------------------------------------------' Program starts here Do Set Blueled 'turn led on For Cyclecount = 0 to Maxcyclecount1 Waitus Halfperioddelay1 Set Piezo Waitus Halfperioddelay1 Reset Piezo Next Reset Blueled 'turn led off Waitms 2000 'quiet time Loop End 'end program
140
.4 'use useful name BLUELED not PORTB.3 Blueled Alias Portb.dat" 'the micro we are using $crystal = 1000000 'rate of executing code '-----------------------------------------------------------------' Hardware Setups Config Portb = Output ' Hardware Aliases Piezo Alias Portb.Collis ' Date: 22 Feb 08 ' File Name: SirenV1.'-----------------------------------------------------------------' Title Block ' Author: B.

Subroutines are a great way of decomplicating your programs. How code is indented/tabbed over to aid readabilaity If you are using a do-loop – remember to reset your counter Use constants rather than putting numbers into your code (waitus halpperioddelay2).5
Siren exercise
Modify the delays and count values in this to find a siren you like the most. ‘waitus a’ isn’t much use when trying to debug a program Use pictures/diagrams to help you plan things
11. constants aand aliases. It makes it so much easier to read Use decent names for variables.
142
.' Program starts here Do Set Blueled For Sirens = 1 To 3 'just make 3 for testing purposes For Cyclecount = 0 to Maxcyclecount1 Waitus Halfperioddelay1 Set Piezo Waitus Halfperioddelay1 Reset Piezo Next For Cyclecount = 0 to Maxcyclecount2 Waitus Halfperioddelay2 Set Piezo Waitus Halfperioddelay2 Reset Piezo Next Next Reset Blueled Wait 10 'have a bit of quiet!!! Loop End 'end program '------------------------------------------------------------------
Point to take note of:       A single sirensound has been put into a subroutine. this subroutine will last approx 350mS + 240mS = 590mS.

is an extremely important aspect of writing programs. OOPS – need to move the Next above the Loop and then indent it so that it lines up with the For
143
. In this case it can now be seen that the For has no closing Next as the Next is outside the Do-Loop.11. it adds to their readability and your ease of debugging.6
A note about layout of program code
We could create a program that flashes an LED 3 times waits a bit then flashes it again.
I often fix students code simply by setting up the indenting and find things like this HARD TO SPOT THE ERROR EASY TO SPOT THE ERROR Do Do For Num_flashes = 1 To 10 For Num_flashes = 1 To 10 Set Dontcrosslight Set Dontcrosslight Waitms Flashdelay Waitms Flashdelay Reset Dontcrosslight Reset Dontcrosslight Waitms Flashdelay Waitms Flashdelay Loop Loop Next Next When a block of code is inside a control structure of some kind the inside code is indented and the end of control structure lines up with the beginning of it.
Indenting (tabbing code.

D.B.
144
.7
Using variables for data
We have seen ho w a variable can be used to create a stepping pattern in program code now we see how numbers can store information.C.11. This means it is much easier for you to remember what is in the memory location and easier to use within your program. Here are some examples of using variables Dim Width as Byte DIM is short for dimension and means set aside a part of RAM for our program to use.E. It is easier for us to have names for memory locations such as ‘width’ than using the physical address of the RAM.F. etc. Dim Height as Byte Dim V_Position as Byte Dim Speed as Byte Dim X_position as Byte Dim Color as Byte Dim Mass as Byte Here are some common things you will see in programs Height = 10 (put 10 into the memory location we dimensioned called height) Incr X_position (increase the value in X_position by 1) Color = Width / Height (divide the number in Width with Height and put the answer into Color . In a calculator with several memory locations each is given a name such as A.Y. In a microcontroller each memory location is given a name by the programmer. address 1.X. From now on in the program it will be called Width.M.the values of Width and Height do not change) Speed = Speed + 12 (get the number from memory location called Speed and increase it by 12 and put it back into the same memory location)
A variable of type Byte can store numbers from 0 to 255 (&B11111111) so it has limited use so often we group bytes together to store bigger numbers. The name of the memory location has nothing to do with what you are using it for and it is up to you to remember what was stored in each location.

its just a matter of knowing about so that you can find it when you need it.8
Different types of variables
Bigger numbers require more RAM than smaller numbers.
145
. also different kinds of numbers require different amounts of RAM (e. decimals).program size(bytes) EEPROM size (bytes)
There is no point in memorizing this data. negative.g. so to make the best use of RAM we use the best variable type we can. Microcontrollers have limited RAM. If we dimension a variable as a type that can store huge numbers and only every use numbers up to 10 then we are wasting a precious resource.11. Using the Bascom-AVR help file research the following information on the different types of variable you can use. Variable type Bit Minimum Value (before underflow) 0 Maximum Value (before overflow) 1 Number of bytes used to store it 1byte for 1 bit however if you dimension 8 bits they will all be stored in the same byte 1
Byte Word Integer Long Single Double
0
255
Every microcontroller has different amount of RAM available for storing variables Carry out research on these different AVR microcontrollers RAM size (bytes) ATTiny13 ATTIny45 ATTIny461 ATMega48 ATMega16 ATMega32 ATMega644 ATMega1284 FLASH .

11.9
' ShowComandsV1.a byte can only represent whole numbers from 0 to 255 so division truncates (IT DOES NOT ROUND) 16/10 = 1 (whole numbers only!) MOD gives you the remainder of a division (16 mod 10 = 6) This gives the wrong answer because a byte can only hold a number as big as 255 This gives the right answer! need negative numbers then use integer or long
need DECIMALS use single or double
Make sure you put an END to your program or it will continue on and potentially cause crashes (if you micro was controlling a car then it might be a car crash.6 = Input 'dimension variables Dim Byte1 As Byte Dim Byte2 As Byte Dim Word1 As Word Dim Int1 As Integer Dim Single1 As Single Dim Single2 As Single Byte1 = 12 Byte1 = Byte1 + 3 Incr Byte1 Byte2 = byte1 Byte2 = Byte1 / 10 .
Variables and their uses
Allocating some parts of the RAM.dat" Config Porta = Output Config Portb = Output Config Pinb.bas $sim $crystal = 1000000 $regfile = "attiny461.
What is the value of the variable byte1 after this?
Byte2 = Byte1 Mod 10 Byte2 = Byte1 * 150 Word1 = Byte1 * 150 Int1 = 200 Int1 = Int1 – 100 Int1 = Int1 – 100 Int1 = Int1 – 100 Int1 = Int1 – 100 For Single1 = 0 To 90 Step 5 Single2 = SQR(single1) Next End
Division .ouch!!)
146
. and giving those parts names so that we can refer to it more easily (dimensioning).

Dim band As Byte not Dim And As Byte Variables must contain no spaces e.g. means yu cannot have Const Red_cars = 12 as well
11. Incr Hurricanes (adds one to their score) Blues = Blues + 1 (adds one to their score) Waratahs = Waratahs + 3
Conversions between units Dim Celcius As Integer Dim Fahrenheit As Integer Fahrenheit = 100 Celcius = 32 .g.g. Dim Red_cars As Byte.g.11.Fahrenheit Celcius = Celcius * 5 Celcius = Celcius / 9
148
.g. Dim Red_cars As Byte not Dim 1cars As Byte Variabes must not be Bascom reserved(special) words e.11
Rules about variables
Variabes must start with a letter not a digit e. Dim Red_cars As Byte not Dim Red cars As Byte Variable names should relate to what the variable is used for e. Dim Red_cars As Byte. not Dim hgashg As Byte Variable names cannot be used for other things such as constants or subroutines e.12
A points table for a competition Dim Blues As Byte Dim Hurricanes As Byte Dim Waratahs As Byte
Examples of variables in use
as the season progresses the points are added.

In the decimal system the numbers we are used go from –infinity to +infinity. so the numberline goes on forever. no decimal fractions. No negative numbers can be stored.g. This is a finite range of positive. whole numbers from 0 to 255. It has overflowed 255.11. Binary Number 00000000 00000001 00000010 ------11111101 11111110 11111111 Decimal equivalent 0 1 2
243 254 255
We can see the diference by comparing counting in byte math to counting in the decimal system. Byte arithmetic because it has a finite set of numbers is like having a number line that goes around on itself.13
Byte variable limitations
RAM (the memory inside a computer) is capable of storing 1 byte (or 8 bits) of binary data. and no number greater than 255. what does 250 + 9 = ? What does 4-7 = ? When we add 9 to 250 we get 3.
The difficulty arises when we do arithmetic that exceeds the limits of our range. e. The opposite to OVERFLOW is UNDERFLOW and is seen by using the circular number line above.
149
.

g. dicethrow = dicethrow + 1 Loop End Compile the program and then open the simulator (F2). Dim dicethrow As Byte With variables you can do maths Do E.14
Random Numbers
This program generates a random number from 1 to 6 and stores it into a variable in memory ‘ DiceV1. and then put the answer back into 'change the range to 1 to 6 dicethrow. Config Porta = Output Config Portb = Input Every variable must be dimensioned before it can be used.11. dicethrow=dicethrow+1 'generate a random number from 0 to 5 literally means get the contents of dicethrow add dicethrow = Rnd(6) 1 to it. add 1 to throw.dat" dicethrow.bas $sim The line Dim dicethrow As Byte means allocate to $crystal = 1000000 the program 1 byte of ram to use and refer to it as $regfile = "attiny461. select the variable dicethrow from the variables list and use F8 (don’t press run) to step through the program to see the numbers generated by the program
150
.

151
.
Press F8 to step through the program and see what happens to the value of the variable at each step.11.15
Press F2 to pen the simulator
The Bascom-AVR simulator
Double click in the yellow area under the word VARIABLE to select the variables you want to watch.

16 11.11.7 NO LED 1 2 3 4 5 6 A.17
Electronic dice project
Programming using variables – dice
A dice can be made using 7 LEDs (why do we need 7? – look closely at the patterns here)
In the above circuit the LEDs have been labelled to match the pin of porta they are connected to.2 LED2 A.0 LED0
off
on
off
on
off
on
off
on
portA=&B01010101
152
.6 LED 6 A.4 LED4 A.3 LED3 A.5 LED 5 A. A. Note there is a switch connected to Pinb. remember that even though only 7 LEDs are used we need to control the whole port so need to specify all 8 bits.6
Fill in the table below which shows which LED are on and whichare off to make a particular pattern.1 LED1 A.

but to do that the middle LED has had its legs bent so that it lines up with the middle LED but does not share any breadboard connections with it
153
.11.18
Dice layout stage 1
In the diagram the 7 LEDs have been physically arranged to match the dots on the face of a dice.

11.19
Dice layout stage 2
In this second stage the resistors have been added and the wiring has been started for the LEDs.
154
.

155
.11.20
Dice Layout final
Before the rest of the wiring for the LEDs has been added the switch has been connected. agin note that it is switch wiring that confuses students the most.

11.21
First Dice Program flowchart
156
.

The problem with this is that the sequence is always the same.6 Dim Dicethrow As Byte Const Dicedisplay = 80 Const Displaytime = 3 Do Dicethrow = Rnd(6) 'get a random num from 0 to 5 Incr Dicethrow 'make it from 1 to 6 If Dicethrow = 1 Then Porta = &B0... 'turns on 6 leds Wait Displaytime End If Loop End In this case we don’t need any debounce timing because there is a long delay after the switch is pressed....... microcontrollers use a maths equation to do it... 'turns on 3 leds If Dicethrow = 4 Then Porta = &B01010101 'turns on 4 leds If Dicethrow = 5 Then Porta = &B0... To get around this problems we use a little trick........dat" Config Porta = Output Config Pinb. 'turns on 2 leds If Dicethrow = 3 Then Porta = &B0... 'turns on 5 leds If Dicethrow = 6 Then Porta = &B0..bas ' 7 leds arranged in a pattern on a breadboard $crystal = 1000000 $regfile = "attiny461.6 = Input Blu_sw Alias Pinb. you can check this out using the simulator or by modifying your dice program later to see that the sequence is always the same... 'turns on 1 led If Dicethrow = 2 Then Porta = &B0..... 'a variable to hold the value 'waiting time in seconds
11... 'turns on 3 leds If Dicethrow = 4 Then Porta = &B01010101 'turns on 4 leds If Dicethrow = 5 Then Porta = &B0...
157
. 'turns on 1 led If Dicethrow = 2 Then Porta = &B0..' DiceV1-random.... 'turns on 5 leds If Dicethrow = 6 Then Porta = &B0........ 'turns on 6 leds Waitms Dicedisplay 'wait a little If Blu_sw = 0 Then 'if switch is pressed Dicethrow = Rnd(6) 'get a random num from 0 to 5 Incr Dicethrow 'make it from 1 to 6 If Dicethrow = 1 Then Porta = &B0... we always have the program generating random numbers even when the button isn’t pressed......22
A note about the Bascom Rnd command
It is actually quite difficult to generate random numbers...... that way the position in the sequence when we press the button cannot be guessed.. 'turns on 2 leds If Dicethrow = 3 Then Porta = &B0.....

23
Modified dice
In this dice the number stays on the screen and when the switch is pressed it displays 30 random numbers before stopping on the 30th
158
.11.

Do a trial of at least 200 presses and draw a tally of the results.' DiceV2-random. how ‘fair’ is our dice? 2.bas ' 7 leds arranged in a pattern on a breadboard $crystal = 1000000 $regfile = "attiny461.6 Dim Dicethrow As Byte Dim I As Byte Const Dicedisplay = 100 Dicethrow = 1 If Dicethrow = If Dicethrow = If Dicethrow = If Dicethrow = If Dicethrow = If Dicethrow = Do Dicethrow = Rnd(6) If Blu_sw = 0 Then For I = 1 To 30 Dicethrow = Rnd(6) Incr Dicethrow If Dicethrow = 1 Then If Dicethrow = 2 Then If Dicethrow = 3 Then If Dicethrow = 4 Then If Dicethrow = 5 Then If Dicethrow = 6 Then Waitms Dicedisplay Next End If 'get a random num from 0 'if switch is pressed 'do 30 random numbers 'get a random num from 0 'make it from 1 to 6 = &B0 'turns on = &B0 'turns on = &B0 'turns on = &B01010101 'turns on = &B0 'turns on = &B0 'turns on 'wait here a while to 5 to 5 1 2 3 4 5 6 led leds leds leds leds leds 1 2 3 4 5 6 Then Then Then Then Then Then Porta Porta Porta Porta Porta Porta = = = = = = 'a variable to hold the value
'initial display &B0 'turns on &B0 'turns on &B0 'turns on &B01010101 'turns on &B0 'turns on &B0 'turns on
is 1 1 led 2 leds 3 leds 4 leds 5 leds 6 leds
Porta Porta Porta Porta Porta Porta
Loop End Exercises for the dice program 1.
159
.6 = Input Set Portb. Make the electronic dice display 2 random numbers to simulate 2 dice 4.dat" Config Porta = Output Config Pinb. then 10 random numbers are generated and it stops for 5 seconds 3.6 Blu_sw Alias Pinb. Merge the two progams above so that random numbers are displayed until the button is pressed. Make your own dice that is different to this described so far with some interesting sound feature Achieved Do number 1 and 2 above with comments in the program Merit Also implements 3 above and uses lots of comments to explain the program Excellence Implements 4 above with good explanatory comments in the program.

Decrflashdelay. Sub Decr Checkdelay Loop Until Checkdelay = 0 If Direction = 0 Then Gosub Nextright Else Gosub Nextleft End If Loop End ' Subroutines Decrflashdelay: Decr Flashdelay Return Incrflashdelay: Incr Flashdelay Return Nextright: … Return Nextleft: … return
N
checkdelay=0 Y
next led in sequence
160
.24
Modified Knightrider
A neat feature for the Knightrider program would be if the speed of the sequence could be varied. Incrflashdelay. a second variable checkdelay is needed as a copy of flashdelay
start flashdelay=1000 checkdelay=flashdelay check switches incr/decr flashdelay decrease checkdelay
Dim Flashdelay As Word Dim Led As Byte Dim Checkdelay As word dim direction as bit Flashdelay = 1000 Do Checkdelay = Flashdelay Do Debounce Sw1 . if one button is pressed increase the delay time. The switches should be checked often so that they can detect user input and I have chosen 1mS because its easy to do the maths with 1mS. wait a preset amount of time.11. 0 . 0 . So for the same reasons as before the switches need checking often. Sub Debounce Sw2 . To do this we implement a loop within the program that initially begins at the value of flashdelay and counts down to 0. so after each led in the sequence of LEDs. if the other button is pressed decrease the delay time. read the switches.

b. All the cathodes (negative ends) are connected 161
.1 7 segment displays
It is important to understand a new device so that it can be used with confidence. d.g
To create the number 2 you turn on segments a.e. e.12 Basic displays
12. Each LED is a segment of the display and they are labelled a. c. g
The LEDs have separate Anodes but COMMON Cathodes so our display is called ‘common cathode’.
The first thing to know is how the LEDs are connected within the package.
They are available in many different styles and sizes. The 7 segment display is simply a number of LEDs put together inside a package with pins sticking down so that they can be soldered into a PCB. b.f. They are still very common today in many electronic products. d.

This display is the WS1001GAS.togther and will be connected to the negative (0V or ground) of the circuit. A component for the Eagle library was created so it could be used in making our own schematics.
162
.
It had 10 pins and using a powersupply on 5V and a resistor we figured out what each pin does. so had to figure out the wiring for ourselves. we had no datasheet for it. Then realised that tgis seems to be a reasonably standard setup for the displays.

163
.

You only have to connect one of the two pins 3 or 8 to gound not both.The schematic was started.
164
. We didn’t connect the pins on the schematic as it is easier to connect the pins on the layout and figure out which is best and then draw the schematic afterwards.

Stage two was to connect a switch to the circuit.
165
.Start with the display. the 8 resistors and the power conections to the breadboard We had to use two breadboards because the display was too big to fit onto one.

And finally stage 3 to connect the microcontroller IO pins to the segments
After wiring the schematic was completed in Eagle
166
.

g
b.f.c.f &g must be on. the order is 0cdebafg for this wiring
Display 0 1 2 3 4 5 6 7 8 9 A b C d E F g H
Segments ON
Segments OFF
PORT Binary command Segment order is 0cdebafg
a. and the code &B01100111 must be written out the port.c.e
&B01100111
Complete this table for yourself
167
.d. Things such as tables to help manage your programming will help you achieve really good results in Technology.7 isnt used so it will always be 0. Work out the other values required to show all the digits on the display and determine their corresponding values in Hex and Decimal and put them in the table below NOTE portA. only the segments a.Outcome development in Technology education includes not just making the product (outcome) but includes the development of it.
To display the number five.d. Complete the table below and use things like tables yourself to logically lay out things .

g. 390R) and a test wire check the segment works .8 &15 don’t exist they are still counted!!
Connect the 7segment display to the breadboard.Another different 7 segment display
This particular display was made by OasisTek. the + indicates the pins in the two rows underneath. Through a current limit resistor (e. 168
.
Each segment should glow like segment a does in the next picture. Note that it has 2 decimal points (LDP and RDP)
This view is from the front of the display. so that the common cathode is connected to the 0V/GND line. Pin 1 is segment A Pin 2 is segment F Pin 3 is the common cathode Pin 4… Note that although pins 7.

After testing the segment connect it to the correct pin of the microcontroller.In the photo below note the side of the display has been written on to help identify where the pins are
.
169
. Then connect and test each segment in turn until all 7 are connected.

170
. Print your name program for your workbook. On the next page you will find a layout partially started.
Draw a flowchart and write a program to display the numbers 0 to 9.Complete this diagram with the rest of the connections to the 7 Segment display. Design as many letters of the alphabet as you can and write your name. then make the circuit on breadboard.

Complete this diagram with the connections for all of the seven segments
CAN YOU MAKE THIS 7 SEGMENT DISPLAY INTO A DICE?
171
.

Now the ATtiny461 doesn’t have 16 I/O pins so we combined a couple of the segments and used only 14 I/O pins of the micro.
172
.12.
Here there are 16 segments plus 2 decimal points.2
Alphanumeric LED displays
These are very similar to the 7 Segment. but have multiple segments so that you can easily make letters as well as digits. In this schematic the top two segments A1 and A2 were combined and used as 1 also the bottom two segments D1 and D2.

Here is how the layout looked
See below how A1 and A2 were linked together to one I/O pin (but 2 100ohm resistors were used)
173
.

174
.5W) or find your own. The project involves making a portable (battery powered) audio amplifier that can be used with an MP3 player and keeping a portfolio of the processes used. You may design and make or modify something else fro your case
You will design and make the printed circuit board and case for the amplifier. You may use the provided speakers (50mm.13 TDA2822M Portable Audio Amplifier Project
This project is based around the TDA2822M IC (integrated circuit) from a company called SGS Thompson Microelectronics. 8 ohm 0.

named and follow and all materials are very well a logical sequence presented. and explanation is given of these elements
Printed Datasheet Component Price List Schematic Diagram from Eagle Layout Diagram from Eagle OHT of PCB
All solder joins reliable. stress relief on all wires CAD Design drawing for At least two design case drawings for case With changes made Photo of case Photos of case + some description of process of making Final Outcome Quality outcome. Key Competencies Interacts with others Works cooperatively. innovation or creativity. Helps others and seeks others help in occasionally or when relates easily and shares the workshop often asked to work in groups workshop resources freely with others. heat shrink used correctly to strengthen joints.13. heat shrink used correctly to strengthen joints. puts tools workshop and materials away for others regularly Generally uses Efficient use of workshop Disciplined. elegance. Cleans up after self Works cooperatively with Takes initiative in keeping the others to clean up the workshop clean and tidy. stress relief on all wires AT least two design drawings for case With detailed explanation for changes Photos of case With detailed explanations of process of making Final product shows some flair. optimised and efficient workshop time well time use of workshop time
175
. (refer to codes of practice)
Workbook Presentation Material is readable All materials are clear. Overall presentation is easy to follow labelled.1
Achieved Workbook content Printed Datasheet Component Price List Schematic Diagram from Eagle Layout Diagram from Eagle OHT of PCB Board works Merit
Portfolio Assessment Schedule
Excellence Printed Datasheet Component Price List Schematic Diagram from Eagle Layout Diagram from Eagle OHT of PCB All solder joins reliable. a table of contents is given and page numbers are used.

2
Initial One Page Brief
Project: TDA2822 Portable Audio Amp Date: _____ Client. customer or end-user: ME! Description of the problem. need or opportunity(diagrams may be required): MP3 players are useful personal items however the music cannot be shared with others Conceptual Statement: Design and construct a portable audio amplifier to allow music to be played when with a group of friends
System Block Diagram: (include all input and output devices)
Further written specifications: Need to make or find a case for it all
176
. issue.13.

it is easily available on the WEB. a simplified internal schematic diagram. Find and print the datasheet for your portfolio of the TDA2822M.
177
. current and power specifications.3
TDA2822M specifications
Electronic components are complex (especially IC’s) and manufacturers provide detailed specifications called datasheets for their products.13. recommended circuits and voltage. It contains things such as the pin connections.

54/0.
178
. From your schematic Click the ADD button in the toolbox and the ADD dialog box will open (it may take a while) Open the CLS library Add all of the following parts LIBRARY cls cls cls cls cls cls cls cls cls PART REU-0204/7 2.4.4
Making a PCB for the TDA2822 Amp Project
Open eagle and create a new schematic.8 C-EU050-025x075 C-POLB45181A C-POLE5-10.1
Moving parts
they are
Move the parts around within the schematic editor so that arranged as per the schematic below.13.5 led 5MM TDA2822 RTRIMMECP10S GND Qty 6 10 2 5 2 1 1 2 3
13.

179
.brd file and restart the board from scratch. Remember to left click on the very end of a component and draw in a straight line either up. down. The ERC gives a position on the circuit as to where the error is.4
Laying out the board
Open the board editor Remember: once you have started to create a board always have both the board and schematic open at the same time.
13. and components unconnected are very common. Left click again to stop at a point and draw before drawing in another direction. never work on one without the other open or you will get horrible errors which will require you to delete the .13.4. You must correct all errors before going on. often zooming in on that point and moving components around will help identify the error.3
ERC
The ERC tests the schematic for electrical errors. left or right.
13.2
Wiring parts together
Select the net button from the toolbox.4. Click at another component or net to finish the connection. Errors such as pins overlapping.4.

Turn off the names. This will keep the screen easier to read. Reduce the size of the highlighted area you are using for the components. You want to make track lengths as short as possible
13.4. Turn off the layer by selecting the display button and in the popup window pressing the number of the layer you no longer want to see. As you place components press the Ratsnest button often to reorganize the Airwires. so spending most of your time (90%) doing this step is crucial to success.5
Minimise airwire length
Move the components into the highlighted area.4.6
Hiding layersto help you see the airwire paths clearly
The DISPLAY button in the TOOLBOX is used to turn on and off different sets of screen information.13.
Good PCB design is more about placement of components than routing. Turn off tnames and tvalues now
180
. Progressively arrange the components so that there is the minimum number of crossovers. Keep the components in the lower left corner near the origin (cross). Then zoom to fit. and values while you are placing components. Eventually your picture will look like the one here.

Route the track by moving the mouse and left clicking on corner points for your track as you go. * Select process job Open the TDA2822verA.ps * make sure fill pads is NOT selected this makes small drill holes in the acetate which we use to line up the drill with when drilling * for layers select only 16.4. Left click on a component. Tracks may go underneath the body of a component as long as they meet the above rules
After track routing add holes for mounting the board and any for looping wires through to act as stress relief DO NOT ROUTE TRACKS BETWEEN THE PINS OF IC’S 13. Route tracks so that no track touches the leg of a component that it is not connected to by an airwire 2.13.7
Routing Tracks
Now is the time to replace the airwires with actual PCB tracks. YOU ONLY WANT TO CONNECT THE PADS ON THE SAME NET. * make sure ALL other layers are NOT selected. Double check that you can see the drill holes and then print it on to an OHT (transparency) 181
. Tracks need to connect all the correct pads of the components together without connecting together other pads or tracks.4.ps file with Ghostview.04.17. This means that tracks cannot go over the top of one another! Select the ROUTE button and on the Toolbar make sure the Bottom layer is selected (blue) and that the track width is 0. DON'T CONNECT ANY OTHERS OR YOUR CIRCUIT WILL NOT WORK.8 Make the Negative Printout
(Remember the text on the PCB appears reversed)
* Open TDA2822verA.brd in Eagle * From within the Eagle Board Editor start the CAM Processor * select device as PS_INVERTED * Scale = 1 * file = . No track may touch another track that it is not connected to by an airwire 3.18 and 20.
Track layout Rules
1. Note that around your circuit all of the pads on the same net will be highlighted.

A track of 0. now you are stuffed. If they get too hot they will burn up (and smoke and possibly flames will appear). If you want to carry 10amps then go to about 0.04 inch tracks on our boards in the classroom as they print and etch easily. The current grid spacing is shown in the layout window most likely as 0. We almost always make single sided pcbs so its a good idea to put a ground right around the whole circuit board.05 inch.8mils). Forwards and Backwards You must always have your schematic and layout open at the same time. Even though tracks are made of copper and are a conductor. We generally use 0.13. That equals 0.006 ohms per inch will when carrying a current of 4 amps will rise in temperature by around 10 degress which is ok. Also never change the grid size.15 inch to be on the safe side! Grounding The ground connection is a circuit is the path for current back to the power supply. If you want ot start squeezing things together – well don’t especially in your first few boards. this is because IC’s (such as the TDA2822) and other components have legs that are 0. it just makes the boards hard to etch and to solder. There is an example of using polygon fill later on. we will use 0.8 thou – or just to confuse you PCB people often say 2.0028 inches thick (2.032 or 0. This means that as charges move through the circuit the tracks get warm! The thinner they are the higher the resistance and the warmer they get. that means the amount of copper in one square foot of pcb is 2oz. copper thickness and current ratings The board we buy is 2oz (ounces). Then when you open them both Eagle will complain and say that no forward-backward annotation will happen.04 inches width on the boards we use is about 0. it can actually take longer to fix annotation problems tha starting all over again!
182
. Our circuits don’t in general need to carry 4 amps but its good to know this sort of thing.05 inch (50 thou). if you have only one open then any changes you make to one will not appear on the other.5
Extra PCB making information
Grids An important point to note is that the rulers and grids in Eagle are generally in inches. they are not perfect conductors and have some resistance. if you want to see the actual grid. Although when we specify a drill size wew ill use mm. For all layouts we will use inches because that is the spacing of component legs. type grid on.1 inch between centres. Track width. and the bigger and the more of it we can make the better.

The component is placed firmly against the PCB. during soldering they act as a heat sink and keep excess heat away from the component.
Component leads are cut off after soldering. This helps mechanical rigidity. they are not bent flat as then it would be difficult to remove the component later on. (Components would only be put up off the board if during normal operation they would become warm enough to damage the PCB itself)
If there is not enough room to lay the component flat on the PCB then one leg may be bent over.6
Component Forming Codes of Practice
Component leads are bent at least 2 mm away from the component body. not bent close to the body as this would stress the component and reduce its life expectancy.
183
.
Under the pcb the component leads are bent over slightly to hold the component in place during soldering.13.

7
TDA2811 wiring diagram
184
.13.

185
. Under the menu is the tool bar identify the Iso view button (isometric) and click it. 12. identify the zoom extents tool by hovering the mouse pointer over the buttons. Click once on the surface and drag the rectangle upwards along the blue axis into a 3D box. a grey construction point will appear. set up units as shown in this picture. From the toobox select the Dimension tool.13. Close this dialog box 3. 13. then click on the line and drag the new dimension away from the edge to place it. Select the Rectangle tool in the toolbox (the set of tools on the left hand side of the SketchUp window). Your box should be aligned to the three axes and the edge colours should match the axes colours. In the bottom right hand corner the dimensions of the rectangle are shown. Using the push pull tool push the new surface completely away to change your box to one with a sloping front panel. 10. 7. Select the Tape Measure from the toolbox and click on the upper front right corner and then move along the green axis. type 75 as a dimension and press enter. From the toolbox choose the line tool and draw a line between the two construction points. From the tool box. 5. From the same corner place another construction point 50mm down the blue axis. 6. Your rectangle may well have disappeared because you are zoomed out too much. the rectangles surface will change in appearance. Click the nouse mouse pointer once on the origin and move it right and upwards to start drawing a rectangle (do not click again to stop drawing). add dimension lines by hovering the mouse over an edge line (it will change to yellow). Get use to the other zoom controls now and zoom out a little. From the menu select Window then Display Settings and change the Edge Color to By Axis (now you can see whether what you are drawing lines up with the axis you want it in). notice how the cursor snaps to the construction points as it nears them (it also snaps to edges. From the menu select Window then Model Info and then select units.100 and press Enter. 11.8
SKETCHUP Quick Start Tutorial
1. 9. 2. without clicking there just type on the keyboard 200. The rectangle will take on the dimensions you have typed in. In the toolbox identify the Push/Pull tool and then move the mouse pointer over the rectangle. ends and centre points and each has a different colour). 4. type 30 and press enter. 8.

From the menu choose File then Import 3.
186
. Use the TapeMeasure button to mark out the two points for the groove in the centre of the breadboard 5. 4. For example. In the new SketchUp drawing 2. Then draw two parallel lines. 3. Optionally enter a description of the component.13." o Cut opening. Extrude the breadboard 10mm.9
Creating reusable components in SketchUp
Creating a component that you can reuse in other SketchUp drawings is simple if you follow a few simple steps 1. Adding a component to another drawing: 1. Type a name for the component. For example. Select a glue-to alignment. 2. Then right click and in the drop down menu select Make Component. Extrude downwards 3 mm to make the slot 7. if we are to make a breadboard. The most flexible choice for components you want to glue is "Any. create a flat horizontal surface larger than the breadboard to start with (e. a rectangle 165 x 55 mm). o Glue to. You need to view the components in your model. The Create Component dialog box opens: o Name.g. You need a large surface on which to create the component. o Description. From the menu select Window then click Components. 300 x 300mm). 9. 6. 8. Select all of the entities you want to include in the component.g. In the Components window click the “In Model” button (little house). Create the base for the breadboard component (e. you would typically use this option for a window. In the components window right click the component and save it somewhere you can find it again. It should ‘glue’ onto faces of your model. Select the component you want to import 4. 10. Select this if you want the component to cut an opening in the face to which it is being glued.

to make the program lock out other users and wait for the quiz master to press the reset button. We will use  Input circuits  Output circuits  Input code  Output code  Variables  Process code
In this program we will use the concept of Do Loop unitl ….
187
.14 Basic programming logic
Using our knowledge of programming so far we can create a quiz game controller. Here is the full project including using veroboard as a prototyping tool. make sure you understand throroughly everything that is going on. We have some important specifications we need to meet with this program.1
Quiz Game Controller
In this program we will cover everything that has been learnt so far. there is a short beep and all the other users are locked out until the reset button is pressed
14. Specifications When the user presses their button.

4
Quiz game controller Algorithm
Note the addition to the variables table.14. the winner of the round.
190
. we will need to store data in the program.

The decisions about where to connect the LEDs and switches are not really important.5
Quiz game schematic
The circuit for the device has been drawn in eagle.
191
.14. This means that while the programming cable is connected it may interfere with the correct operation of the program. but do take note that three of the switches are connected to the pins used for programming.

I have a 4. Veroboard or strip board is a highly useful pcb for prototyping one off circuits. As per the picture(below left) it is a predrilled board with tracks at 0.5mm drill bit with some tape around it so that I don’t cut my fingers while using it. Don’t use an electric drill just turn the bit by hand so that you cut through the copper track and not the board.1 inch spacing so DIP IC packages and sockets fit exactly.14.
192
.6
Quiz game board veroboard layout
It was decided to use veroboard for the circuit rather than design a PCB. The board (below right) shows where cuts have been made using a drill bit. The copper tracks will occasionally need to be cut in certain places.

Plan the layout of vero board first
193
.

Quiz game Veroboard
194
.

switches and piezo
Remember to cut the tracks between the LEDs so they don’t short cirucuit
195
.
The board power supply lines have been coloured in red and black to make design easier
Remember to cut all of the 10 tracks under the IC so that the pins don’t short out!
A loop of wire soldered onto the board acts as stress relief for the wires going off board to components such as the battery.Points of note when using veroboard
When I start laying out veroboard for a project I first plan it using either software or I place as many of the components as possible onto the board first before I start cutting any tracks so I can move them around before commiting to my design.

' add a timing fucntion that gives players a fixed number of seconds to answer ' a counter that tracks how often each person has won ' .
198
. 200 'make a beep Do 'stay here until reset pressed Loop Until Resetsw = 0 Reset Grnled Elseif Yelsw = 0 Then 'its important to use an elseif Set Yelled 'rather than separate if statements Sound Piezo . 90 . 90 . 200 'make a beep Do 'stay here until reset pressed Loop Until Resetsw = 0 Reset Redled Elseif Ornsw = 0 Then Set Ornled Sound Piezo . 90 .'program starts here Do Winner = 0 'reset the winner flag Do If Grnsw = 0 Then Set Grnled Sound Piezo . 90 ... 200 'make a beep Do 'stay here until reset pressed Loop Until Resetsw = 0 Reset Yelled Elseif Redsw = 0 Then Set Redled Sound Piezo . 200 'make a beep Do 'stay here until reset pressed Loop Until Resetsw = 0 Reset Ornled End If Loop End 'note you could add other features to the device such as: ' having a different number of beeps for each player ' have some indication that the device is on as normally there are no LEDs lit.

g. it is vital to start to learn how not to use them! Here is the do-loop. With a do-loop we are repeating something a number of times that is unknown at the time we start the loop.9
Don’t delay . as they can be used very differently when programming. and we know the number of times before the loop starts.14. in real life we don’t say hammer the nail 5 times. we say hammer the nail UNTIL IT IS IN Do Gosub hammer_nail Loop until nail_height = flat_in_wall
The do-loop is similar to the for-next however in the do-loop we have to remember to write the code to clear the variable everytime we start the loop (count=0) and increment the variable (incr count).
Although they are both looping structures the do-loop is significantly different to the for-next. Take the example of hammering a nail E.
199
.use logic
Delays such as wait and waitms can become real headaches in longer or complex programs. Siren: Siren: For count = 0 to Maxcount1 count=0 Waitus Halfperioddelay1 Do Set Piezo Waitus Halfperioddelay1 Waitus Halfperioddelay1 Set Piezo Reset Piezo Waitus Halfperioddelay1 Next Reset Piezo Incr count For count = 0 to Maxcount2 Loop until count = Maxcount1 Waitus Halfperioddelay2 count=0 Set Piezo Do Waitus Halfperioddelay2 Waitus Halfperioddelay2 Reset Piezo Set Piezo Next Waitus Halfperioddelay2 Return Reset Piezo Incr count Loop until count = Maxcount2 Return Here we aren’t using the do-loop any differently to the for-next I am only showing you how to write the code properly. Here is the siren code rewritten using do-loops so you can see how to structure it. With a for-next we repeat something a fixed number of times.

Do gosub wash_clothes gosub rinse_clothes gosub measure_water_mirkiness Loop Until water_mirkiness < 10 What is the point of washing clothes 100 times.g. We will use do-loop like this in the next solutions. we just wait or do something until we are told to move on. but we don’t know how many times it has to be repeated.Sometimes in a program we want to repeat something. At this stage we are working on simple programs so we can see the consequences of a small delay. in other programs it is not.g.in this loop we are using our own counter to keep track of the time. You must start to think through the consequences of putting a delay within your specific program. We start it at 1000 and then decrement its value until it gets to 0 then we toggle the LED.
If this loop takes approximately 2 uSec (microseconds) to complete and does it 1000 times then it will give a delay of 2 mSec How many times would the loop have to repeat to delay: 1mS ? 10mS ? 1 Second ? 1 Minute ?
In some programs it is acceptable to put in a very small delay. Do Loop Until clear_sw=0 In this case the length of time we are waiting is unknow as we are waiting for a user. when they might only need 50 or they might actually need 200 so we wash the number of times it takes for the clothes to be clean. In big programs the consequences of delays can be very hard to fix!
200
. e. To begin to solve the issue you should understand that a delay routine in a program is simply a loop that repeats a large number of times e. But in a program we may have to wait for some calculation to complete e.g. Now back to the delay issue.

Here is a way of speeding up or slowing down the rate at which an LED is flashing.
Dim count as word Dim delay as word Delay = 1000 do count=delay do if swa=0 then decr delay if swb=0 then incr delay waitms 1 decr count loop until count = 0 toggle led loop
Note that we need to keep 2 variables. A variable is used to count 1mS delays. Now we add to the program the ability for thew user to prss a switch to change the value of the delay. therefore making the flashing rate shorter or longer. There are debounce issues 2. 201
. Perhaps a bigger increment/decrement value might be more useful (instead of incr delay we could use delay=delay +50). Although the main problem is fixed there are some other problems to fix: 1. The resolution (degree of change) of our delay program is not very good if we increase or decrease each time by one. one is DELAY which we increase and decrease using the switches. When you keep incrementing delay eventually it will get to 65535. and another increment will cause it to roll over or overflow back to 0 (an If-then would help you)/ 3. another decrement will cause it to underflow to 65535!(another if-then would fix this) 4. We can use 1mS delays because when a user presses a switch they will always press it for longer than 1mS. Also when delaycount gets down to 0. The other is a temporary copy of it COUNT which is decremented within the loops.

Note that with technological practice (at all levels) students are required to plan. This is seeing a problem as an ordered and organised process of steps. So when writing software students must not write software without spending time planning it first AND keep a record of their work. The process of development of a program should be incremental – don’t try and do everything in one program all at once. however you must move on to the next level and this requires learning about another way of thinking called algorithmic thinking. When the trigger switch is pressed the LED flashes and it makes a siren (using our siren subroutine from the previous programs)
In this first alarm the alarm only sounds while the switch is pressed
Alarm Unit
Alarm_LED Trigger_Sw
piezo
202
. Programs become confused very quickly in this situation. In these next examples instead of presenting a final prototype the process of development is produced from the very simple to the more complex (as complex as we will go with flowcharts).15 Algorithm development – an alarm system
When learning to program students find it straight forward to write programs which contain one simple process and which require a few lines of code. Because of their growing knowledge of computer syntax students generally begin programming at the keyboard rather than with thinking through a problem and using a pen and paper to organise their program.1
Simple alarm system – stage 1
Here is a very simple alarm. All that does is produce loads of errors and even if you fix the errors the software probably wont work!
15. trial and test ideas.

Piezo on portA.3 Piezo Alias Porta.6
203
.2
Alarm System Schematic
Note that the connections.0 = Input Trigger_sw Alias Pina.0 NOTE THE NAMES PORT for outputs PIN for inputs
The next thing to do is to record the configurations for the I/O devices.5 LED on portA. Config Porta = Output Config Pina.15.3 Switch on pina.0 Alarm_led Alias Porta.

Here is one INCORRECT attempt at wiring up the circuit There are several problems with the wiring; how many can you spot?

204

Problems: 1. forgotten the red and black power wires to the breadboard. 2. the LED and resistor dont link on the breadboard. 3. the switch wring is quite incorrect. 4. there is a resistor in series with the piezo.

In this second alarm the IF-THEN has been replaced by a DO-LOOP-UNTIL It is a much tidier piece of code, replacing the If trigger_sw=0 with a do loop until separates the two concepts of waiting for the switch and what happens after it is pressed. This reduces the complexity of the main loop by a layer, 'B Collis 2009 'file: ALARM_2.BAS $regfile = "attiny461.dat" $crystal = 1000000 executing code Config Porta = Output Config Pina.0 = Input Trigger_sw Alias Pina.0 Alarm_led Alias Porta.3 Piezo Alias Porta.6 Const Const Const Const Const Flashdelay = 50 Halfperioddelay1 Halfperioddelay2 Maxcyclecount1 = Maxcyclecount2 = = 200 = 500 350 150

'rate of

'white switch

' first tone 1/2 period second tone 1/2 period 'length of first tone 'length of second tone

Dim Cyclecount As Word 'keep count of number of cycles Dim Sirens As Byte 'wait for trigger switch to be pressed Do Loop Until Trigger_sw = 0 Do Gosub Siren_sound 'flash the led rapidly Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 The problem with this bit of code is that the siren keeps going until the power to the circuit is turned off. This is not very satisfactory. Loop End

208

15.4
In this version we the siren only goes 10 times and then the LED stays flashing.

= 200 ' first tone 1/2 period = 500 ' second tone 1/2 period 350 'length of first tone 150 'length of second tone

Dim Cyclecount As Word 'keep count of number of cycles Dim Count As Byte 'wait for trigger switch to be pressed Do Loop Until Trigger_sw = 0 For Count = 1 to 10 Gosub Siren_sound 'flash the led rapidly Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Next Do 'flash the led continuously Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Loop End The problem with this is that there is no way to reset the system without removing the power from it. All the code realy needs to be inside the main doloop.

= 200 ' first tone 1/2 period = 500 ' second tone 1/2 period 350 'length of first tone 150 'length of second tone

Dim Cyclecount As Word 'keep count of cycles Dim Count As Byte Do 'wait for trigger switch to be pressed Do Loop Until Trigger_sw = 0 For Count = 1 to 10 Gosub Siren_sound 'flash the led rapidly Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Next Do 'flash the led until the reset button is pressed Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Loop Until Reset_sw = 0 Loop 'return to the start The problem with this stage of the alarm project is that the alarm is always on, there is no way to turn it on or off, apart from the power supply.

210

15.6

More complex alarm system

Program for a more sophisticated alarm unit, with 2 switches and 2 LEDs. In this alarm the reset switch been replaced by a set switch which is used to activate and deactivate the alarm.

Initially the two LEDs are off Then When SetSw is pressed the Toggle Alarm_LED to monitor Trigger_Sw program begins and Set_LED comes on waitalittle If TriggerSw is detected Alarm_LED flashes If SetSw is pressed Alarm_LED stops

d If

PROBLEMS WITH THIS VERSION When thinking through this after planning it it a problem was identified. When the alarm is turned on it waits at point A for the SET switch to be pressed. When it is pressed the program continues on to point B where it checks the trigger switch, it is not triggered so it takes the path to the loop until unset at point C where it immediately exits the loop. This is caused by the program being carried out so fast. We need to add a debounce to the reset switch to fix this. So this program is not developed any further but it is kept on file for an important reason. In technology education a record of trialling is essential to developing clear problem solving and leads to good grades.

is released AlarmLed stops flashing ndication that the alarm occurred

212

15.8

Alarm 6 algorithm:

 Initially the two LEDs are off  When Set_Sw is pressed and released A  the program begins to monitor Trigger_Sw  and the Set_LED comes on  If Trigger_Sw is detected Alarm_LED flashes  If Trigger_Sw is reset Alarm_LED keeps flashing  If Set_Sw is pressed and released (D) the Alarm_LED stops NOTE: at point B there is no debounce, this is because we want the program to continue to sense the switch is pressed at point C and then wait for it to be released. Now this is a complex piece of code and really we have gone justabout as far as we should with flowcharts. Later in the book there is another concept called state macines which is much easier for laregr programs! 'file: ALARM_6.BAS 'compiler setups $regfile = "attiny461.dat" $crystal = 1000000 '-------------------------------------'Hardware setups Config Porta = Output Config Pina.0 = Input Config Pina.1 = Input '------------------------------------'Hardware Aliases Trigger_sw Alias Pina.0 'my white switch Set_sw Alias Pina.1 'my green switch Alarm_led Alias Porta.3 Set_led Alias Porta.4 Piezo Alias Porta.6 'use useful name PIEZO not PORTb.3 '------------------------------------'Variables Dim Count As Byte Dim Cyclecount As Word 'keep count of number of cycles '----------------------------------'Constants Const Flashdelay = 50 Const Debouncedelay = 30 Const Halfperioddelay1 = 200 ' first tone 1/2 period Const Halfperioddelay2 = 500 ' second tone 1/2 period Const Maxcyclecount1 = 350 'length of first tone Const Maxcyclecount2 = 150 'length of second tone '---------------------------------------'program starts here Do 213

'turn off both LEDs Reset Alarm_led Reset Set_led 'wait for set switch to be pressed and released Do Loop Until Set_sw = 0 Waitms Debouncedelay Do Loop Until Set_sw = 1 Waitms Debouncedelay Set Set_led 'wait for set switch to be unset and check for alarm at same time Do If Trigger_sw = 0 Then 'sound alarm For Count = 1 To 10 Gosub Siren_sound 'flash the led rapidly Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Incr Count Next 'flash the led until alarm is unset Do Set Alarm_led Waitms 20 Reset Alarm_led Waitms 200 Loop Until Set_sw = 0 End If Loop Until Set_sw = 0 'debounce set switch Waitms Debouncedelay Do Loop Until Set_sw = 1 Waitms Debouncedelay Loop End

214

16 Basic electronic theory
16.1 Conventional Current
Before the electron was discovered it was thought that the movement of charge was from positive to negative. It is common when current is being discussed for conventional current to be meant, that is current will be from positive to negative. If we want to make the difference clear we will say conventional current (positive to negative) or electron current flow (negative to positive)

16.2

Ground

In a circuit we need a reference point for all the voltage measurements, we often refer to this point as ground. At the ground point in the circuit the voltage potential is zero. In a battery powered circuit the negative side of the battery is often referred to as ground. These are the symbols you will see for a ground connection.

16.3

Preferred resistor values

Not every resistor value is made, there are ranges called the E series (Exponent?) This is useful because then not all values have to be held in stock by a company for manufacturing purposes. E6 series E12 series 1.0 1.0 E24 series 1.0 1.1 1.2 1.2 1.3 1.5 1.5 1.5 1.6 1.8 1.8 2.0 2.2 2.2 2.2 2.4 2.7 2.7 3.0 3.3 3.3 3.3 3.6 3.9 3.9 4.3 4.7 4.7 4.7 5.1 5.6 5.6 6.2 6.8 6.8 6.8 7.5 8.2 8.2 9.1 In the E6 series there are 6 values per decade, so the following values are made: 0.1, 0.15, 0.22, 0.33, 0.47, 0.68 1,1.5, 2.2, 3.3, 4.7, 6.8. 10, 15, 22, 33, 47, 68, 100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700, 6800, and so on

215

16.4

Resistor Tolerances

Resistors are not perfect values they are made by machine and therefore have a NOMINAL value which is correct to a reasonable accuracy. Usually we buy 1% resistors for the workshop so they are guaranteed to be close in value. Calculate these tolerances: Nominal Value Tolerance Min value 390R 1% 390 - 1% = 390 - 3.9 = 386.1R 1K 4k7 10K 33K

Max value 390 + 1% = 390 + 3.9 = 393.9 R

16.5

Combining resistors in series

Sometimes it is necessary to put resistors in series to get the value we need. In circuit diagrams we use names for components such as R1, R2, R3, R4 and Rt means the total resistance. (Wherever you see ohms you can replace it with the symbol Ω in your work) 1.
R1= 100R R2=300R Rt =

2.
R1= 10k R2=30k Rt =

3.
R1= 1k8 R2=10k Rt =

4.
R1 = 4k7 R2 = 1K8 R3 = 9K2 Rt = Rt = Rt =

5.
R1 = 2M6 Rt = R2 = 110K Rt = R3 = 330K Rt =

R1 = 1M8 R2 = 720K Rt = R3 = 390K R4 = 180K

6.

216

16.6

Combining resistors in parallel
The current will split between the two resistors, the current in each split will be related to the values of each resistor. The overall effect is the same as if a smaller value of resistance was used.

When two resistors are put in parallel the current has 2 paths it can take.

You need 180R, you have the following resistors choose 2 in parallel that would give the value closest to the desired value: 360R, 4k7, 680R 2k2

217

16.7

Resistor Combination Circuits

When solving these circuits you have to look for the least complicated thing to solve first. This can be thought of as which resistors are in a very simple combination, one that I could replace with a single resistor and not affect the current flow and voltage in another part of the circuit (its not easy and takes a lot of understanding to be able to do this, the yellow colours are hints to help with the first few) 1. R2 and R3 can be replaced by a single resistor that would not affect the current through or voltage across R1 R1 = 10k R2 = 2k R3 = 3k

Rt=

2. R1 and R3 can be replaced. R1 = 4k7 R2 = 8k2 R3 = 1k5

Rt=

3. R1 = 16k R2 = 12k R3 = 18k R4 = 15k

Rt=

4. R1 = 1k1 R2 = 1k5 R3 = 470R R4 = 680R

Rt=

Rt= 5. R1 = 4k7 R2 = 1k8 R3 = 33R R4 = 560R R5 = 330R

218

16.8

Multimeters

To understand how circuits function and to find faults with them when they are not working it is necessary to know how to use a multimeter.

There is a rotary switch to select the correct measurement scale.

If you are measuring voltage in a circuit with a 9V battery you would put the meter scale onto 20V . As the range gets closer to the actual value the accuracy gets better.

219

16.9

Multimeter controls
This multimeter is a common type.
The display has ______ digits. It can display numbers from 0.00 to 1999. There are ________ different positions on the rotary switch. V is for ______ and the ranges are ______________________________ A is for ______ and the ranges are ______________________________ The ohms scale has an ______ symbol. Its ranges are ____________________ _______________________________ There are 3 different sockets for the probes to plug into these are labelled

___________________________________

The hFE selection is for testing ___________________________

COM stands for ___________ and the black/red probe goes into it.

The black/red probe goes into one of the other sockets.

What is the power source for the meter itself? ________________________

220

16.10

Choosing correct meter settings

Selecting the switch position is very important to making accurate measurements. Know what you want to measure voltage, current or resistance.

The second step is selecting the range of the measurement. If an approximate value is known then choose the next higher setting on the range switch. Generally we use 9 volt batteries in our circuits, if you want to measure voltages around a 9 volt circuit then what range would you choose for the meter? ________ If you did not know the voltage in the circuit which range would you choose? __________ Many of the resistors we use are 5 band, very small size and hard to read. What range would be best to choose first on the meter? ___________ What range would you choose to measure a resistor you thought was 91Kohms.________ What range would you choose to measure a resistor with colours red, red, orange, brown? ____________

What is the highest resistance value that can be read on the meter? ________

What is the lowest resistance that could be measured on the meter? ________

When measuring current where would you put the probes and what range would you choose to start with? __________________________________________________________

If no current readings are being shown on the meter it is possible that the ______________________________.

When making a measurement and its value is greater than the scale used the display shows ______________

221

16.11

Ohms law

This a very important formula in electronics. You must be able to use it correctly and develop a comprehensive understanding of its meaning. In a circuit one volt will drive one ampere of current through a one ohm resistor (or when one amp is flowing in a one ohm resistor one volt will be developed across the resistor) The formula is Voltage = Current times Resistance or V

=IxR

If 0.5A is flowing through a 10 ohm resistor then what is the voltage across the resistor? Answer: V=I*R, V=0.5*10, V=5Volts. If the voltage is 10volts and the resistance is 2ohms then what current through the circuit? Answer:I=V/R, I=10/2, I=5A. At 9V, if 0.0019A is flowing through the circuit what is the value of R? Answer: R=V/I, R=9/0.0019, R=4,700 ohms

Calculate the voltage across each resistor Circuit current first. I = V/R =____________ V(1k1) = IxR = ___________________ V(150R) = IxR = _________________ Setup the multimeter correctly and measure the voltages in this circuit.  What was the voltage measured across the 1k1 ________across the 150R _______________

16.12.2

Measuring Current

To measure current in a circuit the circuit must be broken and the meter inserted into it.
       

There are at least two reasons for differences between calculated and measured values in this circuit what could they be? _______________________________________________________ _______________________________________________________

16.12.3
    

Meter Safety

The meter is a delicate instrument handle it with care. Estimate what your measuring first and set the meter range to a larger value( or even to the maximum value), Do not measure resistance in a circuit when the circuit is on. Check the internal fuse is correct before measuring current. Turn the meter off after use.

16.12.4
 

Circuit Safety

Using the meter on a current setting when wanting to measure voltage can easily damage components and even the circuit board. Take care not to short parts of the circuit with the probes.

16.12.5


Battery Life

Switch the meter off when finished using it.

223

or a very low value of resistor is connected.1
In-circuit measurements
When a resistor is unknown or suspected faulty its resistance can be measured using the multimeter on ohms range. When measuring resistors "in circuit" you must disconnect the power. It is very useful for  checking cables are not broken
 
checking that tracks between parts of a PCB are not broken checking that tracks are not shorted together on a PCB
Find 6 items that are good conductors __________________ __________________ __________________ __________________ __________________ __________________ and 6 items that are poor conductors __________________ __________________ __________________ __________________ __________________ __________________
16. To measure resistance the meter puts current through the resistor and measures the voltage across it so current from within the circuit will confuse the readings and the meter or the circuit could be damaged.
all three resistors are measured at once so the meter reads only the parallel combined resistance
224
.16.14.
Can you explain your readings for the second circuit. Measure the resistors in the following circuits.14
Continuity
One range on the meter will beep when the probes are shorted together.

000 R 5. Others are called trimpots and are meant to be varied only by service people when working on the inside of equipment. such as those used as volume controls.000 R 1. are used to change the input to an electronic circuit.000 R 4. and are fitted with knobs to turn them.
For this 10k pot. only the resistance between the centre terminal and both the outer terminals.000 0R
If a lever was attached to the control of a pot what sort of things could be sensed by the circuit?
225
.15
Variable Resistors
Variable resistors or potentiometers. sizes and values as well ‘dual-gang’ (what use is a dual one?)
Some are designed to be varied by the user of the circuit.000 R
5. fill in the missing values from the table
angle 0 to centre 0 30 108 190 270 0R 1. Most pots vary over 270 degrees not the full 360 degrees. these are turned with a screwdriver.
They come in different shapes.000 R 7. The resistance between the two outer terminals does not change.000 R
centre to 10k 10.000 R 10.16.

nF . Look at the capacitor to see what is written on it. Electrons do not flow through a capacitor.000nF to uF 370pF to nF
A B C D E
226
. some in nF and some in pF.000 pF.1uf = 100nF = 100. and it can be confusing until you learn the few simple rules. A capacitors action is to store charges. However when it is written with 3 digits such as 333.000pF
10nf to pf 82nF to uF 2200pf to nF 100. learn the prefixes first.
Convert the following 333 = 33.16
Capacitors
A capacitor is made from 2 conductors separated by an insulator.18
Converting Capacitor Values uF. 2. nano in the middle and pico the smallest and learn how to convert between them. Once the capacitor is full no more electrons can flow.
1. and the last digit will be the number of zeros ( a bit like resistor colour codes) so 333 means 33. micro uF.000. nano nF.000pF
0
0 0 0 0
0
0
0
0.000nF = 1.17
Capacitor Codes and Values
Capacitors not only come in a variety of packages and types but there are also a number of different ways that their values can be printed onto them. they flow onto one plate causing electrons to flow away from the other plate. If it has 10uF or 22n the it is obvious what value it is. Some values are in uF. and pico pF micro is the biggest.16.000pF 330 = 330pF 221 = 470 = 474 =
33 = 685 = 220 = 68 = 276 =
33pF
16. pF
farads
micro
nano
pico
units 1 1 1
u 0 0 1 1 1 0 0 0 0
n
p
0
0
0
1uF = 1. then it will be in pF even though it it not stated.
16.

The value of capacitance is the amount of charge that can be stored. 5V).g. If there is no capacitor close to the IC.1uF cap next to the power pins of every IC to minimise this effect. Many circuit boards have multiple layers of copper tracks inside the board. This acts as a large store of charges.
A common practice in electronics is to have a 0. when moved to the lower position the stored charges will be released back to ground through the LED and resistor. this appears as rapid changes in voltage level or ‘spikes’ in the voltage. it is related to the size of the plates and the thinness of the insulator.
227
. This ability to store charge is absolutely crucial in circuits that need quality power.
Another common practice nowadays is to have large areas of copper on the circuit board connected to ground (0V). it pulls the extra charges it needs from the power supply wires close to the chip. 1 nanoseconds (0. A Capacitor is fully charged when the voltage across it equals the supply voltage. these spikes transfer along the power lines on a pcb and upset nearby ICs as well. The higher the value of the capacitor and the lower the value of the resistor the longer the capacitor will take to discharge and the longer the LED will glow.g.16. In a computer circuit that switches signals at megahertz or gigahertz a lot of power can be required for tiny periods of time e.19
Capacitor action in DC circuits
In this circuit when the switch is in the upper position the capacitor will store the charges on its plates.000000001 second). one of which is ground and another of which may be the power (e.

To understand its operation you must know about ohms law.16. It is used extensively in input circuits.001*5000 Vout = 5V
Work out the solution to the following. Voltage and total resistance are known.
R2 = 1K
I= Vin/Rt I = 9/ (4000+ ________) I = ___________ Vout = I * R2 Vout = ________ * 1000 Vout = R2 = 4K I= I= I= Vout= Vout =
R2 = 8K I= Vin/Rt I = _____________________ I = ___________ Vout = I * R2 Vout = ________ * 1000 Vout =
Vout =
228
. The output voltage is the voltage across R2. Step 1. so Vout = I*R2
With 9 volts across both resistors then: I = Vin/Rt I = 9/(4000 + 5000) I = 9/9000 I = 0.20
The Voltage Divider
The voltage divider is is one of the most important circuits in electronics. so I = Vin/Rt Step 2: R2 and Current through R2 are known.001A across the 5k resistor Vout = I*R2 Vout = 0. Below is a 2 resistor voltage divider circuit.

They now come in all shapes and sizes.21
Using semiconductors
Semiconductors are the group of electronic components responsible for everything smart that electronic circuits do. they take on fantastic features when mixed with other material.
Since the first transistor was developed in 1947 they have come a long way. which is itself a very poor conductor. from miniature surface mount packages to large high power packages.16. Made mostly from the semiconductor silicon. switch.
They amplify. and control every conceivable process
all over the world
229
.

g. The resistor in series with the LED functions to limit the current through the LED.  AN LED requires a small forward voltage e. _____V across it to operate.  Choose the closest value from the available values of resistors.  The resistor will have 9V . however the circuit is powered by a 9V battery.22
Calculating current limit resistors for an LED
In the amplifier circuit there is an LED to indicate that power is on. If two LEDS were placed in series what value of resistor would be required?
230
.  Ohms law will assist with this calculation. this current goes through the resistor so  the resistor will need to be R = V/ I = ______ / ______ = ______ ohms.16.  An led draws about _____mA of current. The rest of the battery voltage must be dropped across the resistor.____V = ____V across it.

Small variations in the base voltage Vbe can create large changes in the collector current Ic.
Transistors are amplifiers.
The small voltage across the base is called Vbe .23
The Bipolar Junction Transistor
There are thousands (millions?) of different types of transistors made by different manufacturers all over the world.
The BC547 transistor is just one of the many different types of BJT transistor. a base and a collector. and they come in all shapes and sizes.
231
.6V to 0. a small voltage across the base-emitter junction (the small arrow in the transistor symbol) will control the current (the large arrow) from the emitter through to the collector. there are also PNP transistors the BC557 is an equivalent PNP transistor .16. the current through the base caused by this voltage is called Ib. The voltage required across the base of the transistor (Vbe) is normally around 0. Transistors are semiconductor devices with three leads: an emitter.7V when it is fully conducting. We could have used a BC547 instead of the 2N7000 FET for the darkness detector. The correct name for the usual transistor is the BJT or Bipolar Junction Transistor. The BC547 is an NPN transistor. And the current through the collector is called Ic.

26 Transistor amplifier in a microcontroller circuit
We often use a NPN transistor in our circuits so that the microcontroller can control low to medium power devices such as small motors or lots of LEDs
232
. this is the ratio of base current (Ib) to collector current (Ic).16. Transistors have limits to the voltages and currents applied to them in circuits.25
T0_________
Transistor Case styles
T0_________ T0_________
T0_________
16.24
Transistor Specifications Assignment
Transistors have current gain (hFE). If Ib is 2mA and Ice is 100mA then the gain is said to be 100/2 = 50. They should not be exceeded. if you try to draw too much current from the collector then it will most likely overheat and burn up Look up the specifications for the following transistors in a catalogue BC547 Type NPN Case T092 IC (mA) 100 mA Vce MAX 45 V hFE (gain) 110-800 PTOT (power) 500 mW BC557 BC337 BC327 BD139 BD140 TIP41C TIP42C 2N3055
16. If the voltages across the base or collector are too high then the transistor will most likely blow up internally.

Audio signals such as voices are not single waves but complex waves of many frequencies each of differing amplitude as in the picture below.16.
When amplifying audio through a transistor amplifier the frequency should not change but the amplitude will. (In a single transitor circuit the signal is inverted. but that doesn’t really make any difference to what we hear)
This transistor circuit is setup to amplify small audio signals (it is not a very high gain/amplification circuit) A lot of components are required to control the transistor circuit so that it doesn’t distort the audio signal.
233
.27
Transistor Audio Amplifier
Audio signals are not DC like that in a microcontroller circuit they are alternating current (AC) signals. AC is measured in frequency (number of cycles per second) and amplitude (size).

They also have a power rating e. and tweeters (high frequencies).16.g. mid-range speakers (middle frequencies). a speaker will change the audio signal from an amplifier by moving the cone of the speaker rapidly back and forth vibrating the surrounding air.
Speakers come in various types each with specific frequency ranges they can reproduce: subwoofers (very low frequencies).25W. Speakers have a resistance and typical values are 4 or 8 ohms. woofers (low frequencies).28
Speakers
Sound is vibrations of air particles. 100W.
234
. If you connect a speaker directly to a battery you will destroy it (no smoke or explosion just a dead speaker). 20W or o.

org As you go thorugh the various stages of developing a project.
236
. such as:  action plans  Gantt or PERT charts  timelines  goal/target setting  keeping a journal  publishing a website  stakeholder surveys and questionnaires  emails  spreadsheets  mind maps  presentation software  drawing software  surveymonkey  CAD and PCB design software  Block Diagrams  Schematics and Layout Many planning tools can be found at www. it requires students to undertake a full development process of planning. design.17 Basic project planning
The development of a technology project requires much more than the making of a working prototype.visual-literacy.mind-tools.com or www. A great number of tools are available for use when planning and executing the development of a project. review and use of these tools will count towards your grades. your effective selection. client and stakeholder liaison along with much modification to develop the prototype that meets a clients’ needs.

1
System Designer
System Designer software was developed to help students both design and manage their project. it contains various different types of drawings that will be used during development of a prototype
237
.17.

Next create a Timeline – go back and modify the mind map diagram (and use the auto create timeline function) a. Flowcharts/Subroutine diagrams a. Then develop a System Context Diagram a.-This will also be an iterative process so keep different drawings for different options 5. Veroboard and selected development boards. 7.1. Next create a System Block Diagram a. Larger systems will need a State Machine Diagram and possibly some subroutines b. This diagram will help you to think about the different stages required when developing your project. This diagram shows your system from the outside.17. An Algorithm is a written explanation or set of instructions that describe the functions the microcontroller program will carry out. First create a Mind map for the project a. Use the toolbar along the top to create various diagrams.1
Creating a new project. A board layout can be used to plan the layout of components onto breadboard. In this diagram you can begin to plan the processes and resources required to develop the prototype. A state machine is a very common diagram used in designing software for embedded systems
238
. Keep different diagrams for the different stages and changes you go through 3. In this diagram you can visualize the internal subsystems within the device. State machines a. The process you go through may vary but here is a guide to follow initially: 1.
It is essential that each project is saved into its own folder. 8. Note that a board layout will not be required if a PCB was designed specifically for the project 6. as a unique file for each diagram within System Designer is created. Initially there may not be much in the diagram as the planning cannot really be undertaken fully until after the system is designed 2. 4. all of the internal workings of it are hidden. Smaller systems can be designed using a Flowchart and as many subroutines as required. Add an Algorithm a. A Board Layout can be created next a. b. b. This will take several iterations (cycles of development) b.

1. Some components are the same in each diagram though
17.1. links and backgrounds of each diagram
239
.17.2
Toolbars
The toolbars in each diagram contain tools to add specific components to each diagram.3
Context Menus
Many features of diagrams are accessed through right clicking on the components.

17. or copy as an image to the clipboard so they can be copied into another program.5
Pan diagrams
Press the mouse wheel button to select the diagram to move (pan) it around.1.Zoom diagrams
Use the mouse wheel or the buttons on the toolbar
240
.1.6
.17.1.4
Selecting items to copy them
Press the ctrl key and click and drag over portions of the diagram to select it. so they can be pasted into another diagram. Then right click on the selection to decide whether to copy them to the clipboard.
17.

17. 241
. Students can develop their own diagram or use the example project milestones (and modify them)
Colours and other details can be changed by right clicking on the milestone or background.2
Project mind map
This diagram is a simple brainstorm of the milestones (major stages) required to develop a project from an issue right through to a working prototype.

242
.
17. (0.3).1
Milestone duration
At each milestone if the number of weeks is added in brackets it can be copied thru to the timeline Values include part weeks e.g.
The form that opens will automatically start from the beginning of the current year.2.2
Automatic timeline creation
Once the milestone stages have been decided upon a timeline can be automatically created using the milestone colours and weeks values from the mind map.2.17.

3
Project timeline
In the timeline diagram milestones can be drawn (if not already created automatically from the mind map). Double clicking on a milestone allows it to be edited. 243
.17.

first resize and move the tables around the diagram and also change the zoom level to obtain the view wanted.1
Milestone Planning
A milestone is made up of several planning steps as well a review of progress ad reflection at the end of it. The following information is required by the planning standard: actions.
244
.3
Critical review points
Each milestone in the project will have critical points associated with it that will need to be overcome so that they don’t stop you from reaching the next stage and subsequently the final goal of finishing your project.3. Take time to complete these as thoroughly as possible. As well as the information required from them. resources. using the button on the toolbar. research. The tables can be resized and moved around the diagram to create a better layout for exporting.3. expertise. The visible portion of the diagram can be copied to the clipboard for pasting into a word or other document.3. You need to identify these and comment on them.4
Copying Timelines to put them into your journal
To export a timeline to another document such as Word etc.
17.
17.
17. equipment.2
Stakeholder Consultations
It is important to identify the points in your project where different stakeholders will have to be consulted.3. and budget.17.

all we know about it are its inputs. A context diagram shows how your prototype interacts with users (called ‘actors’ in the programming industry) and its immediate environment.17. Think of the prototype as a 'black box'. planning.4.4
System context diagram
Although you are developing a prototype (product/outcome). functions. No detail about the inner workings of the prototype is required. outputs and attributes (physical characteristics.
17.1
First step is to create a main system device
245
. The system context diagram is to recognize that your prototype is a subsystem within its larger context/environment. the system context diagram will provide evidence for the following standards: modeling. systems. and prototyping. qualities and features) A system context diagram is also an essential tool in writing an initial brief as it helps to document stakeholder requirements As well as this. you need to see it as both a system and a subsystem (smaller component of a larger system) with all the associated inputs and outputs. brief writing.

17.2
Add attributes to the device
Use the rectangle and circular buttons on the toolbar to add physical attributes to the device (right click on an attribute to change its shape) Give the device and all its attributes useful names.4.
246
.

4. (these are things not contained within the device itself.3
External sensors and actuators
Add any external environmental sensors or actuator outputs.
247
. note that the devices are not hardware specific names like ‘LM35’ but ‘water temperature sensor’. These are useful for stakeholder consultations and identify the information the sensor gives.17.

cellphone have normal users and technicians which have access to extra features). Some systems have different categories or levels of users (normal and special e.g.4
User interactions with the system (social environment)
Add a normal user .how will this user interact with the prototype (input things into it and be alerted by it).
248
.4.17.

also the cellphone must not have a negative effect on the clothing it is kept in. cellphones are kept in the pockets of clothes.g. e.
249
.5
Physical Environment
Each product exists within with a physical world that forces certain things upon it. In the bathtub controller the device will be inside but near water.17.4. what influence does this have on their design.

6
Clients and stakeholders
Add stakeholders to the diagram.4.
250
. at this stage you can discuss the diagram with the client and other stakeholders to make sure that their needs have been fully documented.17.
If you change the design after speaking with the stakeholders keep a record of the old design or even start a new system context diagram within your project. The reason for keeping ongoing changes will be to show you iterative (ongoing) planning and proof of stakeholder consultation.

Describe the physical attributes (characteristics and features) of the system.17. Why is the device to be created? b.7
Conceptual statement and physical attributes
1. 3 sentences is usually enough a.
251
.4. What is it? c. Write a conceptual statement. Why do it? 2. the function of the system (functional attributes) need not be described here as they will be thoroughly covered in later drawings.

Take note that the communication between these two devices in this system is in one direction only. In some systems it will be bidirectional.17.4. 252
.8
Secondary system devices
If the system includes external devices you have to develop as well then add another system device.

17.4.
253
.9
External system connections
Some systems interact with external systems such as if the bath tub controller was to send a signal to the home alarm system.

254
.In this system context diagram a fish tank controller is linked to the internet.

and then a written version of it can be produced by clicking on the ‘Written brief’ button in the toolbar. This text document can then be expanded to include more detail
255
.10
Export diagram to written documentation
Once the diagram is completed it can be checked with stakeholders for its accuracy.4.17.

A block diagram allows you to plan where interfaces will be connected before you do the connection. using blocks to represent subsystems within the device.
A system block diagram reveals the inner secrets of your prototype. 256
. allowing changes to be made. Start by adding the microcontroller you are using and right click on it to edit part numbers etc. Note that some specific detail is hidden and will be found in a schematic (circuit diagram).17.5
Block Diagram
In this diagram you need to develop the design of your product as a system itself.

LEDs. an LCD. piezo.Then add things that it might have. inputs and variables that are created. You do not show the current limit resistor. buttons. Make sure that links between the micro and inputs/outputs are made in the right direction either coming in to the micro or out of it. The detail about port connections is useful in developing the setup program code for your program.
257
. so an LED subsystem is created by just adding a circle and calling it red led. These will be modified in later diagrams. Sometimes it may be a good idea to have two separate block diagrams. Blocks are used to represent parts of the circuit. Use the rectangle and circular buttons and other shapes to add to the device. On the right hand side of the diagram are tables that list the outputs. By clicking on the Basic Code button in the toolbar the program code to form the setup area in your program will be automatically generated. detail for that will be in the schematic. one for I/O (input and output) devices and a second for the power supply (it just makes it easier to separate the two parts of your design).

(also If a schematic and PCB have been developed using a program such as Eagle then a board layout may be useful as you can create your own background using your layout from eagle and add I/O devices to it yourself) Planning your layout before you start soldering is a really good use of time. it’s a lot easier to change the diagram than your physical board!!
258
.17.6
Board Layouts
If you will be using breadboard or an existing development board then completing a board layout drawing will be a useful planning tool.

1
Backgrounds
Start by selecting the background image for the drawing.6.
259
.17.

6.17.
260
. then right clicking on them will allow you to change features.2
Add Components
Components can be added by clicking on them in the toolbar.

17.6.3
Add your own pictures to the layout
Here a servo has been added to the layout and the 3 pin header for it to connect to
261
.

Again no spaces and the underscore separates the category from the image name 5.gif 2. If a component doesn’t appear then check your spelling! 8.gif 6. There can be no spaces in the file names 3. Capacitor_Electrolytic_10uF.17.gif a. If you create a component type but forget to create the icon then it will not appear 7. If a component is to have a text value it can be added to the component name with another underscore a.4
Create your own backgrounds and components
The software is flexible enough for you to add your own backgrounds automatically. The name must be capitalized the same background is NOT the same as Background b. The images can only be of type . Have fun
262
. The naming must be with an underscore between the category name and the word icon 4.6. Background_SmallVeroboard. Background_icon. Each image must start with the same category name e.g. Open the installation folder and find the folder named layout images
1.g.gif a. Each category must have its own icon e.

767) LONG (uses 4 bytes of memory . dim X_position as byte.483. Pseudo-code is when an algorithm is written down using 'sort-of' program code commands.483.values can be positive and negative fractions as small as 5.648 to +2.147. before you start programming • As well as reading inputs and controlling outputs your programs use.g.0x10^-324 up to 1. • e.g. Stage 1: determine the initial states of each output device.5x10^-48 up to 3.values can be positive and negative fractions as small as 1.147. create and change data.values can be any whole number from -32. • This means dimension (allocate or set aside) 1 byte of ram and in the program and from now on the location can be called X_position To make the use of ram as efficient as possible different variable types exist. 1 character takes up one byte of ram) e. • What data will your program be processing? • The data is stored inside the microcontrollers RAM (memory).g. • A variable is the name given to a location in RAM.7
Algorithm design
Algorithms are well defined instructions for getting the microcontroller to do something. If you can solve the problem on pen and paper with an algorithm then you can write a program that will solve the problem.647) SINGLE (uses 4 bytes of memory .(right click on the row you want to moidify in the outputs table) • e.values can be any whole number from -2. will LEDS be on or off when the power is turned on • what will a display show • will a pump. motor or relay be on or off Stage2: Data storage (cariables) – you need to specify these at this stage.values can be any whole number from 0 to 255) WORD (uses 2 bytes of memory .4x10^38 DOUBLE (uses 8 bytes of memory .values can be any whole number from 0 to 65535) INTEGER (uses 2 bytes of memory . Why write an algorithm (either using pseudo-code or flowcharts)? Because it helps you solve the problem and you need to do this before you start programming.7x10^308) STRING (uses ascii code to represent letters and digits. Algorithms can also be designed using diagrams such as flowcharts or state machines as well as several others. dim my_name as string * 10 can store up to 10 characters only! the largest string you can have is 254 characters 263
.768 to +32. BIT (uses 1 bit of memory .values are either 1 or 0) BYTE (uses 1 byte of memory .17.

must start with a letter.When choosing a variable to store data think about the right type to use (so as not to waste memory). retrieving data.535) Calculate the difference in milliseconds between 2 dates – Dim millsecs_diff as long Dividing numbers requires decimals. But make sure you choose one that gives you what you need. such as: o Read the temperature (input) o Close the door (output) o Keep the last 2 temperature readings (data storage) o Read the humidity (input) o Move the arm up (output) o Keep the last 2 humidity readings (data storage) o Read the distance from the infrared sensor (input) o Find out if we need to open or close the vent o If the second temperature readings minus than the first is > 2 then open the vent (calculation) o Find out how long to turn the fan on for (calculation) o Open the window (output) o Display the time (output) o Tilt the deck (output) • In each calculation add some maths or logic about what your program will do using the IF. NOT o IF the blue switch is pressed AND NOT the red switch THEN make the led flash (logic) o IF the blue switch is pressed AND the end is NOT reached THEN X_position = X_position + 4 (calculation and logic) • Repetition o DO increase X_position UNTIL end is reached (uses calculation) o WHILE the temperature > 5 flash the led (uses calculation)
264
. AND. Does your variable need to store both positive and negative numbers? Whole or fractional numbers? Big or small? Variable names cannot have spaces. OR. WHILE. can contain digits but not symbols. repeating actions and driving outputs.Dim outside_temperature as byte (is within the range 0 to 255) Temperature range is from -30 to 12 – Dim freezer_tempr as integer (needs to store negative numbers) Angle to move is from 0 to 360 – Dim move_angle as word (positive whole number from 0 t 65. DO. Dim percent_of _day as single
Stage3: Decomposition • Break up your problem into small solvable chunks • The conceptual chunks should separate between: reading sensors. doing calculations. storing data. • Examples Temperature range is from 3 to 40 degrees .

8
Flowcharts
System Designer software includes a flowcharting feature which can be used to graphically explore programming concepts.17. 265
.

269
. note it is not a full circuit or schematic diagram. Make sure links between I/O devices and the microcontroller go inthe right direction. but is still in some conceptual form.18.2
Hot glue gun timer block diagram
This reveals detail about the inner physical attributes or characteristics of your product.

Describe the algorithm – how the device responds to user input and computations it must carry out. At the same time begin to identify any data the program will need and give these variables useful names. 3.18. Start by identifying the initial states of any outputs – on or off in this situation 2. 1.3
Hot glue gun timer algorithm
Here the functional attributes (characteristics and features) of the product are revealed.
270
.

18.4
Hot glue gun timer flowchart
A flowchart is a visual algorithm for a simple system
Intepreting the algorithm:
Initially: OFF_LED = on ON_LED = off GLUE_GUN = off
Wait until START_BTN is pressed
OFF_LED = off ON_LED = on GLUE_GUN = on Zero the counter
Wait 10 ms Increase counter by 10
Check the switches -If start pressed reset count to 0 to restart the timing for another hour
-If stop pressed set count to max so looping stops
Repeat until the time has reached 1 hour
271
.

272
.2 = Input Config Pina.dat" 'hardware setup Config Porta = Output Config Portb = Output Config Pina. Tthere is no debouncing of the switches.5
Hot glue gun timer program
' GlueGunTimerVer1.3 'Dimension variables Dim Mscount As LONG 'need a variable that can hold a really big number Const Max_mscount = 3600000 'program starts here Do Set Offled Reset Onled Reset Gluegun 'initially off Do Loop Until Startbutton = 0 Reset Offled Set Onled Set Gluegun Mscount = 0 'wait for start button press
'glue gun on 'start counting from zero
'note the use of a do-loop rather than a for-next to count the repititions 'we do this because it is unknown when the user will push a button and reset/restart the count Do Mscount = Mscount + 10 'add 10 to milliseconds Waitms 10 If Startbutton = 0 Then 'Check Switch Mscount = 0 'reset time to zero.bas ' B.600. We wait 10mS – we could wait 1MS however 10mS is not so long that we would miss the switch press 2.18.2 Stopbutton Alias Pina.5 'names easy to read and follow Offled Alias Porta.7 Startbutton Alias Pina.000 times unless user changes mscount Loop Notes: 1.3 = Input 'Alias names for the hardware Gluegun Alias Porta.6 Onled Alias Porta. this is not really needed in this program because repeat switch presses don’t cause any problems for us. so restart timer End If If Stopbutton = 0 Then 'Check Switch Mscount = Max_mscount 'set time to max. so cancel timing End If Loop Until Mscount > Max_mscount 'loop 3.Collis 1 Aug 2008 ' 1 hour glue gun timer program ' the timer restarts if the start button is pressed again ' the timer can be stopped before timing out with the stop button 'compiler setup $crystal = 1000000 $regfile = "attiny461.

Switches
Analogue to digital conversion using
LDRS Boosting the power output
and Thermistors
to make sound
and drive small inductive loads
Parallel interfaces to Liquid crystal displays and multiple seven segment displays
Serial interfaces to Real Time Clocks and computer RS232 ports
273
.19 Basic interfaces and their programming
Having completed some introductory learning about interfacing and programming microcontrollers it is time to learn more detail about interfacing.

A bus is often 8 bits/wires (byte sized) however in systems with larger and more complex microcontrollers and microprocessors these buses are often 16. They all share access to the data. these are groups of wires. So data can move fairly fast on a parallel bus.
274
.535 and 32 bits can carry numbers/codes from 0 to 4. Only one printer can be connected to the parallel port on a computer.967.295.1
Parallel data communications
Both internal and external communications with microcontrollers are carried out via buses.19. however within the computer itself all the devices on the bus are connected all the time to the data bus.294. because of this speed. This is efficient as an 8 bit bus can carry numbers/codes form 0 to 255. however only the device that is activated by the address bus wakes up to receive/send data.
Communication is carried out using 8 or more bits at a time. a 16 bit bus can carry numbers/codes from 0 to 65. 32 or 64 bits wide. Parallel communication is often used by computers to communicate with printers.

Monochrome alphanumeric LCD wirh no backlight
4 line alpahanumeric mono LCD with backlight
Mon graphic lcd 128x64 pixel
Colour graphic LCD 320x128pixel.19.
275
. Some LCDs which are made for specific purposes with fixed Characters such as these two. alphanumeric/graphic. Colour/Monochrome.2
LCDs (liquid crystal displays)
There are a great many different types of LCD available. we describe them by there various attributes.

D7 15.3
Alphanumeric LCDs
One of the best things about electronic equipment nowadays are the alphanumeric LCD displays these are simple single.will display hello on the display  locate y. These displays are becoming cheaper and cheaper in cost. with 4 bit operation the data/command is split into 2 parts and each is sent separately. E . R/W.Enable 7. D1 9. E. double or 4 line displays for text and numbers. They fit the need for student learning in technology education very nicely.
276
.register select 5. RS . 0V 2. Hence it takes twice as long.line and position on the line of the cursor (where text will appear)  Cursor OFF – hide the cursor (still there but invisible)  LCD temperature – will display the value in the variable temperature on the display Connecting an LCD to the microcontroller is not difficult. D2 10. When using Bascom the R/W line is connected permanently to griund. Some common commands are  cls . D4 12.x . +5V 3. RS . Apart from the 4 data lines another couple of lines are necessary. R/W . D0 8.read/not write 6. D5 13.clear the screen  LCD "Hello" . and the other two lines need to be connected to the micro. At the current time the contrast line can be connected to ground as well. these are control lines. The faster system is 8 bits as all the data or commands sent to the LCD happen at the same time.alibaba. we buy them in bulk from China using www.19. Backlight 0V (optional) Most LCDs are set up so that they can communicate in parallel with either 4 bits or 8 bits at a time. The LCD is a great output device and with Bascom so very easy to use. D3 11.com. The advantage of 4 bit operation is that the LCD uses only 6 I/O lines in total on the micro. Contrast 4. D6 14. Backlight + (optional) 16. There are 14 or 16 pins on the LCD 1.

trying to use a breadboard to connect an LCD is not easy. It makes use of a standard 2 line 20 character alphanumeric LCD. Here is a development PCB that was designed to be useful for students when building their circuits. it also made the PCB much easier for students to solder not having so many thin tracks.4
ATTINY461 Development PCB with LCD
Although a breadboard was useful earlier for some introductory learning about connecting a microcontroller and interfacing simple components such as LEDs and switche. These are left unconnected so that students become familiar with the connections.
277
.. It is more useful to have a circuit board of some description. It has a 16 way connector (although the LCD used has no backlight so only 14 connections are used)
In the schematic we have connected the power to the LCD but not actually connected the control lines. you just end up with too many wires that fall out of the breadboard if the LCD gets moved.19.

Top or Component view
Take care when wiring the header pins (connector) for the LCD as he polarity for the power must be correct.The physical pcb is designed around the physical dimensions of the LCD. so that the LCD and board can be bolted together. there is a an area for prototyping other circuits on the board PCB tracks view from Eagle
278
.

3.3 . Db4 =Portb.4. They are on the same port and 2.19. The 6 connections have been added on the diagram below. To program the LCD using Bascom we need to add two lines of configuration program code.5
Completing the wiring for the LCD
Here are the details for the specific Sure Electronics LCD we are using. Db5 =Portb. The 4 data lines are DB4 to DB7. and then use specific commands to make the display show something
Config Lcdpin =Pin . E =Portb.1 . The two control lines are RS(register select) and Enable.2.6 .
Looking at the development board it can be seen that there are already pads for the LCD.5 are already connected via PCB tracks). Rs =Portb. Db6 =Portb. the order used matches the configuration command in Bascom. Db7 =Portb. The order the 6 lines are connected from the LCD to the micro does not matter as long as 1. Highlighted are the 6 data and control connections we need to make (note that pins 1.3 .0 Config Lcd = 20 * 2 'configure lcd screen
279
.

there are two more pins on the LCD for power (5V-VDD and 0V-VSS) and one for adjusting the contrast or viewing angle (VO or VEE). HThe voltage divider here is made up of both fixed and a variable resistance. If the trim pot was 10k and the resistor was 47 k then the voltage for the contast would be
280
.6
LCD Contrast Control
In addition to the 4 data lines and the 3 control lines. Check the displays’ datasheet to find out what is required for VO however for almost all modern alphanumeric type LCDs the voltage is often very close to 0V so can be connected to 0V directly.19. You can connect via a potentiometer or trimpot so that it is adjustable as in this circuit.

step -1 Locate 2. position ‘move cursor Lcd “ “ ‘blank lcd Next For Position = 16 To 1.1 Lcd “ “ Locate 2. This is perhaps the essence of computer programming.8
Repetition again .3 ‘third posistion Lcd “Hello” Waitms timedelay Locate 23 Lcd “ “ … . This is only one of several looping commands which all do similar (but not exactly the same) things. If you want some text to move across an LCD then you could do it the long way Do move cursor to position 1 Locate 2.the ‘For-Next’ and the LCD
This command makes programmers life easier by allowing easy control of the number of times something happens.2 Lcd “Hello” Waitms timedelay Locate 2. position ‘move cursor w Lcd “Hello” ‘display text Waitms Timedelay 'wait a bit Locate 2.
282
.. Loop
move cursor to position 3 put text on screen wait move cxursor back to postion 3 put spaces on screen
OR the smart way Do For Position = 1 To 16 ‘ Locate 2.19. getting the computer to do repetitive work for you.. position ‘move cursor Lcd “world” ‘display text Waitms Timedelay 'wait a bit Locate 2.2 Lcd “ “ ‘second position
move cursor to position 2 put text on screen wait move cxursor back to postion 2 put spaces on screen
Locate 2. position ‘move cursor Lcd “ ” ‘blank text Next Loop End 'end program
position = 1
move cursor to position put text on screen wait move cxursor back to postion put spaces on screen
incr position
N
position = 16 Y
Identifying where and how to use loops in your programs is an essential skill to practice lots when learning to program.1 ‘first position put text on screen Lcd “Hello” wait Waitms timedelay move cxursor back to postion 1 put spaces on screen Locate 2.

You need to separate the two things going on here in your system The first is the process of counting: 1.1.4.5.… And the second is the output code LCD count. 1 'blank the digits we are going to use before using Lcd " " Locate 2 .20. 1 Lcd Count Waitms 1500 Next Loop Try this out on your LCD.2. Now here is a really important conept you need to understand.6…18.When you run this program you will see there is a problem with the displaying of the numbers The zero stays on the LCD whenthe counter goes from 20 back to 1 again. it puts the variable count onto the LCD if countis 1 digit it writes 1 digit. When we say LCD count. So it looks like 10 but its actally only 1
Of course 6 looks like 60
So you need to know how to clear some digits on the lcd and you also need to know how to apply it logically to each problem you encounter like this. These are two very separate things. So the first time through the loop is does this
But after it has displayed 20
It goes back to 1 again and the 0 is stuck on the LCD. 1 Lcd Message1 For Count = 1 To 20 Locate 2 .3. does the counting on the look nice or not. Fix 1: In this case we are displaying 2 digits so we could do this in our program Do Locate 1 .3.2. The program doesn’t care what is on the LCD already it just overwrites it.
284
.19. if count is 2 digits it writes 2 digits.

1 Lcd Count Waitms 1500 Next Loop
These ideas are repeated in different conexts in the next few sections to help you get used to them. 1 Lcd Count If Count < 9 Then Lcd " " Waitms 1500 Next Loop Note in my fixing of this probelm that I didn’t even consider using CLS in my loop.Fix 2: add an extra space to the end o fthe count like this Lcd Count . 1 Lcd Message1 For Count = 1 To 20 Locate 2 .
285
. 1 Lcd Count . and if you are displaying anything else on the LCD then it might overwrite it. " " Waitms 1500 Next Loop This code has a hidden problem. Fix3: only fix exactly what we want to fix In this case when there is 1 digit blank the unused digit on the LCD Do Locate 1 . when the count is over 9 it takes up not 2 but three digits on the LCD. 1 Lcd Message1 For Count = 1 To 20 Locate 2 . this is because these LCDs are so slow that using a CLS in a loop causes the whole display to flicker a lot and it looks aweful – to prove this I suggest you try this solution! Do For Count = 1 To 20 Cls Locate 1 . " " Do Locate 1 . 1 Lcd Message1 Locate 2 .

Second I will solve the leading zeros. Also the clock is quite inaccurate.e.
Do ‘display the time Locate 1 . it is if the minutes are less than 10. 11 Lcd Seconds Wait 1 Incr Seconds If Seconds > 59 Then Seconds = 0 Incr Minutes End If Loop End
'end program
Now you can write the rest of the code to sort out minutes and hours. 289
. Some of this can be fixed by checking how accurate the clock is over a day and changing wait 1 to waitms something. 8 Lcd Minutes Locate 1 . the clock will also need some more code so that you can set the time. Think about when we want a leading zero. 5 Lcd Hours Locate 1 . 5 Lcd Hours Locate 1 . ’fix the time If Seconds > 59 Then Seconds = 0 Incr Minutes End If Loop End 'end program
Note that when an if-then has only one command it can go on the same line and we don’t need the end-if. There is no ‘leading 0’ before any of the numbers i.. 5 is shown not 05 Firstly lets solve the 59 going back to 0
Do Locate 1 . There is a third issue. This wont really fix the issue but it will improve it. you can check this by monitoring the time over a few minutes. The clock goes up by 1 second. A better solution is later in the book. however it doesn’t go from 59 back to 0 2. 8 If Minutes < 10 Then Lcd "0" Lcd Minutes Locate 1 .Here is what the display looks like at the start (using the simulator)
There are two big problems to solve with this program: 1.. 11 Lcd Seconds ‘increase the time Wait 1 Incr Seconds ’add code to read switches and set time ’.

470. two LEDs and a piezo added to it. The schematic above shows the series connections of the LED. Wire them up and add your changes to the schematic.19. note that the LED and resistor canbe reversed in order but that the polarity of the LED must be the same. We have not chosen a specific I/O pin at this stage. 4. Note that when this board was made an area around the outside of the board was left with holes for stress reliefing wires that go off the board. Decide what you want to add and find out the correct wiring connections for it 3.
Using this board we can add other components such as LEDs. The process for adding these components is: 2.
First stage: add an LED An LED requires a current limit resistor of about 1k in series with the LED (it could also be another common value such as 390.560. Find the most convenient place for them to connect to on the board. switches and a PIEZO. 820 – changing the value will make the brightness change). Now we will look at how to add these components one at a time.13
Adding more interfaces to the ATTiny461 Development board
Here is a board with two switches.
290
.

the positive anode) of the LED (white wire) is connected to the pin of the microcontroller. What is the voltage on the micro when the switch is open? What is the voltage on the micro when the switch is closed?
291
.0 and PortA.1 were chosen. when they are in series between VCC and ground. So be very careful and make sure that the resistor goes from the pin to VCC and the switch goes from the pin to ground
In the diagram only one switch and pullup resistor are shown however 2 switches and their 2 pullup resistors are shown in the picture.
Adding 2 switches – each switch requires its own pullup resistor
This is a circuit that students initially get wrong very often. Here PortA.
The negative(cathode) of the LED (blue wire) is connected to a resistor. they connect the switch and resistor in series from the pin to gound. the other side of witch connects to ground.Stage two find the best I/O pin to use An LED can be connected to any available I/O pin so in this case it was easier to choose the pin based upon where the LED was to be mounted and then select a close I/O pin.

19.
292
. there are 4 legs
Note the wiring inside the LED how all the cathodes are connected together.Look carefully at the physica llayout.14
Ohms law in action – a multicoloured LED
Here is the datasheet for a multicoloured LED.

4V Needs 3.
To work out the values of the 3 resistors we need toloo at the datasheet.4V (same as green) 20mA max current = 20mA max brightness V = 5V .6V/0. If we found that 5mA was enough we would need to calculate the values again.020A R = 150 ohm R = 80 Ohm If the LEDs don’t need to be so bright we could test them with a power supply and try different values of resistors. then we turned on the green LED the current in the resistor would change changing the current in the red LED as well.005A R = 600 ohm R = 320 Ohm
293
.To wire this to a microscontroller we will need to use three I/O pins of the microand three resistors. R = V/I R = V/I same as green R = 3V/0. Why?Imagine we turned on the red LED and i ws going.6V R = V/I R = V/I same as green R = 3V/0.020A R =1.6V/0. (yet another good reason for not using 1 resistor) RED Green Blue Needs 2V Needs 3. there we find that the LEDs have different volage requirements.4V V = 3V V = 1.2V V = 5V .3.005A R =1. We do not use a single resistor on the cathode to ground.

294
.

weight. Get an LDR and measure the resistance when it is in the dark and measure the resistance when it is in bright sunlight.
A computer works in binary (or digital) which means it has the ability to sense only two states. Record the two values. We can then make decisions within our program based upon this information to control some output. Using the AVR this analogue value can then be converted to a binary number within the range 0 to 1111111111 (decimal 1023) within the microcontroller. 1 and 0. The LDR The LDR (Light Dependant Resistor) is a semiconductor device that can be used in circuits to sense the amount of light. To do this we convert a continuously varying analogue input such as distance.Analog to Digital conversion
We need to be able to determine measurements of more than on and off. height. lighltlevel etc to a voltage.983 metres or perhaps 1.20 Basic analog to digital interfaces
In the real world we measure things in continuously varying amounts.2
Light level sensing
We will measure the amount of light falling on a sensor and use the LED's on the microcontroller board to display its level.1
ADC . It might be 11 metres from the hole.
295
.g. For example the golf ball is either in the hole or not.
20.46236464865465437326542 metres from the hole. or in and out.38765983 metres. The golf ball is some distance from the hole. 101011010 (=346 decimal) metres. When we want to measure the actual distance in binary we must use a number made up of many digits e. it might be 213.380. The airplane might have an altitude of 11. The plane is either in the air or not.
20.

A voltage divider is typically two resistors across a battery or power supply. this can be changed for a higher or lower value to achive the effect you want with the LDR (also the LDR and resistor can be swapped in the circuit to alter the effect as well)
296
. We do that with the built in ADC (Analogue to Digital Converter) inside the Microcontroller. If the light level is high then the resistance is _____(high/low). But computers only know about digital voltages 0 volts or 5 Volts. In the diagram a 4k7 resistor is shown. Its second function is that of input to the internal ADC. it has been divided by ______ (2/3/4). In fact there are 8 separate inputs to the ADC one for each pin of portA. A voltage divider is shown here. Port A has dual functions inside the microcontroller.e. therefore the output voltage is _____ (low/high). therefore the output voltage is _____ (low/high).4
AVR ADC connections
On a micro such as the ATMega8535/16. we know that the resistance of an LDR changes with the amount of light falling on it. If the two resistors are the same value then the output voltage will be one_____ (quarter/half/third) of the input voltage. Analogue means that the voltage varies continuously between 0 and 5 volts. If we change the ratio of the two values then the output voltage will vary. With the 5volts applied to the circuit the output voltage will be some proportion of the input voltage. If the light level is low.
Replace one of the resistors with an LDR.
20.3
Voltage dividers review
When you studied ohms law you also studied the use of voltage dividers. With R1 larger than R2 the output voltage will be low and with R2 larger than R1 the output voltage will be high. i. and then the resistance is _____ (high/low). Now this is what we call an analogue voltage. We need to convert the analog voltage to a digital number that the computer can work with.20.

20. Specification from the brief: Turn on one of 4 leds which represents one of 4 levels of light.5
Select-Case
In this example you will learn about how to use select case which is a very tidy way of writing a whole lot of if-then statements. Algortithm When the lightlevel is brightest turn on the 4th led When the lightlevel is medium high turn on 3rd led When the lightlevel is low turn on 2nd LED When the lightlevel is very low/dark turn on 1st LED Planning Tool Selection (A table is selected to help us clarify the algorithm and plan the program) Lightlevel range From 901 to 1023 From 601 to 900 From 401 to 600 From 0 to 400 Planning using a flowchart testing values using simple math Lightlevel > 900 (ignore over 1023) Lightlevel > 600 AND Lightlevel < 901 Lightlevel > 400 AND Lightlevel < 601 Lightlevel < 401 output LED 3 LED 2 LED 1 LED 0
lightlevel > 900? N
Y
led 3
lightlevel > 600 and lightlevel < 901? N
Y
led 2
lightlevel >300 and lightlevel < 601? N
Y
led 1
lightlevel < 301 N
Y
led 0
If Lightlevel > 900 Then Portc = &B11110111 If Lightlevel > 600 And Lightlevel < 901 Then Portc = &B11111011 If Lightlevel > 400 And Lightlevel < 601 Then Portc = &B11111101 If Lightlevel < 401 Then Portc = &B11111110 297
.

There is a much better way to plan this code, so that it is more efficient (the micro has less to do and the program runs faster). It does this by once having found a solution it stops checking for any other solutions. This can save a lot of processing in large programs. You do however have to watch the order in which you check values and how you use the < and > tests.

lightlevel > 900? N

Y

led 3

lightlevel > 600? N

Y

led 2

lightlevel > 300? N

Y

led 1

lightlevel < 301 N

Y

led 0

This is handled for us by the select case statement Select Case Lightlevel Case Is > 900 : Portc = &B11110111 Case Is > 600 : Portc = &B11111011 Case Is > 400 : Portc = &B11111101 Case Is < 401 : Portc = &B11111110 End Select Once the select case has found a solution it does no more checking and exits the at the END SELECT

298

20.6

Reading an LDR’s values

Now we will write some code to make use of the LDR. Note that the variable used in this program is of size WORD i.e. 2bytes (16 bits) This is because the values given from the analogue to digital converter are bigger than 255. Note also a new programming structure select-case-end select has been used.Select-case is equivalent to a whole lot of IF-THEN statements '-----------------------------------------------------------------' 1. Title Block ' Author: B.Collis ' Date: 7 Aug 2003 ' Version: 1.0 ' File Name: LDR_Ver1.bas '-----------------------------------------------------------------' 2. Program Description: ' This program displays light level on the LEDs of portc ' 3. Hardware Features: ' LEDs as outputs ' An LDR is connected in a voltage divider circuit to portA.0 ' in the dark the voltage is close to 0 volts, the ADC will read a low number ' in bright sunlight the voltage is close to 5V, the ADC will be a high value ' 4. Software Features: ' ADC converts input voltage level to a number in range from 0 to 1023 ' Select Case to choose one of 8 values to turn on the corresponding LED ' 1023, 895, 767, 639, 511, 383, 255, 127, ' -----------------------------------------------------------------' 5. Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 'the speed of operations inside the micro $regfile = "m8535.dat" ' the micro we are using '-----------------------------------------------------------------' 6. Hardware Setups ' setup direction of all ports Config Porta = Output 'LEDs on portA Config Portb = Output 'LEDs on portB Config Portc = Output 'LEDs on portC Config Pina.0 = input ' LDR Config Portd = Output 'LEDs on portD Config Adc = Single , Prescaler = Auto, Reference = Avcc Start Adc ' 7. Hardware Aliases ' 8. initialise ports so hardware starts correctly ' must not put a high on the 2 adc lines as this will turn on the micros ' internal pull up resistor and the results will be erratic Portc = &B11111100 'turns off LEDs

In this project Marcus used 28 high intensity surface mount LEDs soldered to the copper side of the PCB.

301

The schematic is quite straight forward with an LDR on PinA.0.

Initial programs were desgined to Test the LEDs and the LDR, then the next program combined them together. '------------------------------------------------------------'Program Description 'This program shows LED working when LDR detects different light level '------------------------------------------------------------'Hardware features: 'LEDs as outputs 'An LDR is connected in a voltage divider circuit to portA.0 'In the dark the voltage is close to 0 volts, the ADC will read a high number 'In bright sunlight the voltage is close to 5v, the AVC will be a high value '-----------------------------------------------------------'Software features: 'ADC converts input voltage level to a number in range from 0 to 1023 '----------------------------------------------------------'Computer directives $crystal = 8000000 $regfile = "m8535.dat" '-----------------------------------------------------------'Hardware setups Config Porta = Output Config Pina.0 = Input Config Portb = Output Config Portc = Output 'make these micro pins outputs 302

The usual temperature sensor that comes to mind is the Thermistor however thermistors are not linear but logarithmic devices as shown in this graph. If you do want to use a thermistor then try putting a resistor in parallel with it to make it more linear, however it will not be linear over its whole range.

The LM35 varies linearly over its range with typically less than a ¼ degree of error. The voltage output changes at 10mV per degree. Connect the LM35 to 5V, ground and one analog input pin. The code is very straight forward Config ADC= Single, prescaler = auto Dim Lm35 as word Read_LM35: Lm35 = getadc(2) Locate 2,1 Lm35 = lm35 / 2 (rough conversion to degrees) Lcd “temperature= ” ; LM35 ' return The value increases by 2 for every increase of 1 degree. When connected to 5V a temperature of 25 degrees will give an output of 250mV and an ADC reading of approximately 50 (the ADC range is 0 to 1024 for 0 to 5v).

304

20.9

A simple temperature display

Algorithm: In this project there is no display apart from the LEDs so the temperature is displayed by flashing the LEDs, Red is 10s of degrees, Green is units of degrees. So a temperature of 23 degrees celcius will be displayed as the red LED flashing twice followed by the green LED flashing 3 times, followed by a 2 second wait. Here is the code for this
'-----------------------------------------------------------------' Author: B.Collis ' Date: 19 June 2010 ' File Name: Tiny45_temprV3.bas '-----------------------------------------------------------------' Program Description: ' reads LM35 connected to ADC and displays temp by flashing leds ' Hardware Features: ' _____ ' RESET -| |- VCC ' LM35 - ADC3/PB3 -| |- PB2/ADC1 - RED LED ' ADC2/PB4 -| |- PB1 - GRN LED ' GND -|_____|- PB0 - YEL LED ' '------------------------------------------------------------------

It is good practice to include a title block and full description of your hardware and program at the beginning of your code. With a small micro a simple text diagram was created to show the connections.

Although a conversion of 9 looked like it would work, the temperature was out by a degree at room temperature. This was found by measuring the LM35 voltage out put as 0.228 and seeing the LED flash the number 24. This probably enough accuracy for room temperature measurements as the LM35 has at best an accuracy of ¼ of adegree anyway. Variables used in the program These are not

306

'------------------------------------------------------------------

' Program starts here Set Redled Set Grnled Set Yelled

'led off 'led off 'led off

given initial values because they are measured Turn off the LEDs at the beginning

The first part of the program reads the temperatire and converts it to a useable value

This is a vital piece of learning here about division and the use of modulus. We are dealing with whole numbers when we use words , bytes and intergers in Bascom. So if we divide 27 by 10 we get 2 (note that there is no rounding) so a command exists <MOD> that allows us to get the remainder of the division 27 MOD 10 will return 7. 'flash the tempr on the LEDs Flashing the leds While Tempr_10s > 0 'flash the red led the number requires us to set a of 10s loop in motion, we Reset Redled control the number of Waitms Flashdelay Set Redled times the loop Waitms Flashdelay repeats by starting it Decr Tempr_10s with the number and Wend progressively Waitms 200 subtracting 1 each While Tempr_1s > 0 'flash the grn led the number of units time.
Reset Grnled Waitms Flashdelay Set Grnled Waitms Flashdelay Decr Tempr_1s Wend

Wait 2 Loop End

'end program

This is actually an efficient piece of code as microcontrollers programs are generally more efficient if they loop down to zero rather than some number other than zero, this is because of the way the hardware in a micro works

' -----------------------------------------------------------------'Subroutines -these are actions so often start with words like read, calc, displ, squeeze, move... ' a subroutine is best if it only contains one action (even if it consists of only a few lines of code ' this makes them easier to follow, modify and reuse.

Calc_accurate_temp: 'using singles we can have decimal places in our calculations Accurate_temperature = Adc_value 'convert word to single 'adc_value of 51 = 0.259V 'conversion factor is 51/25.9= 1.96911197 Accurate_temperature = Accurate_temperature / 1.96911197 'turn the single into a string and round it to 1 decimalplace Temperature = Fusing(accurate_temperature , "#.#") 'note we can do maths with numbers stored in singles ' we cannot do maths with numbers strored in string form ' as they are no longer numbers just codes representing digits Return Disp_accurate_temp: 'this subroutine displays the two accurate readings one is a number 'the other is a number in string form Locate 3 , 1 Lcd "tempr= " ; Accurate_temperature ; " " 'display 1 decimal place plus deg symbol and capital C Locate 4 , 1 Lcd "tempr (1dp)= " ; Temperature ; Chr(223) ; Chr(67) Return

311

20.11

Force Sensitive Resistors

The FSR is a neat device for sensing pressure, its not accurate enough to measure weight but useful to detect the presence of someone standing on a mat or tapping on a surface.

These are used in exactly the same type of circuit as the LDR (voltage divider with a 10K). You must be extremely careful trying to solder to these as the plastic melts so easily. You may find that the use of some type of connector may make your project cheaper!

20.12

Piezo sensor

A piezo make s aperfect vibration sensor in exactly the same voltage divider circuit, especially if you fixed one side of it mechanically to something and the other side is left to float inthe air. You can even buy more sensitive version of this type of sensor – they make great impact sensors.

312

20.13

Multiple switches and ADC

There is a very convenient way of reading multiple switches with your microcontroller and only use 1 input port. By making up a long voltage divider as in this diagram and connecting its output to a microcontroller ADC pin, the voltage will change to a different voltage output for every different switch press. This happens because the voltage divider changes the number of resistors in the voltage divider for every different switch press

If no switch is pressed then there is no voltage divider as all the resistors R21 to R31 are unconnected. The input voltage to the ADC will be Vcc (5V) and the ADC reading will be max (1023).

If S1 is pressed then othere is also no voltage divider, however the adc input is now connect to ground (0V) and the adc reading will be 0.

If s2 is pressed there will only be two resistors in the voltage divider and the output will be Vout = = 0.5V (ADC reading of 0.5/5*1023 = 102)

If S3 is pressed then only 3 resistors will be in the voltage divider and the output will be Vout = = 0.667V (ADC reading of 0.667/5*1023 = 136

If S4 is pressed then only 4 resistors will be in the voltage divider and the output will be Vout = = 0.75V (ADC reading of 0.75/5*1023 = 153

The emerging patterns here are that the output is becoming larger and larger, and the differences between the steps are becoming closer and closer. Note the pattern in the voltages 1/2Vcc , 2/3Vcc, 3/4Vcc, 4/5Vcc, 5/6Vcc, 6/7Vcc.... This means that there is a limit to the number of switches that can be put in this type of circuit.

313

21 Basic System Design
21.1 Understanding how systems are put together
A product or device is not just a collection of components, it is much more, the inventor of the device didn’t just combine some parts together, they created a system. They envisaged it as a whole system where all the parts have a unique purpose and together they function to make the product complete.AND they developed it as part of a bigger process. An example is a food processor. To analyse the system 1. Draw a system block diagram identifying and describing all the inputs and outputs of the system a. Motor – 3 speed b. Motor driver electronics c. speed control – 4 position switch d. bowl safety switch e. Power LED, Bowl Lock LED (not shown in picture) 2. Describe in words how these interact with each other, use logic descriptors such as AND, OR and NOT. 3. Design the flowchart to represent the operational logic

21.2
PSU

Food Processor system block diagram

A B Bowl Safety Switch Off Low Med High controller

Motor Driver

motor

Speed Control Setting

Power LED

Bowl Lock LED

21.3

Subsystems

Note that some of the items in the above system are systems themselves. The motor driver, the PSU, the motor and the controller are all systems (the LEDs and switch are components). When we use a system within another system we call it a subsystem.

21.4
   

Food Processor system functional attributes- algorithm

When power is applied the power LED goes When power is applied AND the bowl is securely fitted the Bowl lock LED is on. When power is applied AND the bowl is securely fitted AND the speed control is set above zero the motor will run. The motor has 2 inputs:  When no power is applied to either the motor is off.  When power is applied to A it goes slow. 314

 

When power is applied to B it goes medium speed. When power is applied to both it goes fast. When the speed control is varied the motor

21.5

Food Processor system flowchart

Food Processor power LED on MotorA off MotorB off BowlLockLED off

Here is a first pass at a flowchart for the system. It does however need work as there are a number of problems with it. Can you identify any? 1. It can be turned on but when the speed switch is turned off, the motor does not turn off. 2. If the bowl is removed while turned on then the motor does not turn off. 3. The BowlLockedLed can never be turned off.
MotorA on

N

bowl locked? Y

BowlLockedLed on

Speed 1 N

Y

Develop a better flowchart for a program for the food processor.

Speed 2 N

Y

MotorB on

Speed 3 N

Y

MotorA on MotorB on

315

21.6

Toaster Design

A toaster is another good example of a system.

1. Identify all the parts of the toaster and draw a system block diagram 2. Describe the system operation – how the parts of the system interact with each other 3. Design the flowchart

21.7

Toaster - system block diagram
Heating elements

PSU Left Toast setting Toast down Stop Normal Crumpets Frozen Relay 1

Right

Relay 2

controller cook time

Hold down solenoid

Normal LED Crumpet LED Toast cooked sensor Frozen LED Piezo Beeper

21.8

Toaster Algortihm

Initially: the solenoid is off, the LEDs are off,the piezo is quiet and the elements are off When the toast lever is pressed down the solenoid is activated to hold the toast down If the setting is normal both the elements turn on and the normal LED comes on for the time set by the cook control If the setting is crumpets, the left comes on max and the right comes on at half power and the crumpet LED comes on for the time set by the cook control If the setting is frozen the time is extended by 1 min (either crumpet or normal) and the frozen LED comes on If the sensor detects smoke the solenoid is released and the piezo beeps quickly 4 times If the time is up the the solenoid is released and the piezo beeps twice 316

22 Basic System development - Time Tracker.

It is often useful for students to see worked examples; this small project is a worked example not just of a timer project but of the process of development for an electronics project at school. The process requires several iterations (cycles) of development. For some students the process described here will be trivial (extremely simply), however it is important that students understand the process and can carry it out. Stage 1:  Stakeholder consultation  Initial brief  Block diagram  Algorithm  Flowchart - a model of the internal process that the microcontroller must carry out  Schematic  Prototype development  Program development  Feedback from stakeholder Stage 2:  Refinement of brief – modify/ add/delete specifications  Modification of schematic/algorithm/flowchart/prototype/program as required  Feedback from stakeholder Stage 3:  Refinement of brief – modify/ add/delete specifications  Modification of schematic/algorithm/flowchart/prototype/program as required  Feedback from stakeholder Stage 4:  Refinement of brief – modify/ add/delete specifications  Modification of schematic/algorithm/flowchart/prototype/program as required  Evaluation by stakeholder

317

22.1
System context diagram and brief
The system context diagram is a visual representation of a brief.
318
.

2
Time tracker block diagram
319
.22.

3
Algorithm development
22.4
Schematic
The schematic for the ATTiny461 prototype PCB has been modified to include the components for the switch and LED.22.
320
. and the switch connection has a pullup resistor. Note the LED connection via a current limit resistor.

Program – saves as new version. Flowchart – saves as new verison.4 . make changes and print for journal 5. Schematic: save as new version.just write it into the journal) 3.3 . Block diagram – saves as new version. Brief: new or changed specifications recorded. Db7 = Portb.22. makes changes and print for journal 4.6
Time Tracker stage 2
At this point the student should make contact with their stakeholder or client and show them what has been done.6 . Rs = Portb.0 Config Lcd = 20 * 2 'configure lcd screen 322
. 2.5VDC Batteries
Grn Led Output Devices
'-----------------------------------------------------------------'Program Description: '30 second countdown timer 'lcd displays seconds counting after switch pressed 'green led is on when not counting 'double beep at end '-----------------------------------------------------------------'Compiler Directives (these tell Bascom things about our hardware) $regfile = "attiny461. Layout: make changes to layout in journal or print new version with changes 6. makes changes and prints for journal 7. Db5 = Portb.1 . Db6 = Portb. Algorithm changes described (no need for a new form . Db4 = Portb. makes changes and prints for journal
Time Tracker System Block Diagram v2
Piezo Grn Sw Microcontroller
lcd
Input Devices Process Device 4.5 . After the client in this case wanted an LED added to the product to show when the timer was not timing and to change to a double beep when the timer times out.7 = Input 'LCD setup Config Lcdpin = Pin . The student makes the following additions to their journal for their project: Stakeholder consultation carried out and: 1. E = Portb.dat" 'our micro $crystal = 1000000 'the speed of our micro '-----------------------------------------------------------------'Hardware Setups ' setup direction of all ports Config Porta = Output ' Config Pina.

0 324
. Rs = Portb. Block diagram: saves as new version. makes changes and prints for journal 7. E = Portb.22.6 .5 .5VDC Batteries Grn Led Output Devices
lcd
'-----------------------------------------------------------------'Program Description: '30 second countdown timer 'lcd displays seconds counting after switch pressed 'green led is on when not counting 'double beep at end 'red led flashes once per second '-----------------------------------------------------------------'Compiler Directives (these tell Bascom things about our hardware) $regfile = "attiny461. makes changes and prints for journal 4. 2. Db5 = Portb. Brief: new or changed specifications recorded. Schematic: save as new version. Db6 = Portb. Db4 = Portb. After this the client wanted a second (red) LED added to the product to flash while the timer was timing.dat" 'our micro $crystal = 1000000 'the speed of our micro '-----------------------------------------------------------------'Hardware Setups ' setup direction of all ports Config Porta = Output ' Config Pina. Db7 = Portb. Flowchart: saves as new verison.4 . Algorithm: changes described (no need for a new form .just write it into the journal) 3.1 . make changes and print for journal 5. The students makes the following additions to their journal for their project: Stakeholder consultation carried out and: 1. Layout: make changes to layout in journal or print new version with changes 6.3 .7 = Input 'LCD setup Config Lcdpin = Pin .7
Time Tracker stage 3
At this point the student should make another contact with their stakeholder or client and show them what has been done. Program: saves as new version. makes changes and prints for journal
Time Tracker System Block Diagram v3
Piezo Grn Sw Microcontroller Red Led Input Devices Process Device 4.

30-60-90-120-150-180-210-240-270-300 seconds.
Time Tracker System Block Diagram v4
Piezo Grn Sw Microcontroller Wht Sw Input Devices Process Device 4.22.just write it into the journal) 3. however in doing this they are missing out on critical marks. makes changes and prints for journal
Of course some students may be able to go straight to this final version of the product straight away. makes changes and prints for journal 7.8
Time Tracker stage 4
At this point the student made yet another contact with their stakeholder or client and showed them what has been done. Specifically they want to be able to push a second switch to increase the count time from 30 to 100 seconds in amounts of 30 seconds. they thought the timer would be really useful if the time delay could be changed. make changes and print for journal 5.
326
. e. makes changes and prints for journal 4. Program: saves as new version. The students makes the following additions to their journal for their project: Stakeholder consultation carried out and: 1. Flowchart: saves as new verison. f they press the white button the time will increase in amount sof 30 seconds to a maximum of 300 seconds. Schematic: save as new version. Algorithm: changes described (no need for a new form . After this the client wanted a significant change to the project.g. as the highest grades come from stakeholder consultations and subsequent modification to their project. The algorithm now has been modified to include: While waiting for the user to press the green start button. Layout: make changes to layout in journal or print new version with changes 6.5VDC Batteries Red Led Grn Led Output Devices
lcd
This final version of the block fiagram has all of the components to date. Block diagram: saves as new version. 2. Brief: new or changed specifications recorded.

5V  Pressing the third button increases the current that you want by 1mA o A maximum of 50mA o A minimum of 1mA o After 50mA it wraps back to 1mA  After any button press the new resistor value is calculated and displayed Take note here that I separate the processing from the output code by writing the two different and separate things the micro must do.0V o A minimum of 1. Vl (short for Vled) is the manufacturers voltage specification for the LED o A maximum of 4.1
Ohms law calculator
Specifications  Pressing the first button increases the voltage in the circuit by 1 Volt o A maximum of 24V o A minumium of 3V o After 24V it goes back to 3V  Pressing the second button increases Vl by0.5V o After 4.0V it wraps back to 1. soit follows logically that they can do maths with these numbers.1V. first calculate (process code) and then display (output code). 330
. Here is a program that makes use of some maths and some different types of variables.
23.23 Basic maths time
Microcontrollers only store numbers.

331
.

There is one reason why these might be better in the main loop and not each switch press. This actually makes our program take up less room in program memory.
332
. we could miss switch presses while the micro was busy doing nothing. o Even though the only time we use these two subroutines is together it is better to separate them because they do different things. o We can reduce size of program code through strategic thinking and understanding of how a program runs.  I have put the calculation and lcd drawing into the main loop rather than into each loop. This code only does something when a value changes otherwise it just recalculates using the same values and redraws the same values on the LCD. However they don’t take long enough to cause a problem.  Again I have separated out the process code from the output code. o In general these would be better in the subroutines because it is better programming practice. o This means however that my program needs a delay in the loop somewhere otherwise the values count up much too quickly when a button is pressed.The flowchart for the program reveals my thinking while designing the program flow.  I put the subroutines calc_new_r and display_values at the beginning of theprogram so that they are used once. This makes the code easier to understand and easier to recycle into other programs. If you don’t do this then the program sits there with a blank LCD until the user presses a button. o This delay should be moved into each switch press loop. This is an important concept in programming. If these two routines took a long time then we would have the same effect as putting the 500mS delay into the main loop. What I mean by redundant is that it is put there but not doing anything useful. o There is no real reason for this. So putting them in the main loop or putting them into each subroutine isn’t important because of speed. o Alternatively you could put in an instructions screen at the beginning that told the user what to do and then either automatically times out or waited until the user pressed a button to continue. So why didn’t I do this already. o This is redundant. It is that a button can be pressed and the micro can easily miss it because it might be in the waitms 500 doing nothing. However I chose not to because the debounce command doesn’t allow auto repeat (you have to let the button go before you can press it again to increase the value). the separation of different functions. I felt that the program would be easier to use if you could just hold the button down and the values would increase at a regular rate. Now the problem with putting a 500mS delay in the main loop has been covered before. and there is little side effect from it either in this program. it is in the main loop. because then it only occurs when a switch is pressed and not at any other time. because I wanted you to learn about it again! o If you wanted to you could write a really neat debounce command that checked the switch and if it was held down increased at a slow rate. This is hardly noticeable (its just 4 Gosub lines that we save) in this program but I say it because there is an important concept in programming here.  I could use the Bascom debounce command rather than reading the switches with IFTHEN. o See where the delay (waitms 500) is in the program.

Test the flowchart with an example Answer Num2 6 8 12 7 18 6 24 5 30 4 36 3 42 2 48 1 54 0 Identify the control statements to be used. a long stores -2147483648 to 2147483647)
Note the shapes of the elements: Start and end Inputs and outputs Processes Decisions Learn the process of keeping track of how many times something is done. This stage can be a little confusing and often we can be out by 1 either way (if it is then our answer might not be 54 but 48 or 60) If you get wrong answers after a loop check that you are decreasing or increasing them the right number of times. Within a microcontroller though it is often faster to test a variable against 0 than some other number.23.2
Process
more maths . A variable is used to count the number of times a loop is carried out.multiplication
Notes
Issue: Multiply two numbers together Pretty much all microcontrollers do multiplication inside using only addition e. An alternative is to increase a variable until it reaches a specific value. 335
. AxB=Answer their hardware nowadays but its useful as a learning exercise. This can be a step students struggle with. In this case the variable is decreased each time through the loop until it is 0.
Variables: (memory locations to store data in) numA – byte size numB – byte size Answer – word size Flowchart:
Choose useful names and think about the size of the variable (a byte stores 0-255. you need to concise. accurate and clear.
In BASCOM there are several control mechanisms to manage loops. 5 x 4 = 5+5+5+5 Finding the right words to describe the algorithm can be difficult at times. Algorithm: Add A to the answer B times e. an integer stores -32768 to 32767.g. a word 0-65535.g.
Does it work? Note how the columns in the test follow the same order as the processes in the loop.

' SimpleMultiplicationV1. Do-Loop Until…
For-Next… this requires another variable to act as the loop counter. then save it and compile it you can try it out using the simulator (F2).3 = Input Dim I As Byte Dim Num1 As Byte Dim Num2 As Byte Dim Answer As Word '************************************ Num1 = 6 Num2 = 9 Answer = 0 Do Answer = Answer + Num1 Decr Num2 Loop Until Num2 = 0 '************************************ Num1 = 6 Num2 = 9 Answer = 0 For I = 0 To Num2 Answer = Answer + Num1 Next '************************************ Num1 = 6 Num2 = 9 Answer = 0 For I = Num2 To 0 Step -1 Answer = Answer + Num1 Next '************************************ Num1 = 6 Num2 = 9 Answer = 0 While Num2 > 0 Answer = Answer + Num1 Decr Num2 Wend End
If you copy this code into BASCOM-AVR. While – Wend
When you run this program you will find that two of them work correctly and two do not! You need to understand which and fix them.bas $crystal = 1000000 $regfile = "attiny461.
336
.dat" Config Porta = Output Config Portb = Output Config Pina. so watch carefully the values of the variables in the simulator and fix the two that need fixing. and can either count up or count down.

3
Algorithms for multiplication of very large numbers
The previous code is OK for small to medium size problems however there are much more efficient algorithms. Num2. here are 2 alternatives. Total Config Porta = Output Config Portb = Output Dim Temp As Word Dim Num1 As Word Dim Num2 As Word Dim Answer As Word Num1 = 16 Num2 = 39 Answer = 0 ‘note again the use of do-loop as we don’t know how many times the loop needs to be repeated Do (Mod is used to find if a number is odd or even) Temp = Num1 Mod 2 If Temp = 1 Then Answer = Answer + Num2 Num1 = Num1 / 2 Num2 = Num2 * 2 Loop Until Num1 = 0 End
337
. If the second number is odd add it to the total. What variables will be needed: Num1.dat" Write down the Algorithm: Divide the first number by 2 (ignore remainder) and multiply the second number by 2.bas 2 1312 1 2625 $crystal = 1000000 3075 $regfile = "attiny461. ‘Peasant’ Multiplication 75 x 41 Program: 75 41 37 82 18 164 9 328 4 656 ' PeasantMultiplicationV1. Keep doing this process until after the first number is 1.23.

then display the number of guesses and start again If incorrect then give as too high’ or ‘too low’ When the number of guesses goes over 8 the player loses
6A. 2 5 = 32 (use only addition and loops)
60
339
. 2. when number of cartons is over 48 then increase the number of pallets.
5.Design an algorithm and flowchart for a program that calculates powers eg.
into
4. or E based upon the following scores 0% to 33% = N. In this game the first person picks a number between 1 and 10 and the other person must guess this number in 4 or less guesses. Can you write the process down? 2. A. it has a machine that puts the drink bottles into cartons and full cartons onto pallets. This is a game played with any number of players who take turns saying a number. There is a winning strategy for this game you will need to research it or figure it out to be able to write a program that can beat a human opponent.algorithm and flowchart exercises
1. 34% to 55% = A. If you play this game a few times with someone you will get a feel for the algorithm (the process for solving the problem) . the player forced to say "21" loses. 3A. If correct. Extend this in a second algorithm and flowchart that tracks the number of bottles and the number of cartons.23. The first player says "1" and each player in turn increases the number by 1. A factory fills drink bottles. A program marks test scores and gives grades of N. 56% to 83% = M 83% to 100% = E Write the algorithm and draw the flowchart for this process. Design an algorithm and flowchart that counts 24 bottles each carton and keeps track of the number of cartons.
3. 6B. or 3. the watering system comes on for 30 minutes then waits minutes to measure the moisture level and comes on for a second watering if it is below a fixed level.4
Program ideas . but may not exceed 21. 3B. Design an algorithm and flowchart for a program that gets a player to guess a random number from 1 to 1000. a golf course watering system monitors the time and moisture level of the ground and waters the grass in the early evening if it is needed. M. 7.

Mount Roskill” When you dimension a string you must think about how big it might become during the time your program will use it.g. Computers all store text in the same way too.). different names and addresses or different colours or different days of the week. so to diaplay an A LCD CHR(65).g. ‘A’ is 01000001 or 65 in decimal.. All computer languages allow you to store this text in a variable called a STRING. But what if we want our text to vary e.g.24 Basic string variables
So far we have used constants on the display such as lcd”Hello”. This table gives us the binary code for each character e.
A string is a variable that is a collection of letters (and digits) such as “My name is Fred” or “37 Frost Road.. e. In a program text can be displayed using the command LCD CHR(. Ram stores only numbers so to store text in RAM we store a code for each letter of the text string. dim address as string * 20
340
. and then allocate enough memory for it.

Variables are stored in ram in the order in which they are declared in Bascom. You can look up the values in the ASCII table for the above RAM. The next byte of ram has the number 5 stored in it. these are hexadecimal numbers hexadecimal binary Decimal ASCII 68 &B 0100 1000 104 H 65 &B 0100 0101 101 E 6C &B 0100 1100 108 L 6C &B 0100 1100 108 L 6F &B 0100 1111 111 O
341
. so after the first loop of the program the memory looks like this above. The next byte is the variable count it goes up from 1 to 3 to control the number of times the text flashes on the LCD. again 21 characters are used. this is because Bascom puts a 0 on the end of each string in memory. The simulator conveniently displays any viewable ascii characters stored in ram on the right hand side of its window.Below is a snapshot of the RAM from the simulator in Bascom this program. You can see that Bascom has actually allocated 21 bytes not 20 as we asked for when we configured the string. Message1 has ‘hello’ stored in it. Dim Message1 As String * 20 (first 21 bytes in red below) Dim Message2 As String * 20 (second 21 bytes in green below) Dim Xposition As Byte (a single byte in dark red) Dim Count As Byte (a single byte in dark green)
The data stored in the variable changes during the program . Message2 has ‘there’ stored in it. this is the position on the lcd that we want the text to appear at.

24. 6 Dim Month As Byte 'e. "2012" Dim Today As String * 20 'a variable to store some text 'Initialise Variable Day = 6 Month = 4 Year = 12 '---------------------------------------------'Program starts here Do Gosub Makedate Locate 1 . 4 Dim Month_str As String * 3 'e. 12 means 2012 Dim Year_str As String * 4 'e.g.g.g. apr Dim Year As Byte 'e.g. 1 Lcd Today Loop End Makedate1: 'str is a function to convert a number to a string Today = Str(day) + "/" + Str(month) + "/" + Str(year) Return
This displays
Which is not what we want we want to be able to display it in either of these formats 06/04/2012 or 06 Apr 2012
On the next page you will see the code for this it needs completing
349
.g.4
Date in a string
Here is a program segment to display the date in a string '----------------------------------------------'Declare Variables Dim Day As Byte 'e.

1 Lcd forty_chars Waitms 150 Wend Return This routine scrolls the complete message once then returns to the main loop.40) Locate 1. The message will be an information message regarding a news item or weather forecast up to 200 characters in length..24. If the string was 50 charcters long as with the one below and the LCD was 16 characters wide then using the mid command we could take the first 16 characters and put them on the display then wait a bit.
In this assignment you will scroll a message across the screen.scroll_posn. then get the next 16 characters and put them on the display.5
Scrolling message assignment
An alphanumeric (text) LCD is a very common output device used with microcontrollers however they have limited screen size so a longer message must be either split up and shown page by page or scrolled across the screen. This makes it a very long routine to execute (150mS times the number of characters in the string) Change the code so that it uses: a Do-Loop-Until structure and then a For-Next
351
.” Scroll_text: Scroll_length = len(message) If Scroll_length > 40 then Scroll_length = scroll_length – 40 End if Scroll_posn = 0 While scroll_posn < scroll_length Incr scroll_posn Forty_chars =mid(message. ‘Declare Variables Dim message as string * 200 Dim scroll_length as byte Dim scroll_posn as byte Dim forty_chars as string * 40 ‘Initialise Variables Message = “ the weather today will be …. and so on continuously.

24. then the weather report scrolls back on again. these graphics should be larger than a single lcd square. have the pacman move around the screen and when it lands on the target the target explodes and the pacman moves on around the rest of the screen Proficient: create ‘12TCE’ in one large font that covers all four lines of the lcd like the wording of atmel in this picture Proficient: flash the message on the screen three times. 1 second on then 1 second off after that have it stay on for 12 seconds then repeat the 3 flashes. perhaps 2/3 lines x 4squares Advanced: Scroll the message on and off the display and have the graphics flash for a while.000 Proficient: repeat this process continuously. wassup_p. have a 3 second delay between each new calculation Advanced: Scroll the results off the display 0.
352
.
These exercises will require you to manipulate the display. And become familiar with the use of loops to get things done. wet. cloudy.bas. and snowy for your weather report. one a target and the last the target exploding Proficient: Have the pacman move around the screen these. and also subtract the smaller from the larger number and display the answer.5 seconds. Basic: calculate 2^8 and display it Proficient: for n from 1 to 25. You need to save each version of the program separately e. Basic: Display 2 random numbers between 2. manipulate numbers. Advanced: Generate a random location on the LCD and place the target there. manipulate text.6
Some LCD programming exercises. wait for 1 sec and then do the next number Advanced: Write you own code to calculate the square root of the answer for each of the above answers Basic: Display a static weather report for Auckland on the LCD screen Proficient: Do graphics for sunny.g wassup_b.bas. wassup_a. that flash on the screen. Basic: put ‘wassup’ on the display Proficient: Have ‘wassup’ scroll around the screen continuously Advanced: Have the 6 letters of ‘wassup’ appear spread out over the display and then after a brief delay move in towards the centre and in order.5 seconds after the calculation Basic: Create 4 different pacman graphics: one pacman mouth open.bas. display 2^n on the screen. one pacman mouth closed.000 and 99. staying on each square for only 0.

know about the extra features the AVR has to help us drive those devices
25. know some more detail about how certain semiconductors are used and work 4.
We are initially interested in the DC current specification 40mA per I/O pin –that sounds great 40mA is heaps for a pin we could do lots with that. BUT wait – the next line says 200mA for the power pins so we cannot draw 40mA from all 15 pins because that would exceed the 200mA for the power pins by 400mA (15 x 40 = 600mA)
There is more data we need to know about. 2. here are the specs for an ATTiny461.
353
.25 Advanced power interfaces
So far we have looked at lower power output interfaces for the microcontroller such as LEDs and LCDs the problem though is that we will want to add high power things to our designs so we must know what to use and how to use it. The learning for this best takes place in some order. know about power 3. know about the output devices and their power requirements 5. know what we can do and what we cannot do with a microcontroller output port.1
Microcontroller power limitations
The microcontroller specifications we are interested in are found in the electrical characteristics section of the datasheet for the microcontroller. here is what I have chosen: 1.

They are with repect to conventional current (not electron current).
The really important characteristic from the datasheet is in notes 3 and 4 where it states that the sum of all currents for all ports should not exceed 60mA sink and 60mA source.
354
. So if we wanted to use all 15 pins of the ATtiny as outputs and switch them all on at the same time then we cannot sink more than 4mA current from each pin (60mA/15pins)! So be warned!!
In the first example we will use the microcontroller to switch a backlight for an LCD on and off. either to positive or ground.
The names sink and source describe which way the current is going in a circuit.Two terms sink and source are used here we first need to understand these specifications. It was common for microcontrollers to have different sink and soure characteristics but nowadays it seems more common to see the sink and source ratings for a microcontroller are the same (but not always).

become burnt and have its life shortened or be destroyed. and therefore dissipates this energy in the form of heat.2A What wattage resistor would you use for 36V and 100mA
P = V * I. Any device that has a voltage across it and current is flowing uses energy. P= 0.2
Power
So far the concepts of voltage and current have been introduced however when these are present a third important aspect of circuits is present as well. 5 & 10 Watts. I=0. The more energy the hotter a component gets and the more likely it is to overheat and be destroyed
25. what is the power? What wattage resistor would you use for 15V and 0.4W. P=V*I . P=2*0. On the right 5 and 10 watt metal cased ones Note that the physical size grows proportionally with the rating
V = 10V I = 2A V = 5V I = 0. 1. 1/2. 1/4. Components don’t like to get too hot and are rated to work only below a certain temperature. I=V/R.2A.3A I = 200mA V = 12V V = 100V I = 3mA V = 100V P = 50W V = 48V I = 20mA A 5 Watt bulb draws 1. Resistors can be bought in various ratings. Resistors come in different power ratings so it is important in a circuit to understand that the power ratings should not be exceeded or the component may overheat.6A what is the voltage? A 12 battery supplies 20mA to a resistor. Power is measured in Watts. P=20W
355
. so P=V*I. on the left are 1/8.3
Power dissipation in resistors
Power = voltage times current.25.2. I= 2/10. 2V across a 10ohm resistor. that is power. P = 10*2.

as this increases there is little current until the voltage reaches 0. when it is reversed biased it will not conduct until it safe operating voltage is exceeded. At reverse voltages higher than that it will probably be detroyed.
This graph decribes the characteristic of diode conduction in a visual form. In a normal diode exceeding the reverse voltage specification will generally destroy the diode.25. When voltage is applied in a reverse direction it is called reverse biased and as the voltage is increased a point will be reached where the voltage is greater than the diode can handle the diode will suddently conduct.7V and the diode will conduct fully.4
Diode characteristics
When a voltage is applied to the diode in a forward direction it is called forward bias.65 the diode conducts.65 to 0.
356
. When the diode is forward biased above 0.

Vin 20 12 24 Vout 5.3W PZener = Vout x Izener 0.9 ILoad IZener 0.1)/0.155 = 96ohms. a small microcontroller circuit might draw 150mA (0. The issue however with zener circuits is not so much the voltage and resistance calculations it’s the power calculations.1 x 0.
The current though the load will be 150mA.1) x 0. not a usual 400mW one we would find in the workshop! For a zener diode.005 Itotal 0.79W
357
.Vout
We must know what load the rest of the circuit presents to the power supply. Note the symbol for a zener is different to a normal diode and shows the knee and avalanche effects in the symbol with the angled line at the cathode end.g.1 5.
If we want to make a small power supply for a common circuit (5V) and we find a 20V dc power pack we can use a zener diode.5
Using Zener diodes
The reverse conduction effect can be put to use in controlled circumsnaces and in Zener diodes this effect is used to make small regulated power supplies.155A).155 = 2.005 0.155 R = VR/Itotal 96 PR = VR x Itotal 2. a zener requires some small current to work e. power is also factor and worst case will be when the load draws no current.08 0. Using Ohms law the value of R will be V/I = (20-5.Vout 14.15 0. We don’t need to draw the rest of the circuit to help us we can represent it as a resistor RLoad e. 5mA.15A).1 5. We assume worst case so the power the resistor has to dissipate is V x I = (20-5.79W so a 1W zener would be used (not a usual 400mW one).155 = 0. Power = V x I = 5.g.1 VR = Vin .3W so we would use a 5W resistor. so the total current will be 150mA + 5mA – 155mA (0.25. The first calculation is simply the voltage across the Resistor VR = Vin .

To the silicon other materials (impurities) are added. these other materials have either more or less electrons in the outer shell.6V) electrons will flow from the negative to positive.
When no voltage is connecte some (the
When a large enough voltage is applied to a diode 0. Knowing how a normal diode works will help you understand the basics of how an LED gives off light.4v to 0. This is called forward bias. in the other part P-type impurities are added (slightly less conductive).
358
.
One part of the silicon has N-type impurities added (slightly more conductive).
d to the diode there is a region in the middle where electrons flow over and the effect is cancelled out depletion region). Semiconductors have more electrons in their outer shells than conductors.25. This explains why diodes conduct
only when connected into a circuit the right way around.
(about the the
When the battery is connected back to front the diode is "reverse biased" and the depletion region in the middle gets larger. A diode is made from a piece of silicon which is doped with both N-type and P-type impurities. so electrons cannot flow. In the process depletion region disappears.6
How diodes work
A diode is made from silicon (a semiconductor).

Photons are released whenever electrons move from one shell level in an atom to another.6V. Note that the voltage required for an LED to conduct is much greater than a normal diode. Typical values range from 1.25.
Light Emitting Diode Colour Variations
Color Name Infrared Ultra Red Super Red Super Orange Orange Yellow Incandescent White Pale White Cool White Pure Green Super Blue Blue Violet Ultraviolet Wavelength (Nanometers) 880 660 633 612 605 585 4500K (CT) 6500K (CT) 8000K (CT) 555 470 430 395 Semiconductor Composition GaAlAs/GaAs GaAlAs/GaAlAs AlGaInP AlGaInP GaAsP/GaP GaAsP/GaP InGaN/SiC InGaN/SiC InGaN/SiC GaP/GaP GaN/SiC GaN/SiC InGaN/SiC
359
.7
How does a LED give off light?
In an LED when electrons move from the N side to the P side photons are released. In an LED the electrons move from the N to the P and also change levels within the atomic structure at the same time. therefore releasing photons.8V to 3. and like an ordinary diode they only work in one direction
LED Colours
In an LED different colours are achieved by using different types of impurities.

8
LCD Backlight Data
In the datsheet for a 4 line LCD.7V. As the backlight LEDs draw 70mA in total and a typical LED is up to 20mA we could guess at either 3 or 4 sets of LEDs in parallel. it also requires 4. so if the backlight LEDs require 4.5V to drive it. Although we don’t have a schematic for the backlight we can make a good guess at what the circuit for it might look like. we need another control component in between. A typical LED requires 2V to 2. the LCD typically draws 2mA with the backlight off and 72mA with it on.25.7V we can safely assume that there are 2 LEDs in series.
360
.
As the backlight LEDs draw 70mA it is not possible to drive them directly from a microcontroller I/O pin. so the backlight requires 70mA.

7V and a Vce of 0.07 = 0. (collector current) We want this to be 70mA.021W = 21mW.3V for a BJT transistor when it is fully switched on. The relationship between Colector and base current is called gain or hFE.3 x 70mA = 0. This fine for a 70mA. 4.25.7V backlight but more powerful devices will require bigger transistors.3V The current to the LED backlight comes from the transistor and is the same as Ic.3 x 0. Looking at the specifications in the above table the BC547 can dissipate 500mW and we want it to dissipate 21mW. BC547 NPN T092 100 mA 45 V 110-800 500 mW
Type Case IC (mA) Vce MAX hFE (gain) PTOT (power)
BJT type The maximum current that we can control The maximum voltage we can apply to the circuit The amplification factor Ic/Ib The maximum power that can be dissipated by the device What we know: The backlight is a bunch of LEDs requiring 4. This will always be about 0. Now the hidden calculation is power. The problem with bigger transistors however is that you have to drive them with a lot of current from the microcontroller which cannot provide a lot of current!! So…
361
.7) / 0.0006A flows. To get and Ic of 70mA we need some current through the base Ib.6mA The current in the base is the same as the current in the the resistor R from the microcontroller.9
Transistors as power switches
There are many different types of transistor and the BJT has already been introduced so we will investigate it as an intermediate stage of switching between the microcontroller and the backlight. Power = V x I = 0. so it should work fine. So we would choose a convenient 4k7. You need to know: A transistor when it is completely switched on will have a Vbe of 0.7V and 70mA. Using ohms law R = V/I = (5-0. Gain or hFE = Ic / Ib
I b = IC / hFE = 70/110 = 0. the transistor has a voltage of V CE across the emitter and collector. In fact it would be fine to go lower or a bit higher.0006 = 7k166 ohms A suitable value of R would be lower than 7K to make sure that at least 0.

Here is an LED based traffic light. it has 168 LEDs and requires a 12V supply voltage.011A = 11mA
5 Vbe
6 R
7 Vce
8 Ptot
Now 11mA from a microcontroller sounds ok but lets review the datasheet for the AVR. so if we were to draw 40mA from 5 I/O pins then we would have reached the maimum for our device.
1 Load Green 300mm traffic light 12V 14W (168 LEDs)
2 Ic I=P/V = 14/12 = 1. But theres more…
362
.16/110 =0.
25.16A
3 hFE BC547 = 110
4 Ib Ib = Ic / hFE =1. However there is an absolute maximum rating of 200mA from the power supply pins.10
High power loads
When we have a load that requires higher power we may need a higher voltage supply and more current.25.11
AVR Power matters
The datasheet might initially lead you to believe that we can draw 40mA from an I/O pin.

we could drive a few of them from our AVR but not many. so that we do cannot stress the AVR. So back to our LED traffic light. Sink current is when the current is from ther AVR I/O pin to Vcc (a low or 0 turns on the load) Source current us when the current is from ground to the AVR I/O pin (a high or 1 turns on the load)
So there are significant limits to what we can drive from our AVR. This is in effect 120mA in total. It would be better to use an alternative.In note 4 and 5 above from the datasheet there is a maximum rating of sinking 60mA and sourcing 60mA total from all I/O ports. This is why the current has been limited to a few mA by a 1K resistor with the all the multiple LED circuits so far.
363
.

364
.high power
A darlington transistor is two transistors inside one package like this BDX53C
This device has a gain of at least 750 so to get the maximum current of 6A out of it will require only 6/750 = 0.12
Darlington transistors .25.008A = 8mA into the base.

25W per IC (all 8 outputs) at once.
366
.
The protection diodes go to pin 18 which must be connected to the power for loads you are driving. light bulbs Each transistor can switch 500mA each however you cannot have more than 1W per output and a total of 2.13
ULN2803 Octal Darlington Driver
This really useful IC has 8 darlington transistors built into it. In this circuit for one I/O of the ULN2803 you can see the protection diodes on both the input and the outputs. solenoids. Which makes it really useful for connecting to the 8 pins of one port on a microcontroller.
This device is great for connecting high power loads such as relays.25.

15A) plus other power requirements of the circuit.In this example we want to drive 8 bulbs. 367
. this measn if we want all 8 bulbs on at once we will have P = 8 x 0. We can do this as the specification for each transitor and for the the whole package have not been exceeded.2A (8 x 0.165 = 1.165W 2.15 = 0. Power for each transistor The transistor will have to supply 0. We will need a power supply capable of delivering 12V and 1.1V (worst case) So the power for each transistor will be P = V x I = 1.15A. when it is turned on (saturated) The voltage across the Collector to Emitter will be 1. bulbs are not socommon but theywillserve as an example of power calculations. 1.32W 3.1 x 0. 4.

14
Connecting a FET backlight control to your microcontroller
The LCD requires six I/O lines to be used on the micro to control the data to it plus 1 more to switch the backlight
368
.25.

369
.07 x 5 ohms P = 0. This is the case when an AVR is turned on and before any config statements have been run in your program. The 2N7000 is a logic MOSFET. Note the 5 ohms in the datsheet is a maximum value for RDS. The reason being that the gate is so highly sensitive that if the micrcocontroller pin is configured as an input it will easily drift in voltage and the FET might turn on due to noise nearby in the circuit (and so will the device you have connected to it). however we prefer to connect it with a high value resistor. It is measured by multiplying the current flowing by the Rds value (5ohms for a 2N7000.  Generally FETs require about 10V to drive the gate but low voltage versions called ‘logic’ FETs are available.  A FET’s output current is controlled by the voltage in and there is almost no current in the gate of the FET from the microcontroller meaning a microcontroller can control large FETs directly.07 x 0.0245W = 24. but typically milliohms for high current FETs)
2N7000 – ‘N channel enhanancement-mode MOSFET’
The FET can be connected directly to the microcontroller output pin without the 100k resistor. but we used 5 as a worst case scenario.25.15
FET backlight control
The FET (field effect transistor) is different to the more familiar BC547 which is a BJT (bipolar junction transistor). In worst case the power dissipation will be P=V x I and V= I x R so P = I x R x I P= I2R = 0. It is good practice to connect the gate to ground with a high value resistor.5mW So a lot less power is wasted by using a FET rather than a BJT. looking through the datsheet shows that it is typically going to be around 2 ohms. capable of driving 200mA loads and dissipating 1W of power at 25 degrees Celsius AND can be controlled directly by 5V (a logic 1) from a microcontroller  The power dissipated by a FET is much lower than a BJT.

26 Advanced Power Supply Theory
Every circuit needs high quality power
Over time a significant number of students have developed power supplies and breadboard prototyping centres for their own use
Some have been built into existing items like this toolbox
Some included microcontroller based control of the voltages
A range of various materials are used Sheet metal Acrylic MDF Pine Plywood
Sketchup plays a significant role in helping students visualise and plan the final product
370
.

In NZ we use an AC (alternating current) mains power supply system which delivers 230V to our homes.414 ( +325V and – 325V).3
Stage 1: step down transformer
372
. The 230 is an RMS (root means square) value. We use a transformer to convert the voltage to a lower value.2
The four stages of a PSU (power supply unit)
Most modern electronic devices require fixed and stable power supply voltages. to achive this we follow a recommended design.
Of course we cannot use 230V directly in our projects as it is unsafe to so so.
26. If we want 23Volts out of our transformer we would have 1/10 th the number of windings on the secondary as we have on the primary. A transformer is 2 (or more) insulated coils of wire wound on a laminated metal core. The ratio of the number of turns between the primary and secondary windings determines the voltage out put. Although it is 230VRMS it peaks at about 230 x 1.26.

In this power supply DH covered the mains area with a plastic cover. fuse.
However the actual product requires very specific wiring and earthing as well as testing by a registered person before it is used.Wiring up our own mains transformer within a project is complex and requires a specific process to be followed thoroughly. then we had it certified by an electrician before mounting and testing the rest of the low voltage circuits. This circuit looks simple enough it shows the switch.
373
. mains connector and primary of the transformer all in series.

26. This is however very inefficient use of a resource as half the power is never available for use – this means we might buy a 100VA transformer but only be able to use 50VA – translrmers are expensive so this is a waste of money. where there are 4 diodes. The output however is always the same polarity
374
. A diode rectifies the AC .
When the mains voltage is one polarity only two diodes conduct.
A more efficient use of the power is to use a full wave rectifier.
A half-wave rectifier (a single diode) blocks the negative voltage.
When it is the opposite polarity the other two diodes conduct. The output power of the bridge rectifier is almost all the power going into it not half of it.4
Stage 2: AC to DC Conversion
The second stage of the power suppy requires the conversion of AC to DC because all the circuits we use require DC voltage.

to assits we will use a capacitor. while it is high the charges used by the circuit will be supplied by the rectified AC which will also charge the capacitor. when the applied voltage is removed the capacitor will release these to the circuit. In a power supply we typically use very large capacitors e. So a 13VAC transformer will have a peak output of 13x1.26.414 = 18V. If there is no voltage on a capacitor and a voltage is applied a large flow of charges (current) will occur.6
Stage 4: Voltage Regulation
The ‘DC’ coming out of the filter section of the PSU is not completely smooth and it has a slight ripple component due to capacitor discharging and recharging. A capacitor is made of two metal plates separated by an insulator (called a dielectric).
26.g. 2200uF or 4700uF. Also we want 5V for our microcontroller. In our Power supply circuit the voltage rises and falls 100 times per second. This means that the voltage can go up and down as the load changes. while the voltage is low the charges stored in the capacitor will be used by the circuit. The characteristic of a capacitor is to store charges (electrons).
375
. A 16V capacitor will not do. Capacitors come in standard values 16V is a common value as is 25V. something that happens a lot in digital circuits as things switch on and off. here a 25VDC one was used. As the load changes the ripple increases (the load is the circuit we connect to the PSU and we show it as a resistor in the circuit below). These capacitors are polarised.5
Stage 3: Filtering AC component
We need a steady DC voltage from our power supply. so an unstable 16-18V DC supply is too high. so must go around the right way – they can explode so get it right! We also need to make sure that the voltage rating is more than the peak volate of the transformer.

5V will very like damage the microcontroller. The opamp compares the difference between the output voltage (Vfeedback from the voltage divider) and the reference voltage (Vref from the zener diode).
376
. Here the regulator is a series pass transistor controlled by an opamp and transistor. Every now and again there is a loud POP in the classroom and the smoke inside a microcontroller is released as another student forgets to check the voltage on the bench power supplies we are using and tries to run their micro at 30VDC!!
The output voltage must be controlled by some form of voltage regulator circuit. It increases or decreases the drive voltage to the series pass transistor to keep the two input voltages equal.From the portions of the datasheets below for the ATMega16 and the ATTiny461 we can see that they need around 5V for the standard higher speed devices and 3V would be fine for the type L devices Voltages that exceed 5.

more about that later.
Inside the 7805 IC there is a reasonably complex circuit. It comes in various package styles depending upon its use or its current limiting characteristics. R16 is a 0. This circuit has a current limit built into it. TO220 T092 TO5 SMD (surface mount device)
There are also different voltage ratings available e.Here is a common commercial device to do just that for us. 7812 (12V).25ohm resistor and is used to detect the amount of current flowing. R20 and R21 (Vfeedback). Transitors Q1 and Q18 form the main part of the comparator circuit. 7815 (15V). It is the 7805 (or LM340T-5). 7808 ( 8V). The components of interest however can be identified easily they are R1 and D1 (Vref).g. Q16 (series pass transistor).
377
.

This spec is called dropout voltage and it is the voltage difference between the input and output that is required to make sure the 7805 operates correctly. the maximum output voltage?_____________ the minimum output voltage? _____________
From the small section above we can determine what the minimum input voltage is that we can use to get 5V out.A 7805 can be added easily to our circuit. here are some sections from it. To get 5V out we need at least ____________ input voltage
378
. The datsheet for a 7805 can be downloaded from the internet.
What is the maximum input voltage? _________________ What do you think storing the device below -65 degC might do to it? If it got hotter than its maximum operating temperature of _______ degC what might happen? What is the typical output ?________________. But we must know about it so that we use it correctly.

The 7805 rejects ripple. A Decibel is a measure that is not linear but logarithmic in scale .000.000 x the power (10.1V) coming in it would be ______________ coming out of the 7805 (not much!) The power supply units looked at earlier had ripple specifications of 10mV that means that if we set our PSU to 5V then the voltage will fluctuate from 4.010V at the rate of 100 Hertz (100 because we full wave rectify the 50Hz AC voltage) Often a datasheet will give typical applications for a device
The note about the two small capactiors is very important when designing a 7805 circuit put them real close to the IC (within a few millimetres) As an aside I always use at least a 10uF electrolytic capacitor on the output of the 7805 if I will be using the ADC circuit of the ATMEL AVR.000 x the voltage) -80dB means 1/100000000 of the power (1/10000 the voltage) 80db from the datasheet means it reduces ripple output to 1/10000 of the ripple voltage coming in. If the ripple voltage was 100mV (0. the datasheet gives its specification as 80dB (decibels).4 times the voltage) -3dB means half the power (0. +3dB means 2times the power (or if a voltage is specificed . as this makes the ADC readings more stable! 379
.71 x the voltage) +6bB means 4x the power (2x the voltage) -6dB means ¼ of the power (1/2 the voltage) +80dB means 100.990V to 5. That sort of thing really upsets fast switching digital and microcontroller circuits and also can create hum in audio circuits.26.7
Ripple (decibel & dB)
Although the filter capacitor reduces the ripple voltage we do not want any of it getting onto the power pins of our microcontroller.1.

which means that if the input DC voltage changes then the output voltage will change no more than 10mV. So it is really good!
380
.01%+2mV The first one is the worst upto 230mV variation. So these changes in line input voltage should not effect the output voltage. One of the power supplies above quoted Line regulation (240V +/-5%): 10mV this means that if the mains voltage varies by up to 5% either side of 240V then the output voltage will change by no more than 10mV.
26. Three of the power supplies had specifications for load regulation.e. Load regulation: 230mV @ 0 . we trun LEDs.100% Load regulation (0-100% load): 10mV Load Regulation:≤0.8
Line Regulation
Line regulation refers to the line input voltage varying.990V and the last one by a little more than 2mV. This voltage however fluctuates as people turn applicances on and off. expecially large power users. so a 5V setting might drop down to 4. motors etc on and off). In our case we have a nominal (typical) mains voltage of 230V AC. The 7805 has a load regulation specification of 10mV typical and a maximum of 25mV. Another one quoted Line Regulation: ≤0. The 7805 Line regulation from the datasheet is 10mV. the second at 10mV means that the 5V would drop down to 4.01%+3mV so when the input AC voltage varies 0.9
Load Regulation
Load regulation is perhaps the most important specification for our power supplies as we want the output voltage to be constant while our circuits current load changes (i.26.01% of that variation + 3mV may be passed through to the output.770V.

don’t try this on your calculator because it generally gives E.5A or 500mA
In this circuit 5V into a load of 1 Ohms I=V/R = 5/1 = 5A (!!!!!!!!!) NO it wont work. sorry
I=V/R =5/0. if your 9VDC coming in is provided by a plugpack that has a 500mA output rating then you will only ever get 500mA max (trying to draw more may kill the plugpack) If it is coming from a 10A power supply then it will allow you to draw an absolute max of 2. HOWEVER.1A if you put a short circuit on the 7805.05A or 50mA
In this circuit 5V into a load of 10 Ohms I=V/R = 5/10 = 0. current limit is a function of the whole circuit.1A maximum. Using ohms law we can work out what the different currents are for circuits below
In this circuit 5V into a load of 100 Ohms I=V/R = 5/100 = 0.26.
381
.10
Current Limit
Although we regulate voltage we seldom regulate the current that a circuit can draw. which students sometimes think is infinity so infinite Amps!
The 7805 has a built in current limit circuitry to protect itself
It can deliver no more than 2.

This is fine if the circuit is working well.8/0.12 =) 40 ohm equivalent resistance.
If however you make a mistake with your breadboard or pcb and the circuit becomes 0 ohms then a problem can occur! In fact explosions can occur!!!
Batteries are not perfect but they are very good. When testing circuits if it doesn’t work check the temperature of your batteries.What exactly is current limiting and why is it important? Often batteries are used to test circuits. as they may explode even after having been disconnected as they can continue to heat up. The circuit under test may be drawing 120mA so it can be thought of as a (R=4.
In the class we have had batteries explode into fire.15 = 32A!! This internal resistance depends on things like temperature and the chemical reactions going on and could even be lower.8/0. Check out the internet for videos and pictures of exploding batteries if you don’t believe!
382
. they have a small internal resistance. which will limit the current. if they are very hot disconnect them and if they are really hot put them outside immediately. I = V/R = 4.

The current that the 7805 supplies to the circuit goes through the 0.25ohm).25 = 0. this has been reduced down to a basic block type diagram in the circuit below.ohms law .How does current limiting work?
The 7805 current limiting circuitry from the datasheet (above).0125V At 100mA V = 0.25ohm Current Sense (I sense) resistor.as current increase so does voltage).25 = 0.1 x 0.
383
. This resistor will develop a voltage (potential difference) across it which is directly proportional to the current (V = IxR .025V At 1A V = 1 x 0.05 x 0. Between the input and output of the 7805 is transistor Q16 and resistor R16 (0.25 = 0.25V At some point the current sensing transistor Q14 will turn on and shut off the main transistor Q16.
V=IxR At 50mA V = 0.

then it will have to dissapate 0. The 7805 is able to radiate heat however it has only a small surface area and so it is not very efficient at getting rid of heat. if this goes over 150 °C the device will shut itself down.26. Damage is not really a problem with the 7805 as it is “essentially indestructible” as the datsheet says.11
Power. Its warms up at the rate of 54 °C/W . This is where the specifications for a device become very important. The specification of interest is Θj-a (theta junction to ambient). In doing this the 7805 will act as a heater and get warm. So we bolt a heatsink to the 7805. clearly the device will shut itself down if this were to happen as it would get too hot.05 x 4 = 2Watts. The specification of interest becomes Θj-c (theta junction to case) which is 4°C /W
384
. If in the example we want to dissapate 4W then the junction temperatire will rise to 4 x 65 or 260 °C. However it will shut itself down if it gets too hot.05A.
If the 7805 needs to drop 4V at 0. as we do not want to exceed the power ratings or damage may occur.05A x 4V watts of power P=VI = 0. temperature and heatsinking
Using this diagram we can work out some power calculations for our 7805.
The ‘die’ is the internal silicon wafer (slice) that the circuit is built on.

Each part of the chain of dissipating heat has a negative impact. To be within range of our 150°C we will have to have reduce the rating to 150/11 = 13°C/W. but that is a reasonable size heatsink. If we use a mica insultor between the 7805 and the heatsink and thermal paste (to exclude any air from the join) it adds 1°C/W.
If we raise the input voltage to 16VDC. Much better than 54°C/W.
385
. A large heatsink might be 4°C/W. which is below the max of 150°C . If we have a heatsink of 8°C/W it will be OK. and we want to draw 1A from the 7805. At 4W our junction temperatire will be 4*22 = 88°C. in this case the one shown is 17°C/W. At 22 °C/W. We will have 16-5 = 11V across the 7805 and it will have to dissipate 11V x 1A = 11Watts. the lower the overall number the better heat can be dissipated. A small heatsink might be 20°C/W. that means 11W x 22 = 242°C. Our total is now 4+1+17 = 22°C/W.

386
. there is no need to add wires to connect the points. these points are connected as they are all called GND.14
PSU Schematic
In this circuit the thick lines indicate higher current paths.13
Regulators
Transformer Rectifier & Filter
LM317
Variable Voltage
26.12
Typical PSU circuit designs PSU block diagram
7805 Fixed 5V
26.26. which will require thicker tracks on the PCB Note that there is no current limit apart from the 7805 and LM317 internal current limits (at least that’s better than 30+amps direct from batteries). Note the three GND connections.

we must know about the current limits of the PCB tracks.Initially layout your components in a logical way Here a small heatsink was used in the centre of the PCB and the two regulators were mounted on either side of it. This equates to 0. Type ‘polygon gnd’ into eagle and set the values for width. The wires to connect to other components were all placed around as few sides of the board as possible.0028 inch thick tracks. A 0. and as close to the edges as possible.086in thickness. A ground plane also reduces the amount of copper that will need to be etched. A copper track although a conductor still has a finite resistance and will burn up if too hot (too much current flows through it). This is all to do with resistance and heat. The components that belonged with each part of the circuit were put on each side of the heatsink.032 inch. In an effort to reduce electrical noise and any voltage fluctuation a large ground plane is added to the board.1inch apart. this is a powersupply designed to deliver current to other ciruits.5A and will increase in temperature by about 10 degrees C.086 inch wde track can carry about 3. this is the thickest track possible to connect to the voltage regulators as their leads are 0. Then draw the polygon around the edge of the board and redraw the ratsnest to fill in the polygon. (which is ok). 3. isolate and spacing for 0. saving on chemicals. There is another consideration here. We use PCB which has 2oz (ounce) of copper per square foot. The capacitor and voltage regulator were added to one end f the board.5mm mounting holes were placed in the corners. Next the tracks were started.
387
. The ground was laid first around the outside of the board and using 0.

If we were to bolt them to the heatsink without insultating them the variable voltage would short out to ground. In the LM317 variable voltage regulator the metal tab is connected to Vout. because the metal tab of the IC package os electrically conneted to one of the legs.Insulating of heatsinks and voltage regulators
Most devices need insulating from heatsinks. the variable voltage.
388
.
In the 7805 the metal tab is electrically ground (or 0V). When we have a 7805. its case is already ground sowe don’t need to insulate it. but the LM317 still needs insulation.

The current can be controlled by using different values of resistor (a potentiometer could be fitted if it was a special high power one).
From the LM317 datsheet there is an application to build a current limit. Check out the datasheet for other applications for the LM317.26.
In this circuit below the current can be set using two values for R1 and R2 and a switch to select either or both (giving three different preset values) If 1R2 ohms gives 1 amp limit What value of R would give a current limit of 200mA?
389
.15
Practical current limit circuit.

This means that we can solder them onto the PCB and then heatsink them easily against a large heatsink or a metal case.In this layout the 3 voltage regulators are mounted on the very edge of the PCB.
390
.

2V 1k 5V 10k V = 5 x 1/11 =0.
DC input 317 Variable DC output
7805
LCD Attiny ADC GND/OV Voltage Divider
GND/OV
In the block diagram above the voltage divider divides the output voltage of the PSU down to a value within the range of the ATTiny461 ADC port and uses that to measure the voltage.56 volts so you must make sure that the voltage into the ADC cannot exceed 2.p. We can monitor the output of a power supply by reading the voltage with an ADC pin on the microcontroller and converting this to voltage display on the LCD.56 x 1024 =727
391
. 5V and 20V in along with the reading for the ADC.16
Voltage measurement using a voltage divider
Having developed a variable power supply it is important to be able to measure the voltage it is set to.) would be for 2V.8 / 2.56V so some ohms law and resistance calculations are necessary. If the maximum voltage out of the PSU is 20V then a ratio of 10:1 for the resistors would be satisfactory The following shows what the voltage (to 1d.5 / 2.5V 1k 20V 10k V = 20 x 1/11 =1.56 x 1024 =73
ADC reading = 0.
2V 10k V = 2 x 1/11 =0.56 x 1024 =182
ADC reading = 1.2 / 2.8V 1k
ADC reading = = 0. The AVR has an internal reference voltage we can use. It is 2.26.

This computer program simulates the variable power supply. the action of the voltage divider and the conversion process within the microcontroller
392
.We used the Attiny461-20PU for this project. The ATTiny461 has 11 ADC inputs (although we cannot use ADC10 because it’s the reset pin and we need ot for programming). ATMEL like to change models of its microcontrollers all the time. we don’t mind this as each time they do they tend to get a little better for the same cost! However it does mean keeping up to date with the micros specifications.

3 .2 . since then he has taken his program to a further stage to incorporate more features such as audible warnings and other visual warnings.26. Prescaler = Auto . AN ADC requires an input voltage and a reference voltage against which to compare the input voltage. In terms of systems knowledge this is is an example of sub systems where students must be familiar with the I/O characteristics and function of a device but not the detail of its internal operation.4 .bas '-----------------------------------------------'Program Description: 'use ADC to read voltage from output of a voltage divider 'convert adc value to one that matches the voltage into the voltage divider 'use an LCD to display value of the voltage '-----------------------------------------------'Compiler Directives $crystal = 1000000 'speed of operations inside the micro $regfile = "attiny461. Db5 = Portb. where a 0 means 0Volts and 1023 means the same as the reference voltage.17
Variable power supply voltmeter program
This program was developed to display the voltage of the variable powersupply. In this case we are using the internal 2.56 volt reference with a 0.11V or 2.dat" 'the micro we are using '-----------------------------------------------'Hardware Setups Config Porta = Output Config Pina. Db6 = Portb. 1.1 Config Lcd = 20 * 2 'configure lcd connections Config Adc = Single .7 = Input Config Lcdpin = Pin .56 internal. external. Rs = Portb. Db4 = Portb. E = Portb.1uF capacitor on AVCC (pin 15). It has different voltage references we can use. Db7 = Portb.5 . 393
.6 . The ADC reading will be in the range of 0 to 1023.Collis and Anka 'Date: May 2010 'File Name: Voltmeter. Anka (year11) and I worked on it together.56_extcap Start Adc
Initially we configure all the pins on port A as outputs. however the voltage divider is connected to A. Reference = Internal_2.
'Title Block ‘Name: B.
The first line sets up the analogue to digital conversion circuits within the AVR. The Attiny461 has 11(though we can only use 10) ADC inputs.7 so it must be configured as an input.

This number will not be the voltage but a number that changes in relation to the voltage so we must convert it into a number that is the same as the voltage. 1.'initialise hardware Cls 'clears LCD display Cursor Off 'cursor not displayed '----------------------------------------------'Declare Constants 'Declare Variables Dim Adc_in As Word Dim Voltage As Single Dim Dividor As Single Dim Volts As String * 5 'Initialise Variable Dividor = 32. 2. This must be a word sized variable as it may store up to 1023 (remember a byte can only store upto 255). Read the voltage into the word variable adc_in. display the string version of the voltage. here we need a variable to store the value we read from the ADC input.6255 '---------------------------------------------'Program starts here Do Adc_in = Getadc(6) Voltage = Adc_in Voltage = Voltage / Dividor Volts = Fusing(voltage . the string is formatted to have only 2 decimal places. the letter V and then a couple of blank spaces on the LCD. 4. We want to display decimals so we must use a single or a double. " " Loop End
No need to display the cursor on the LCD
Variables store data. 6. "V" . we do not need the precision of a double so we use the single. 1 Lcd Volts . We could use the same variable voltage however it will give us loads of decimal places so we will convert it to a string and then format the string so we need a varibel that can hold a string. repeat the process all over again
394
. position the cursor 7.##") Locate 1 . Put this number into the single variable 3. We want to display the number on the LCD as well. This will be a number with loads of decimal places so we conver it to a string 5. 8. "#.

in pF? nF? uF? What is the number written on it and what does it mean? Why is it used? What does polarised mean? What are the two ways of knowing how to put an electrolytic capacitor into the circuit correctly? Resistors Calculate the value for a current limit resistor with a 12V battery and an LED drawing 2mA Select the closest value we have in class that you could use.27 Year11/12/13 typical test questions so far
Capacitors What is the value of the small yellow Capacitor in the microcontroller circuit. one to move it left. using 3 switches. Programming Write a short piece of code that counts 15 switch presses and then flashes an LED Write a short piece of code that checks 4 switches to see if they are all pressed. Algorithms/Modelling Why do we write algorithms before we program? (Do 2 of the following algorithms) Write pseudo-code then draw a flowchart for a program to read 2 switches to control the position of an LCD character. one to move it right and press both to change line. FLASH & EEPROM Subsystems Draw a system context diagram for your project 395
. the second to move to the next letter. If you could use 2 values of resistor found in class combining them together which 2 would you use? Explain what a voltage divider does What do we use potentiometers in circuits for? Expalin how a potentiometer is a voltage divider Multimeter use You want to measure the current drawn by your LED in a microcontroller circuit. Write an algorithm to play as many different tones as possible if you have 4 switches and press them in different combinations Write an algorithm to change the speed of a flashing led using 2 switches Write an algorithm that uses 1 switch to enter the number of times an led will flash and a second switch to start the LED flashing Write an algorithm to allow a user to enter their name into a variable. Variables If you were to record the position of a character on an LCD what type of variable would you use? Describe overflow If you were have a user enter their age what type of variable would you use? If you were counting seconds in a minute what type of variable would you use? In an hour? In a day? In a year? In a century? Give good names for these variables. draw a diagram of how you would do it and what settings you would use on the multimeter. last and any middle names. the first to increase the litter. Write a subroutine to check if a value is a multiple of 10 and if it is to flash an led once Write a subroutine to add three strings together with a space beweeen each string Write a subroutine that gets the first character from each of three strings and displays it on the lcd Write asubroutine to get the middle letter of a string and display it on the lcd Write a subroutine to get a random letter from a string and display it on the lcd Microcontollers What are the different uses of the three microcontroller memory types:RAM. the third to finish. Dimension variables that would hold each of your first.

Explain each of the main commands to use an LCD
396
.Draw a block diagram for your project What does ‘black box mean’ What are at least 3 things about a 7805 that makes it so useful for a microcontroller circuit Describe the inputs and outputs of an LCD.

Note that the flowchart is split into 2 parts to allow for 1 page printing. 'get 50 values and store them in the array For index=1 to 50 lightlevel(index) = getadc(0) Waitms 50 Next 'read the 50 values from the array and display them For index=1 to 50 Locate 2.g. . however what do you do when you want to store many similar variables e.g Dim lightlevel as byte(50) this array becomes very easy to read and write using a loop. e. ..28 Advanced programming -arrays
It is easy to dimension variables to store data. Think of the data we want to collect as in a table. lightlevel1. each row is labelled with a number to identify the row – we call this an INDEX. Do you create 50 variables e. lightlevel50 ? The answer is no because it is so difficult to read and write to 50 different variables.1 Lcd lightlevel(index) Waitms 50 Next In this next program a system has been developed that takes 50 lightlevel readings. There are 8 if conditions.. lightlevel2. In Bascom the variable lightlevel(1) will be the first value and lightlevel(50) will be the last.. lightlevel3 . Arrays are a highly important programming structure in computer science. the second are carried out depending on the value of the variable MODE. All processing is within the subroutines. The user can start the readings process and control the display of the readings on the LCD. .g. the first 4 read the 4 buttons. 49 432 50 198
An ARRAY type variable is dimensioned to store the data. Index lightlevel 1 345 2 267 3 378 4 120 5 203 .
397
. 50 light level readings over a period of time.

1 Lcd "continous readings" Locate 2 . can you modify the proram so that prev and nxt buttons change the timing of the reading. Fix the bugs with the prev and nxt routines so that they don’t go below 0 or above 50. 1 Lcd Lightlevel(index) . can you modify the program so that the prev and nxt buttons change the number of readings to be stored. " Return Cont_reading: Locate 1 . 1 Lcd index .
401
. " " Locate 2 . 1 Reading = Getadc(0) Lcd Reading . " " Return
"
Prev: Decr index ‘fix this routine so that it doesn’t underflow Return Nxt: Incr index ‘fix this routine so that it doesn’t overflow Return
1.Locate 1 . 2. which mode would it be best to place the new code in? 3.

These can be activated from within software. well its important to understand the concept of pullup resistors and by physically using them you gain a better understanding of them. however you still have to activate it.2 = Input Set portd. this means you don’t have to connect a separate resistor.
Config Pind.2 = 0 then … … … end if Why didn’t you learn about this straight away.
402
.2 ‘activate internal pull-up If pinb.29 AVR pull-up resistors
A useful thing to know about is that the AVRs have internal pullup resistors for use when you connect a switch to an input pin. Note that by default it is not activated.

this stops the key frombeing sensed multiple times. Db7 = Portc. Then this routine can be called from anywhere in the program.bas ‘develop a simple subroutine that translates key press codes into more recognisable key values. '-----------------------------------------------------------------' 5. rows as outputs and puts a low on those set as inputs. It is also better to have a subroutine handle this process and keep it away from your main code.3 . Title Block ' Author: B. Db4 = Portc.2 . just 8 pins. initialise hardware 403
. Hardware Setups Config Lcdpin = Pin .
The code which is returned from getkbd() will not match the number on the keypad so a translation process is required. E = Portc.30 Advanced keypad interfacing
It is quite straightforward using Bascom to read a keypad.5 .
30. Rs = Portc. Config Kbd = Portb Dim kbd_data As Byte Kbd_data = Getkbd() 'keybdb returns a digit from 0 to 15 LCD kybd_data The connection to the microcontroller is straightforward as well.dat" 'the micro we are using '-----------------------------------------------------------------' 6. The columns are any key is pressed there is a 0 then it inputs and columns as rows it has a valid to determine exactly arranged in a matrix of 4x4 and each row connected to the microcontroller. Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 'the crystal we are using $regfile = "m8535. it reads the columns and if there will be a 0 on one of the columns. Solder headers into the 8 pins of the keypad and 8 pins as shown on the PCB How do the 16 key keypad and the software work together? The Keypad is and column are Software: The micro sets the ports. it handles all the hard work for us with the built in function Getkbd(). In this code not only is the key translated but it is not returned untilt he user releases the button. Db6 = Portc.4 . If reverses the situation with the rows as outputs and if there is a low on one of the keypress.1
Keypad program 1
'-----------------------------------------------------------------' 1. The combination of 0's is used which key is pressed.Collis ' Date: 14 Aug 2003 ' File Name: keypad_Ver1.1 . Db5 = Portc.0 Config Lcd = 20 * 4 'configure lcd screen Config Kbd = Portd '8.

A cursor is a flashing or steady line on a screen to show you where the next text will be entered. If you want text to appear in a certain location on the screen then you have to move the cursor with Bascom’s LOCATE function. When text is sent to the display it will appear at the cursor location and the LCD will move its cursor one space to the right. that numbers on an LCD are not data. the LCD itself has very limited cursor control. when programming keep them within separate sub routines. In this program data is collected from a keypad and stored in a variable. 2. In simple programs as with the above two the microcontroller has no idea where the cursor is. Often with LCDs there appears to be no cursor. these are two separate and different control processes. it just gives the LCD data to display. 1. In this case you need to keep track of the cursor location yourself by using some variables. just invisible.3
Keypad program 3 – cursor control
The really big concepts to understand here are 1. * to clear the screen. Data is in your program. ' Declare Variables Dim I As Byte Cursor Dim Cursor_x As Byte control Dim Cursor_y As Byte variables Dim Kbd_data As Byte Dim Key As Byte ' Initialise Variables I=0 Cursor_x = 1 Cursor_y = 1 Key = 16 'nothing to process to start with Cls 'clears LCD display Cursor Noblink 'steady cursor '-----------------------------------------------------------------' Program starts here Locate Cursor_y .C. as it is not turned on. In a complex program you may want to move the text around the screen at will. The cursor however is still there. If you want text to appear in certain places on an LCD (or any screen) you must control it within your program.D to move the cursor . cursor control and 2. Don’t mix them up. as in this next program. Then this data is put onto the LCD.B.30. so you do this by moving the cursor first and then sending data to the display. # to insert space 'the use of key=16 is so that the key is sensed only once per press 406
. Cursor_x 'move lcd cursor to top left corner of LCD Do Gosub Read_1_keypress 'get a single key press Gosub Disp_char 'display char and move cursor Loop End 'end program Disp_char: 'displays numbers on lcd 'uses A.

Chrcodes) End If Return
'read a key 'store the keypress 'no key pressed 'remember no key pressed 'return '?' 'exit the subroutine 'same key still pressed 'count in 1ms increments 'check we havent gone too far 'so we dont overflow end of table 'MOD means get remainder '0 means it is a multiple of 80 'how many multiples of 80 'get char from table
'new keypress 'remember key press 'start counting again 'get char from table
413
. Chrcodes) End If Else Oldkey = Key Lookupval = Key Key_counter = 0 Key_char = Lookupstr(lookupval . Chrcodes) Return End If If Key = Oldkey Then Waitms 1 Incr Key_counter I = Key_repeatdelay * 8 If Key_counter > I Then Key_counter = I I = Key_counter Mod Key_repeatdelay If I = 0 Then I = Key_counter / Key_repeatdelay Lookupval = I * 16 Lookupval = Lookupval + Kbd_data Key_char = Lookupstr(lookupval .5
Keypad texter program 1a
This version of the program instead of having a lot of repeating code does some maths to work out the multiple of 80 and uses that to lookup the key character. ' new constants to replace all the old ones Const Key_repeatdelay = 80 ' ADD ONE NEW VARIABLE TO THE OTHERS ABOVE Dim I As Word
' Subroutine Read_keychar: Kbd_data = Getkbd() Key = Kbd_data If Kbd_data = 16 Then Oldkey = 16 Lookupval = 144 Key_char = Lookupstr(lookupval .30.

bas '-----------------------------------------------------------------' Program Description: ' Hardware Features: ' LCD on portc .Collis ' Date: July 2010 ' File Name: keypad1ioLine. NOTE YOU MUST NOT HAVE AREF PIN CONNECTED ON THE MICRO WHEN USING THE INTERNAL VOLRAGE REFERENCE!! '-----------------------------------------------------------------'Title Block ' Author: B. The values of resistor chosen in the above schematic allow a range of values from 0-2V.30. so we will use the internal reference voltage rather than the VCC voltage as comparison value for our ADC converter.
This program reads the ADC value and displays both it and a value representing which key is pressed on the LCD.note the use of 4 bit mode and only 2 control lines ' keypad connected as per R4R circuit on 1 ADC line ' lm35 on adc 414
.6
ADC keypad interface
A 16 button keypad is a really nice feature for our projects but generally it requires 8 lines to connect it to a microcontroller. In this voltage divider circuit whenever a key is pressed the voltage to the microcontroller changes and can be sensed using a single ADC input. and sometimes we just don’t have these available as we have used them all up.

Note the changes in the lines in bold that are different or in different locations to the previous routine. When the bullet reaches the target it first replaces the target then there is a delay and then the dying man image appears. Bullet_pos Lcd Chr(bullet) 'draw bullet Waitms Bullet_speed Locate 2 .
420
.
Fire_bullet_do_v2: '1343 bytes 'this routine moves a bullet across the display If Target_pos > Shooter_pos Then 'shooter is left of target Bullet_pos = Shooter_pos + 1 'start in next lcd segment Do 'not hit yet Locate 2 . Target_pos Lcd Chr(deadman2) End If Return
Using the do-loop this way resulted in the programming taking up 1336 bytes in flash making it the shortest version. However it has a subtle problem. Target_pos Lcd Chr(deadman2) End If Return
This code implements the bullet hitting the target properly as the last bullet appears in the space before the target and then after the bulletspeed delay the target becomes the dying man. Bullet_pos 'blank the bullet Lcd " " Loop Until Bullet_pos = Target_pos Locate 2 .Fire_bullet_do_v1: '1336 bytes 'this routine moves a bullet across the display If Target_pos > Shooter_pos Then 'shooter is left of target Bullet_pos = Shooter_pos 'start at the shooter position Do 'not hit yet Incr Bullet_pos ‘increase first Locate 2 . Bullet_pos ‘draw bullet Lcd Chr(bullet) Waitms Bullet_speed Locate 2 . To do this the code had to be changed. Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 . Bullet_pos 'blank the bullet Lcd " " Incr Bullet_pos ‘increase after Loop Until Bullet_pos >= Target_pos ‘check if gone past Locate 2 . Using a high value for bulletspeed allows you to see the problem happen. Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 .

Target_pos Lcd Chr(deadman2) End If Incr Bullet_pos Wend Return
In this subroutine the initial if-then statement that checks the relative positions of the shooter and targets is removed in an attempt to streamline the code. Target_pos Lcd Chr(deadman2) End If Return
This code segment uses the while-wend. Even though it is longer than the above code when compiled it correctly implements the final bullet not hitting the target. When the target is left of the shooter 2 lines of code are executed. Bullet_pos Lcd Chr(bullet) 'draw bullet Waitms Bullet_speed Locate 2 . Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 . Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 . However it is not quite as efficient code as the first. Bullet_pos Lcd Chr(bullet) 'bullet Waitms Bullet_speed Locate 2 .
Fire_bullet_while_v2: '1342 bytes 'this routine moves a bullet across the display Bullet_pos = Shooter_pos + 1 'start in next lcd segment While Bullet_pos <= Target_pos 'not hit yet Locate 2 . Bullet_pos 'blank the bullet Lcd " " Incr Bullet_pos Wend Locate 2 .
421
.Fire_bullet_while_v1: '1344 bytes 'this routine moves a bullet across the display If Target_pos > Shooter_pos Then ' shooter is left of target Bullet_pos = Shooter_pos + 1 'start in next lcd segment While Bullet_pos < Target_pos 'not hit yet Locate 2 . It also reintroduces the same problem as first do-loop with the bullet replacing the target. first the bullet pos is calculated and then the position is checked. Bullet_pos 'blank the bullet Lcd " " If Bullet_pos = Target_pos Then Locate 2 .

It is really bad programming practice though as the variable shooter_pos had to be increased for the code to work. Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 .Fire_bullet_while_v3: '1340 bytes 'this routine moves a bullet across the display Bullet_pos = Shooter_pos + 1 'start in next segment While Bullet_pos < Target_pos 'not hit yet Locate 2 . Bullet_pos Lcd Chr(bullet) 'draw bullet Waitms Bullet_speed Locate 2 . Bullet_pos 'blank the bullet Lcd " " Incr Bullet_pos Wend If Bullet_pos = Target_pos Then 'hit Locate 2 . Lessons:  Get to know the three looping methids  TEST TEST TEST your code carefully and methodically to identify correct operation  When changing code retest it thoroughly for introduced errors  Avoid changing variables you shouldn’t change  Keep records of your experiments to get the best possible grades
422
. It is really untidy code as it tries to separate the 2 ideas which are integrated together in the flowchart by separating the while and if parts. Target_pos Lcd Chr(dyingman) Waitms Deathroll Locate 2 . If you use the variable shooter_pos elsewhere in your program then it could have disastrous effects. Target_pos Lcd Chr(deadman2) End If Return
Fire_bullet_for: '1352 bytes 'this routine moves a bullet across the display If Target_pos > Shooter_pos Then ' shooter is left of target Incr Shooter_pos 'start in next segment of lcd For Bullet_pos = Shooter_pos To Target_pos Locate 2 . it is the easiest to follow and works correctly. Bullet_pos is calculated. Target_pos Lcd Chr(deadman2) End If Return
This code executes correctly however it is also inefficient. Bullet_pos 'blank the bullet Lcd " " Next Locate 2 . Bullet_pos Lcd Chr(bullet) 'draw bullet Waitms Bullet_speed Locate 2 . This can lead to real big problems as changing one of them has consequences on the other. If the target is left of the shooter three lines of code are executed. This also compiled into the longest code
The best of these is the first while loop. This also has the problem of the bullet replacing the target. the while is checked and the if is checked. It is poor programming practice to alter a variable you don’t need to. These 2 ideas are importantly linked together.

an inductor. similar to the LCD backlight control. There is a neat video on youtube http://www. this is due to the current being switched on and off by the commutator several times per second. the field collapse causes charges to flow in the opposite direction and these can flow back into tyour transistor killing it instantaneously. a magnet. brushes and a commutator (rotary switch).com/watch?v=zOdboRYf1hM of a simple motor and another one that demonstrates the importance of the commutator (only one side of the wire has its insulation removed) http://www. The diode is another important safety device to protect your transistor and microcontroller from sure desctruction. a battery. when there is current a magnetic field forms around the coil and when you turn it off this field collapses back into the coil turning your coil into a generator for a very short period of time. The diode conducts these charges away safely.32 DC Motor interfacing
Nowadays who doesn’t want to see motor attached to a microcontroller moving something around! But to do this a bit of knowledge and understanding is required first.youtube.  many turns on each coil of wire  a shaft through the coil to which we can connect things like wheels or gearboxes.
We can control a small DC motor with a simple transistor switch ciruit.In this case the backlight has been replaced by a motor. A dc motor is made from a coil of wire.
423
. A motor is a coil of wire i.com/watch?v=it_Z7NdKgmY While a diagram such as this on the left shows a simple description of the construction of a DC motor a typical dc motor has:  several separate coils and multiple connections to the commutator. some of which is important physics knowledge. a capacitor and a diode. When a motor is running it produces a lot of electrical noise.youtube. This noise appears as spikes in the voltage on the power lines to the microcontroller and can cause your micro to reset all the time.e. The actual sparking can be seen between the brushes ane the comutator on some motors.

Another current rating is of significance it is the stall current. Less voltage less torque. Your power supply must be able to meet this power requirement. You must understand this when designing the power control circuits. A DC motor is rated at the voltage it is most efficient at. It is always tempting to run it at a higher voltage but if you apply too much it will overheat. The reason being that voltage is directly related to motor torque. They have an operating current which is the typical current the motor will use under normal load/torque. but you hold the shaft so that it stops rotating a lot of current will flow (stall current) and a lot of power will be required. If you run you motor. Your power supply should be fused as well in case problems with the motor draw too much current over heating it.DC Motors come in all shapes and sizes
Knowledge about driving these devices relies on understanding the specifications for your motor. it just wont work or it wont work anywhere as well. If you have a 12V 2A (24W) motor and your power supply is only capable of 12V 500mA you will never drive the motor properly. The power used wll be the operating current times the rated voltage. If you run it at a lower voltage. DC motors are generally made as non-polarized do if you reverse the voltage it goes in the opposite direction.
424
. when it gets too hot the insulation on the wires of the coil will melt shorting the whole lot out and cause a small (hopefully not big) fire. more voltage more torque.

1
H-Bridge
A single transistor may be useful for turning a motor on or off however if a motor needs to be reversed in direction then an H-Bridge circuit is called for.32. The principal is simple to reverse direction reverse the connection to the battery
B and C switches closed A and D switches MUST BE OPEN or the battery will be shorted out!
A and D switches closed B and C switches muts be open or the battery will be shorted out!
NOTE : the circuit has fuses in it – these are a really really really good idea!!
425
.

In the above diagrams the thick lines represent the fact that large currents are drawn through the motor and transistors. so heavy wiring is also required as well as fuses!
426
.A microcontroller can be used successfully to achieve this by switching 2 out of 4 transistors on and off in sequence.

With 4 inputs there are 16 possible inputs. All combinations of inputs have been covered in this table. To do do this we turn on two transistors such as A and B OR C and D . If we want it to stop in a hurry though we can force the motor to brake by shorting it out.
A H L H L L H L L L L H X
B L H H L L L H L L L X H
C L H L H L L L H L L H X
D H L L H L L L L L H X H
Motor Rotate Left Rotate Right Brake Brake Free Free Free Free Free Free Shorted Battery!! Shorted Battery!!
H = high = 1 L = low = 0 X = don’t care ( this means that the otherinputs selected as high or low already have priority over these and it doesn’t matter what you choose here) 427
.2
H-Bridge Braking
If we turn off all the transistors in an H-Bridge then the motor is free to turn.
Truth table This is a common thing to see in electronics a table that describes what happens on the output for each different combination of inputs.32.

There are a couple of different versions of this IC the D model has internal protection diodes. they act as a heatsink for power to dissipoate through. one of these is the L293D.32.
There are 4 ground pins which all must be connected to the pcb.3
L293D H-Bridge IC
Making an H-bridge circuit is not necessary for small and medium sized motors as plenty of ICs exist to help you.
428
.

The Enable pin must be high (1) for the chip to do its job. that means floating. what we call high impedance.
429
. if it is low (0) then the output is off. something we normally want to avoid on input pins to a microcontroller but whichis great on outputs.

32.4
L298 H-Bridge IC
430
.

32.5
LMD18200 H-Bridge IC
In this diagram two LMD18200 circuits are connected to two DC motors from handheld drills.
431
.

but some LEDs have been added so that the operation of the circuit can be observed while under the control of the microcontroller. the brake should be high.The circuit is straight forward. There is on this chip a great current sense feature that we can use to feedback information to the micro. PWM should be high and DIR can be either high or low.
To control this IC we need to know how to turn it on and off From this truth table we read: To run the motor brake should be low. direction will be high or low and PWM should be high To stop the motor.
432
.

note the very large tracks becase a lot of power can be used in this circuit.
433
.Layouts for the board.

hFE for the BDX53C is at least 750. because they effectively have 2 transistors one after the other in the circuit. Two castors were also needed for the final product. Note that it has a protection diode built into it already.32.\
435
. A high current circuit was needed so Darlington transistors were used. The motors are used electric window motors form a car and the wheels were from roller skates. Here is it shown upside down with two darlington H-bridge boards on it. They have an hFE of at last 1000.
In other uses of this circuit TIP126 and TIP127 transistors were used. Darlingtons such as BDX53C have much higher gain.7
Darlington H-Bridge
In this project TC developed a tool trolley for a mechanic working under a car. but more were added in the circuit in case transistors without protection diodes were used to replace them in the future.

This circuit was based upon the circuit from www.mcmanis .com all we did differenyl was use parts easily available to us in NZ. It has a really neat feature of protectingthe micr from transistor and motor noise using opto isolators and the smart way in which it is wired means we cannot turn on Q1 and Q3 (or Q2 and Q4) at the same time and blow them up!
436
.

437
.fo this sound tracking robot.Layout diagrams
An important point to note are the heavy current tracks from the power supply to the power transistors. 4 of these were needed with one mounted in each corner. Here is the microphone sensor circuit.

32.8
Stepper motors
Stepper motors can be found in old printers and depending on the voltage and current can make small robots.
438
.

they can be driven in full step mode where only one winding is on at a time.Think of a stepper motor as having 4 windings.
439
. however they are better driven in half step mode where either one winding or two windings are on at a time.

which requires an H-Bridge type circuit.
440
. sometimes in differentdirections.To get drive the motor in either of the above ways a simple ULN2803 darlington transistor array could be used
However there are a lot of inefficiencies in this sort of circuit and the motor power can be more fully made use of by driving more than one winding at a time.

441
.The L297 and L298 are some great driver chips for stepper motors. they do require careful use and are probably harder to find nowadays.

Full schemtic of the PCB with two complete driver circuits
442
.

Component layout for the PCB
443
.

As with all motor circuits there is a need to keep tracks as short and direct as possible do note how this is achieved on the board
444
.

If the rate is fast enough then the flickering of the LED or the pulsing of the motor is not noticeable.
445
. yet the pulsewidth (on time) is different for each one (other modes do exist however these will not be described yet).
If this waveform were applied to an LED it would be at about ¾ brightness
If this waveform were applied to an motor it would be run at about ¼ speed
The AVR timer/counters can be used in PWM mode where the period of the wave or frequency is kept the same but the pulse width is varied.9
PWM . This is shown in the 3 diagrams.32. a better solution is to turn it on and off rapidly. the period is 2mS for each of the three waveforms.pulse width modulation
To control the brightness of an LED or speed of a dc motor we could reduce the voltage to it. however this has several disadvantages in terms of power reduction. If this waveform was applied to a motor it would run at around half speed.

the inverse of the period.
Period .11
Uses for PWM
A pulse is used to charge a capacitor through a resistor. Frequency .the time from one point in the waveform to the same point in the next cycle of the waveform.
The width of the pulse determines to the motor which in turn slows or advantage of using PWM rather is that torque (power) of the motor
the average DC voltage getting speeds up the motor.the length of time the pulse is high or on.
447
. when the pulse is high the capacitor will charge.the on time of the pulse as a proportion of the whole period of the waveform. if period = 2mS the frequency = 1/0.002 = 500 Hz (Hertz). Pulse width .32. the than reducing the actual voltage maintained at low speeds. when it is low the capacitor will discharge. Duty cycle . The 'mark' time. the wider the pulse the longer the capacitor charges and the higher the voltage will be.

32.12
ATMEL AVRs PWM pins
As time goes by every new model of the AVR microcontroller that is introduced has more features. and it can be hard to keep up with all these features. AVR PWM Pins ATTiny13 2 using Timer 0 OC0A OC0B ATTiny45 2 using Timer 0 OC0A OC0B 2 using Timer 1 OC1A OC1B (note OC0B and OC1A share the same pin so cannot be used at the same time) ATTiny2313 2 using Timer 0 OC0A OC0B 2 using Timer 1 OC1A OC1B ATTiny26 2 using Timer 1 OC1A OC1B ATTiny461 6 using Timer 1 OC1A OC1B OC1D (and their inverses) ATMega8535 / 16 / 32 1 using Timer 0 OC0 2 using Timer 1 OC1A OC1B 1 using Timer 2 OC2 ATMega48 / 644 2 using Timer 0 OC0A OC0B 2 using Timer 1 OC1A OC1B 2 using Timer 2 OC2A OC2B
448
. For instance PWM each chip has different capabilities for hardware PWM.

Here is a PWM solution for PWM on portA. freq = 64Hz T2_ovf: Set PORTA. Compare Pwm = Disconnect Compare2 = 50 Enable Timer2 : Enable Oc2 Enable Interrupts '********************************************** 'Program starts here Do Loop End '********************************************** 'Interrupt Routines 'Timer2 pwm on any port.7 using the 8 bit timer0.7 Return
449
. What happens then when you want more PWM outputs or to use different pins.8mS =64Hz (suitable for driving a servo motor) Config Timer2 = Pwm .13
PWM on any port
The issue with hardware PWM is that it is fixed to particular pins on the microcontroller. 'PWM Timer2 pwm on any port 'Timer 2 PWM 8bit period = 15.32. Prescale = 256 .7 Return T2_oc2: Reset PORTA.

 In 9 bit mode the counter counts from 0 to 511 then back down to 0. The 3 PWM modes for timer1 discussed here are the 8.32.5 (OC1A) would switch from 0Volts (0) to 5 Volts (1) as in the next picture. If the value were set to 100 then the output pulse on portd.
The programmer sets a point from 0 to 255 at which the output will change from high to low.
To work out the frequency of the pulses For 8 bit: Freq = 8000000/prescale/256/2 For 9 bit: Freq = 8000000/prescale/512/2 For 10 bit: Freq = 8000000/prescale/1024/2 450
.  In 8 bit mode the counter counts from 0 to 255 then back down to 0. 9 & 10 bit mode.14
PWM internals
Each PWM output has independent settings for the pulse width however if they are controlled by the same timer they will will run at the same frequency.  In 10 bit mode the counter counts from 0 to 1023 then back down to 0.

768Khz crystal to be connected to the micro.
In System Designer you can add the crystal to the diagram. Separator=/ Enable Interrupts
452
. These require a 32.33 Advanced System Example – Alarm Clock
Bascom has built in functions for managing the time and date.
To use the cryatal and these features add the following 3 lines to your program Config Clock = Soft Config Date=Mdy. In the variables table the variables that Bascom creates automatically are avaialbel for you to use within your program. So it canot be used for anything else. Take note that this must go onto the pins shown and that Bascom software routines for the time use Timer2.

Using knowledge of maths with byte type varibles (there are no fractions) we can divide the variable _hour by 10. which gives us the remainder of a division in byte math. So in a program we might have the code Digitpos=1 Gosub dispA and digitpos = 5 gosub dispT
If we wanted to display the time on the LCD this subroutine might be used.3 in the next.33.g. 23:57 is made up of 2x10 hours and 3 hours. That would be very inefficient.g. however it was static. 19/10 = 1 (byte math!!) Digitpos = 1 Gosub Show_bigdigit 'find the digit in the units of hours position I = _hour Mod 10 'e.e. 19 If _sec < 10 Then Lcd "0" Lcd _sec Return
460
. Dim I as byte ‘ a temporary variable I = _hour/10 ‘ e.3
LCD big digits
In the exercise above large text was to be displayed on the LCD. To display large text on the LCD that is changeable by the program we need to be able to create any character at any location on the display.g. to get the value we want.g. and 5x10 minutes and 7 minutes. 21/10 = 2 (byte math!!) Digitpos = 11 Gosub Show_bigdigit 'find the digit in the units of minutes position I = _min Mod 10 'e. First the program must extract the digits from each of hours and minutes. if _hour = 23 then I will be 3
Show_bigtime: 'find the digit in the tens of hours position I = _hour / 10 'e.g. if _hour = 23 then I will be 2 To get the units of hours we use the mod command.1 in one subroutine and 1. it wasn’t changeable using the program. i. This does not mean that we have to setup the letter A at 1. 19mod10 = 9 (finds remainder) Digitpos = 5 Gosub Show_bigdigit 'find the digit in the tens of minutes position I = _min / 10 'e. I = _hour mod 10 ‘e.g 21mod10 = 1 (finds remainder) Digitpos = 15 Gosub Show_bigdigit 'display the seconds in the bottom corner of the display Locate 4 .g. we will ue a variable to determine where on the display the A will be.2 in the next and 1. e.

however it would need all of them as in thelisting below Show_bigdigit: If I = 0 Then If I = 1 Then If I = 2 Then If I = 3 Then If I = 4 Then If I = 5 Then If I = 6 Then If I = 7 Then If I = 8 Then If I = 9 Then Return Gosub Gosub Gosub Gosub Gosub Gosub Gosub Gosub Gosub Gosub Disp0 Disp1 Disp2 Disp3 Disp4 Disp5 Disp6 Disp7 Disp8 Disp9
461
.This routine doesn’t have all 10 digits shown in the flowchart.

The stage is to wire the 4 connections to the microcontroller.
by first be
468
.
There are two resitive layers that when pressed together conduct. The resistance is measured passing a current through one layer and measuring the voltage on the other layer. at least two adjacent pins must connected to the ADC input pins.34 Resistive touch screen
The resistive touch screen is made of several layers all transparent.

469
.Following are the flowcharts for the routines to read the touch screen coordinates and then convert these to a grid position.

It is before this stage that the designer needs to step back and redesign the control process for the project. Many of the I/O functions may be coded at this stage but there is little appreciation for the overriding control nature of the system as it has not been planned from the beginning. 474
. often a system’s components are seen as separate objects that will just fit together and the important relationships (interdependencies) between these objects are missed. It exists as a portion of sub 1 address in main loop RAM after the variables and may removed grow downwards towards the end of RAM. and a problem arises where the program crashes after it has been running for a short time or after a certain number of things have happened such as switch presses. In practice this is seen when a project is started with a simple or familiar I/O component such as an LCD and code is written for that device. at some stage though the programming begins to break down.1
Keeping control so you dont lose your ‘stack’
As students begin to develop projects they seldom take a big picture approach to what is required. In a microcontroller Program X there is a portion of the RAM set Main Loop Y sub 2 aside by the compiler as the temperature STACK. A common fault that causes this is treating subroutine RAM calls (GOSUBs) in a similar way sub 1 to GOTO statements (which are VARIABLES not allowed). the stack is used to remember the address in main memory where code was running so that when the subroutine exits the program may restart at the correct address in the main code.
After some time helping students with their code I have recognised this as “my program crashes after I press the switch 6 times” or “after a while it just stops working”. ultimately however when too many subroutines are called the stack overflows around into the top of RAM overwriting variables. When a subroutine is entered.
RAM sub 1 saved Program Main Loop sub 2 saved sub 1 saved sub 2 program crashes! saved VARIABLES X Y temperature position STACK address in main loop address in main loop address in main loop address in main loop no room on stack so it writes over the variables in RAM
When a program leaves a subroutine for another subroutine the stack grows. Often around this stage the project will have a number of subroutines. it is used by the position saved compiler to manage program STACK flow. Then another I/O device is added to the project such as a temperature sensor or a switch and more code is written. then another I/O device is added.34.

A flashing light that can be seen from 6 meters away d. Draw interface circuits for each of the interfaces 5. If the temperature rises at any time then the alarm will automatically reset. The system will monitor temperature inside a room and display it on an LCD. a. Research and identify the interfaces to the system e. An LM35 temperature sensor b.g.35 System Design Example – Temperature Controller
Here is a more complex system that we will develop the software for 1. Build the interfaces one at a time.g. A keypad for entering values 4. A light will stay flashing until reset. an alarm will sound for 45 seconds if it goes below a user preset value. Draw a system block diagram of the hardware (identify all the major sub-systems)
3. 2. design test subroutines for them and test them thoroughly
475
. e. A speaker with sufficient volume to be heard in the next room e. Define a conceptual statement for the solution to the problem. A 2 line x 16 character LCD c. If not reset within 5 minutes the alarm will retrigger again.

until the sub-systems are trivial (simple) in nature. Problem decomposition stage: break the software for the system down into successive subsystems.6. Design the logic flow for the solution using flow or state diagrams Test your logic thoroughly! If you miss an error now you will take 219. In this diagram the systems function has been broken down into 4 parts of which one has been broken down further.2 times longer to fix it than if you do not fix it now!!!
476
.
7.

horrible) programming practice and not a feature of the higher level languages you will meet in the future. C. It is difficult to manage all the relationships to get the logic absolutely correct. abysmal.Here is a possible flowchart for the temperature system. it took a while to think it through and it may not be exactly right yet! B. Because the loops in the flowchart overlap it is not possible to write a program without the use of goto statements which are poor (terrible.
This is a small but very complex flowchart and it is not a good solution for a number of reasons: A. if a flowchart has more than 3 or 4 loops or the loops cross over each other as above use an alternative method!
477
. Once the code is written it is difficult to maintain this code as it lacks identifiable structure It is OK to use flowcharts for small problems with only a few variable tests but by attempting to put too much logic into a flowchart you astronomically increase the difficulty of turning it into program code.

State machines are much better at modelling software than flowcharts because our systems react to inputs and events that can vary at anytime whereas a flowchart is not as responsive to this type of behaviour.36 Advanced programming . a flowchart looks primarily at the process operating within a system a state machine looks primarily at the state the system is in and then the processes that support those states.
36.
You transition from one state to another as the day progresses. They are one of the 7 behaviour modelling diagrams in the UML (unified modelling language) specification from OMG (Object Management Group – a consortium of software organsiations).
478
.state machines
State machines are very different to flowcharts.1
Daily routine state machine
Earlier we looked at a flowchart for a daily routine. These diagrams have been used extensively in industry for modelling systems and software behaviour for a long time. The black circle represents which state you start the day in. Note in UML specification 2. Lets develop a state machine for a school day.2 OMG have changed the name from statechart back to state machine diagram so if you hear the term statechart it means the same thing. Here are some different states you might be in.

Transitions normally occurred when triggered by some event or condition. The transition actions are throw alarm clock across room and stay in bed. It does however show how to start using state machines. you can see that there are no choices in it so a simple flowchart would be just as useful.
Now although this is a state machine it is not necessary to use a state machine to develop this system. 479
.
The transition condition is time=6:45 AND day=school day. If we develop this a little further we might see the following state machine develop. Here is one possible transition condition and an associated transition action.

It could be represented by a graph of speed versus time. note the flow of the diagram.. Think of a truck driving around town and its speed as it moves from one set of traffic lights to another.2
Truck driving state machine
Lets look at a second example for a state machine based system and introduce how a state machine is more suitable for reactive systems and so much easier than a flowchart. The truck has 4 states: A: stationary B: accelerating C: constant speed of 50km/hr D: decelerating
speed C B A time D
Here is the beginning state machine.
480
.36.

481
. These are things that have to be repeated while the machine is in that state.
The flow at this stage is still very linear. The transitions are triggerd by some change in the environment.
Here is the state machine with transitions.Here is the state machine with some actions within each state. some conditions and their associated actions. however that doesn’t really describe what happens in real life.

We can easily modify our state machine with another transistion to add this detail. however they are not useful for what embedded systems such as microcontrollers are used for: REACTIVE systems.It is now that we will explore what a state machine can do for us that a flowchart cannot! A flowchart is ok for routine systems which have fixed choices. In our case what happens if while the truck is accelerating the driver sees another red traffic light ahead. According to our state machine he must continue unitl 50Km/hr and then he can react to another red light. Flowcharts cannot handle reactive systems very well.
482
.

what people and devices are doing.
483
. According to our state machine he must stop first. We are interested in a micro view.The same exists if during the state of decelerating for a red light the light changes to green.
These two example systems we have looked might be described as a macro view. Another transition will fix this easily. for us that means modelling what software is doing within our microcontroller and a state machine id perfect for this. what is actually happening inside an electronic black box.

g.  Control output devices o turn light on o turn light off o sound alarm o display temperature o show main instructions screen o show temperature setting screen  Monitor input devices o Read a keypad o Read the temperature sensor  Control functions o start the timer o stop the timer o zero the timer When do these actions have to take place?  Repeated all the time within a state o Read keypad o Read temperature o Display temperature  Only once in the transition between states o Turn LED on o Turn LED off o Save a new setting Some actions could be put into either category. you might plan each different screen of the LCD (which could include instructions)  Displaying the temperature  Modifying the temperature alarm Temperature now 22c Alarm on below 18c # to set alarm A to increase * to reset alarm B to decrease Test A=light B=sound D=save&exit C=cancel (Note that if you hear the word ‘mode’ this also means the state of a device) Developing Actions. temperature alarm system outputs:  LCD – displays temperature / displays setting of the temperature alarm value  Light – on / off  Alarm – on / off If you have an LCD.g. what are the actions the device needs to carryout e.  What is the effect of putting the action clear_the_lcd inside a state compared to inside a transition?  What is the effect of putting the action led_on inside a state compared to inside a transition?  What is the effect of putting the action zero_timer inside a state compared to inside a transition?
Developing Transitions  Testing inputs and variables to see if some condition is true or not o Was a particular key or button pressed o Has a variable reached a particular value
484
.3
Developing a state machine
Developing States (starts with defining outputs) To identify the different states for your machine.36. but some couldn’t e.g. identify the different states of the various output devices e.

It is good practice not to put code into the state.36. Also if any subroutine is complex it may require a flowchart or even another state machine to plan it. but almost all (though not all) transitions will have conditions 485
. An action could be a call to a subroutine or a very short one or two lines of code. The black circle indicates the starting state for when power is applied. Here one transition is shown for when the temperature reading has fallen below the set level. The second part of the process is to build the transitions between the states and what conditions cause them to occur. Actions are optional.4
A state machine for the temperature alarm system
Here are the 4 states for the temperature controller and a diagram representation of it State 1: measure and display temperature State 2: light and alarm are both on State 3: light only is on State 4: modify the preset temp alarm setting
Each state includes the names of ations(subroutines) that will be called to do different things. so that the control structure is not confused with control of I/O devices. it looks like any test that would be part of an if…then. while… wend or do loop until… Along with the condition are the actions you want the program to carry out after one state has stopped execution and before the next state starts executing. A condition is in square brackets [ ].

 It is actually very easy to write the code to match this diagram using if-then and while-wend statements  The code is easily maintained in the future and flows logically when it is written making it easier to remember what you did or for others to read and maintain.  Students can very easily develop quite sophisticated software solutions using this process. 5 minute time out finished changing setting
Note that this state machine has a central state and it can be seen that there are a transitions into and out of this state.
This style of problem solving overcomes the issues identified relating to flowcharts  They are intuitive – in fact clients can easily understand them  Errors are seen easily as the relationships between states are logically laid out. keypad to change setting reset pressed.  If you closely follow the structure using subroutine names then you can use the software I have developed to create your code for you in BASCOM_AVR!!!
486
. temperature <= setting. temperature <= setting. 45 second time out reset pressed. Not all systems will have a central state like this. State 1: display temperature Conditions: State 2: light and alarm are on Conditions: State 3: light on Conditions: State 4: modify temp setting Conditions:
temp < setting.Here are all the states and transitions for our temperature system.

but some couldn’t e.g.States Each unique state of your device is represented by a block in a state machine diagram To identify the different states for your machine. temperature alarm system outputs:  LCD – displays temperature / displays setting of the temperature alarm value  Light – on / off  Alarm – on / off If you have an LCD.  What is the effect of putting the action clear_the_lcd inside a state compared to inside a transition?  What is the effect of putting the action led_on inside a state compared to inside a transition?  What is the effect of putting the action zero_timer inside a state compared to inside a transition? Transitions  Testing inputs and variables to see if some condition is true or not o Was a particular key or button pressed o Has a variable reached a particular value 487
.  Control output devices o turn light on o turn light off o sound alarm o display temperature o show main instructions screen o show temperature setting screen  Monitor input devices o Read a keypad o Read the temperature sensor  Control functions o start the timer o stop the timer o zero the timer When do these actions have to take place?  Repeated all the time within a state o Read keypad o Read temperature o Display temperature  Only once in the transition between states o Turn LED on o Turn LED off o Save a new setting Some actions could be put into either category.g. identify the different states of the various output devices e. what are the actions the device needs to carryout e. you might plan each different screen of the LCD (which could include instructions)  Displaying the temperature Temperature now 22c # to set alarm * to reset alarm Test A=light B=sound  Modifying the temperature alarm Alarm on below 18c A to increase B to decrease D=save&exit C=cancel (Note that if you hear the word ‘mode’ this also means the state of a device) Actions.g.

Having drawn the transition line between the two states. Adding transitions by clicking on a state and drawing with the mouse (make sure the state is not selected first) Identify the transition arrow that indicates program flow outwards towards the state ModifyTemprSetting. then some states and then transitions.36. double clicking on the line allows the user to add conditions that trigger the transition and any actions that might need to be performed between state changes.5
Using System Designer software to design state machines
After opening System Designer add a state machine. As seen in this diagram colours and even fonts can be changed (by right clicking on the diagram/state/transition) 488
. Key will be a variable and setTemprbtn will be a constant in our program. In this case the state change is triggered when a keypad is read and the value setTemprbtn is returned.

Transition conditions and actions are edited by double clicking on a transition
Transitions that don’t change state are common in state machines
489
.

dim state as byte Const st_light_alarm_on = 1 Const st_Light_On = 2 Const st_displ_tempr = 3 Const st_modify_tempr_setting = 4
Using constants rather than values within program code makes the code so much easier to read.
Do while state = st_light_alarm_on wend while state = st_light_on wend while state = st_displ_tempr wend while state = st_modify_tempr_setting wend Loop
Note: so far we have predominantly used do-loop-until as a looping control in our programs.6
State machine to program code
Once the initial logic of the state machine is planned the program code can be written. To write the code in BASCOM a state variable is dimensioned and each state is assigned a value as a constant.36.
The starting state is determined by initialising the state variable
state = st_displ_tempr
In the main body of the code a do-loop is used to enclose all the states. The while –wend is a little easier to follow in this instance but both do exactly the same thing. So we could replace the the while-wend’s above with Do Loop Until state <> st_Light_On
490
. which are coded using whilewend statements.

If the value of state changes then a different section of code will be executed.
dim state as byte Const st_light_alarm_on = 1 Const st_light_on = 2 Const st_displ_tempr = 3 Const st_modify_tempr_setting = 4 state = st_measure_displ_tempr Do while state = st_light_alarm_on wend while state = st_light_on wend while state = st_displ_tempr wend while state = st_modify_tempr_setting wend Loop
491
. When the value of state is 4 (St_measure_displ_tempr) the code within that while wend will be executed.Program flow is controlled by the value of the variable state.

however using a very structured process means that novice student programmers begin good practices early on with strong naming conventions and logical practices. the currently executing while-wend will continue on to completion. then from within the main do-loop the new state is identified and the appropriate while-wend is entered. the state variable takes on a new value. these have conditions (if-then-end if) tests that trigger or cause one state to transition to the next: while state = st_displ_tempr gosub ReadLM35 gosub DisplayTempr gosub ReadButtons
if btn = setTempr then state = st_modify_tempr_setting end if if tempr < setTempr then state = st_Light_Alarm_On GOSUB startTimer end if
wend When a condition or trigger for a state change has occurred.The next stage is to add calls to subroutines within each state.
492
. In this example there are many shortcuts that proficient and competent programmers could take. It makes my job as teacher less difficult as I can debug code more easily and will therefore grow gray less quickly. for example: while state = st_Measure_displ_tempr
gosub ReadLM35 gosub DisplayTempr gosub ReadButtons
wend
Next the code for the transitions is written.

A user could add this code to the state machine program very easily. while state = st_modify_tempr_setting gosub DisplayOldTempr gosub DisplayNewTempr gosub ReadButtons gosub ModifyTempr if btn=setTempr then state = st_measure_dspl_tempr GOSUB SaveNewTempr end if
if btn = cancel then state = st_displ_tempr end if
Wend
493
.36. A cancel or nosave button could be implemented very easily? This is shown via the change in this version .7
The power of state machines over flowcharts
Having coded the system and got it working any changes or new features are easily implemented. What if the client adds the specification that the user should be able to either save or exit without saving. In the current state machine a user can only exit ModifyTemprSetting state by saving the change.

The Bascom Program for our temperature alarm system
Const Const Const Const Do
st_Light_Alarm_On = 1 st_Light_On = 2 st_measure_displ_tempr = 3 st_Modify_Tempr_Setting = 4
while state = st_Light_Alarm_On gosub ReadLM35 gosub DisplayTempr gosub ReadButtons if secs > 45 then state = LightOn GOSUB AlarmOff end if if tempr > setTempr then state = St_displ_tempr GOSUB LightAlarmOff end if if btn=reset then state = St_measure_displ_tempr GOSUB LightAlarmOff end if wend while state = st_Light_On gosub ReadLM35 gosub DisplayTempr gosub ReadButtons if btn=reset then state = St_measure_displ_tempr GOSUB lightOff end if if tempr>setTempr then state = St_displ_tempr GOSUB lightOff end if if secs>300 then state = St_measure_displ_tempr GOSUB lightOff end if wend while state = st_measure_display gosub ReadLM35 gosub DisplayTempr gosub ReadButtons if tempr < setTempr then state = LightAlarmOn GOSUB startTimer end if if btn=setTempr then state = ModifyTemprSetting end if wend
Labels are used for states rather than numbers to facilitate program readability
'********************************* subroutines ReadLM35: Return DisplayTempr: Return ReadButtons: Return
The rest of the DisplayOldTempr: program controls Return all the I/O and is in subroutines which DisplayNewTempr: are then easier to Return write and check startTimer: individually
Return
The state variable is used to manage which code segment is executed
lightOff: Return AlarmOff: Return SaveNewTempr: Return LightAlarmOff: Return
Changing to another state only occurs when specific conditions happen.
while state = st_modify_tempr_setting gosub DisplayOldTempr gosub DisplayNewTempr if btn=setTempr then state = St_measure_displ_tempr GOSUB SaveNewTempr end if wend Loop
494
.

36.all leds flash together 3rd press .sequence pattern 4th press .all leds come on 2nd press .
uC First press of button . In this example they are called states: State1: LEDs_OFF State2: LEDs_ON State3: ALL_FLASH State4:SEQUENCE_FLASH (1-2-3-4-1-2-…) The light ‘transitions’ between the 4 states every time the ‘condition’ occurs (button is pressed).8
Bike light – state machine example
These rear lights for bicycles have different modes of operation.
495
.leds off
System Block Diagram
Here is a first state machine to describe the process
This needs some further development and subroutines have been added to each state to handle the various activities.

The actual code for the routine might look like Waitforbuttonup: Do Waitms debouncedelay Loop until button=1 Waitms Debouncedelay Return
496
.There is an issue with transitioning between states as microcontrollers are very quick and our button pressing skills by comparison are very slow! So we need to wait during the transition from one state to another so that the micro will not skip states. We setup an’ action’ to wait for the button to be released. and every state transition needs it.

9
Bike light program version1b
Using system designer the following code was produced Dim State As Byte 'REMEMBER TO DIMENSON ALL YOUR VARIABLES HERE Const st_LEDs_off = 1 Const st_LEDs_Sequence_Flash = 2 Const st_LEDs_On = 3 Const st_LEDs_Flash = 4 'REMEMBER TO DEFINE ALL YOUR CONSTANTS HERE state = st_LEDs_off Do while state = st_LEDs_off gosub LEDs_Off State 1 if button=0 then state = LEDs_On GOSUB waitforbuttonup end if wend while state = st_LEDs_On gosub LEDs_On if button=0 then state = LEDs_Flash GOSUB waitforbuttonup end if wend while state = st_LEDs_Flash gosub LEDs_Flash if button=0 then state = LEDs_Sequence_Flash GOSUB waitforbuttonup end if wend while state = st_LEDs_Sequence_Flash gosub LEDs_sequence_Flash if button=0 then state = LEDs_off GOSUB waitforbuttonup end if wend Loop
State 2
State 3
State 4
497
.36.

498
. During sub_LEDs_Flash if the delays are short enough then we can get away without checking the switch. There are no delays in sub_LEDs_Off and sub_LEDs_On as they have no need for them. and the code is not hard to modify either. Bike light state machine V2 solves this by introducing some new states for the sequence flashing.'********************************* ’subroutines LEDs_Off: Return LEDs_On: Return LEDs_Flash: Return LEDs_sequence_Flash: Return waitforbuttonup: Return
All these subroutines need code to be written for them BUT WAIT A SECOND!!
Seeing the code led me to the realisation that during the subroutine sub_LEDs_sequence_Flash the micro needs to check for a button press from the user or it is possible that it might miss it while it is doing the full sequence of flashing each LED individually. However sub_LEDs_sequence_Flash and sub_LEDs_Flash need some form of delay.
See how easy the state machine is to modify. However during sub_LEDs_sequence_Flash we will need to check the switch .

 Build a simple picture of the device with all its inputs and outputs  A conceptual statement gives a one line overview of what is to be designed  Physical Attributes: these describe a bit more detail about what the device looks like  Operational Attributes: these describe how a user operates the device.
37.1
System Designer to develop a Product Brainstorm
Start with a brainstorm of the milestones (major steps) that you will need to carry out
There are some important attributes (characteristics) of the system to describe that will make designing the hardware and software easier later on.
501
.37 Alarm clock project re-developed
Let’s try building a digital alarm clock.

A button on the toolbar in system designer will generate a written brief built from the information in the diagram. Physical Attributes for Digital Alarm Clock It contains: -red btn -LCD -yel btn -blu btn -Piezo Digital Alarm Clock interactions with Normal user are: -The piezo will sound a tune when the clock reaches the set alarm time Normal user interactions with Digital Alarm Clock are: -The red button is used to select which setting will be changed The Blu button will increase the setting The Yellow button will decrease the setting
502
.
System Description (Brief) Conceptual Statement: A digital alarm clock for personal use with three different alarm times Physical Attibutes: 4 Line LCD to display time piezo for alarm sounds three buttons to set the time and different alarms.

The xtal32 is a 32.
Note the following devices: LM35 .768Khz crystal for making a clock. when it is added the variables associated with it are automatically created in Bascom and are also shown in the table.(ADC inputs to the microcontroller have yellow pins) LDR – produces an analog rather than binary signal and requires an ADC input.
503
.2
Initial block diagram for the alarm clock
Using System Designer the block diagram is created to express the electrical connections to the microcontroller but without full detail of the schematic diagram which includes things like current limit resistors and pullup resistors.a temperatiure sensor – produces an analog rather than binary signal and requires an ADC input.37.

37.3
A first (simple) algorithm is developed
It is important to understand some of the things the device will have to be doing ‘inside’. If you are aware of any Variables you will need to keep data then add them as well at this time. Note that this is an initial algorithm without a great deal of features. The inputs and outputs you have created in the block digram will appear here making it easier to think about the functions you need to describe.
505
. it is a good idea to build your ideas up as you go as they will be easier to develop.

506
.4
A statemachine for the first clock
When starting out using state machines it is important that you take on a little piece of advice! It doesn’t take long to gain a lot of confidence and understanding in using statecharts and it wont be long before you are producing large ones. throw their hands up in horror and go back to trying to rescue their old program because it only had one error in it (even though I told them it would never work) SO START WITH LITTLE STEPS – your very first real program should have only 1or 2 states in it!! YOU HAVE BEEN WARNED!
Here the statemachine consists of only one state.37.967 errors in it! I have seen it before where students look at this.
THEN you want to turn them into program code and you end up in a heap on the floor cursing your
teacher because your compiler just told you that your code has 1.

To change state the process is simple.The code for this state is very straightforward Note: There is an overall do-loop A state consists of a While –Wend loop. change the value of the state variable! Code has been added to one of the subroutines to make it work as needed '********************************************** 'State Variables Dim state as byte Const st_disp_time = 0 State = st_disp_time 'set the initial state Do '*************** state st_disp_time *************** While state = st_disp_time Gosub Display_time_on_lcd If red_btn = 0 Then Gosub increase_hours If yel_btn=0 Then Gosub increase_minutes Wend Loop End '********************************************** 'Subroutines Display_time_on_lcd: Return increase_hours: incr _hour if _hour > 23 then _hour = 0 waitms 150 Return increase_minutes: Return '********************************************** 'Interrupt Routines //increase by 1 //fix rollover of hours //delay between increments
507
. There is a variable named state to store the current state in.

5
Alarm clock state machine and code version 2
'********************************************** 'State Variables Dim state as byte Const st_powerup = 0 Const st_display_time = 1 State = st_powerup 'set the initial state Do '*************** state st_powerup *************** While state = st_powerup Gosub display_instructions If sec_count>5 Then st_display_time Wend '*************** state st_display_time *************** While state = st_display_time Gosub disp_current_time If yelbtn=0 Then Gosub increase_minutes If red_btn=0 Then Gosub increase_hours Wend Loop End '********************************************** 'Subroutines display_instructions: Return disp_current_time: Return increase_minutes: Return increase_hours: Return '********************************************** 'Interrupt Routines sectic: incr sec_count Return
These are the first 2 stages of development of a state machine for an alarm clock.37. Students must keep progressive versions of plans such as state machines to show their ongoing development work.
508
. only 2 states and some transitions have been added.

g. When the player has captured a token.
T
▲ ◄ P ► ▼
Here is the state machine for this game (note in this version after collecting 10 tokens nothing happens). After capturing 5 tokens the time taken is displayed. 6(right) and 2(down) to capture the token. 509
. after capturing 10 tokens display the time taken. The game waits until a button is pressed then a token T is randomly placed onto the LCD.
( UMLPAD) In the program there is a state variable that manages the current state and controls what the program is doing at any particular time. 4(left). a token has been captured) or by user input (pressing a button to restart the game).6
Token game – state machine design example
BRIEF: The game starts with a welcome screen then after 2 seconds the instruction screen appears. 4 buttons are required to move the player P around the LCD: 8(up). Note that the player movements wrap around the screen. This state variable is altered by the program as various events occur (e.37. another is randomly generated.

Notice how the reading of buttons and processing of actions relating to the buttons are different things
. The variable state is a 'flag'. It is a very common technique. We set the flag in one part of the program to tell another part of the program what to do.dim state as byte 'REMEMBER TO DIMENSON ALL YOUR VARIABLES HERE Const got5tokens = 1 Const HitEnemy = 2 Const YouLose = 3 Const InPlay = 4 Const HighScores = 5 Const level2Instructions = 6 Const got10tokens = 7 Const got1token = 8 Const YouWin = 9 Const Welcome = 10 Const Instructions = 11 'REMEMBER TO DEFINE ALL YOUR CONSTANTS HERE state = Welcome Do while state = got5tokens gosub DispScore state = level2Instructions wend while state = HitEnemy state = YouLose wend while state = YouLose state = Welcome wend while state = InPlay gosub refreshDisplay gosub ReadButtons if xPos=TokenX and yPos=TokenY then state = got1token end if if btn=right then state = InPlay GOSUB GoRight end if if btn=left then state = InPlay GOSUB GoLeft end if if btn=down then state = InPlay GOSUB GoDown end if state = HitEnemy if btn=Up then state = InPlay GOSUB GoUp end if wend while state = HighScores 510
In the main do-loop Remember the subroutines to run are within the While-Wend statements
To change what a program is doing you don’t Gosub to a new subroutine. 'signal' or 'semaphore' in computer science. the current subroutine is then completed. The While_Wend statements detect the state change and control which new subroutines are called. You change the state variable to a new value.

state = Welcome wend while state = level2Instructions if btn=start then state = InPlay GOSUB MakeAToken end if wend while state = got10tokens gosub DispScore state = YouWin wend while state = got1token gosub DispScore if TokenCount=10 then state = got10tokens end if state = InPlay GOSUB MakeAToken if TokenCount=5 then state = got5tokens end if wend while state = YouWin state = HighScores wend while state = Welcome if secs>2 then state = Instructions end if wend while state = Instructions gosub DispInstructions if btn=start then state = InPlay GOSUB startTimer end if wend Loop '********************************* subroutines
511
.

The window He also added controls at his clients request for manual open and close.38.
It has grown in complexity as he realised that he needed to add more states for the motor while it was on and in the process of closing and opening.
515
.2 Window controller state machine #3.

To learn about this read a book on UML. Allowed control of the time and temperature settings AND IT WORKED!
This is a very messy diagram as it suffers from ‘state explosion’. Have a look at… http://www.3 Window controller state machine #5
5th and final state machine for the project.38. It is with a diagram such as this that we see the limitations of our process. unified modelling language. a true UML statechart allows for hierarchies of states (states within states) and would reduce the complexity of this process immensely.agilemodeling.c om/artifacts/stateMachineDi agram.htm 516
.

'--------------------------------------------------------'PROGRAM STARTS HERE Do while state = st_manualopened gosub subMotoroff gosub subLcdManualOpen gosub subReadTime gosub subDisplayTime gosub subMeasureTemp gosub subDisplayTemp if key=adjustTime then state = st_adjustWindowTime rtn_state = st_manualopened end if if key=setTime then state = st_setTime rtn_state = st_manualopened end if if key=setDeg then state = st_setDeg rtn_state = st_manualopened end if if key=manualclose then state = st_manualclose if key=auto then state = st_opened wend while state = st_adjustWindowTime gosub subReadKeypad gosub subAdjustTime gosub subWriteTime if key=adjustTime and rtn_state = st_closed then state = st_closed if key=adjustTime and rtn_state = st_manualopened then state = st_manualopened if key=adjustTime and rtn_state = st_manualclosed then state = st_manualclosed if key=adjusttime and rtn_state = st_opened then state = st_opened wend
518
.

while state = st_closed gosub subMeasureTemp gosub subDisplayTemp gosub subReadTime gosub subDisplayTime gosub subReadKeypad gosub subLcdClosed gosub subMotoroff if key=setDeg then state = st_setDeg rtn_state = st_closed end if if key=manualclose then state = st_manualclose if key=manualopen then state = st_manualopen if temp>25 and hour>8 and minute>30 then state = st_opening if key=adjustTime then state = st_adjustWindowTime rtn_state = st_closed end if if key=setTime then state = st_setTime rtn_state = st_closed end if wend while state = st_setDeg gosub subReadKeypad gosub subAdjustOpendeg gosub subAdjustClosedeg if key=setDeg and rtn_state = st_closed then state = st_closed if key=setDeg and rtn_state = st_manualopened then state = st_manualopened if key=setDeg and rtn_state = st_manualclosed then state = st_manualclosed if key=setDeg and rtn_state = st_opened then state = st_opened wend while state = st_closing gosub subReadTime gosub subDisplayTime gosub subReadKeypad gosub subMotorreverse if switchclosed = 1 then state = st_closed if key=manualopen then state = st_manualopen if key=manualclose then state = st_manualclose wend
519
.

while state = st_setTime gosub subReadKeypad gosub subAdjustOpenTime gosub subWriteTime gosub subAdjustCloseTime gosub subWriteTime if key=setTime and rtn_state = st_closed then state = st_closed if key=setTime and rtn_state = st_manualopened then state = st_manualopened if key=setTime and rtn_state = st_manualclosed then state = st_manualclose if key=setTime and rtn_state = st_manualopen then state = st_manualopen if key=setTime and rtn_state = st_opened then state = st_opened wend while state = st_opening gosub subReadTime gosub subDisplayTime gosub subReadKeypad gosub subMotorforward if key=manualopen then state = st_manualopen if switchopened = 1 then state = st_opened if key=manualclose then state = st_manualclose wend while state = st_manualopen gosub subMotorforward gosub subMeasureTemp gosub subDisplayTemp gosub subDisplayTime if key=setTime then state = st_setTime rtn_state = st_manualopen end if if switchopened = 1 then state = st_manualopened wend
520
.

while state = st_opened gosub subMeasureTemp gosub subDisplayTemp gosub subReadTime gosub subDisplayTime gosub subReadKeypad gosub subLcdOpened gosub subMotoroff if key=setTime then state = st_setTime rtn_state = st_opened end if if key=setDeg then state = st_setDeg rtn_state = st_opened end if if key=manualclose then state = st_manualclose if key=adjustTime and rtn_state=st_opened then state = st_adjustWindowTime if temp<18 and hour>3 and minute>10 then state = st_closing if key=manualopen then state = st_manualopen wend while state = st_manualclose gosub subMotorreverse gosub subMeasureTemp gosub subDisplayTemp gosub subDisplayTime if switchclosed = 1 then state = st_manualclosed if key=setTime then state = st_setTime rtn_state = st_manualclosed end if if key=auto then state = st_closed wend while state = st_manualclosed gosub subMotoro0ff gosub subLcdManualClosed gosub subReadTime gosub subDisplayTime gosub subMeasureTemp gosub subDisplayTemp if key=adjustTime then state = st_adjustWindowTime rtn_state = st_manualclosed end if if key=setDeg then state = st_setDeg rtn_state = st_manualclosed end if if key=manualopen then state = st_manualopen if key=auto then state = st_closed wend
521
.

The difference though is that there are no actions perfomed between states. that must happen between states. This code will be executed only once and the state will change automatically to State2.
In the state machine above there is an action ACTION_1. Here is an alternative code segment for control of states using a Select-Case-End-Select methodology Do Select Case State Case State_1 Gosub Actions1a Gosub Actions1b Gosub Actions1c Case State_2: Gosub Actions2 Case State_3 : Gosub Actions3a Gosub Actions3b Case State_4 : Gosub Actions4 Case State_5 : Gosub Actions5 Case State_6 : Gosub Actions5 End Select Loop This code is similar to the previous examples using while wend in that you can still have multiple actions within states. (remember an action is code that will be run only once between states)
In this second state machine Action_1 has been replaced by a state state_action_1. and a second transition that has no condition attached to it.39 Alternative state machine coding techniques
The While-Wend method of coding a state machine is not the only option available to you.
524
. While State1 is executing once condition_1 is met the state will change to Action_1. In code like this if you want to perform an action between two states you need to implement another state inbetween the two states as in the example below.

once condition =1 has happened
while state = State2 If Condition = 2 Then State = State3 wend while state = State3 If Condition = 3 Then State = State1 wend Condition Loop testing is within the Action_1: while wend 'actions for this state Return State1_actions: 'actions for this state Return State2_actions: 'actions for this state Return State3_actions: 'actions for this state Return
Do Select Case State Case State1: Gosub State1_actions Case State_action_1: Gosub Actions Case State2: Gosub State2_actions Case State3: Gosub State_3_actions End Select Action_1 is a Loop state on its own
State_1_actions: 'actions for this state If Condition = 1 Then State = State_action_1 Return Condition testing has moved to the subroutines to keep the select case code tidy. note there is no condition testing in sub actions: for state_action_1
Actions: 'actions for this state State = State2 Return
State_2_actions: 'actions for this state If Condition = 2 Then State = State3 Return State_3_actions: 'actions for this state If Condition = 3 Then State = State1 Return
525
.Do while state = State1 If Condition = 1 Then state = State2 Gosub Action_1 end if wend Action_1 will run between state1 and state2.

g. 1.
Synchronous communications is where a second wire in the system carries a clock signal. then a 0.1
Simplex and duplex
In serial communications simplex is where data is only ever travelling in one direction. A combined transmitter and receiver in one unit is called a transceiver. as either Simplex. the sender sends a 1 . therefore the receiver will know when to move on to receiving the next bit. then a 1. this is quite straight forward.
40. the receiver gets a one then a zero. then a 1. In an asynchronous system the sender and receiver are setup to expect data at a certain number of bits per second e. In half duplex communications both ends of a link will have a transmitter and receiver but they take turns sending and receiving. 2400. Now send 1100 the sender sends a 1 then a 1 then a 0 then a 0.serial communications
Parallel communications is sending data all at once on many wires and serial communications is all about sending data sequentially using a single or a few wires. The receiver gets a 1. there is one transmitter and one receiver. No problems. 19200. then a 0. then a 0. With serial communications the data is sent from one end of a link to the other end one bit at a time. as either synchronous or asynchronous
40.
526
. half duplex or full duplex And 2. Knowing the bit rate means that the spacing is known and the data is allocated a time slot.then a 0. In full duplex both ends can send and receive data at the same time. hey what happened!!
The receiver has no way of knowing how long a 1 or 0 is without some extra information. to tell the receiver when the data should be read. There are 2 ways of classifying serial data communications.2
Synchronous and asynchronous
Imagine sending the data 1010 serially.40 Complex .

Now there is no confusion about when a 1 is present or a zero. both transmitting and receiving at the same time. and asynchronous.
40. these are the three lines used for programming the microcontroller in circuit as well as for communications between the AVR and other devices. which when used with suitable circuitry is used for serial communications via RS232. it has 1 data line and 1 clock line. Because it has only 1 data line it is half duplex. the sender and receiver take turns. It is also full duplex. This is a synchronous communications interface.
Bascom also has libraries of software commands built into it for two other communications protocols   I2C: (pronounced I squared C) this stands for Inter IC bus.
527
. Bascom and the AVR
The AVR has built in serial communications hardware and Bascom has software commands to use it. It has separate txd (transmit data) and rxd (receive data) lines.  USART: (universal synchronous and asynchronous receiver transmitter). because data can travel on the 2 lines at the same time. it is capable of synchronous (using a clock line) and asynchronous (no clock line). Computers have RS232 (or comm) ports and the AVR can be connected to this (via suitable buffer circuitry)

SPI: (serial peripheral interface) which has 2 data lines and 1 clock line.3
Serial communications. so the data is half duplex.Every time the clock goes from 0 to 1 the data is available at the receiver. it is capable of full duplex. and because it has a clock line it is synchronous. The receiver checks the data line only at the right time. it has a separate clock line. The 2 data lines are MISO (master in slave out) and MOSI (master out slave in) these are full duplex. Dallas 1-Wire: this is literally 1 wire only.

There is a common or ground wire and a number of signal wires. their functions and the process for communications. receive etc. The AVR microcontroller has built in hardware to handle RS232 communications. There are two data lines one is TXD (transmit data) the other RXD (receive data).0 (RXD) and portd.4
RS232 serial communications
RS232/Serial communications is a very popular communications protocol between computers and peripheral devices such as modems. more commonly today the PC has two 9 pin male connectors.e. as these are independent lines devices can send and receive at the same time. making the system full duplex.
A connector (DB9-Female) is required for the PC end and a simple 3 way header can be used on the PCB (SV4 in the diagram) TXD (PortD.1) will go through the buffer in the Max232 then the header to pin 2 of the DB9 RXD(PortD. Therefore a buffer circuit is required. but +15V as a zero and -15V as a one. These two data lines however cannot be directly connected to a PCs RS232 port because the RS232 specification does not use 5V and 0V. cables.40. the MAX232 is a common device used for this.1 (TXD). i. the lines involved are portd.0) comes from the buffer of the MAX232 which is connected to pin3 of the DB9
528
. It is an ideal communication medium to use between a PC and the microcontroller. There is no clock wire so the system of communications is asynchronous. which device is ready to transmit. The plugs have either 9 or 25 pins. The different parts of the RS232 system specification include the plugs. There are a number of separate control lines to handle 'handshaking' commands.

the capacitors we use with the ST232 do not need to be polarised and 0.The ‘MAX232’ is a common chip used. It will give +/.1uF values will do. in the classroom we have the ST232. Some ATMega chips have two UARTs and if your ATMega has only one that is ok as BASCOM has the software built into it to handle software UARTs.8V.
The ST232 (and MAX232) have two sets of buffers so two separate devices can be connected to the AVR at the same time.
529
.

5
Build your own RS232 buffer
Why do we need a buffer again? RS232 is designed to send data over reasonable distances between different devices that might run on different voltages.15VDC and a receiver should be able to reliably detect signals if the voltages were as low as +/3VDC.40. Note that a ‘1’ is 5V for a microcontroller and -3 to -15 for a RS232(it is inverted). but it seems to work OK most of the time.
It is easy to build a simple transitor circuit to achieve this buffering for us (it is however not a perfect circuit).6V). this is outside the RS232 specification of -3V. AVR to RS232 When the AVR transmits it switches from 0V to 5V and the output to the RS232 actually only switches between 5V and 0V.
530
.
RS232 to AVR The input to the AVR is more accurate as it converts the +V input to 0V and the –V to 5V (note the diode protects the transistor by not allowing the base voltage to go below -0. To do this the designers of the specification decided that a transmitter could send up to +/.

6
Talking to an AVR from Windows XP
There are several different software options for communicating over rs232 from the AVR. Windows has HyperTerminal already built in to do this. Start a new connection and name it comm1
On the next screen make sure you select comm1 as the port. print "hello" will send the ASCII text string to the pc.40. Open HyperTerminal (normally found in programs/accessories/communications).
531
. At the pc end there must be some software listening to the comport. the simplest is the print statement.

If nothing happens make sure the communications is connected. 1.Then setup the following properties. none
When you click on OK HyperTerminal can now send and receive using comm1. none. 9600. Termite is one that is useful.8.
There are many many different communication programs on the internet to try.
532
.

use the menu (options then communications) to set it up
533
.40.7
Talking to an AVR from Win7
Hyper terminal no longer exists in Windows7. Bascom has abuilt in terminal under the options menu. but there are many useful applications that we can use.

Db6 = Portc.2 .4 . No capacitors just the IC and a three pin header. Db7 = Portc.3 . ' Program Features: ' input statement ' string variables '-----------------------------------------------------------------' Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 'the crystal we are using $regfile = "m8535. then wired to a DB9F. Hardware Aliases Cls Cursor Noblink '-----------------------------------------------------------------536
.Another useful interface (if you have easy access to the IC) is the DS275.0 Config Lcd = 40 * 2 'configure lcd screen ' 7.dat" 'the micro we are using $baud = 9600 'set data rate for serial comms '-----------------------------------------------------------------Config Lcdpin = Pin . Db5 = Portc.1 .9
Receiving text from a PC
' Hardware Features: ' DS275 connected to the micro TXD and RXD lines. it means that if you get the wiring wrong all you have to do is unplug it and try it in reverse!
40. I always wire up the three pin headers with ground in the middle.5 . Rs = Portc. Db4 = Portc. E = Portc.

Declare Variables Dim Text As String * 15 ' 11. Print PrintBin Config SerialIn Config SerialOut Input InputBin InputHex Waitkey Inkey IsCharWaiting $SerialInput2LCD $SerialInput $SerialOutput Spc Some AVRs have more than one UART (the internal serial device) and it is possible to have software only serial comms in Bascom and use Serin. Program starts here Print "Can you see this" Do Input "type in something" . Text Lcd Text Wait Timedelay Cls Loop End 'end program '-----------------------------------------------------------------' 13. Initialise Variables Text = "" '-----------------------------------------------------------------' 12. Subroutines
40. find these in the help file and write in the description of each one. Open Close Config Waitsuart
537
.' 9. Declare Constants Const Timedelay = 2 '-----------------------------------------------------------------' 10. Serout.10
BASCOM serial commands
There are a number of different serial commands in Bascom to achieve different functions.

but you have to poll (check ) regularly that a character is there and process it or it will disappear when a new one comes in (the AVR’s have a USART with error detecting that can inform you if you have missed reading the buffer. There are also interrupts built into the AVR for serial USART comms. Count . Subroutines Sub_send1: Print "this is hard work" Return Sub_send2: Print "not really" Return
'send it to comm port
'send it to comm port
Dispmessage: Cls Lcd Message Message = "" Charctr = 0 Incr Count 'send some data to the comm port Print "you have sent = " . " messages" Return '-----------------------------------------------------------------' 14. you might want to get to understand that if you are going to do commercial programms).
540
. Interrupts
Inkey allows you to manage the input of characters yourself. but these are not implemented in BASCOM.'-----------------------------------------------------------------' 13.

40.
541
. It is written in Visual Basic 6.12
Creating your own software to communicate with the AVR
Several student projects have incorporated PC based software that communicates with an AVR.
Internet
Gateway PC
Dialup Modem AVR TX
The receiver consisted of a single box of receiver.
At this point we are interested in the PC software. the internet was connected and that the wireless network was up. decoder and AVR. In this project CZL built a unit that informed remote users in the building that a gateway was on. There isn’t much point in going into VB6 as it has been superceeded by Visual Studio (currently 2010) and the Expres edition is available freely from Microsoft.

with controls on it. button. textbox. their different parts and what they are called. THAT COMES IN A FEW PAGES) The actual program is called a form. property and function.
What we think of a program is a GUI (graphical user interface) to…
Your functions(subs or subroutines) in your program code which is written in Visual basic (or C#) which uses … Microsoft dotnet functions within which use…
Windows operating system functions which requires…
Drivers and hardware such as a PC with an Intel or AMD microprocessor. this way you don’t have to figure out how to draw lines on the screen and check where the mouse is and how to read and write to hard drives etc etc.
(THIS ISNT THE HARD BIT. control.40. 542
. form. Programs you write for a pc make use of the software already on the PC.13
Microsoft Visual Basic 2008 Express Edition
To begin you must understand just a little about how Windows based programs work.
Textboxes and buttons are examples of controls on a form Controls have properties such as a ‘name’ property and a ‘text’ property (things written on the control) as well as many other properties
Take note of the words GUI.

microsoft .First make sure you have installed the latest version of Microsoft Visual studio and dotnet (free from www.14
From the menu select file then new …
Stage 1 – GUI creation
Select Windows form application and name it AVRSimpleComms 543
.com)
40.

A blank form will appear where you can add controls. If you cannot see the form or it disappears at any stage behind new strange looking windows with code in them.vb(Design) Tab. then click on Form1.vb in the solution explorer on the right hand side or select the Form1. Adding a control is easy click on the Toolbox popup on the very left hand side of the screen…
544
.

545
.Select the Button control and double click it or drag it onto your form.

the first three letters tell us what type of control it is btn for button. The next part of the name tell us a short description of what it is used for OpenPort. On the left hand side you should see the properties. starts with lowercase 3 letters to tell us what sortof control it is. Remember the whole name btnOpenPort has no spaces in it. change its size by dragging the corners and locate it in the upper area of the form. this is always in lower case. 546
.Controls such as buttons have lots and lost of properties. we use uppercase letters to separate the words not spaces. find the Name property the default name Button1 is no use to us when programming so change its name to btnOpenPort We will follow the same simple convention for naming every control. Click on the button to highlight it.

8. 9600.
547
. Find this and type in Open Comm1. You can experiment with other properties like colors and fonts as well.The button btnOpenPort has another property its Text property.N.1 – spaces are fine in this.

a TextBox control.Add another control.
548
.

txt tells us it is a TextBox control and Send is its purpose.Change the Name property to txtSend. capital letters for the following words in the name and NO SPACES!
549
. text to send! We follow the naming convention 3 lower case letters for the type.

Add a second TextBox control and change its name size.
550
. position and text.

551
. We wont bother to change its name from SerialPort1 as we only need one of these for the whole program.The last control to add is a hidden one (the user cannot see it). But do check its properties are correct. It is a SerialPort contol.

Its just that windows handles all the calling of these routines.The GUI is finished!!! But the program isn’t. they are event driven.
Stage 2 – Coding and understanding event programming
This means that nothing happens in your program until the user interacts with it.15
Programs in windows are not sequential as they are in BASCOM.
40. you can select buttons and type in text but nothing will happen yet as you have not written any code. Your program will run. This is called an event. This means that you write a whole bunch of what looks like disconnected functions (subroutines) without any overriding control structure.
552
. An event might be a mouse click on a Button or the user changing text in a TextBox. You can run your program (in debug mode) by pressing F5 or the green play button.

sub or subroutine) has been started for you.
Continue typing ‘if ser’ and the box will show you just a few options.
Visual studio is very helpful with the next steps as well.
553
. you just add code within it. Type ‘if s’ and the drop down menu will appear.vb Also the method (function. Form1. as it has a fantatstic autocomplete feature. Note the title of of it.To add code to your program double click on the Open Port button in the designer and this new window will appear.

Click on ‘SerialPort1’ and then press the fullstop ‘. choose ‘IsOpen’.
It would be useful to show users of the program if the port is open or not so add some more code.
Finish typing the full line of text and the comment above it. MAKE SURE YOU PUT () at the end of the line. ‘IsOpen’ is a property so no (). subroutine or method so it has ().
554
.’ This will give you the different properties you can access for the serialport. ‘Open’ is the name of a function.

Text + Environment.
'if the port is open then send the text from the textbox with a linefeed (Ascii #10) on the end of it. then add the following code.IsOpen = True Then SerialPort1.You can run this program now.
555
. and if your computer has a Com1 then it should work (if not. Double click on the other button in the GUI the SEND button. Click on the SerialPort1 control and then on the lightning symbol.Write(txtSend. If SerialPort1. it will crash). Use Visual Studio’s autocomplete to help you enter the code. This is more tricky. this will then list all the available events for the control.NewLine)
The next step is to add code that will allow your program to display incoming text. Double click on the DataReceived event.

we can also create it in …
556
. but it is necessary because of how Windows multitasks everything. we will go on to develop a larger program as well. but if you are interested in learning more get a book out of the library or jump on the wen and learn more. To do this windows creates two threads (parallel running tasks which are part of the same program) one to monitor the serialport and one for our form.
The program now works! This is a very short introduction to Visual Basic. When we want to pass something from the serial port to the form it must go from one thread to another. to do this the code below is required.The code window will appear
Then enter the code below. This code is very complex to understand. just why it is required and a bit about what it is doing. We will not try to understand how it works. Our program must monitor the serialport as well as our Form at the same time because data could come in while someone was typing text into a textbox. Having created this program in Visual Basic.

change its Text property to AVR Simple Comms
558
.Having created the form.

two textboxes and serialport
Call the buttons btnOpenPort and btnSend. Call the textboxes txtSend and txtReceive and change their text properties as well. change their text properties.Add the two buttons.
559
.

The serialport control is different. you must select events in the properties window and add the DataReceived event. you will then go to the code window and can add code to the control.
560
.C# Events As with VB when you double click on a control.

7 PortD Speaker C.2 A.1 B.5 B.6 B.7 A.
562
. This is achieved through setting up a counter and counting up to 65000 before reading and sending.17
Microcontroller with serial IO.5 PortC RS232 to PC
4Line x 20 Char LCD
A.3 B.0 B.0 B.1
Potentiometer
Keypad
This AVR based system monitors some input devices and outputs the data from them to the local LCD as well as via the RS232 port to a PC. Note that the analog inputs are not read and sent all the time just every ½ second. It also monitors the serial input to see if there are ant messages to display on the LCD or to decode to do certain tasks.2 B.768 kHz Crystal red push button switch green push button switch blue push button switch yellow push button switch white push button switch LDR LM35 Tempr Sensor B.4 A.4 A.
32.40.6 C.

This will create a data table. Sin_x If we want just a single piece of data then we can put it into a specific cell on the table.8.Open "comA. C2. It will be called #1 in the program.5). The next time it will put it into A3." .D. ". B3.C.5." . Note this can only be in columns A. "LABEL. The actual data are the sin values for each degree from 0 to 359. A2.SET. In the code the data is sent 360 times (using the For W = 0 To 359) This is the number of degrees in a circle.B. Radians. "CLEARDATA" Clear all data from the cells we are controlling in spreadsheet (other cells contents will not be deleted) Print #1 . no paraity and 1 stop bit. A1.SET. Note that PLX-DAQ requires a comma between each piece of data. E2.n. B2. "DATA. The first time PLX-DAQ receives this command it will put the data into A2. it will be at 9600 baud. A3. This can be plotted by a line/bar/dot graph that will follow the changing value.. ". "CELL. "F2. Print #1 . X . "MSG. B & C.tan not degrees so we convert it to radians with R = Deg2rad(D) Print #1 .
572
. W . Because there are three pieces of data they will automatically go into columns A. 8 data bits. Note that Bascom works in radians to do sin." . so we will get PLX-DAQ to plot the data on a graph. data1_in" Write a label in a specific cell in excel.cos. Degrees. C3 and so on. The words following LABEL will appear in excel cells. Sine" This line sends the LABEL command out on #1 (portA." .. Starting data plotting " send a message to be displayed in PLQ-DAX Print #1 . note that LABEL must be in capitals. or F. Print #1 . in that order. Sin_x Now send some data.5:9600.1" For Output As #1 This line sets up Bascom to know that you are going to send data out Porta. Print #1 .. "CELL." .

Excel may complain about macros and ActiveX controls.
573
. To connect to the incoming data from your microcontroller you must setup the comm port and the baud rate. The R will flash with incoming data so that you know it is all running ok.40.20
PLX-DAQ
Download and install PLX-DQA and run it. you must allow these or it will not work. The line graph plots the values in Column C and the other 4 graphs look only at the data in F2. Note that PLX-DAQ will ony respond to data in the first sheet in a multisheet spreadsheet!
Several different types of graphs have been created to plot the values. You can try faster baud rates but 9600 is reliable in most instances for the AVR at 8MHZ. The data coming intot excel is plotted according to the commands sent my the microcontroller.

1
StampPlot is highly configurable with alarms and meters
575
.In the next screen start the comms (comm. Port 1 and 9600) in the bottom left corner and change the scale in the top left corner to -1.

40.. They could be driven directly from a microcontroller.22
Serial to parallel
We came across some bi-colour LEDs and wanted to add them to a circuit in a circular pattern. but would require two I/O pins each as in this diagram
This schematic shows the LS164 serial to parallel ICs used to implement control 16 LEDs and the 8 I/O connections required to drive them .
When driven in one direction the LEDs glow red. when reversed they glow green. The ICs require a data line and a clock line (so it is synchronous communication)
576
.

Note the wiring on the socket is the mirror image of the plug. and that it is the socket we will be wiring to a microcontroller. it is known as the male connector. The socket on the right is as seen on a computer motherboard and is called the female connector. On the left is the PS/2 (or 6-pin mini DIN) plug on a cable.40.
581
.23
Keyboard interfacing – synchronous serial data
The computer PS/2 keyboard is an example of synchronous serial communication and can be connected directly to an AVR microcontroller (synchronous means that a clock signal is sent as well as the data signal to help the receiver know the timing for the data).

Here is the result of pressing 3 keys one after the other. These are the 2 lines.1 seconds per division. and the horizontal scale is 0. 582
. there are 3 sets of data
Zooming in on one set of data it can be seen that it is actually 3 individual chunks of data
And zooming in further still we can see that a single chunk of data is a series of 1’s and 0’s
The clock is a regular alternating signal of eleven 1’s and 0’s. data and clock. from the keyboard. The data must be read along wth the clock so there are eleven bits of data even though it appears tere are fewer.The data from the keyboard has been captured using a Saleae Logic Analyser. and indicates to us when the data is valid (can be read).

then a parity error checking bit and finally a stop bit) The data is sent LSB (least significant bit) first so when it is used by your micro it is binary 00010101 (which in hex is15H) The specification for data from a keyboard can be found on the internet and states that the data bit must be valid at least 5uS before the clock goes negative.
583
. its just a matter of working out its speed (bits per second) which is around 12.
Once these settings are made the logic analyser software will show the hex code for the data. So we can read the data any time after the clock goes low.000 bits per second for the keyboard which we tested.The data sequence is reguar it always consists of a start bit. followed by 8 data bits.
The logic analyser has the ability to interpret the data for us .

g. At the receiving end the number of 1’s is added up and compared to the parity bit.Each key of the key board has a unique scan code (some have a sequence) e. In our case the data has 3 bits set to 1 so a 0 is sent. Ctrl is E0(hex) then 14(hex) The key that corresponds to the scan code of 15(hex) is the letter ‘Q’
Party Along with the data a single parity bit is sent. However if a single bit of data was corrupted then the receiver could identify a problem (wouldn’t this be useful when people are talking to each other!!) The use of parity along with the use of a synchronous clock makes this communication protocol reasonable robust to interference. Do note though that it is not completely immune to corruption as if 2 bits of thedata were corrupted then the parity bit might still be correct. if there is a match it was assumed that the data was received correctly. the parity bit is set (to 1) if there is an even number of 1's in the data bits or reset (to 0) if there is an odd number of 1's in the data bits.org/ps2protocol/ 584
.computer-engineering. Lots more information about the data being sent (protocol) can be found at http://www. The purpose of parity is to help the receiver know if the message was received correctly.

A radio wave consists of two signals. With audio signals this can be AM (amplitude modulation). FM (frequency modulation). These two are combined together to produce the radio signal.8MHz (Life FM) and an audio tone is applied then the signal transmitted will vary in frequency depending upon the frequency and amplitude of the audio wave. PM phase modulation. If the carrier is 89.
591
. a carrier wave and the information to be sent called the modulating wave this wave could be audio or digital data.1 An Introduction to data over radio
Radio (electromagnetic) waves are used to transfer information from one place to another through the atmosphere (that’s without wires) .
In FM the carrier signal is modulated by an audio signal. There are many different ways that the carrier can be modulated.41 Radio Data Communication
41.

In Amplitude modulation the frequency of the carrier wave is fixed however its amplitude changes in time with the modulating signa. AM picks up interference from other electrical and electronic devices and is noiser than FM..
592
. e.g National Radio 756Khz.

A receiver just cannot reliably determine a zero.1. pulses represent either a 1 or 0.1
Pulse modulation
Data is often sent using some form of pulse modulation.
593
.41. as how can it determine that an absence of signal is a zero or due to a lost or broken transmission? Also how long is a 1. which means that the receiver has to figure out from the transmitted signal what is a 1 and what is a 0. OOK is ‘on off keying’ (keying is the term originally used to describe controlling a radio carrier wave with a Morse key). the difference is the length of time the transmitted signal is present. Using OOK the signal is turned on and off in patterns to send 1’s and 0’s. if 111 is sent will the system get a 1. a 11 or 111?
Digital modulation systems range from very simple to highly highly complex. If we want to send data then we need to send something for a ‘1’ and we need to send something for a ‘0’ We canot rely on the absence of data to be a ‘0’ as in this diagram below. This is asynchronous. When sending data over any communication link it is important to realise that the system is asynchronous (no clock) so the receiver relies solely on the incoming signal to rebuild the data. The sequence is very easy to receive though as the overall length of a 1 and 0 is the same.

434MHz is a frequency that can be used in many countries for free (unlicensed) radio transmission and is commonly used in systems such as remote controlled garage doors. receivers and tranceivers (a device which both transmits and receives) available in 434Mhz.
Transmitter
Encoder
Receiver
Decoder
594
. Here is a block diagram of a student (PB) radio system that was designed to send messages from loation to another. There are a large range of transmitters. There are also simple encoder and decoder ICs to help with the modualation of the signals.

This needs to be 16.4cm long.The transmitter has a built in antenna.
595
. if you were making your own PCB you make it a track.2mm in diameter.5mm wire around something 3. the receiver has a wire soldered to it as an antenna (green wire currently cable tied in the picture). or you could also wind 24 turns of 0.

596
. Also any convenient pins can be used on the microcontroller.In this partial schematic the HT12Encode receives 4 bits of data from the microcontroller and sends it along with the 8 address bits serially to the transmitter. The speed of the data is set by the value of the resistor.

the receiver board has more power pins to connect and two output pins.The receiving system is very similar to the transmitting system. The audio out pin is not used. otherwise the data will be ignored. audio out and data out. It is essential that the address on the HT12D is the same as that on the HT12E.
597
.

One confusing thing about datasheets is that they sometimes cover a number of different parts in one sheet. Datasheets also have various pinouts for the ICs such as DIP (dual inline package) and SOP (small outline package) in this case. the line should usually be high and when it goes low the IC will do something.
The second diagram is the same.41. The line or bar above the TE in the daatsheet means that it is an active low signal. Make sure you order the right one! In the datsheet you will find timing diagrams. When TE (transmit enable) goes low Dout (data out) goes high and sends the data 4 times.2
HT12E Datasheet. this diagram has been taken from the HT12E datasheet and modified a little to help explain its detail. We are not looking at what comes out of the transmitter.
598
.e. transmission and timing
It is quite important to gain experience reading manufacturers datasheets.
In this diagram two time-voltage graphs are drawn one above the other. however in this case it shows that if TE is held low then the HT-12E continues repeats sending the word until it goes high again(however it will always send at least 4 words) These diagrams represent the flow of the process from the micro to the HT-12E and the HT-12E to the transmitter. the reason for this is that they line up in time. This datsheet covers the HT12A and HT12E. the HT12A is used for infrared remote controls the HT12E for RF (radio) . they occur a great deal in electronics. it is worth reading this with the datasheet for the HT12 open as well. i.

These rates are all determined by the value of R connected to the HT-12E.5mSecs to transmit.
Each full bit includes a period of low and a period of high time and lasts for 687. then the 8 address bits (10110011) then the 4 data bits (0001). which in our case is 750K. it can be seen that the whole sequence of 4 data words took almost 60mS to send. A single start bit. The time in millisecs is shown on the X axis. with the whole word taking about 8.The datasheet gets a little confusing and isn’t clear about he data word structure for the two devices so an oscilloscope was use to capture the transmission sequence on Dout from the HT-12E. a data ‘word’ is 13 bits of data from the oscilloscope.5uSecs (the difference in time between the o and the x on the scope display) Other measurements were taken and a single pulse was measured as 229 uSecs in duration and a double pulse was measured as 458 uSecs. (Why does it send the data word 4 times?)
Here is one data word.
599
.

256mSecs (256uSecs). resistance or even inside the IC. voltage. The measured value was 228uSecs which is a 4.
600
.9Khz. This could be due to variation in temperature.4kHz It doesn’t quite match. its about 10% off.9Khz wave form has a period of 0.This graph from the datasheet shows how the frequency of the oscillator relates to the supply voltage and resistor value. A 3. The 750k resistor at 5V will make the oscillator run at about 3.

The transmitter is on the left.3
HT12 test setup
The above 2 boards have been setup in the classroom to test the system.41. the schematics for these are:
601
.

Note that the encoder repeats the data 4 times.5
HT12D datasheet
The matching part for the HT12E is the HT12D. this repeating or sending duplicate data is called redundancy.41. this allows for some error.
604
. if it receives the same message 3 times in a row it will put the 4 bits of data onto the 4 data pins and then put the VT (valid transmission) pin high for a short period. The flowchart from the datasheet explains the process. The HT12D decodes the data from the receiver.

The datasheet states that the decoder oscillator must be about 50 times that of the encoder oscillator.The graph from the datasheet shows that a 33k resistor at 5V will oscillate at 210kHz.
605
.

it can easily be replaced with a program as in this code below. then 8 bits if address then 4 bits of data.
607
. The program continuously sends the numbers 0 to 15 as data to a fixed address &B01101111.7
Replacing the HT12E encoding with software
The HT12E is not that complex (the HT12D is). The code is in the subroutine transmit: It sends the start bit.41.

i selects each bit of the address. To do this it uses the code If Addr.. The loop goes from 7 down to 0. within the loop it checks each bit to see if it is a 1 or 0..dat" '--------------------------------------------------------------2 1 ' Hardware Setups 1 1 ' setup direction of all ports 0 1 Config Porta = Output Config Portb = Output Config Portc = Output Config Portd = Output ' Hardware Aliases Tx_data Alias Portd.1 '-----------------------------------------------------------------' Declare Constants Const Tx_del = 230 'micro seconds ' Declare Variables Dim I As Byte 'temporary variable Dim J As Byte 'temporary variable Dim Addr As Byte Dim Dat As Byte 'the 4 bits of data to send ' Initialise Variables Addr = &B01101111 'the address for this system '-----------------------------------------------------------------' Program starts here ' the main program is just a test routine to test the subroutine ' that does the actual work ' Continuously transmit the values 0 to 15 For I = 1 To 4 ' toggle the LED on and off a few times Toggle Tx_led ' to show the PCB is working Waitms 500 Next Do For Dat = 0 To 15 ' test code Gosub Transmit ' Allow the data to be transmitted Waitms 2000 ' Delay is for visual testing. portd.The code is easily implemented using for-next loops .i portd.g.2 Tx_led Alias Portc. Next I Loop '-----------------------------------------------------------------' Subroutines Transmit: 608
. if the address is &B01101111 then as i changes the code addr.i = 1 Then . This is similar to addressing port pins e.0 ' initialise ports so hardware starts correctly Porta = &H00 Set Tx_data Set Tx_led Set Portc.7 or i Addr.0 7 0 '--------------------------------------------------------------6 1 ' Compiler Directives (these tell Bascom things about our 5 1 hardware) 4 0 $crystal = 8000000 ' internal clock 3 1 $regfile = "m32def.

It should be noted that although the HT12E sends the data word 4 times.Reset Tx_led For J = 1 To 6 'send the start bit first Set Tx_data Waitus Tx_del Reset Tx_data 'send the address For I = 7 To 0 Step -1 Waitus Tx_del If Addr. we found it necessary to send the data word at least 6 times to get a reliable transmission.i = 1 Then Waitus Tx_del Set Tx_data Waitus Tx_del Reset Tx_data Else Set Tx_data Waitus Tx_del Waitus Tx_del Reset Tx_data End If Next 'send the data For I = 3 To 0 Step -1 Waitus Tx_del If Dat.i = 1 Then Waitus Tx_del Set Tx_data Waitus Tx_del Reset Tx_data Else Set Tx_data Waitus Tx_del Waitus Tx_del Reset Tx_data End If Reset Tx_led Next Waitus 9000 Next Set Tx_led Return
'light tx LED 'send full word 6 times 'carrier on 'start bit time 'carrier off 'send most significant bit(7) first 'start with 1 period of no carrier 'extra low time for 1 'carrier on 'carrier off 'carrier on 'extra carrier on time for 1 'carrier off
'send most significant bit(3) first 'start with 1 period of no carrier 'extra low time for 1 'carrier on 'off 'on 'extra carrier on time for 0 'off
'pause between words 'TX LED off
Here are two screen shots from the oscilloscope the timing in each is almost identical apart from the delay between datawords. This time period could be reduced from 9000uS to 8000uS to match the HT12E.
609
.

610
.

the first event is when the master issues a start pulse causing all slaves to wake up and listen.it increases the number of devices 1 micro can interface to and several manufacturers now make I2C devices. It is now popular and is often used when short distance communications is needed. It is normally used within equipment to communicate between pcb's. Data is then sent over the bus by the transmitter.
611
. which means that only one end of the link can talk at once (half duplex) and that there are separate data and clock lines (synchronous). This is then followed by an ACK bit (acknowledge) issued by the receiver.42 Introduction to I2C
The Inter-IC bus (I2C pronounced "eye-squared-see") was developed by Philips to communicate between devices in their TV sets.Serial Clock Communication The system of communications is not too difficult to follow. the master then sends a 7 bit address which corresponds to one of the slaves on the bus.g. Bascom comes with the software already built in making I2C very easy to use. saying it got the message. e.
The two lines are SDA . main boards and display boards rather than externally to other equipment.
The I2C protocol is not too hard to generate using software.Serial data and SCL . Then one more bit is sent that tells the slave whether it is going to be receiving or sending information. The real strength of this protocol is that many devices can share the bus which reduces the number of I/O lines needed on microcontrollers. It is a half duplex synchronous protocol.

maxim-ic.
When we want to put the variable onto an LCD we cannot write lcd seconds as the number would not be correct. Each of these devices has other unique features that can be explored once the basic time functions are operational. What this means is that instead of storing seconds as one variable it splits the variable into two parts the units value and the tens value.. Tens of .. we must convert the binary to bcd.. SCL (serial clock) and SDA (serial data).
All three require an external 32.768KHz crystal connected to X1 and X2. Temp = Makebcd(seconds) I2cwbyte Temp
612
. 5Volts from your circuit connected to Vcc. a ground connection (OV) and connection of two interface pins to the microcontroller. This will last for a couple of years and note that it is not rechargeable.com website for each of these components as well as many other interesting datasheets on topics such as battery backup. We must first convert the BCD to true binary using Seconds = Makedec(seconds). There are datasheets on www. DS1678 and DS1307. Some common devices are the DS1337.42. The DS1678 and DS1307 can have a 3V battery connected to them as backups to keep the RTC time going even though the circuit is powered down.. LCD Seconds The oppositeneeds to happen when writing to the time registers. Units of . In these RTCs the registers are split into BCD digits.. register 0 Tens of seconds Units of seconds register 1 Tens of minutes Units of minutes register 2 Tens of hours Units of hours register 3 Tens of hours Units of hours register .1
I2C Real Time Clocks
These are fantastic devices that connect to the microcontroller and keep the time for you.

connect it between 0V and the battery pin of the RTC. but check the datasheet first. Also fix the crystal to the board somehow to reduce strain on the leads. The reason for the strange number is that 32768 is a multiple of 2. /2 = 2. If a battery is not used then the battery backup pin probably needs connecting to 0V. /2 = 1
42. 32768 /2 = 16384.42.
42. /2 = 8192.2
Real time clocks
These devices are very common in microcontroller products such as microwave ovens.4
Connecting the RTC to the board
Take special note about bending the leads and soldering to avoid damage to the crystal. /2 = 4096. The I2C lines SDA and SCL require pull up resistors of 4k7 each to 5V.768khz crystal. cellular phones. wrist watches.3
Connecting the RTC
The crystal for the RTC is a 32. The battery is a 3V lithium cell.
613
. /2 = 2048….2 = 8. industrial process controllers etc. so all that is needed to obtain 1 second pulses is to divide the frequency by two 15 times to get exactly 1 second pulses. /2 = 4.

07. Here is the layout of the memory within the RTC ADDRESS Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0 00 0 10 Seconds Seconds 01 0 10 Minutes Minutes AM/PM 02 0 12/24 10Hr Hour 10Hr 03 0 0 0 0 Day of week 04 0 0 10 Date Date 10 05 0 0 0 Month Mo 06 10 Year Year 07 CONTROL 08 RAM 3F
The date and time Sunday. (SEND DATA FROM ADDRESS 0) and it sends 0.7.48.5
Internal features
First open the datasheet for the DS1307 RTC There is a memory within the RTC. firstly all the time and dates are stored individually.24.08.21. until we tell it to stop sending
614
..42.. 24 September 2007 21:48:00 are stored as this ADDRESS Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 00 0 0 01 4 8 (02 2 1 03 0 7 04 2 4 05 0 9 06 0 7 Bit0 Seconds Minutes Hours (Sunday) Day month Year
When we read the RTC we send a message to it. The units and the 10s of each number are stored separately.

6 . step 5 : write a subroutine that sets the time. etc from the 1307. Step 3: write a number of subroutines that handle the actual communication with the control and status registers inside the 1307. These routines make use of the Bascom functions for I2C communication. hours. switches etc. Step 4: write a subroutine that gets the time.3 'Config lcd Config Lcdpin = Pin . This is only ever sent once to the 1307.3 '-----------------------------------------------------------------' Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 'the crystal we are using $regfile = "m32def.2 Config Lcd = 16 * 2 'configure lcd screen
615
. Don't forget to configure all the compiler directives and hardware such as the LCD.7 . setup the SQW pin at 1Hz 'added subroutines to read and write to ram locations ' LCD on portc .42.write time/date to the rtc. thermistor.2 SDC=porta. '-----------------------------------------------------------------' Title Block ' Author: B.note the use of 4 bit mode and only 2 control lines ' DS1307 SDA=porta. Dimension the variables used to hold the year. step 6: write a program that incorporates these features and puts the time on an LCD. temp. ' read date/time from the rtc.4 .Collis ' Date: 26 Mar 2005 ' File Name: 1307_Ver4. E = Portc. hours. hours. month. date. day. Db6 = Portc. Rs = Portc.3 .2 Config Scl = Porta. Db5 = Portc. etc from the 1307.bas '-----------------------------------------------------------------' Program Description: ' use an LCD to display the time ' has subroutines to start clock. Db4 = Portc. to hold the data we want to send to/receive from the 1678. date. Db7 = Portc.5 . etc. Step1: configure the hardware and dimension a variable.dat" 'the micro we are using '-----------------------------------------------------------------' Hardware Setups ' setup direction of all ports Config Porta = Output ' Config Portb = Output ' Config Portc = Output ' Config Portd = Output ' ' config 2 wire I2C interface 'Config I2cdelay = 5 ' default slow mode Config Sda = Porta. to specify the unique functions we require the 1307 to carry out. Step2: setup the control register in the RTC.6
DS1307 RTC code
Here is the process for setting up communication with a DS1307 RTC followed by the code for one connected to an 8535.

VOL DOWN and MUTE. Bascom has a serial out command however it sends 8 bits.
636
.
The DS1267 digital pot has 256 settings and requires a serial signal of 17 bits in length sent to it to control it. Jonathan decided to ‘bit-bang’ it (send serial bit by bit via software rather than using any hardware device). There are 3 buttons on the device VOL UP.44 Bike audio amplifier project
In this case the client wanted an easy to use and safe audio system for mountain biking. The solution was to have a small box containing the circuit and battery mounted to the rear of the helmet and speakers clipped onto the helmet near the ears but not blocking out surrounding sounds from other bikers. The amplifier is a common TDA2822 stereo audio amp and there is a digital potentiometer controlled by an ATTiny13 to manage the volume settings.

Reset = 0 .
A Bascom program requires a config line for the display: Config Graphlcd = 240 * 64 . There are also built in fonts so it can be used in a similar way to a character LCD (the FS pin is used to select either a 6x8 or 5x7 size font).1 The T6963 controller
There are a number of different types of graphics LCDs. Wr = 6 . Rd = 5 . Fs = 7 .
The LCD is a complex circuit as shown in the block diagram below. Controlport = Portd .45 Graphics LCDs
45. Ce = 4 . Mode = 6
642
. The display is from TRULY and is 240 pixels wide x 64 pixels high. this display is based on the T6963 driver IC. Cd = 1 . Dataport = Portc . however Bascom has built in routines to drive it which makes it very straight forward to use.

in MSPaint the attributes can be set from the menu. Each digit was 24 pixels wide and 40 pixels high (they need to be in multiples of 8 pixels).
In Bascom open the Graphic Converter. Use exactly the size BMP file you want the picture to be.
645
.
The full program is not listed here however the routine to display the time is.The big digits are actually 10 individual pictures which are selected to be displayed on the screen.
Each one is created in a simple drawing program like MS Paint. load the bitmap image and then save the file as a BGF (Bascom graphics file) into the directory where the program will be.

(The display was purchase from sure-electronics)
647
. Here the Veroboard. And as it was a one off veroboard was a good choice. datasheet for the Microcontroller showing its pin connections and the datasheet for the LCD showing its pin connections are in use to help decide on the ciruit and layout. LCD.2
Graphics LCD (128x64) – KS0108
In this project the goal is to keep the final product the same size as the LCD.
Veroboard is straight forward to use however to get a good product requires some careful planning.45.

It is always a balance working out which pins on the micro to connect to the I/O devices. 648
. Choosing the port for the 6 control lines was easy. It shows a trimpot between pins 18 and 3 of the LCD. as we will have 2 spare. Note that it is a good idea not to write data to the LCD while doing an ADC conversion as this could mess up the ADC results. Port A has the ADC on it and if a touch screen is required we must have at least 2 ADC pins available. one on the power pins of the micro and one next to the power pins of the LCD.1uf (100nF) bypass capacitors were added to the circuit. Port D has interrupt pins and is more likely to be useful in the future than portC. In this case it is a process of elimination of constraints. 0. We need to bypass each device with a capacitor real close to the IC.The circuit was drawn up next. portA. It was decided not to use PortB because sometimes I/O devices can interfere with uploading programs and the LCD would have to be removed everytime you want to program. these stop voltage spikes on the power supply caused by fast switching devices like microcontrollers and LCDs upsetting the power supply to other devices like microcontrollers. This is the contrast adjustment for the LCD. LCDs and any other ICs that will be added. so portC was chosen for the 8 data lines.

The 7805 was positioned so that it was directly onto the 5V and 0V lines. and the names of the LCD pins were written using a permanent marker onto the board itself. The 5V and 0V/GND lines were coloured red and black on the board. Perhaps a real time clock and a touch screen connection. The reason these are where they are on the veroboard is that they line up with the power pins of the LCD.
649
. This reduced the wiring.To make assembly easier to follow the IC was mounted right up to the edge of the board so that its portc pins physically lined up with the 8 datalinesof the LCD. This really helps avoid confusion when flowing the schematic. There is plenty of space left on the board for other circuitry. Before attempting to do the wiring of the micro to the LCD a label was placed onto the IC socket with the names of the pins.

This block diagram shows the power supply voltages required and how they were developed. The 317 is an adjustable regulator and a trimpot on it will be used to vary the voltage and consequently the LCD’s contrast. however they did not have the negative voltage circuit on the display for the contrast adjustment making them a little trickier to use.
ICL7660 negative voltage converter
Voltage input approx 15V DC
317 voltage regulator
10V
-10V Graphics LCD 5V
7805 voltage regulator
5V
Microcontroller
652
.3
Generating a negative supply for a graphics LCD
These particular displays were available at a very good price.45.

653
.

This makes a Sensor total of 7 control lines between the 8 data lines Microcontroller microcontroller and the GLCD.
192 x 64 KS0108 GLCD Temperature and Humidity plotter
654
. I had the following: a 192x64 pixel GLCD (KS0108 type from Sure Electronics) an LM35 temperature sensor an HiH4030 humidity sensor The 192x64 GLCD has 1 more interface pin than the 128x64 GLCD as it has a third controller for the LM35 Tempr display. When I HiH 4030 7 control lines Humidity designed this board for Sensor student use I decided that the data lines could be on PortB (shared with the programming port – which is ok if you add the 10k resistors as per the schematic) and that the control lines would have to be flexible so that depending on the use for the board the students could change them.1 Project hardware
In thisproject I wanted to use a GLCD to display a graph of temperature and humidity over time.46 GLCD Temperature Tracking Project
46.

the next will be reading the values from the sensors and translating these to humidity and temperature.2
Project software planning
This is a realtively complex system which will require some interesting software to plot a graph of values so I will use decomposition to break the software down into subroutines each with its own job to do. Here is what the display looks like with the graph scales and the temperature and humidity values displayed.
656
.
Temperature & Humidity Logger
draw the graph scales on the GLCD
get Tempr
get humidity
save tempr values
save humidity values
graph the tempr and humidity values
display tempr
display humidity
The least complex parts of the software for the project will be the displaying of the graph scales and the values. the most challenging will be the last part actually graphing the values.46.

20 . 181 . 1 Pset 179 . 0 . 1 'right vertical Line(12 . 53) . 53) -(178 . 40 . "0" Return This routine makes use of some of the Bascom functions for the display and use two different font sizes. 1 Setfont Font 5x5 Lcdat 1 . 0) -(12 . I now have 165 data points that I can use to display values out fo the full 192 pixels width.
657
. There is one small point to make about the 100 on the left of the display. 3 . 30 . 1 'left vertical Line(178 . 1 'bottom horizontal 'left hand side humidity scale Setfont Font 8x8 Lcdat 4 . 3 . 40 .3
Draw the graph scales
'---------------------------------------------------------------Draw_graph_scales: Line(12 . 1 Pset 179 . 50 . 52) . 1 Pset 11 . 1 Pset 11 . 0) -(178 . 0 . 2 . 1 Pset 11 . 30 . "H" Pset 11 . 181 . 1 Pset 179 . 20 . I reduced that by drawing a line in place of the character 1 and then putting in “00” after it. "T" Pset 179 . 1 Pset 11 . leaving me room for 3 more data point in the display itself. thus reducing my width for the 100 from 15 pixels to 12. 10 . 52) . 50 . 0) -(0 . 0 . "00" Lcdat 7 . 1 '1 in the 100 to save space Lcdat 1 . 1 Pset 179 . 1 Pset 179 . I wanted to maximise the display space for plotting values so when I went to display the number 100 it took up a lot of space as each character is 5 pixels wide. 10 . "50" Lcdat 7 . 1 Pset 11 .46. I use comments to help me to remember what each part does. When I went to draw the check marks for the scale I wrote the check mark over the top of the last 0 increasing my display by another data point. "50" 'right hand side temperature scale Setfont Font 8x8 Lcdat 4 . 1 Setfont Font 5x5 Line(0 . 4) .

com mounted on a small PCB. 176 . "C" Return ' '---------------------------------------------------------------Note the need to convert the between different variable types. I got a simple conversion factor of 1. After I have finished doing the fomula I want to store the values in memory and I want to store a lot of them so I convert the values to byte type variables which take up much less space (e. I measured 2.2 degrees) the ADC value was 56 (on a scale from 0 to 1023) and as I know there is a straight line relationship between the two that starts at 0.46. Tempr_single Lcdat 8 . 145 .g LM35 above). it can be bought from Sparkfun.9858 Lm35 = Getadc(7) 'get the raw analog reading Tempr_single = Lm35 'convert to single to use decimals Tempr_single = Tempr_single / 1.2 = 1. It is another easy to use analogue sensor and has a very linear scale so a straight forward formulae is required. so these are initially word types(e. 658
.
In this case the voltage corresponds to a humidity value which we look up on a graph from the datasheet.g. The ADC readings are whole numbers in the range of 0 to 1023.9858 Tempr = Tempr_single 'convert to byte for storage Return Disp_tempr_val: Setfont Font 8x8 Lcdat 8 . tempr above)
I used the HIH4030 humidity sensor. I want to do division with these though and word type variables truncate division so I convert the values to single variable types (tempr_single above).7 ' calibrated at adc=56 and temperature=28. An ADC value of 480 (2.282V (28.282V) ' 56/28. In maths I might express that as a formula of the type Y=mX+C or in this case Tempr = conversion factor times ADC reading (plus zero for C as the graph crosses at 0 volts). To do this I measured the voltage on the LM35 it was 0. '---------------------------------------------------------------Get_tempr: ' lm35 temperature sensor on pinA.37V which was an ADC value of 480.37V) is a humidity of about 55% on the graph.2deg (0.9858.4
Read the values
The LM35 temperature sensor has been covered already but note the conversion from volts to degrees.

In the main loop I wait for 5 minutes (wait 300) between readings and after each reading I increase a variable which is keeping track of the number of readings. '-----------------------------------------------------------------' Program starts here 'setup inital screen Cls Gosub Draw_graph_scales Do Gosub Get_humidity Gosub Save_humidity Gosub Get_tempr Gosub Save_tempr Gosub Disp_humidity_val Gosub Disp_tempr_val Gosub Draw_tempr_hum_graphs Wait 300 'reading every 5 minutes Incr Curr_reading If Curr_reading > 165 Then Curr_reading = 1 Loop End
I have two routines for storing the values in ram even though I could do it in one subroutine and call it something like save_values.46. This is because each has a slightly different function to perform and if I extend the program in the future I might want to add features to one routine that aren’t in the other such as keeping track of the maximum temperature or something else.5
Store the values
First I need to store 165 readings for each so I dimension two arrays Dim T(165) As Byte '165 readings stored Dim H(165) As Byte The first location is T(1) and then next T(2) all the way up to T(165). '---------------------------------------------------------------Save_humidity: H(curr_reading) = Humidity Return '---------------------------------------------------------------Save_tempr: T(curr_reading) = Tempr Return Storing the values is easy I copy the value from the variable Humidity into the array at the position determined by my increasing variable curr_reading
660
. I also do not want to go over 165 so I test this variable and reset it back to 1 if it goes over 165.

another person might look at this problem and solve it in another (and even better) way.
661
. If my current reading is 80. Note that I solved it this way. but that didn’t work and I got a strange shifting of the display.46. This code does this
Tmp = Xpos .
To do this was not difficult in the end but to understand it may take a little explanation.165
175 176 177
78 79 80
When I first wrote the program I declared Tmp as a byte. I realised it was because tmp can actually get much larger than 255 before I subtract 165 from it. This will achieve the effect of the data scrolling left with each new value. then I want to draw the data points from 81 to 165 and 1 to 80 inthat order on my graph.Graph_left Tmp = Tmp + Curr_reading Incr Tmp 'exceeds byte size
163 164 165 1 2 3
Of course we want to restart at 1 again after 65 so we add this as well
If Tmp > 165 Then Tmp = Tmp .6
Plot the values as a graph
What I want the graph to do is to always draw the current value at the very right hand side of the display. plus current location(80) + 1.
pixel
13 14
Data location in array 81 82
If you look at these two sequences you can see the pattern for my program is that it must lookup the data location which is the pixel location minus 13.

if > 0 'Pset Xpos .if > 0
the display points 0. 51) . Ypos . T(tmp) 'set the pixel. 1 'set the pixel Next Return
662
. Ypos . 51) . 0) -(xpos .
Ypos = 50 . H(xpos) . (pixel 0) and 0 degrees is 50 pixels down the display (pixel 50)
Here is the complete loop
Draw_tempr_hum_graphs: 'draw the two sets of data For Xpos = Graph_left To Graph_right Line(xpos .Graph_left Tmp = Tmp + Curr_reading 'exceeds byte size Incr Tmp If Tmp > 165 Then Tmp = Tmp . 0 'remove anything on col already there
I also must plot the actual point.0 is the top left pixel on the display so I turn my temperature value into a location 50 degrees is at the top.The final part of the routine requires me to make sure that the display os blank before I draw data on it. T(tmp) 'turn the value into a position 'set the pixel. There are two ways(at least) that I could do this I chose to draw a blank vertical line before I put the data at that point.165 Ypos = 50 . 0) -(xpos .
Line(xpos . 0 'remove anything on col already there Tmp = Xpos .T(tmp) Pset Xpos .T(tmp) 'turn the value into a position Pset Xpos .

However what happens if we want to interrupt the usual program because some exception or irregular event has occurred and we want our micro to so something else briefly. they step through the program code one step after another faithfully without any problem.47 Interrupts
Microcontrollers are sequential devices. a bottling machine is measuring the drink being poured into bottles on a conveyor. For example. These are connected to switches on the development pcb.2 and pind. Software Features: ' do-loop to flash LED ' Interrupt INT0 and INT1 '-----------------------------------------------------------------' 5. Title Block ' Author: B. When using the interrupts the first step is to set up the hardware and go into a normal programming loop.bas '-----------------------------------------------------------------' 2. When the bottle is expected but not there (an irregular event) the code can be interrupted so that drink is not poured out onto the conveyor. and it is for this reason that they are used reliably in all sorts of environments. Hardware Setups ' setup direction of all ports Config Porta = Output Config Portb = Output Config Portc = Output Config Portd = Output Config Pind. Then at the end of the code add the interrupt subroutine (called a handler) The code to use the interrupt is: '-----------------------------------------------------------------' 1.Collis ' Date: 9 Aug 2003 ' Version: 1. All microcontrollers/microprocessors have hardware features called interrupts.2 = Input 'Interrupt 0 Config Pind.3 = Input 'Interrupt 1 On Int0 Int0_handler 'if at anytime an interrupt occurs handle it On Int1 Int1_handler 'if at anytime an interrupt occurs handle it 666
.3 and are called Int0 and Int1.0 ' File Name: Interrupt_Ver1. Hardware Features ' Eight LEDs on portb ' switches on INT0 and INT1 ' 4.dat" ' the micro we are using '-----------------------------------------------------------------' 6. Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 'the speed of operations inside the micro $regfile = "m8535. There could be a sensor connected to the conveyor which senses if the bottle is not there. There are two interrupt lines on the ATmega8535. these are pind. Program Description: ' This program rotates one flashing led on portb ' when INT0 occurs the flashing led moves left ' when INT1 occurs the flashing led moves right ' 3.

The main program loop just sits there displaying the value of count and if a switch on PINB.2 Set Portb.5 . E = Portc.
'debounce test program $regfile = "m644def.4 . Db7 = Portc. Hex(count) Loop End
'reset count
'Interrupt service routine .3 Set Portb. " " Locate 3 . 117. Count .dat" $crystal = 8000000 Config Lcdpin = Pin . In addition to this when the switch is released te variable count also increases as the countacts bounce when they come apart.1 .0 = 0 Then Count = 0 Locate 2 . Bin(count) Locate 4 .program comes here when int2 pin goes low
Int2_isr: Incr Count Return
The results of this program show how poor quality the switch actually is. 1 Lcd "decimal=" . 29. Db6 = Portc. 59.2 . 36. a soft press of the switch can increase the count by hundreds.0 Config Lcd = 20 * 4 Config Portb = Input Set Portb. Rs = Portc. This should happen when the switch is pressed but not released.47.0 is pressed reset the count to 0. 29.1 Set Portb. Db5 = Portc.4 'pullup 'pullup 'pullup 'pullup 'pullup resistor resistor resistor resistor resistor on on on on on
'Interrupt INT2 'this code enables an interrupt on pin INT2
Config Int2 = Falling On Int2 Int2_isr Enable Int2 Enable Interrupts
Dim Count As Byte Cls Cursor Off Lcd "debounce test" Do If Pinb. Db4 = Portc.1
Switch bounce problem investigation
Most peole don’t have an oscilloscope at home to investigate switch bounce but its effects can be seen in programs. 1 Lcd "hex =" .0 Set Portb. 102. 27.3 . 9. Results from 10 trials of a single press and release were 11. When an INT2 occurs a counter value is increased. A single firm press of the switch will increase the count by as much as 16 or more. The interrupt is setup so that when PINB. Connecting a poor quality press button switch to portB.2 goes low an interrupt occurs.
668
. 1 Lcd "binary =" . 15.2 on an ATMega64 running at 8MHz and running this program reveals what happens with contact or switch bounce.

2
Keypad.polling versus interrupt driven
With the earlier keypad circuits we have had to poll (check them often) to see if a key has been pressed. The outputs are driven low and one of the inputs will become low. Then the inputs become outputs and the outputs become inputs. when a keypad button is pressed down the 0 on the output pulls the diode down triggering the interrupt. This combination is unique and identifies which key was pressed. It is not always possible however to poll inputs all the time to see if they have changed it can be much easier using an interrupt. In the interrupt routine the inputs are read to identify which pin is 0.
In this circuit 4 pins are configured as outputs and 4 as inputs.47.
669
.

Here is the circuit diagram for an ATMega64 with the keypad circuit shown
670
.

3
Improving the HT12 radio system by using interrupts
Earlier a radio system was described that used the HT12E and HT12D ICs. Db6 = Portc.3 Config Portb = Input ' Valid data is input on this port Config Portc = Output ' Used for LED's and LCD Config Portd = Input ' PortD.2 is used for Data Valid input 'setup LCD Config Lcdpin = Pin .
It would be useful in some situations to have an interrupt driven design.5 . Db7 = Portc. Db4 = Portc.
Start
interrupt on receive Normal program flow
read data from HT12D
In this program the data is stored when it arrives and the main program loop is free to check it when it wants.3 .6 .2 ' Turn off LED's on PortC. E = Portc.47.7 . The receiver side of the system used a polling type design.1 '-----------------------------------------------------------------' Declare Constants Const True = 1 Const False = 0 ' Declare Variables Dim Rcvd_value As Byte Dim Data_rcvd_flag As Bit Dim Data_rcvd_count As Byte Dim Message As String * 81
674
. Db5 = Portc. so that a program could be doing other functions and only respond when something actually happens. where the program regularly checked the VT pin from the HT12D to see if data was present.0to A.2 Config Lcd = 40 * 2 'setup Interrupts On Int0 Get_data Enable Int0 Config Int0 = Rising Enable Interrupts ' Hardware Aliases Ht12d_dv Alias Pind.
return to normal process
' Compiler Directives (these tell Bascom things about our hardware) $crystal = 8000000 ' internal clock $regfile = "m16def. Rs = Portc.0 & PortC.4 .dat" ' ATMEGA16 '-----------------------------------------------------------------' Hardware Setups ' setup direction of all ports Config Porta = Output '4 leds on PortA.

where data arrives it is stored at one end of the queue and it is processed from the other end . then the first value is lost.' Initialise Variables '-----------------------------------------------------------------' Program starts here Cls Cursor Off Locate 1 . 1 Lcd "HT12D interrupt test program" Do 'do other program stuff here If Data_rcvd_flag = True Then 'do something with the new data Porta = Not Rcvd_value 'display on leds Message = Lookupstr(rcvd_value . In computer programming terms its called a First In First Out (FIFO) queue or buffer. This program could do with a buffer to remember received data.---------------------------------Messages: Data "The only time success comes before work is in the dictionary!!" Data " Ma Te Mahi Ka Ora Fulfillment comes through hard work!" Data "good decisions come from experience experience comes from bad decisions" Data " the trouble with normal is it only gets worse!" Data " What you do speaks so loud that I cannot hear what you are saying" Data "Never confuse motion with action" Data "The only thing necessary for the triumph of evil is for good men to do nothing" Data "Ability is what you're capable of doing Attitude determines if you will do it" Data " The first will be last and the last will be first" Data "If a blind person leads a blind person. both will end up in a ditch" Data "10" Data "11" Data "12" Data "13" Data "14" Data "15"
The limitation of this program is that it only stores one piece of data. in fact a queue would be useful. 675
. and if new data arrives before it has had an opportunity to process the first value. Messages) Cls Lcd Message Data_rcvd_flag = False 'remove flag End If Loop ' End '-----------------------------------------------------------------'interrupt routine Get_data: Data_rcvd_flag = True Rcvd_value = Pinb And &H0F ' get value from lower nibble PortB While Ht12d_dv = True ' wait until data no longer valid Wend 'so that the program only actions data once Return '---------------------------------------.

This is how the interface pins were connected (each pin also had a 4k7 pullup resistor connected to VCC).
676
.4
Magnetic Card Reader
The JSR-1250 is only a few dollars and can make the basis for a neat project involving magnetic cards.6 (data 2) RCP2 onto Pind.47.5 (clock pulse 1)
47.3 .4 (data 1) RCP1 onto Pind.2 .INT1 (card present detect) RDD1 onto Pind. A card was swiped upwards through the reader and using a logic analyzer the data was captured. Note the following:  CPD is high when there is no data. AND before it can be planned the hardware must be understood in fine detail.  When a card is swiped CPD goes low and remains low during the complete data send process.  There are two sets of data (RDD1 And RDD2) and their respective clock signals (RCP1 and RCP2). We can use all this information when writing code to understand the incoming data. RDD2 onto Pind.5
Card reader data structure
Before program code can be written it must be planned. The card reader has 5V and ground/0V power supply pins as well as 5 interface pins.INT0 (clock pulse 2) CPD onto Pind.

677
.47.
In this screen capture from the logic analyser it can be seen that there is a gap of around 15mS between CPD going low and the data starting. and we must know when to read the data in relation to the level of the clock data. When writing program code to read the data from a magnetic card reader it is important to understand exactly when the data is valid. This is a synchronous data transfer process.6
Card reader data timing
There is still much more to understand. The datasheet has this diagram in it and explains that the data should be read when the clock goes from high to low (its negative edge). which means that two signals are sent both clock and data.

sourceforge.
Lcdat Lcdat Lcdat Lcdat Lcdat Lcdat 1 2 3 4 5 6 .net/devel/index.
47. .47. both edge or low level detect. The data is sent 5 bits at a time. then. . as per the diagram
Further research on the web leads to the format that the data is in. There are two tracks available from our reader. .trialling
The tricky thing with Bascom and interrupts is that Bascom does not give us complete control over how the interrupts are configured.7
Card reader data formats
Next we must know how the binary data (1’s and 0’s) needs to be put back into information we can use (numbers such as credit card numbers!). The data comes in LSB (least significant bit) first. The interrupts are controlled by registers (memory locations which directly control hardware) within the micro. 4 data bits and 1 parity bit (error checking). then 19 digit code. There are many sources of information on the internet about magnetic card readers. . to figure out the settings the datasheet was downloaded and the sections on interrupts and external interrupts were read. and then the parity bit is sent.
On Int1 Int1_cpd Enable Int1 Enable Interrupts 'card present detect 'enable card detect interrupt 'enable micro to process all interrupts
However this is not what we need.html. Here is the track 2 data format. In the AVR we can actually configure the interrupts to be negative edge. . "8535 Interrupt Testing" Sreg Gicr Gifr Mcucsr Mcucr
678
. . so interrupts occur when the pin goes low and continue to occur while it is low. It has a start sentinel (signal). perhaps one of the best is http://stripesnoop.8
Understanding interrupts in Bascom. positive edge. .. 1 1 1 1 1 1 . . Here is how the interrupts are configured by Bascom (level detection). . On this site are documents that explain in quite a lot of detail the number of tracks of data on a card and its format. this means that a 1 is sent then another 1 then a 0 then another 0. Bascom configures the interrupt to be level detected. so a program was then written to display all of the register values involved with interrupts. We only want one interrupt to occur on the edges.. . The number 3 in binary is 0011. In this program an edge rather than a level detection is better. 1 and 2. and there are a number of features in the AVR that we can make use of.

meaning low level interrupt is configured.ISC10 When we write in Bascom ‘’On INT0 int0_rcp2’ Bascom configures 2 bits of this register. We really want a negative (falling) edge interrupt on the clock so we write these 3 lines On INT0 int0_rcp2 ‘Bascom sets up the interrupts for us Set MCUCR. So we write these 3 lines On INT1 int1_cpd ‘Bascom sets up the interrupts for us Reset MCUCR. ISC11 and ISC10. If we set this to 1 Reg then any enabled interrupt will occur. and it resets them to 0. General We can disable INT0 using the following commands Interrupt disable INT0 or RESET GICR. Control Reg When we write in Bascom ‘’On INT1 int1_cpd’ Bascom configures 2 bits of this register.ISC00 After doing this MCUCR = &B00000110
679
. We can set it by using any one of the following commands in Bascom enable interrupts or SEI or set SREG. Register Value Meaning SREG &B10000010 This register is the status register for the whole AVR.INT0 Control We can enable INT1 using the following commands Reg enable INT1 or SET GICR.INT1 GIFR &B00100000 We don’t set or reset any of the bits in this register General Interrupt Flag Reg MCUCSR &B00000011 We don’t set or reset any of the bits in this register MCU Control Status Reg MCUCR &B00000000 The type of interrupt is set with this register. ISC01 and ISC00. We really want an interrupt on both the negative edge and positive edge of this pin.ISC11 ‘we modify the type of interrupt Set MCUCR. we are really interested MCU in this. we are only Status interested in bit 7.ISC01 ‘we modify the type of interrupt Reset MCUCR. and it resets them to 0.Here are the results of displaying the values of the registers. which is the global interrupt flag.7 GICR &B10000000 This register is used to control the external interrupts. if it is reset to 0 then any enabled interrupts will not occur (hence the name global interrupt flag). meaning low level interrupt is configured.

The micro has to keep track of all interrupts and has only a finite amount of memory space to do this. It can cause the micro to crash if interrupts occur during the processing of an interrupt and further interrupts occur during that interrupt.when card is swipped.Collis ' Date: April 2011 ' File Name: MagReaderV3a.dat" ' specify the used micro $crystal = 8000000 ' used crystal frequency $lib "glcdKS108-192x64.1 'activate internal pullup resistor Set Portc.47. int1 occurs ' all data is read inside the int routine '-----------------------------------------------------------------' Compiler Directives (these tell Bascom things about our hardware) $regfile = "m8535. If this is understood and the rest of the program is written with this in mind then it will be ok. In the interrupt routine program code has been written that reads data from the card reader.
'-----------------------------------------------------------------' Title Block ' Author: B. too many interrupts inside others and your progam easily crashes.bas '-----------------------------------------------------------------' Program Description: ' uses interrupts to read the data from a magnetic card ' Hardware Features: ' 128x64 GLCD ' JSR-1250 magnetic card reader ' 3a .
It should be noted here that it is considered bad practice to put lengthy code inside an interrupt routine.9
Planning the program
In this first example it was decided that a single interrupt would be sufficient and it would be used to capture the CPD. but in a big project where multiple people are writing different parts of a program this would be bad to do.2 'activate internal pullup resistor
681
.lib" ' library of display routines '-----------------------------------------------------------------' Hardware Setups Config Portd = Input 'Mag card Config Portc = Input 'switches Set Portc.

if neg edge process new data bit ' processing data: ' after 5 data bits.card detected Flag = Fl_cpd 'reading a card Set Or_led 'show an indicator led Carddata = "" 'delete any previously read card data Bit_counter = 0 'reset bit counter Byte_counter = 1 Do 'if cpd=1 then start reading data 'wait for data to start Do If Cpd = 1 Then Exit Do 'card finished so dont get stuck Loop Until Rdd2 = 0 'process all incoming data until CPD goes high at end of read Do Set Yel_led 'wait for clock to go low Do If Cpd = 1 Then Exit Do 'card finished so dont get stuck Loop Until Rcp2 = 0 'process a single bit If Bit_counter < 4 Then 'only store bits 0 to 3 Temp.'this routine is called when there is a CPD interrupt(card present) ' with no card swiped the flag is Fl_nocpd ' when CPD goes low INT1 happens ' flag is set to Fl_cpd. negate and store End If If Bit_counter = 4 Then '5 bits completed Bit_counter = 255 '255 because we incr it after this to 0 'add code to check parity??? . a new byte is created with the data in it ' data comes in the form of 4 inverted bits (LSB first) + parity Int1_cpd: If Cpd = 0 Then 'neg edge.bit_counter = Not Rdd2 'get value of input.not really necessary Temp = Temp + 48 'convert to asci code Carddata = Carddata + Chr(temp) 'store the data Temp = 0 'reset for next 5 bit read Incr Byte_counter 'next store location End If Incr Bit_counter 'wait for RCP to return high Do If Cpd = 1 Then Exit Do 'card finished so dont get stuck Loop Until Rcp2 = 1 'clock has returned high Loop Until Cpd = 1 Reset Yel_led Loop Until Cpd = 1 'will be set by int routine Flag = Fl_newcard Reset Or_led End If Return
683
. at this time RDD is high ' wait for first neg edge of RDD ' process edge ' wait for both new neg edge and CPD ' if CPD exit .

they are arranged into groups of 8 which share one interrupt. 8.47.0-pinb.4) 'jump here when one of the pins is changed 'must enable pcint1 'global interupt flag
In the ISR (interrupt dervice routine) we need to figure out which of the 5 pins actually caused the interrupt and then take the right acton.
Pcmsk1 = &B00011111 On Pcint1 Isr_pcint1 Enable Pcint1 Enable Interrupts 'only use pcint8-pcint12 (pinb.5. so we mask them out using PCMSK1.4 (PCINT8 thru PCINT12) which uses PCINT1 (pin change interrupt 1) So before we use any of the interrupts we need to tell the micro which of the 8 pins on PORTb we want to trigger PCINT1.6 or b.0 with PCINT0 the interrupt!!! In our program we will make use of 5 switches on pins B.0 thru B. PCINT1. Here the interrupt is triggered when the pin changes. PCINT2. We don’t want any changes on pinb. Try not to confuse PCINT0 the interrupt pin PortA.10
Pin Change Interrupts PCINT0-31
Each modern AVR microcontroller has a number of other external interrupts known as Pin Change Interrupts (PCI).
There is not an interrupt for each pin. so that means either from 1 to 0 ot 0 to 1.
684
. Also note that these are pinchange interrupts so if you press a switch you get an interrupt and when you release the swiutch you get another interrupt. In the datasheet for each micro they are labelled. So there are only 4 pin change interrupts PCINT0. and all the switch bounces inbetwen cause more interrupts.7 to cause interruts. PCINT3 in the ATMEGA644.

Db7 = PORTC.2 = 0 Then Count = Count * 2 Do Loop Until Pinb. 1 Lcd "hex =" .0-pinb.3 'pullup resistor on PCINT11 Set Portb.0 'pullup resistor on PCINT8 Set Portb.
685
.0 Config Lcd = 20 * 4 Config Portb = Input Set Portb.3 = End If If Pinb. And to overcome switch bounce there is a short delay at the beginning and end. Db5 = PORTC. the change in logic level will be detected.4) On Pcint1 Isr_pcint1 'jump here when one of the pins is changed Enable Pcint1 'must enable pcint1 Enable Interrupts 'global interupt flag Dim count As Byte Cls Cursor Off Lcd "PCINT test" Do Locate 2 .1 .dat" $crystal = 8000000 Config Lcdpin=pin .2 'pullup resistor on PCINT10 Set Portb. Pcmsk1 = &B00011111 'only use pcint8-pcint12 (pinb.1 = End If If Pinb. Rs = PORTC. Bin(count) Locate 4 .4 . Db4 = PORTC. Hex(count) Loop End Isr_pcint1: 'to find out which pin Waitms 20 If Pinb.2 = End If If Pinb.5 . Db6 = PORTC. Count .0 = End If If Pinb. 1 Lcd "binary =" .0 = 0 Then Decr Count Do Loop Until Pinb. E = PORTC.3 . 1 Lcd "decimal=" .'PCINT test program $regfile = "m644def.4 = 0 Then Count = Count * 4 Do Loop Until Pinb.4 'pullup resistor on PCINT12 'With pcmsk you activiate which pins will respond to a change on the pin 'When you write a 1.4 = End If Waitms 20 Return changed we test each pin 'debounce cheap switches
1
1
1
1
1
To overcome the fact we get an interrupt on switch press and another on switch release in this program there is a do-loop-until in each switch press that waits for the pin to be released before exiting the ISR.2 .1 'pullup resistor on PCINT9 Set Portb. " " Locate 3 .3 = 0 Then Count = Count / 2 Do Loop Until Pinb.1 = 0 Then Incr Count Do Loop Until Pinb.

Timer1. This can be the osciallator frequency. timer1 = 34286. or it can count pulses from an external pin i. and Timer2.  When counting from the internal oscillator it will count at the R-C/Crystal rate or at a slower rate. resistor capacitor. Three of these registers are Timer0. timer1 = timer.48 Timer/Counters
The ATMega48/8535/16/32microcontroller shave a number of harware registers that have special functions.  The rate of counting can be from the microcontrollers internal oscillator.000.1 for timer1). the oscillator/8 or /64 or /256 or /1024.  You don’t even have to keep track of the count in your program. one)
The timer/counters can be written to and read from just like ordinary RAM but they also have so much more to offer a designer. in our program prescale = 256 (which is 8. timer1 = counter (which is pin B. when a timer overflows it will call an interrupt subroutine for you via the command on ovf1 tim1_isr (on overflow of timer1 do the subroutine called tim1_isr). 686
.e. enable timer1 and enable interrupts or to stop i.000/256 = 31.e. disable timer1. so that we can program accurate time periods. i. Timer0 is 8 bits so can count from 0 to 255 Timer1 is 16 bits so can count from 0 to 65535 Timer2 is 8 bits so can count from 0 to 255 Here is a block diagram of some of Timer1’s features – it is possible to set very accurate output timings by varying the prescale and the preload values (of you use an external crystal oscillator rather then the internal RC.  Timers can count automatically. you just give the microcontroller the command to start. an overflow occurs when a variable goes from its maximum value (65535) back to 0.e.250 counts per second)  The timer doesn’t have to start counting from 0 it can be preloaded to start from any number less than 65535 i.e.

you would have to know a lot about assembly language to figure out exactly how long.48. 10’and ‘Lcd millisecs’ is long and very complex and they may take quite some time to execute. 'LCD Config Lcdpin = Pin . Db6 = Portc. too fast to see.
688
.5 .8000000 / ( prescale * intinterval) = 177 (1millisec interrupts) ' there are calculators on the web to help with this sort of thing Config Timer0 = Counter .5 Dim millsecs As byte '----------------------------------------------------------------------'progam starts here Cls Cursor Off Lcd "timer testing" Do Locate 2 .2 . If the code in the timer routine takes more than 100mS
to execute then you have too much code in it and your micro will crash.4 . You could make a stop watch using this.0 Config Lcd = 20 * 4 'configure lcd screen 'Timer 1 ' preload = 255 . 10 Lcd millisecs Loop End 'clears LCD display 'no cursor
'end program
'----------------------------------------------------------------------Timer0_isr: Timer0 = Preload_value 'reload timer1 Toggle Grn_led Incr millisecs Return It is really important to undertstand that the timer will reoccur at the rate you set it at.2
Timer0 (8bit) Program
This program toggles the led 100 times per second. Db5 = Portc. Prescale = 1024 On Ovf0 Timer0_isr Const Preload_value = 177 Timer1 = Preload_value 'reload timer1 Enable Timer0 'enable timer 1 interrupt Enable Interrupts 'allow global interrupts to occur ' hardware aliases Grn_led Alias Portb. E = Portc.3 . but the count is usable. Db4 = Portc. Db7 = Portc. In the program above the displaying of the value millisecs is not in the interrupt routine it is in the main code. The actual program code for commands like ‘Locate 2 . Rs = Portc. The 3 lines of code in the interrupt routine can execute in less than 1 microsecond in total.1 . in this program that is every 100mS.

784mSecs).56 interrupts per second (2 interrupts per heterz of frequency)
Note that the microcontroller is working on an internal R-C (resistor-capacitor) oscillator and it is not very accurate. which is a frequency of 264.78Hz ).48. (There are versions of the above program for timer0 and timer2 as well). If you want more accuracy use an external crystal.4
Timer1 Calculator Program
Using this program the calculations are easily done. the timer was preloaded with a value of 63626 and the following measurement was made on an oscilloscope. This error will vary from micro to micro and even as the temperature increases and decreases it can change. 690
. The actual frequency wanted was Middle C (261. The period actually is 3784uSecs (3.27Hz. this means we need 523. In an experiment to get Middle C. simply enter a value into any of the yellow number boxes and the rest of the values will be calculated automatically.

g. or 64 LEDs arranged as 8x8.
The LED dot matrix display is a grid of LEDs e.
A dot matrix of 40 LEDs does not hace 80 pins (2 pins per LED ) or even 41 pins (40 pins plus 1 common as with a 7 segment display) it needs onlt 13 pins (5+8) as the LEDs are arranged in a grid and share anodes and cathodes
Here is the actual schematic for the Sharlight CMD-3581300-W LED dotmatrix (13 is an odd number so they gave it 14 pins and joined 11 and 4 together)
The final step in understanding the device is the layout of the pins.49 LED dot matrix scrolling display project – arrays and timers
The display is an excellent opportunity to learn more about arrays and timers Before the display can be used though it must be understood. Make sure the display is the correct way around. This means knowing what is indside it. 35 LEDs arranged as 5x7. these are numbered like an IC. Check it with the pins and slots around the edges. Sometimes it is enough to understand how to use a device without knowing everything about it (such as an LCD or LM35) however in this case the display is not really that complex and so must be thoroughly understood before it can be used.or 40 LEDs arranged as 5x8.
692
.

Both pins to the LEDs have to be the correct polarity for it to work/
PORT A PORTB &B1101 1111 (only correct row low) &B0000 0010 (only correct column high) Any other combination will have different effects
To turn on both these LEDs the following sequence is required
PORT A &B 1101 0111 (2 rows low)
PORTB &B 0000 0010 (only correct column high)
693
. initially these could be set at 470R. To get one particular LED to turn on the cathode needs to have a low (0V) applied and and the anode needs a high (5V). There are 5 resistors in series with the cathodes to reduce the 5V or too much current could flow and damage the LEDs.Here is an LED matrix connected to an ATMega8535.

Removing the resistors will help (as the leds are cycled rapidly they effectively don’t get stressed. however when there are 5 leds going they can be a bit dim. but to 5 LEDs it means 4mA each. When a column has 1 or 2 LEDs going they are bright enough. Note that from a hardware point of view this connection method does not really work the best. the columns have to to be scanned one at a time. so can be 0 or 1)) 'turn on column 1 'small delay so it flashes quickly '* * 'turn on column 2 '* * 'turn on column 3 ' *** 'turn on column 4 '* * 'turn on column 5 ' * * 'turn on column 6 ' ** 'turn on column 7 ' ** 'turn on column 8
694
. Here is a portion of a program to display the number of my classroom D7. const w8=1 Do Porta = &B00000111 Portb = &B10000000 Waitms W8 Porta = &B01110111 Portb = &B01000000 Waitms W8 Porta = &B01110111 Portb = &B00100000 Waitms W8 Porta = &B10001111 Portb = &B00010000 Waitms W8 Porta = &B01110111 Portb = &B00001000 Waitms W8 Porta = &B10110111 Portb = &B00000100 Waitms W8 Porta = &B11010111 Portb = &B00000010 Waitms W8 Porta = &B11100111 Portb = &B00000001 Waitms W8 Loop
' ***** (last 3 bits not used.To turn on a pattern all at once is not possible . But the better solution is to use driver transitors on each column. So 1 column might have 2 bright LEDs and the next 5 dim ones! This because a port on a micro can deliver about 20mA max. This is not difficult but requires some fast processing.to 2 LEDS that means 10mA each.

The message is stored in a string 2. Get the first 8 pieces of data (1-8) and store them where the timer can access them  Wait a bit  Get the next 8 pieces of data (2-9)  And so on The timers job is to scan the 8 columns with the data it is given Note that there is no translation process for the ascii codes in the message string to LED dotmatrix data.
696
.Dim Col_count As Byte ' 9 Initialise Variables Timer1 = Preload_value 'preload timer1 Col_count = 1 Col_data(1) = &B00000111 ' ***** (last 3 bits not used) Col_data(2) = &B01110111 '* * Col_data(3) = &B01110111 '* * Col_data(4) = &B10001111 ' *** Col_data(5) = &B01110111 '* * Col_data(6) = &B10110111 ' * * Col_data(7) = &B11010111 ' ** Col_data(8) = &B11100111 ' ** '-----------------------------------------------------------------' 10. Subroutines 'subroutines Timer1_isr: 'puts the data in the array onto the rows. The string is converted to an array of data. this must be created manually . Program starts here Do 'nothing here yet Loop End '-----------------------------------------------------------------' 11. 6 bytes per letter (1 for a space) – this is a large array 3. 1 column at a time 'every time through turn on next column and get data for it Timer1 = Preload_value 'reload timer1 Row = Col_data(col_count) 'put data onto row Rotate Column . Right 'turn on next column Incr Col_count 'increase to next column If Col_count = 9 Then Col_count = 1 'only have 8 columns Return
The next stage on the program is to have a scrolling message. First algortihm: 1.

There is an infrared led on one side and a photodetector on the other to measure the air speed. In that case the device might give a false reading.
703
. 2 outputs were required: good blow and bad blow to interface to the existing circuitry. A second input to the circuit is a start blowing command. Alex and Victor two year12 students designed this product in 2006.50 Medical machine project – timer implementation
Situation: The client had built a machine that measured certain aspects of air in a persons lungs. As the user blows the ball rotatesin the chamber breaking the infrared path between the LED and photodetector. The product was highly satisfactory however it had a limitation in that if the person did not blow long or hard enough then deep air from the lungs might not come out. It required the person to blow a minimum volume of air through a straw into the machine. The client was an expert in analogue electronics and mechanical design but needed some assistance with solving this issue as they did not know enough about programming or microcontrollers.
50.1
Block diagram
A small chamber with a pea sized ball in it (imagine a whistle) was inserted into the airline to measure the air flow.

The client also wanted field adjustments so that when programming in the field they could alter things for different situations. Every 100mS the count must increase by at least 10 or the user is deemed not to be blowing hard enough. This would mean at least 4 seconds of blow.
704
.state machine
This state machine was designed with the student to count the revolutions of the pea once the start command was sensed.2
Blower . As the tacher I was a significant stakeholder in the project as well and I wanted significant input to the project as I knew that in the future if the client wanted anything changed I was the one who would get the call! I therefore made sure that the documentation was of a high standard. The client also wanted 3 tries so that if the user gave a short blow they could try again. So initially there is a wait of 30 pulses from the photo detector before the measurement actually begins
It is important to get enough air for an accurate reading so the user must blow both hard and long enough. If the blow lasts for 400 pea counts then it is a good blow.
When a person starts to blow it takes a short period of time to get up to full speed.50. The timer is used to count the number of pea rotations.

the clock should mean something to that person too! A messge will rotate around the 7 digits that will look like: “ 10-37 3-1 P1-Yr10 4T0G0 CLEANUP ” 10-37 is the time.  The school periods should only be displayed during school weeks. I loose track of the time. the clock needs to show how many minutes are left until the next bell. P1-Yr10 who is in the class at the moment. of which there are about 36 each year. So I needed a special clock one that not only displayed the time but that kept track of how long there was left in a period and could warn both the students and me that the period was rapidly coming to an end. This has changed however but I keep a copy of that version safely stored which means that next year should those in command change again I can reimplement that trickery into the code  I concluded early on that I needed to manage each day of the week individually!  There is an emergency power stop in my room. Weekends and school holidays only the time should display. 4T0G0 how many minutes are left till the bell and finally the CLEANUP message if it is less than 6 minutes to go in the period. this is really redundant information because both the students and I know who is there but it is important in that it clarifies to all who see the clock that it is correct in its operation.
51.  There should be an extra message that happens 5 minutes before the bell goes to remind people to cleanup  My classroom is shared by another teacher once per day.  Thursday and Friday have the same bell times but these are a different to Monday. then 3-1 the rotation (if a Tuesday or Friday).  Mondays and Tuesdays have the same bell times.  Wednesday has its own because of a late start that day.  Because the bell times are so different showing just the the time itself is meaningless.51 Multiple 7-segment clock project – dual timer action
Some surplus 7-segment display boards were found on trademe and it was decided that my classroom needed a fancy new clock. The display digits are 70mm high x 48 mm wide and the whole board is 360mm in length
Not just any clock is required though. I always get asked this by students so it was good to see it. 709
. so the clock must be battery backed up. one of the problems in the classroom is that school periods can be a little short for students and once they get going with practical work it is hard for them to stop when the bell goes – well actually the truth is its my fault. Tuesday and Wednesday (got it so far?)  We actually only teach 5 periods in a day but on a Tuesday and Friday there are 6 periods($%$%#)  This rotates every week so we teach periods 1 to 5 one week periods 2 to 6 the next and 3 to 1 etc etc  In the first version of this project it was made worse by the fact that we use to have assemblies on Friday which changed with the rotation as to who went and who didn’t so the times changed for some Friday periods some weeks and not others.1
Understanding the complexities of the situation
The situation is much more complicated than initially might be thought because the school timetable is actually a device of torture used by those in the know to torment humble teachers and students alike.

This makes them very bright and suitable for the classroom. are Darlington types so are high gain and good for switching medium power.2
Hardware understanding:
There are 7 seven segment diplays on the PCB with a nice connector.
The problem with the dot matrix introductory scrolling text project was the issue of brightness of the LEDs.
710
. this was resolved by developing a circuit with driver transistors. Amongst my component stock pile I had some driver ICs both NPN (ULN2803) and PNP (UDN2580). each segment has 4 LEDs and the decimal point has 2 LEDs.51.Both have 8 transistors each.

As well as the 7seg displays the other interfaces that were added as the project developed have been included:  RTC (real time clock)  Jumper (to select normal/settings modes)  Blue flashing light (with transistor and relay to drive it)  Keypad
711
.3
Classroom clock – block diagram
This is the final system block diagram for the classroom clock it shows the connections for the seven 7-segment displays to the microcontroller (j ust 2 digits and 2 segments are shown in the diagram to reduce complexity).51.

PCB layout
This layout shows the extra breadboarding area available for other circuits (such as the RTC etc) which can be added later.
51.4
Classroom clock .schematic
When the schematic was initially developed it was not known exactly what interfaces would be needed for the clock.5
Classroom clock .
712
.51. so a board that could be added to later was designed.

Measure the resistance between all the different pins on the relay. A relay consists of 2 parts a coil and a set of contacts. Once you have identified the coils apply voltage to the coil. As the light requires 180mA to work it cannot be run straight from a microcontroller port pin as they can only provide 20mA. and others all in between. the coil will have a fixed resistance such as 1000 ohms or less. is real bright. the input and output circuits are not electrically connected. however if I wanted to change it for some other light in the future then I might have to change the transistor as well. So I decided to make the device as general purpose as possible and add a relay circuit that would provide more flexibility. Attached to the metal bar are switch contacts that change connections when the bar moves. If you don’t have a data sheet then use a multimeter to help you. The light could be run from a transistor or fet.6
Relay Circuit Example
A flashing light was needed for the clock to act as a warning that the end of the period was approaching. Some relays work off 5V some off 12V some off 24V.
Relays come in all shapes and sizes and current and voltage ratings. start with a low voltage 5V. A relay is also an isolation device. So some amplifier device was needed. the input will change from being connected to out1 to out2. These contacts are sometimes known as NC. if you hear it click then you have the right voltage. There are two types today electro-mechanical and solid-state. they are however fairly standard in theory.
713
. It uses a xenon tube. A Jaycar blue mini strobe was purchased. The NC contacts will be 0 and the NO contact will have no connection to any other contacts. It’s a good idea to know the current that it draws as well so a bench PSU is useful. In the diagram when power is applied to the coil. if you don’t increase it.
For this project an OKO K51A05 was on hand so I found out the connection details for it. so a high voltage power supplyor the light cannot get backinto the Microcontroller. runs off 12V.51. Through the centre of the coil is a metal bar that moves when power is applied to the coil. draws 180mA and flashes at a rate of 90 per minute.normally closed and normally open. this theory is about the electro mechanical type.

In this case the datasheet gives all the details
714
.The K51A05 part number on the device led to the datsheet on the internet.
The part number or what ever else is written on the relay may give clues as to the ratings of the switching contacts . The connection details are in the datsheet.

R = V/I = 33K. A transistor when it is fully on still has 0.7V avaialble for the relay (the relay requires 4V minimum so that is ok) The BC547 can dissipate (get rid of) no more than 500mW of power. A transistor such as the BC547 could be useful.03 = 0.03/200 = 0. so that is ok too.9ma (confirms our power calculation above) In this case it seems that we cannot drive our relay from the microcontroller directly as it needs 30mA and a micro pin can only give 20mA. 715
. but we could calculate it.
    
We are switching 12BV the BC547 can switch 45VDC so that is fine We need 30mA. We want 30mA out so input current = output current /gain = 0.15mA from the microcontroller.5V.00015A = 0. a 560R was chosen as it was at hand.3 * 0. so we need to a firststage of amplification.3V so P=V*I = 0. we just need a resistor to limit the current from the micro to the transistor. The BC547B we have has a gain (hFE) for at least 200. the BC547 can switch 100mA so it will be ok. %v from the micro and 0. Our micro can supply 20mA so that is no problem.  The current is 29. that is the ratio of output current to input current.03mA (P=V*I.00015A . so I = P/V)  It needs at least 4V to pickup or close the contacts  The contacts will stay closed (drop out) unitl the voltage goes below 0.The interesting specifications are:  Contact ratings: 1A at 24VDC (we are switch a 12V strobe light that requires 180mA)  Coil draws 150mW power. we are drawing 30mA and the voltage across the BC547 is 0. so that means 4.009W = 9mW. so at 5V that’s 0.3V across it.

A coil of wire is known as an inductor and inductors have a very interesting electrical property. This diode is VERY IMPORTANT. To protect the BC547 and the microcontroller we put a reverse polarised diode across the coil.This is the circuit developed. that has not been discussed so far.
716
. they don’t like changes in current flow (just as a capacitor doesn’t like change in voltage across it. Now there is a very important component. I will explain why. this however can have devastating effects as the field causes electrons to flow in the coil which can have very high potential. In fact they could have hundreds of volts potential. the magnetic field that is around the coil slowly collapses back into the coil (its called back EMF). the diode across the relay coil. This is due to the magnetic field that is associated with current and wires. This shorts out that back EMF and protects our circuit. So when the relay is powered up and we switch off the transistor. enough to kill our little 45V BC547B and 5V microcontroller very very quickily. an inductor doesn’t like change of current through it).

7
Classroom Timer
Classroom clock – flowcharts
Timer1 message scroll
setup period times
end of message Y N
pointer = start
read time from rtc
incr pointer
convert time & date bytes to strings
get 7 digits starting at pointer
add time to message string Convert ascii code to 7seg led code N school week? Y
during a period Y N find out which period it is
<5min end of lesson Y N
toggle led
Monday Y N
led off
Tuesday Y N
find out the rotation
return
find out which period it is Timer0 digit scan Wednesday Y N find out which period it is last digit Y N Thursday Y N find out the rotation get a 7seg digit code go back to start
find out which period it is
display it on the correct digit Friday Y N find out which period it is return
The settigs mode is entered by moving the jumper on pinb.minute of day + secs ' B .rotation ' # .increase hours ' 5 .51. when in this mode the display is used to display various times/dates and set them using a keypad on portA.decreas day ' 2 .nothing pressed ' 8 .increase day ' 1 . ' 0 .display date ' A .week of year ' * .increase minutes ' 3 .increase month
717
.weekday ' C .zero seconds ' 7 .decrease minutes ' 4 .display time ' 9 .decrease hours ' 6 .3.day of year ' D .

'-----------------------------------------------------------------' 12. 1jan = 1 'however to get our weeks correct we need to adjust for the fact 'that the first day of the year is not on a monday.e. 'this is important otherwise rotations can be ok on a tue but not fri!! 'the first week of the year is the week that has the first thursday Days = Days + Dayoffset Weekofyear = Days / 7 'must use word size Minuteofday = _hour * 60 'work out minutes since start of day Minuteofday = Minuteofday + _min Weekday = Dayofweek(_day) 'mon = 0 Incr Weekday 'add one so monday = 1 Rotation = Lookup(weekofyear . Program starts here Do 'clock and period display mode Gosub Read1307time 'get the current time and date Gosub Converttime 'put time into a string 14-12-46 'need week of year to see if a school week and not holidays 'first need to know the day of the year to calculate week of the year Days = Dayofyear(_day) '1jan = 0 Incr Days 'so add one. Weekrotation) I = Rotation + 4 'make a string to display rotation If I > 6 Then I = I .6 Rotationstr = Str(rotation) + "x" + Str(i) If Jumper = 1 Then 'normal mode If Minuteofday > 910 Then 'dont disp rotation after sch Rotationstr = "" End If Msgstr = " " 'leading spaces Msgstr = Msgstr + Timestr + " " Periodstr = "" 'week of year starts with first full week i. 4Jan10 = week1 Select Case Weekofyear 'if a school week get current period Case 4 To 14 : Gosub Getperiodstring 'term1 ************** Case 17 To 26 : Gosub Getperiodstring 'term2 ************** Case 28 To 37 : Gosub Getperiodstring 'term3 ************** Case 40 To 49 : Gosub Getperiodstring ' term4 ************** End Select If Periodflag = True Then Msgstr = Msgstr + Periodstr + " " If Periodflag = True And Minutesleft < 6 Then Msgstr = Msgstr + "cleanup " Led = 1 Else Led = 0 End If If Periodflag = True And Minutesleft < 6 And _sec < 15 Then Set Bluelight Else reset bluelight End If Msglen = Len(msgstr) End If ' keep looping forever
721
.

'this routine decreases the minute by one and writes the new time to the RTC Decrmin: Decr _min If _min > 59 Then _min = 59 Gosub Write1307time 'use only to set time Waitms Keydelay Key = 1 'display time Return 'this routine increasea the hours by one and writes the new time to the RTC Incrhour: Incr _hour If _hour > 23 Then _hour = 0 Gosub Write1307time 'use only to set time Waitms Keydelay Key = 1 'display time Return 'this routine decreases the hours by one and writes the new time to the RTC Decrhour: Decr _hour If _hour > 23 Then _hour = 23 Gosub Write1307time 'use only to set time Waitms Keydelay Key = 1 'display time Return 'this routine increasea the day by one and writes the new time to the RTC Incrday: Incr _day If _day > 31 Then _day = 1 'no checking for month of year!!!!! Gosub Write1307time 'use only to set time Waitms Keydelay Key = 2 'display DATE Return 'this routine decreases the hours by one and writes the new time to the RTC Decrday: Decr _day If _day = 0 Then _day = 31 Gosub Write1307time 'use only to set time Waitms Keydelay Key = 2 'display DATE Return 'this routine increasea the day by one and writes the new time to the RTC Incrmonth: Incr _month If _month > 12 Then _month = 1 'no checking for month of year!!!!! Gosub Write1307time 'use only to set time Waitms keydelay Key = 2 'display DATE Return
723
.

These are:  Internal Resistor-Capacitor (lesser accuracy)  External RC  External Ceramic Resonator  External Crystal (more accuracy)
ceramic resonator
crystals
Within the micro reprogrammable fuse links (just like the links on a computer motherboard but set via software) are used to determine which method is used. 2 or 4MHz by selecting the line in the window and using the drop down that appears to. however initially it is configured to run from the internal RC clock at a 8MHz rate.1
AVR clock/oscillator
The AVR executes instructions at the rate set by the system clock (oscillator). The Internal RC oscillator may be changed to 1.52. After changing the Fusebit settings select the Write FS button. The ATMega8535-16PI clock can range up to 16MHz. YOU RISK STUFFING UP YOUR MICRO!
737
. There are a number of different ways that this clock can be set up using either internal components of the micro or external components. select the FlashRom tab before exiting (YOU MAY NEED TO DISABLE THE JTAG SETTING AS WELL) DO NOT CHANGE ANYTHING ELSE. In BASCOM when the micro is connected and powered up the settings can be changed by selecting MANUAL PROGRAM. After it has programmed the fusebits.
From the window that appears select the LOCK AND FUSE BITS tab. Bascom will then read the current settings.

53 Cellular Connectivity-ADH8066
The ADH8066 is a cellular module from www.sparkfun.
738
. The photos below show both sides of the ADHmodule. The larger board is sparkfun’s evaluation board. The module is the green PCB with the SIM card on it.com.

1
ADH prototype development
The evaluation board was built up into a circuit using an ATMega16 and a 20x4 charcter LCD on veroboard.
739
.53.

Even though the evaluation board was used. the power supply was provided by an LM350 voltage regulator on the veroboard not through the voltage regulator on the ADH evaluation board. This prototype was made this way as the eval board was at hand and the circuit design was made to help students design boards for their own projects which would use the breakout board. With the breakout board you must connect DSR0 to DTR0 and both to ground via a 1K resistor)
740
. no features of it were used.

The ADH communicates at 115200 baud 8N1 (8 bit. A 2N7000 FET was used as one of those just to show that a FET could be used just as effectively as a transistor as an interface. at such a high baud rate of 115200 using the internal clock or a crystal 741
. 2.53. An external crystal is used for the AVR. no parity. 1 stop bit) No flow control is required.5. The TX pin of the ADH is connected to the RX pin of the AVR 7. The RX pin of the ADH is connected tothe TX pin of the AVR 6. 5. ADH ON_KEY: a transistor circuit using a BC337 is used to pull the ON KEY input low when portC.3 and PinC. 8.372800Mhz.4 is taken high. 4.2
ADH initial test setup block diagram
Block diagram and schematic explanation: 1. 3. 7. The COMMAND and NETWORK outputs of the ADH Eval board are taken via transistors to two input pins of the AVR PinC. Note how the input pins of the AVR are connected to the outputs of the transistor circuits not the output pins of the ADH module.

Power is applied to the evaluation board. In the above screen shot the text in lower case I typed the text in upper case was received from the ADH. an sms is the text message from another cellular phone to the ADH. o The ON KEY input is pulled low for over 2 seconds then released high. Note in the descriptionhere I refer to both ‘message’ and ‘sms’. o The Command LED will come on o The ADH sends a bunch of characters inclusing the text IIII and the text READY to the AVR (IIII is a unique message so we can detect this to see that the adh is alive and ok and we are reading the serial comms properly). or +CREG: 0 for no network(is the antenna unplugged?). o The module sends CREG+1 to the AVR for registration succesful. o Then the ADH module will try and register with a cellular network. a message is the serial communication sent from the ADH to the microcontroller.
742
. 1. or +CREG: 3 for network denied. I put in a prepay Vodafone NZ sim card and the network LED came on within 15 seconds. o This turns on the LED and giving a hardware input to the AVR that the network is on .53.3
Process for using the ADH
Here the ADH evaluation board is connected to a PC via a USB cable and under the control of hyperterminal.

Every message is tagged as READ or UNREAD and there is a command to read all messages or all unread messages. 7. 5. but chose to have an indication delivered instead. I tried to retrieve the message but made an error 6. o We can send AT+CREG=? And the ADH responds +CREG: 1 (we should test thisoften in our program to see if everything is ok). A good point ot note is to use a prepaid cellular account for this sort of system rather than an account where you are billed.0.0. then a few seconds later sent +CREG: 3 – network denied and the network pin turned off.2. I sent the command at+cmgd=2 to delete the message . This means that a message has arrived and it is in the sim memory in slot 2. CSQ: 99/99 means no signal (did you plug in the antenna?) o We should test this often in our program tosee if all is ok 3. An sms was received and the module sent +CMTI: “SM”. I retrieved the message with at+cmgr=2 as it is in memory slot 2. o It has “REC UNREAD” as it is the first time I have read the message. o However for the above test I sent AT+CSQ and the ADH responded with signal strength e.0. 4. o The number it cam from o The time and date it was received o The message I sent “MSG:123abc456def” o The OK response. The module is ready so it can now be controlled using AT commands.o For testing purposes I put in an old sim card that had expired (not been topped up with credit for over 12months) and it responded initially with +CREG: 1 and the network pin went on. o I could put the ADH into a mode where the message is delivered automatically. The final software will have to do an extensive start up routine to determine that the ADH is ok and on the network.1. o Note this message from the ADH is 60 characters long plus the actual sms contents. o We can send AT+CPIN? To check the sim card is ok and the ADH responds +CPIN: READYOK. CSQ: 27/99 and OK (the number should range from 5/99 to 31/99). Testing for CREG:1 at this stage is not a good idea as it could mislead you) 2.g. I then put the module into txt mode using at+cmgf=1 and set the module to notify us when a new sms comes in with at+2. If the system locks up and sends a lot of messages then it could become very costly!$!
743
. making it over 80 characters in length including any non printable charactersa such as the 4 CR’s and LF’s that are in the message. o Note that the default setting is to have no indication from the ADH that an sms has arrived.

Size = 200 The way the buffering works in Bascom is that when you compile your program Bascom sets aside RAM (200 bytes in this case) to hold the incoming data. So unless you need to really conserve ram space having you own buffer as well is much easier. Config Serialin = Buffered . and we don’t want this as it will try and process data that isn’t there! There is a second way of doing this and that is to use a serial interrupt. and you could just use the Bascom buffer if you really wanted to. one that Bascom dimensioned and one that we dimensioned. The big difference here explains why we have both in programming. So the serial communications requires a buffer to hold all the incoming information otherwise we would only see some of it coming in. If you read the data from the buffer before new data arrives then it wont be lost.53. so if there is no data to read it will skip past and return from the subroutine.4
ADH communications
The ADH will send data to the microcontroller and can send a lot of data at once especially if you tell it to send a stored message to you. A do-loop-until will always be executed at least once.
Check_for_adh_comms: I = Ischarwaiting() 'see if buf has something (I=0 Is no. However because it is a circular buffer then data can be spread from the end of it to the beginning making it hard for doing things with. A while –wend may never execute at all. I=1 is yes) While I = 1 'copy all chars to our string Bytein = Inkey() 'get one char If Bytein > 31 Then 'if printable char Adh_rcvd_message = Adh_rcvd_message + Chr(bytein) 'add End If I = Ischarwaiting() 'see if any more charaters in meesage Set Adh_new_mesg_flag 'flag that our string has something Wend 'if no data exit the loop Return
Note how a while-wend is used here rather than a do-loop-until. This routine checks to see if new data has come in and then copies it to a string we have dimensioned. This is a circular buffer so if too much data arrives then data past 200 characters will overwrite the beginning of the buffer and you will begin to lose data. however I decided to not use the interrupt. I did this because I don’t think speed of getting to the buffer is critical for my application. Bascom has this built into it. Data is read using the INKEY() function in Bascom (or you can have the program wait for data to come in using WAITKEY).
744
. Now it seems a bit redundant to have 2 buffers for the data coming in.

53.5
Initial state machine
There are several different operational aspects of the device to keep track of:  is the hardware ok?  Can we talk to it?  Can it register on the network?  Is the sim ok?  What is the signal strength?  Is their credit?
The initial thoughts about the different states of the device are that it is:  DOWN  TRYING TO BECOME OPERATIONAL  OPERATIONAL  RECEIVED AN SMS
745
.

15 Adh_nw_pin_flag Alias Adh_status.
Adh_com_pin_flag Alias Adh_status.8 'we turned echo off 'we set sms mode
these two flags really aren’t used except to keep track at the beginning that we have set the ADH up how we need it before going on to using it. adh_creg_flag as bit and so on.
Adh_alive_flag Alias Adh_status.11 Adh_ss_flag Alias Adh_status.1 Adh_error_flag Alias Adh_status.   I could dimension a whole lot of flags individually e.00 'sfter send while waiting for sent response 'had an error returned from the adh 'reset all flags for initial start
The reason I chose the second way is because I wanted to be able to display them all easily at once on the LCD.14 Adh_alive_flag Alias Adh_status.10 'serial comms is working between micro and ADH 'ADH is registerd on cell nw 'sim card is functioning ok 'signal strength ok (not 99)
these flags inidicate to us that the ADH is functioning ok.13 Adh_creg_flag Alias Adh_status.11 Adh_ss_flag Alias Adh_status.6 Adh_$_flag Alias Adh_status.9 Adh_sms_mode_flag Alias Adh_status.7 Adh_sms_rcvd_flag Alias Adh_status.12 Adh_sim_flag Alias Adh_status.3 Credit_bal_flag Alias Adh_status.2 Adh_sms_sending_flag Alias Adh_status.4 Adh_ok_rcvd_flag Alias Adh_status.0 Adh_status = 0
'command pin hardware connection ok 'network pin hardware connection ok 'serial comms is working between micro and ADH 'ADH is registerd on cell nw 'sim card is functioning ok 'signal strength ok (not 99) 'we turned echo off 'we set sms mode 'get yourself a smiley here! 'an sms has been received from other cellphone 'we have credit to send 'new serial message from adh to micro 'ADH all functioning ok 'credit over $1.
746
. dim adh_sim_flag as bit.6
Status flags
A number of binary flags were created to keep track of all the different things happening within the system. Or do what I chose to do which was to dimension a status variable (dim adh_status as word) and then allocate my flags to individual bits within that variable using the alias command.14
these two flags will be used to tell us that the ADH pin outputs command and network are functioning. At any stage if either of these drop out then there is a problem with our system. There are (at least) two ways of doing this.9 Adh_sms_mode_flag Alias Adh_status.10 Adh_echo_flag Alias Adh_status. especially during the initial stages of programming.5 Adh_new_mesg_flag Alias Adh_status.
Adh_echo_flag Alias Adh_status.12 Adh_sim_flag Alias Adh_status.13 Adh_creg_flag Alias Adh_status.g.53.
'status bits Adh_com_pin_flag Alias Adh_status.8 Adh_ok_flag Alias Adh_status.15 Adh_nw_pin_flag Alias Adh_status.

7
Second state machine
In the second state machine the detail of most of these flags and their settings are exposed (although at this time the credit amount hasn’t been checked)
747
.53.

8
StateMachine 3
748
.53.

Of special note is how we embed the “ within the string to be sent to the ADH. The print command uses the “ as the start and finish of the string. Sms_number . Sms_number . "{034}" the {034} means put the ascii character 34 within the string. 'send Ctrl-Z suppress crlf Return
The format for sending an SMS requires the number to be entered as AT+CMGS=”02187654321” And the ADH responds with a > (greater than symbol) awaiting the sms contents.9
Sending an SMS text
The state st_adh_operational now has another event. You cannot send a CR-LF to the ADH as that just means a new line of text within the same message. when a switch is pressed the ADH requests a credit balance from the cellular provider. To send a character 26 we again use the {} so the command is Print "{026}". "{034}" Waitms 50 Print Sms_txt Waitms 50 Print "{026}".
749
. When thi sis added at the end of a line it means do not send a CR-LF at the end of the string. If you foget this the ADH will not recognise the special character ascii 26. Now take extra special note of the semicolon at the end of the line.53. but we also need it to be part of the string. This is where we use a special feature of Bascom with braces {} so in the line Print "at+cmgs={034}" . So the string sent to the ADH will be at+cmgs=”777” After the sms text has been sent it needs a CRTL-Z or ascii character 26 to be sent to tell the ADH that all the text contents have been sent.
'************************** Sms_request_balance: Sms_txt = "bal" Sms_number = "777" Print "at+cmgs={034}" .

53. To this subroutine is added another test and another flag is added to the system ‘Adh_sms_rcvd_flag’
'received an sms Temp_b = Instr(adh_message .Temp_b 'get the number of chars in sim mem address Temp_str = Right(adh_message .
750
. displayed and any programmed actions are processed. "+CMTI:") 'see if within message If Temp_b > 0 Then 'yes it is Temp_b = Temp_b + 12 'ignore first part Message_len = Len(adh_message) 'find end of message Incr Message_len 'or we get wrong part Message_len = Message_len . Message_len) Reset Adh_new_mesg_flag 'got the new message Set Adh_sms_rcvd_flag 'it is an sms so move to process it End If
Once the flag is set the state will change to st_sms_received.10
Receiving an SMS text
When an SMS text comes into the ADH it sends a message to the microcontroller Containg +CMTI: this is detected within the Process_adh_comms: subroutine. the sms will be read from the ADH and the sms will be split into its different parts.

g. note the structure has no spaces before or after the comma “777” Again some structure (the “”) and some contents (777) note no spaces . This program is useful in that it exposes all the characters sent e. a final LF then two CRLF then an OK +CRLF at the end 751
. what that means is identify what is structure and what is contents. CR LF and other non printing ascii codes. it is the same for all sms messages “REC UNREAD” This is structure in that it starts with “ and finishes with “ But inside the “” the contents will differ. sometimes the text comes back and has “Customer Service” here .
Specifically this message is of interest
To be able to split this string into its component parts we must understand it in general terms. Also no spaces. The first comma will be before the senders number – very useful structure. Another comma – definite structure indicator here “” This is some sort of sender identification. Not sure what the +48 means Txt message This has a LF between each line of the txt.53.time” Closely inspect the structure here “” to start and stop and comma between the date and time. +CMGR: This is structure.11
Splitting a large string (SMS message)
Using the program Realterm the adh to microcontroller communications were monitored. It might be “REC READ” if the message has been read once before. . so we can use the “” possibly to help us. Another comma “date.

Temp_b
o o
Temp_b2 = Temp_b2 . This means the variable temp_b will have 19 in it o The first character of the phone number will always be another 2 places further on   Temp_b now has 21 in it Find how many characters to retrieve from the string. We use the command INSTR to find the parts of the string. 23:12:45 The sms contents are extracted using the LEN command to tell us the length of the whole message. Include all spaces. ". the last digit will be two back from this
o o
Temp_b2 = Instr(temp_b .g. ".There is a SPLIT function in Bascom. 12/05/23 o And get the date into a temporary string temp_20 Then we get change the date string around because its in year/month/day and in NZ we want day/month/year o This is done by copying the parts we want from temp_20 into sms_date. We will use the commas as they wil always be the in the same place. this includes 13 and 10 (CR LF).g." )
Looking at this message count all the characters from the + at the beginning until you get to the first comma. Temp_b2)
 


 
The number will be located at temp_b and we need to get temp_b2 number of digits So in this message we get the three characters starting from 21 to get 777 Note that most phone numbers will have a + at the front as well (see a few pages back) Now we will ignore the next part of the message the “” or “Customer Service” o So starting from temp_b we find the position of the next comma o We reuse the variable temp_b because we wont need the old value anymore o Then we add 1 to get past the comma Now we will get the date o Find the position of the next comma o Then we add 2 to get to the first character of the date o The date willalways be 8 characters e. o RIGHT. Adh_message .2
Temp_bw will now be 23-21 = 2
Incr Temp_b2

Temp_b2 will now be 3. however its not useful in this situation as the structure is not even between the different parts. In out string adh_message all the ascii characters less than 32 in the ascii table have been removed. Adh_message . the right number of digits to get Get the telephone number
Sms_number = Mid(adh_message . However they aren’t so we need to get the position of the last digit then work out the difference between the two. Find the next comma. Temp_b . If phone numbers were always the same length it would be easy just get X digits starting from the first digit.
752
.")
o o
Temp_b = Temp_b + 2
This means starting at the first digit of the phone number go forward until another comma is found o The variable Temp_b2 will have 25 in it  The last character of the phone number will be 2 places before the comma (23) Find the difference between the two and add 1
o o o o o o o
Temp_b2 = Temp_b2 . So we cannot use those to help us with the messages structure. The first part of the routine to fn the phone number is this:  Find the first comma o INSTR will help here as it gives us the first position of a character in a string
o o
Temp_b = Instr(1 . MID and LEFT are useful commands for this. Time is then extracted – it is also 8 characters e.

Temp_b . to do this 'get the next comma after the beginning of the number 'this will be the end of the number 'note that when you txt bal to 777 this part contains "Customer Service" 'increase this by 1 then get the next comma Temp_b = Instr(temp_b .2 Temp_b2 = Temp_b2 . Temp_b . 2) Sms_date = Sms_date + "/" Sms_date = Sms_date + Left(temp_20 . "{034}") 'find the { Temp_b = Temp_b + 1 Temp_b2 = Len(adh_message ) 'get the full length Temp_b2 = Temp_b2 .Temp_b Decr Temp_b2 'exclude OK on the end of the message Sms_txt = Mid(adh_message .the number Temp_b = Instr(1 . Adh_message . ". Adh_message .Temp_b Incr Temp_b2 Sms_number = Mid(adh_message . Adh_message .") Temp_b + 1 'time is 1 on from the comma = Mid(adh_message . 2) Sms_date = Sms_date + "/" Sms_date = Sms_date + Mid(temp_20 . ". Adh_message . 4 .") Incr Temp_b ' 'get 3rd part of sms this will be date (it is 8 characters long) Temp_b = Instr(temp_b . Temp_b .Here is the routine to split the SMS up into the parts we want
Split_sms: 'identify diff parts of sms by using the commas between them 'get first part of sms ." ) 'find the first comma Temp_b = Temp_b + 2 Temp_b2 = Instr(temp_b .") 'get nex comma Temp_b2 = Temp_b2 . ". Adh_message . 8) 'change to NZ date format Sms_date = Right(temp_20 . Temp_b2) 'ignore second part of sms this will most likely be "" . Temp_b .") 'get next comma Temp_b = Temp_b + 2 'get the first char of date Temp_20 = Mid(adh_message . 2) 'get 4th Temp_b = Temp_b = Sms_time part of sms this will be time (it is 8 characters long) Instr(temp_b . ". Adh_message . Temp_b2) Return
753
. ". 8)
'get 5th part of sms this will be contents 'it starts at 1 after the " after the end of the time ' and goes through to 2 characters before the end Temp_b = Instr(temp_b .

84 would then become 4084.g. Temp_b . $40.
754
.084 in it. Temp_b2) 'convert string to number Temp_20 = Credit_bal_str Temp_b = Instr(Credit_bal_str.12
Converting strings to numbers
The credit balance is currently stored as a string.53. o We copy just the credit amount to another string  Instr is used to finfd the decimal point in this new string  Then we use the DELCHAR command we delete the character at that location  The Bascom command VAL is used to convert the string (e.84 into the variable credit_bal_str o We use instr to find the location of the decimal point and know that the end of the credit value will be two characters after the decimal point. 40. As it has a decimal pointit could be a single type. "Bal:") If Temp_b > 0 Then 'got an sms with Bal in it Temp_b = Temp_b + 5 'starting pt for amount Temp_b2 = Instr(temp_b .") Delchar Temp_20 .34  So first we copy just the characters of the amunt e. A word willd o if we drop the decimal place and just store the creit as cents instead of dollars. but that’s a bit wasteful as a single is 4 bytes.56 or 0. Sms_txt . So we need to convert it and place it in a numeric type variable.") 'find decimal pt Temp_b2 = Temp_b2 + 2 'place of last digit of the amount Temp_b2 = Temp_b2 . ". a bunch of ascii characters.Temp_b Incr Temp_b2 'number of digits to get Credit_bal_str = Mid(sms_txt .g. ".65 or 124. “4084”) to a number and the variable credit_val_cents now has 4.
'what should happen when a specific sms is received Process_sms_txt: 'look for a balance Temp_b = Instr(sms_txt . it is not a number that we can add and subtract to.  It will always be Bal:$ and then a number like 5. temp_b 'remove decimal pt Credit_bal_cents = Val(temp_20) 'convert to word var If Credit_bal_cents > 100 Then 'more than a dollar Set Credit_bal_flag Else Reset Credit_bal_flag End If End If Return
Again the structure is identified.

"+CMTI:") 'see if within message If Temp_b > 0 Then 'yes it is Temp_b = Temp_b + 12 'ignore first part Message_len = Len(adh_message) 'find end of message Incr Message_len 'or we get wrong part Message_len = Message_len . Temp_b .Temp_b 'get the number of chars in sim mem address
768
. Temp_b . "+CMGS") > 0 Then Set Adh_sim_flag End If If Instr(adh_message .") > 0 Then 'SS is single digit Sig_str = Mid(adh_message . "+CREG: 3") > 0 Then Reset Adh_creg_flag End If If Instr(adh_message . "+CREG: 0") > 0 Then Reset Adh_creg_flag End If If Instr(adh_message . "+CNMI:") If Temp_b > 0 Then Temp_b = Temp_b + 7 'get indx of part we want Temp_str = Mid(adh_message . 2) If Instr(sig_str . 1) Sig_str = "0" + Sig_str End If If Sig_str = "99" Or Sig_str = "00" Then Adh_ss_flag = 0 'no sig Else Adh_ss_flag = 1 'ok sig End If End If 'check that sms mode is ok Temp_b = Instr(adh_message . "OK") > 0 Then Set Adh_ok_rcvd_flag End If If Instr(adh_message . "+CPIN: READY") > 0 Then Set Adh_sim_flag End If 'find the position of the signal strength in the string Temp_b = Instr(adh_message . 3) If Temp_str = "2. ".1" Then Set Adh_sms_mode_flag Else Reset Adh_sms_mode_flag End If End If 'received an sms Temp_b = Instr(adh_message . "+CREG: 1") > 0 Then Set Adh_creg_flag Set Adh_alive_flag 'make sure it is set End If If Instr(adh_message .'************************** 'check what was received from the adh Process_adh_comms: If Instr(adh_message . "CSQ:") If Temp_b > 0 Then Temp_b = Temp_b + 5 Sig_str = Mid(adh_message . Temp_b .

there are a number of layers that data is converted through that make the system flexible for all the applications that run on computers. . Important point: When two applications do talk to each other they have to talk the same language. Shrek. You get it? We both have layers. accessing mail. . not everybody likes onions. 2 computers communicating in our classroom. Oh. one is a client PC and the other is the local web server. they make you cry.
PC Application: Firefox
Server Application: Apache
When you interact with a network what actually happens?
A switch is a device that connects together two computers that both talk Ethernet.54 Data transmission across the internet
(its all about understanding layers!!!)
Ogres are like onions.
Switch
Important point: Data does not go directly between the applications on the two computers! Firefox doesn’t talk directly to Apache. e. Apache and Firefox (also Chrome and IE) talk in HTTP – hyper text transport protocol. streaming music videos. -Oh. getting the time.
772
.Layers. e. you both have layers.g. Onions have layers. file sharing. Because some of these applications are so incredibly different a simple conversion to one common layer is not enough so there are a numbers of layers in use in the PC. Onions have layers. No! -Oh. -They stink? Yes. You know.g. No!. Ogres have layers. The whole set of internet protocols that allow communication is called the Internet Protocol Suite. 2001
Here is a very simple network. playing games etc.

0. Type ARP –a into the command window to check out what other devices (PCs/routers..0.168. TCP is then converted to IP (internet protocol).. Humans often allocate and use IP addresses when they refer to computers on a network.. Computers. 773
.168.14
IP 192.168..168. IP addresses must be unique for each computer on the same network.
PC Application: Firefox (talks HTTP)
Server Application: Apache talks HTTP TCP
54.0. We might change the IP of a computer but not the MAC address.254
MAC 00:9d:4e:67:01:5c
MAC 00:45:a6:f4:53:21
Switch/Hub
Our web client (Firefox. IE. however don’t know each other by IP they use the.) that your PC can see. Chrome) asks the OS (operating system) of its PC (with IP address 192.254).
54.2
MAC (physical) address
Computers know each other by attaching their IP address to the MAC (media access layer) of your network card.The HTTP is converted to the TCP (transmission control protocol) layer by programs in the operating system which are part of the TCP/IP stack. You can check out the ip and mac addresses of your network card on a PC by selecting START and RUN and typing in CMD and then typing into the command window ipconfig/all..0.
The PC keeps track of the IP and MAC address of computers around it in a table using ARP (address resolution protocol).1
IP address
TCP
IP 192.14) to get a web page from the server (with IP address 192. MAC addresses are unique for every network card ever made and are assigned by the manufacture.

774
.14
IP 192.0. it communicates with another computer using ICMP (internet control message protocol) which is used by operating systems to manage messaging errors between computers.
54.4
PC Application: Ping Server
Ping
ICMP
ICMP
IP 192. Having multiple layers to communications means that applications can be simpler because they don’t have to know everything about the layers below such as about voltage and wires or IP just http to TCP. In the picture of the layers you can see that ping doesn’t talk using TCP it uses ICMP. one is wireless and one is wired.254
MAC 00:9d:4e:67:01:5c
MAC 00:45:a6:f4:53:21
Switch/Hub
Type in ping and the ip of the computer that you want to check communications with.
54. Ethernet is the name of the protocol for moving data between PCs on the same hub or switch and specifies such things as what wires do what and what voltages are present. you set the subnet mask as well. the other is not used at all so has no IP assigned to it.0 as in the previous window. 255.255.g. If you want computers on the same switch to see each other the subnet mask must be the same.168.255. Both however have MAC addresses as the MAC address is a permanent ID for the hardware.0.3
Subnet mask
When you setup the IP of a network card. On the other computer there is no application above ICMP it answers pings itself.168.
Ping is an application on your computer.The PC shown in the previous window has two Ethernet adapters. Only one is connected and has an IP. whereas IPs can be changed. e.

6
Packets
Having two different protocols. if a packet gets lost across the network then TCP on the receiving computer responds with a message to resend the packet that was lost.54. which means that we don’t resend lost packets. However if you are listening to the radio over the network and some data goes missing you don’t want it sent again so it goes via UDP (user datagram protocol).
775
. Some like Time and Shoutcast and VoIP are really only one way.536 different ports that can be used. on the same layer is useful and necessary.0. here are three. just ignore them. time synchronisation and many others.168.
54. TCP breaks it up into chunks called packets and attaches a sequence number to each packet. we have email. web browsers.14 UDP TCP
Apache HTTP: port 80
IP 192.
Thunderbird POP3: port 110 Firefox HTTP: port 80
Time Application NTP: port 123
Time Server NTP: port 123
Mail Server POP3: port 110
Server UDP TCP PC IP 192.0.254
MAC 00:9d:4e:67:01:5c Ethernet Switch/Hub Ethernet
MAC 00:45:a6:f4:53:21
Some of the applications require two way data transmission . Attached to each IP are 65. Sometimes it doesn’t matter if a bit of data gets lost and sometimes it does.168. When a web page is sent.5
Ports
There is always more than one application on a PC wanting network access. like web browsing and email. TCP and UDP. one way applications can run using UDP. many of them are dedicated to certain applications. Two way applications run on TCP.

15.67 IP 192. You just set up your gateway address on each computer on your LAN.54.0.81. so other technologies are necessary to transport data long distances over the internet. A switch is ok for connecting computers via Ethernet however Ethernet only works for short distances. A gateway translates one type of data protocol to another e.168.1
A gateway has two IP addresses one for the LAN (local area network) and one for the WAN (wide area network).25. your ISP (internet service provider) has hardware that gives you one automatically when your modem logs in. Its only when you want to build servers and things that you really get into it. Ethernet to ADSL.20.1.14 MAC 00:45:a6:f4:53:21 MAC 00:9d:4e:67:01:5c internet Ethernet 192.7
Gateway
There are different ways of connecting to the internet a popular way is via broadband using ADSL.g. If you are setting up a small network at home then you don’t worry about your gateway IP on the internet.168. When you open a web browser you don’t have to worry about any of this because TCP handles it all for you.31 Gateway Device Server Apache HTTP: port 80
10.20.1 ADSL 203.
776
.
Firefox HTTP: port 80 PC TCP TCP IP 10.15.218 Gateway Device ADSL Modem 202.184.180.

You can see your actual ip on the internet by going to a site like www. Or open the status page of your modem.com and find Shieldsup and test the firewall of your modem.grc.
777
.
Better still go to www. a firewall protects (opens/closes/hides) ports on your modem through which other devices can get into your network.whatismyipaddress.com.

235.37
www.54.180.11.31 Gateway Device
PC IP 192.nz into a computer it has to find the ip address for it.15. It is such an important hing that you generally have access to at least 2 of them as they can get busy.14 MAC 00:78:95:f6:BA:F1 MAC 00:9d:4e:67:01:5c Ethernet 10.techideas.11.168. then your PC asks the server at that IP address for a web page.nz or www.37
778
.com When you type www.25.10 Ethernet
192.75.
Firefox HTTP: port 80 PC TCP IP 10.1 202.11.1 ADSL 203.11.0.20.235.com 94.20.techideas.67 DNS Server UDP TCP Server Apache HTTP: port 80
202.15.3 MAC 00:45:a6:f4:53:21 IP 10.8
DNS
Even though computers may work on numbers humans do not.118 what's the IP for mcselec.20.mcselec.14 DNS server at 10. we like to use names for websites on the internet like www.118
When you want a website.
GET 94.64.20.75.118 IP 192.75.81.20.1. Normally your modem gets the IP for the DNS server automatically when it logs on to your ISP.37 IP 10.co.184.mcselec.com? DNS Server It is 94.180.20.co.168. On the status page for your modem is the IP address of the DNS (domain name system) server on the internet (usually at your ISP) that will help you.235. your computer asks the DNS server for the IP of the website.0.168.218 Gateway Device ADSL Modem/Router
internet ADSL
10.

nl/bzijlstra/
779
. You just have to configure its IP and MAC addresses and then talk to it (sounds simple sorry it’s not!!)
internet
System Block Diagram
Our first Ethernet application will be to get a simple Ping working.9
WIZNET812
We are going to build a small webserver using an AVR and put it on the internet so that we can control things from anywhere around the world. you don’t have to write much of a program for this to happen. It has all the TCP/IP stack (protocols) built into it.home.
Much of the code that follows was written based upon the most excellent work from http://members. Note that all that is needed for a ping is to configure the Wiznet. There are a number of ways of implementing a network device but using the Wiznet812 is definitely one of the easiest. the TCP/IP protocol stack is configured within the Wiznet.54.

its pins are however tolerant of 5V so the Wiznet will run off 3V3 and the micro and LCD off 5V 780
.Circuit diagram
The wiznet requires a 3V3 power supply.

54.0. It also sends a CRLF at the end of the body.6.5 Accept-Encoding: gzip.q=0. MSIE 8. .5.7. */* Accept-Language: en-nz User-Agent: Mozilla/4.NET CLR 3.NET CLR 2.8 ( .q=0. InfoPath. application/x-silverlight.2152. image/jpeg.7 Keep-Alive: 115 Connection: Close CRLF CRLF
And from intenet explorer it is:
GET / HTTP/1.ms-excel.deflate Accept-Charset: ISO-8859-1.1 Host: 192.
The actual GET message is a text message like this from Firefox
GET / HTTP/1. CR & LF codes are stored in a document or sent in a message to signify to return to the beginning of the line (CR-carriage return) and go to the next line down (LF-line feed).0 (Windows.en.8) Gecko/20100722 Firefox/3.30729. . application/msword. application/vnd.0.8 Accept-Language: en-us.168.1.2) Accept-Encoding: gzip.ms-powerpoint.9. Windows NT 5.1 Accept: image/gif.q=0.5. The initial request is a GET message which has no body just a header and at least 2CRLF’s (carriage return.NET CLR 3.*.application/xhtml+xml. rv:1. application/x-shockwave-flash.1.ms-xpsdocument. A browser sends a CRLF at the end of each line and after the end of the last line a second CRLF to indicate the break between the header and any body.73 User-Agent: Mozilla/5.0.168.10
Wiznet 812 Webserver V1
To setup a webserver also involves understanding a bit about http communication that takes place between a browser and a server. application/vnd. application/x-ms-application.NET CLR 3.9.2.q=0.q=0.*/*. application/vnd. application/xaml+xml. application/x-ms-xbap.73 CRLF CRLF
786
. image/pjpeg.utf-8. .1. U. image/pjpeg. the code for LF is 10 or &H0A.50727.30729) Accept: text/html. The browser (client) sends a GET to the server and then the server sends its webpage A message from a browser is made up of two parts a header and a body. line feeds) on the end.application/xml.1. en-US. deflate Connection: Close Host: 192. The ASCII code for CR is 13 or &H0D. Trident/4.0.0 (compatible. Windows NT 5.4506.

The Wiznet812 is based around the WIZ5100 IC which has a large memory to store data that it receives and data that you want it to send. As our code becomes more complex.
open connection and listen
GET
Wiz received data? N Y
Header complete? Y N
set flag1
web browser flag1 ? Y N
send webpage
send the webpage to the browser
The server software must wait for data and then check that the header is complete.When understanding the program code for a webserver you start from when the web browser sends a GET and the server receives it. it knows it is complete when it finds two CRLF in a row. &H0000 Common registers &H002F &H0400 Socket registers &H07FF &H4000 TX Memory (8K) &H5FFF &H6000 RX Memory(8K) &H7FFF
787
. Important point: program flags In our program when the complete header is detected a flag is set (a single bit in a byte sized variable). afterwards in a later part of the program the flag can be checked to action something else.g. If that happens it sends its webpage to the client browser. the GET header was 386 bytes. more flags will be necessary. Reasonable size memories are required because there are often significant size data transfers involved: e.

the second from 150 to 249. We would loose important content doing that. The first read is from 1 to 200. The server software must loop through the header to find the end of the header (marked by two CRLF). So an overlap process is used with the buffer to avoid cutting important words or phrases up.2) A complication exists though as we do not want to get blocks of 200 characters at a time and find that an important piece of data was cut. the third from 200 to 249 and so on
789
. To read an HTTP header we only grab 200 characters at a time from the wiznet and check these for the CRLF CRLF end of header. then it extracts the content length and using this value gets that number fo characters from the body. Bascom is set up to handle strings of a maximum of 254 characters in length yet the simple GET header was almost 400 characters and the POST header is over 500 characters.It is a POST so the webpage is not getting something from the server it is sending it to the server. There is a limitation with Bascom-AVR though which really complicates our program. When we have this we set a flag _flag.

At a normal bus stop the people join the end of the queue and as people get on the first available bus the whole queue moves forward.
Imagine a major bus station. and we have a limited resource of memory available in the wiznet to store and send this data. it has a 300metre long platform where a lot of passengers have to transfer from one bus to another. except the busses run at slightly different schedules.11
Transmitting data
There can be a lot of data to send when it comes to web pages.
791
.54. A data structure called a queue or buffer is required to manage the sending of the data and the holding of it until it can be sent. just like people waiting at a supermarket checkout or a bank ATM. It is a FIFO (first in first out) queue.

The first pictures above are clear. the queue grows down the platform. it is of limited length(size) so if we add data to the end of ram. eventually we must run out and then we need to start our queue from the beginning again.However at a busy bus platform that is 300metres long we don’t want the people to shuffle all the way down the platform to catch the outgoing bus. so the bus driver drops them off at the other end of the platform. Everyone would get really cross with having to pick up their parcels and move every few seconds and then wait. then move. Memory in a computer is a bit like the bus platform.
792
. But as we get to the end of the platform it is clear that we cannot drop off the new passengers as there is no room. then the outgoing bus drivers pick up people at the front of the queue. then wait a bit more… So we have the bus drivers drop people off at the end of the queue and the people wait in one spot.

We are going to add the contents of the AVR ram buffer into the wiznet buffer. it then copies the data from that point . the wiznet stops sending when the two pointers are the same as it has then sent all the data in its buffer. The wiznet has a freesize register as well which can be read at anytime to find out how much tx buffer memory is available. read the pointer 3. then calculates the new value for soc0_tx_wr_ptr by adding the length of the new data to it and finally writes the new value into the pointer.g. tell wiz to transmit 2. write the pointer AVR data to be inserted 4. soc0_tx_wr_prtr contains the address &H413E AVR data = “<html><head><meta http-equiv={034}PRAGMA{034} Content={034}NO-CACHE{034}/>” Data length is 74 characters = &H4A new value for soc0_tx_wr_ptr = &H413E + &H41 = &H4188
WIZ 2-Kbyte Circular Memory buffer contents rd_ptr wr_ptr
The wiznet maintains a second memory pointer soc0_tx_rd_ptr which it uses to read the memory content from the head of the queue.
793
. e. pointer = pointer + data length
When inserting the new contents into the wiznet buffer. As data is transmitted across the network the rd_ptr moves towards the wr_ptr.
WIZ 2-Kbyte buffer buffer contents 1.In the wiznet there are two pointers used to manage the head and tail of the buffer or queue. the program first reads the pointer soc0_tx_wr_ptr which tells it where to start copying into the buffer.

After each copy into memory the tx_wr_ptr is set to the new value at the end of the buffer contents and and the wiz sends the data onto the network. each new line replaces the old one in the buffer (the buffer does not get longer).WIZ 2-Kbyte buffer buffer contents buffer contents buffer contents
AVR data (1) AVR data(2) AVR data (3)
The program reads data from the end of the program line by line. After this the entire buffer is copied into the memory at the next location after the last. just like at the bus station.
794
.
&H4000 split buffer contents
WIZ 2-Kbyte Circular Memory
&H4800 split buffer contents
When ther buffer over runs memory the remaining part is inserted at the beginning of memory
split
buffer
start over from &H4000
At the end of WIZnet memory the buffer may be split up and wraps to the beginning again.

Flag As Byte . Top As Word .2 = 0 'for all received data 'get 200 characters at a time from wiz Buffer = "" 'empty the buffer Rx_count = Rx_count . Addr_ptr As Word . Rx_count As Word Local Complete_header As String * 4 .1 Function w812_receive_check() As Byte Local Temp As Word . J As Word . Complete_header) If Temp > 0 Then Flag. _status As Byte Local Contentpos As Word .'check to see if the wiz has received any data ' if a full header has been received set flag.2 = 1 'reached the end End If Next Temp = Instr(buffer .1 Top = &H6000 + Rx_count Top = Top + 3 For Addr_ptr = I To J If Addr_ptr < Top Then 'not at end yet Char = W812_readb(addr_ptr) 'get a byte from wiz Buffer = Buffer + Chr(char) 'store ascii char in buffer Else Flag. Char As Byte Buffer = "" Complete_header = Chr(13) + Chr(10) + Chr(13) + Chr(10) 'gap between header and body Contentpos = 0 Addr_ptr = 0 Flag = 0 _status = W812_readb(w812_s0_status) If _status = &H17 Then 'Check for new data received by wiz Rx_count = W812_readw(w812_s0_rxsizeh)
'check if connected first
If Rx_count > 0 Then 'received something I = &H6000 J = &H6000 + 200 While Flag. I As Word .1 = 1 'full header and body I = I + 150 'slide up the buffer 150 chars J = J + 150 'slide up the buffer 150 chars Wend End If End If w812_receive_check = Flag End Function
798
.

'the main do-loop looks to see if something arrived, 'if it did then it looks to see if it contained a message Do Reset Watchdog 'Reset the watchdog 'Get socket status Gosub Get_w812_status 'do something if a connection has happened If W812_status = W812_connected Then 'if we are connected Rx_flag = W812_receive_check() 'see if anything received If Rx_flag.1 = 1 And Rx_flag.0 = 1 Then 'body and"ContentLength:" both present If Debug_word.6 = 1 Then Print "rx_flag=" ; Bin(rx_flag) Gosub Process_received_data 'here to process received mesgs End If 'if we got at least a request then send the web page back If Rx_flag.1 = 1 Then 'full header found Call W812_writeb(w812_s0_commandreg , &H40) Call W812_send_webpage() 'send out the webpage Rx_flag = 0 'everything processed If Debug_word.6 = 1 Then Print "rx_flag=" ; Bin(rx_flag) End If End If 'Connection was closed or is in the process of closing so we start the socket new If W812_status = &H0 Or W812_status = &H1C Or W812_status = &H18 Then Call W812_cycleport() End If Loop End 805

54.14

process any messages received from browser

'---------------------------------------------------------------------'this sub will be entered when the user has interacted with the webpage in some way 'e.g. pressed a button or pressed enter in a text box. 'it will not be entered when the user first looks at the page in their browser. 'the codes in the buffer that it looks for are built into the webpage below. Process_received_data: 'here we check to see if the user pressed the button ctrl_0_on If Instr(buffer , "CTRL_0=ON") > 0 Then Ctrl_0 = 1 'turn that port on Locate 1 , 1 'blank a line of the LCD Lcd Spc(20) Locate 1 , 1 Lcd "CTRL_0=ON" 'say what was received End If If Instr(buffer , "CTRL_0=OFF") > 0 Then Ctrl_0 = 0 Locate 1 , 1 Lcd Spc(20) Locate 1 , 1 Lcd "CTRL_0=OFF" End If If Instr(buffer , "CTRL_1=ON") > 0 Then Locate 1 , 1 Lcd Spc(20) Locate 1 , 1 Lcd "CTRL_1=ON" Ctrl_1 = 1 End If If Instr(buffer , "CTRL_1=OFF") > 0 Then Locate 1 , 1 Lcd Spc(20) Locate 1 , 1 Lcd "CTRL_1=OFF" Ctrl_1 = 0 End If 'here we process the text the browsersent us If Instr(buffer , "TEXT2SEND=") > 0 Then Cls Lcd "text arrived" 'separate the text into three lines for the lcd Length = Len(buffer) Buffer = Mid(buffer , 11 , Length) 'strip 'TEXT2SEND=' Locate 2 , 1 Length = Len(buffer) Select Case Length Case 1 To 20 : Lcd Buffer 806

'-----------------------------------------------------------------'-----------------------------------------------------------------'-----------------------------------------------------------------'this external file has all the routines we need to control the wiznet $include "WebServ2_functions.bas"

807

54.15

Served webpage

'-----------------------------------------------------------------'here we build the webpage that the wiz will send to the browser Served_webpage: 'BE CAREFUL EDITING AS SOME SPACES ARE CRUCIAL 'Variables must be on their own lines !!! 'everytime an input is wanted a form is created for it ' rather than 1 big form for for the whole webpage ' this means that only the data changed is sent not the whole lot '{013}{010} measb send a CR LF '{034} means send a " Data "HTTP/1.0 200 Document follows{013}{010}" Data "Server: w812MJ AVR server{013}{010}" Data "Content-Type: text/html{013}{010}{013}{010}" Data "<html>" Data "<head>" Data "<meta http-equiv={034}PRAGMA{034} Content={034}NO-CACHE{034}/>" 'tell browser not to cache page Data "<title>WIZNET812 WebServ_V2</title>" Data "</head>" Data Data Data Data Data send Data Data Data "<body>" "<center>" "<h1> Welcome " "<font color={034}blue{034}>" "SEND_CLIENT_IP" your ip back to you "<font color={034}black{034}>" " to my WIZnet812 web server</h1>" "<hr>" 'body of the html document 'center the web page 'in heading 1 format 'this tells the sendng routine to 'in a different colour 'a title for the page 'insert a blank line

55 Assignment – maths in the real world
5 numbers are to be entered into memory via the 5 buttons and then displayed on the LCD. Press btn A to move between the 5 numbers. Btn B to increment the number, btn C to decrement the number. The maximum number will be 255, the minimum number will be 1. The display looks like this.

The program as given to you has a few bugs for you to fix 1. After the power is applied the lcd is blank it should display the 5 numbers. Write your code here that fixes this

2. The display does not blank any zeros when the numbers go from 100 to 99 and 10 to 9. Fix this and explain here how you did it.

3. The numbers start at 0, they need to start at 1, fix this and explain here how you did it

4. Make the maximum number that can be entered 200, Write the code here that fixes this.

813

55.2

Math assignment - part 2

At the moment the user must press the button to increment or decrement the numbers one at a time. There is no auto-repeat feature included in the debounce function. Add some form of repeat feature so that the user can hold a button and after a short delay the numbers will increase/decrease until the button is released. You may want to try and do this using if pin=0 then..... rather than debounce. Make your routine as generic or portable as possible, so that it could be easily transferred to other programs.

Explain how your auto-repeat code works.

814

55.3

Math assignment - part 3

This program is going to be used by a groundsman to calculate the area of a piece of land so that he can work out the amount of grass seed to buy. He will use your program and pace out the 4 sides: a,b,c,d, and the diagonal e.

the formulae to work out the area of a triangle is: s= (a+b+e)/2 Area of first triangle = sqroot(s(s-a)(s-b)(s-e)) t= (c+d+e)/2 Area of second triangle = sqroot(t(t-c)(t-d)(t-e))

1. All the calculations must be in one subroutine. 2. You will also need to dimension some temporary variables to help you, e.g. dim sngl1 as single, sngl2 as single, sngl3 as single 3. Bascom can only do one arithmetic equation per line so you will need to break up each equation into individual parts. Here is half of the routine. calcarea: s= a+b s=s+e s=s/2 singl1=s-a s=s*singl1 's(s-a) singl2=s-b s=s*singl2 's(s-a)(s-b) singl3=s-e s=s*singl3 ' s(s-a)(s-b)(s-e) area=sqr(s) 'area of the first triangle return 1. You complete the rest of the equation to work out the area of the second triangle and then work out the total area for the whole shape. 2. Modify your program to automatically update the lcd with the calculated area as the grounds man enters the data for each variable. Explain where in your code you put the changes to make this update happen all the time.

815

55.4

Math assignment - part 4

When the groundsman gets back to the office, he needs to draw a plan of the area. To do this he needs the angles within the shape. Using the cosine rule we can calculate these for him. U is the angle opposite side E E2 = A2 + B2 - 2ABcos(U) V is the angle opposite side E A2 = E2 + B2 – 2EBcos(V) 1. calculate each of the 6 angles 2. U will be in radians, convert each angle to degrees. 3. display them on the LCD Write the code for calculating one of the angles below.

816

55.5

Math assignment - part 5

When the groundsman has calculated the area and angles, the data must be stored into eeprom so that it will be there when he goes back to his office. To do this you must declare some new variables e.g. eep_a, eep_b, ... and dimension these dim eep_A as eram byte. add a state and subroutine to your program which copies the variables A,B,C.etc into the corresponding eeprom variables eep_a, eep_b, eep_c etc. Write it below (you may want to change the fuselink in the AVR that causes the EEPROM to be cleared every time the AVR is reprogrammed)

add a state and subroutine to your program that reads the eeprom variables and copies them into the ram variables. Copy the subroutine here

817

55.6

Math assignment - part 6

Create a simple menu that allows the groundsman to select the operation to perform      enter 5 lengths calculate and view the area calculate and view the angles store the values into eeprom read the values from eeprom

You must use a state variable to manage the program flow. Explain your code below.

55.7

Extension exercise

Give the groundsman the option to store multiple areas of land

818

56 SSD1928 based colour graphics LCD
The Display used is from techtoys.com.hk, it is not cheap but is the most suitable one I could find for student projects.

So far in this course the LCDs covered have all had driver code built into Bascom or within code libraries that hide the complexity of using the LCDs. This is not the case for the SSD, no libraries exist for driving the SSD from Bascom or even from an AVR. Research to date of these has found PIC microcontroller (not the Picaxe) libraries and faster more capable 32 bit microcontrollers being used. In this case the drivers were written for Bascom. Also note that at this time only a certain amount of SSD1928 is covered here but as students have further opportunity (and the funds) to explore it, more information will be added.

56.1

System block diagram

LVC75Z779 www.techtoys.com.hk Display PCB

320x240 TFT LCD Panel GPIO 320 of 960 column lines used 240 row lines

8Data + 6Control ATMEGA

SSD1928 Driver Data + Control

HX8238 Driver

Touch panel

User PCB

There are three ICs – the ATMEga, THE SSD1928 on the display PCB and the HX8238 hidden on the back of the LCD itself.

819

56.2

TFT LCDs

It is useful to know a little about LCDs so that you can understand the software for driving them.

An LCD requires quite specific driving signals; these are managed by ICs on the back of LCD. To get an LCD pixel to appear requires an AC voltage to be applied to each pixel individually. Light passes through one polarizer, then through a crystal structure which has been twisted and then it passes through the second polarizer which is at 90 degrees to the first one. The applied voltage untwists the crystal and this blocks light from passing through the second polarizer. The darkness of the pixel can be controlled by the amount of signal applied to it. In a colour display each pixel is actually three separate sub pixels (R, G, B) which are controlled individually. Each pixel also has its own transistor embedded in it on the glass and hence the name of the display type TFT, thin film transistor. Having a transistor on each pixel helps switch the signals quickly reducing blurring and other issues. These animations from 3M about how LCDs work are of interest http://solutions.3m.com/wps/portal/3M/en_US/Vikuiti1/BrandProducts/secondary/optics101/?s lideIndex=14 820

Each pixel is driven individually one after another in each line and 1 row after another. In a 320 row by 240 line display there are (320 x 240) 76,800 pixels to be driven. Each pixel is however actually three sub pixels of red, green and blue. If we had 1 byte per colour then we would need 320 x 240 x 3 = 230,400 bytes of information for 1 screen. In our system however we only use 16 bit colour so 2 bytes per pixel (320 x 240 x 2 = 153,600 bytes). The SSD1928 has a 256kByte RAM for storing the LCD panel data which therefore leaves us spare ram.

56.4

System speed

Data must be sent from the SSD1928 to the HX8238 on the LCD many times per second otherwise the LCD image will fade (LCD screens are refreshed at rates of 50 or more times per second). The rate of this particular system setup is 52 screen refreshes per second. You might think then that we need to send 320 x 240 x 2 x 52 = 7,987,200 bytes every second , but it is actually more than this due to the timing requirements of the ICs – more about this later. To achieve all this high rate of timing inside the SSD1928 is a special oscillator circuit called a PLL (phase locked loop) which generates the main internal clock signal of 72MHz from a 4MHz crystal on the PCB.

56.5

SSD and HX ICs

The SSD1928 has 128 pins in what is called a LQFP (low profile quad flat package) and can either be driven with data which is 16bits in parallel or with 8 bit parallel data or even serially. The HX8238 has 1,521 pins(!!); there are 320 columns each of which has a separate red, green and blue line, so 960 connections are needed and another 240 pins are needed for the 240 rows. It comes as a COG (chip on glass) not as a usual package with pins but as a ‘bump’ package which has tiny pads underneath; it is also very small; just 22.18mm long x 0.96mm wide and only 0.015mm high!

56.6

Colour capability

Although the SSD1928 is capable of 16M colours (8bits each of red, green and blue, 255x255x255=16,581,375), we won’t actually get 16M because the HX is only capable of 262k colours (6bits of red, green and blue, 64x64x64=262,144 this is 18bit colour). Note that all 24 bits of colour from the SSD are connected to the 24 colour input pins of the HX, but the HX only uses the lower 6 bits of each colour. 18bit colour is of little use as we send data in byte size chunks, so in our software we are only using 16 bits (2 bytes) to store colour information which gives us 65,536 colours. so our data will take up 320x240x2 =152,600 bytes of the ram. The16 bits are arranged as: RRRRRRGGGGGGBBBBB (5 bits of red, 6 bits of green and 5 bits of blue)

821

it has 2 separate sets of interface pins in the 54 pin flexi circuit. SCK. The colour data and control lines include 8 parallel data lines for colour information (even though we send 16 bits of colour data). These 4 serial lines are used to send commands to the HX8238 to tell it about the LCD panel connected to it and information about the timing of the Sync pulses. the two synchronization pulses (VSync and HSync). These are kept separate because the HX chip requires precise timing for the colour data and timing control signals so these cannot be halted to send control information to HX chip. In the extended block diagram below the SSD to HX connection is shown. over these lines travels both information to control the SSD and HX chips as well as the colour information for the LCD panel.7
SSD1928 and HX8238 control requirements
Referring to the previous block diagram the ATMega controls the SSD through 8 data and 6 control lines. Interestingly although an LCD is technically different to the old CRT screen the terms and signal timings used here are very similar.
HX Colour Control & Data VSYNC HSYNC DOTCLK SSD1928 Driver Data Enable 8 bits of colour data HX8238 Driver 240 rows 320x3=960 columns
LCD panel HX Serial Control Data (SDA SCL EN Reset)
4MHz crystal
822
.56. the clock signal and a data enable pulse that is high only when actual colour information is present. the first is for the colour control and data signals. The SSD1928 control signals to the HX8238 are fairly complex and normally you wouldn’t have to know much about them however we have to write software that sets up the SSD to generate the signals and more software to set up the HX8238 to be able to interpret the signals being sent to it by the SSD1928. SDI and SDO). 4 of which are connected to the 4 serial command lines of the HX8238 (CSB. The SSD1928 has 5 GPIO (general purpose IO) lines. the second for control information for the HX chip.

56.bas and .h). The only function of the main program then is to call the routinwes that set up the LCD and then draw some text onto the LCD.
823
.h files with the same name. This reduces the over all size of the main program and helps to logically structure code for others to understand.bas) and one with the declarations in it (these end with the extension . Before subroutines in other files can be used BASCOM requires that they must be declared. so in the directory there are both . An easy way to do this is to have two files setup one with the saubroutines in it (it ends with .8
SSD1928 Software
The software is broken up into a main program and a number of routines in other included files.

Direct mode is also configurable where the address and data are on separate buses. Indirect mode means sending 3 bytes of address and then the required bytes of data over a single 8 bit data bus. CNF1 & CNF0 on the board and they should be set to 0011. CNF2. These are the 4 switches labeled CNF3.
Before we can access the SSD registers however we need to configure the SSD to micro interface and we have to setup some jumpers on the SSD interface board that tell the SSD the configuration of the data we are going to be sending to it. However this development board does not give you access to the address bus so you cannot use direct modes. To use these features requires the developer to become familiar with many of the thousand plus registers within the SSD.9
SSD1928 microcontroller hardware interface
The SSD1928 is a very complex device with many interfaces and features. these control everything that the SSD does.
827
.56. You can also configure and use 16 bit indirect mode as well. This setting indicates to the SSD to expect 8 bits at a time in indirect mode.

word_data )  Read a long (4 bytes) from a register getregl(word_addr)  Write a long (4 bytes) into a register setregl(word_addr. long_data)
828
. We will need routines that can read and write 8. the addressing however is the same as that used to access the 256kbyte SRAM in the SSD1928 for pixel colour data which requires 19 bits of address [A18:A0].56. To tell the difference between an address of a register and an address in memory the SSD requires the first bit of our three bytes of address to be a 1 for memory and a 0 for a register. Note that this is more than the address range of the actual registers in the SSD which could be addressed using 2 bytes.g. Addressing a register requires 3 bytes of address to be sent to the SSD. The routines we will write are:  Read a byte from a register getreg(word_addr)  Write a byte into a register setregb(word_addr. e. &B1000 0000 0000 0000 1111 1111 is memory and &B0000 0000 0000 0000 1111 1111 is a register address. byte_data)  Read a word (2 bytes) from a register getregw(word_addr)  Write a word (2 bytes) into a register setregw(word_addr.10
Accessing SSD control registers
The first set of subroutines we will need will allow all of our other routines to write to and read from the control registers in the SSD1928. 16 and 32 bit data registers.

Take CS low – triggering the SSD to know that another byte of address is on the data bus 9. Write must be low as we are going to be writing into a register 3. The three bytes of address are sent first and then two bytes of data are sent. the dotted line on the diagram tells us that the previous steps must all happen before the negative edge of CS. 15. Setup the first byte of the data 14. The first byte of data will go into the register we set the address of. this means we have finished sending the address and will now send the data 13. Return CS high 7. the second byte will go into the next register. Take CS low then high again. Read must be high – this is the default or usual state but we set it anyway 2. 12.As an example the sequence for writing one word (two bytes) of data into two consecutive registers is taken from the timing diagram in the SSD1928 datasheet. Setup the second byte of the address 8. RS(DC) – register select or DataCommand must be low (we are sending the address of the register or command 4. Setup first of three address bytes – bit 7 of the first byte must be 0 to tell the SSD that the address we want to access is a register and not a memory address (note that steps 1 to 4 can happen in any order) 5. Take CS low – this is the important action that the SSD is waiting for to trigger it to do something. 6. As we have finished sending the data we return the write line to its default state which is high
829
. Return CS high 10. Setup third byte of the address 11. 1. Take RS(DC) high. Take CS low then high again.

These routines give us access to register &HAC in the SSD which controls the 5 GPIO lines.1 = 0 End If Call Setregb(&Hac .3 = 0 End If Call Setregb(&Hac . 4 of which are connected to the HX. _gpiostatus) End Sub '******************************************************************** Sub Gpio_spena(byval State As Byte) If State = 1 Then _gpiostatus. _gpiostatus) End Sub '******************************************************************** Sub Gpio_spclk(byval State As Byte) If State = 1 Then _gpiostatus. _gpiostatus) End Sub 834
.bas
'******************************************************************** 'these routines manage the communication between the SSD1928 on the PCB ' and the HX8238 on the LCD panel itself $nocompile '******************************************************************** '4 lines are used to communicate to the HX from the SSD 'we must use these routines to configure specific registers in the HX 'the state of these 4 lines is controlled by the GPIO status/ctl register &HAC '_gpiostatus keeps track of which bits are set or reset in the register 'so it must be a global variable ' ' ' ' SSD_Gpio3 SSD_Gpio2 SSD_Gpio1 SSD_Gpio0 = = = = HX_Lcd_reset HX_Lcd_spena HX_Lcd_spclk HX_Lcd_spdat = = = = bit bit bit bit 3 2 1 0
Dim _gpiostatus As Byte _gpiostatus = 0 'initially no bits are set '******************************************************************** Sub Gpio_spreset(byval State As Byte) If State = 1 Then _gpiostatus.
The only way to control the HX is to send data serially from the SSD.13
SSD1928_GPIO_routines.1 = 1 Else _gpiostatus.2 = 0 End If Call Setregb(&Hac .12
Accessing the HX8238. '********************************************************************
56.2 = 1 Else _gpiostatus.3 = 1 Else _gpiostatus.56.

so at the end of a line and before the beginning of the next line a number of clock pulses are needed to allow time for the internal electronics of the HX to reset the line counter inside the HX to the left edge of the panel (the front and back horizontal porch times).625MHz
 The HX must know when a new line begins.56. In an LCD everything is controlled by a single clock rate. and in the upper red areas of the timing diagram the darkest area is the 240 visible lines of data. Note that there is also time at the end of 836
. the rest of the green time is used as a gap between each line. and this is signaled by the HSync (horizontal synchronization) pulse. A frame is a full screen of data sent line by line to the LCD panel.5MHz dotclk LShift
R
G B pixel 1
R
G B pixel 2
R G B pixel 320
PCLK 5. The total red areas of the timing diagram show all the timing for one complete frame of the LCD.
LFrame VSync
Vertical Front Porch time
VSYNC pulse
Vertical Back Porch time
LCD 240 ROWS of Data
Vertical Front Porch time
VSYNC pulse
1 row of data Horizontal FrontHYSNC Horizontal Back Porch time pulse Porch time LLine HSync LCD LINE OF DATA 320 pixels Horizontal FrontHYSNC Porch time pulse
data enable LCD_DEN 22. The data cannot be sent asynchronously (without extra timing pulses) as the HX must know when each new line and when each new screen starts so the synchronizing signals HSync and VSync are sent as well. note that one visible line is 320 pixels and they are all sent during the bright green. In a CRT (cathode ray tube)monitor or CRT TV a delay is required after sending each line of information because the cathode ray (electron beam) had to be repositioned to the beginning of the next line (flyback time) or to the top of the screen.  The SSD must send each row of data one after the other. this requires quite a lot of understanding about how an LCD is setup.  In the timing diagram below the bright green area shows the time for one line of 320 pixels to be sent sequentially (one after the other) to the HX chip. Its positive edge is the reference for the horizontal or line timing  The HX also must know when the colour data is present and this is signaled by the data or LCD enable line being high. which goes low for a short period of time.14
LCD timing signals
Now we know how to write to registers we need to figure out exactly what we should write into those registers.  Data is sent to the HX one pixel at a time in rows to make up one full screen of colour information.  The data cannot be sent line by line continuously as the HX must have time between lines and between frames to set up its internal electronic circuits.

15
HX setups
To use the device you don’t have to understand how the LCD and all the code works however understanding the code and the datasheet is important so that students can explore other features of the device.  Register &H0A of the HX alters the brightness and contrast settings. i. The next 7 bits 1000010 are the horizontal back porch time. It also changes the order of RGB so colours change as well.a frame (whole screen of data) and before the next frame (the light red areas).g.875). You can rotate the display by changing both TB and RL bits (but again the colours are changed and BGR doesn’t seem to affect the colours for some reason). the time after VSync goes high and before the next frame starts. H17 sets up two vital aspects of the synchronization. it would seem we can fix this by changing the BGR bit which should reverse the colours but for some reason it doesn’t work. it is 22. the range of brightness is from 7F (+126) to 00 (-128).
837
.5MHz. The next 7 bits 0100010 are the vertical back porch time.
56.  Register &H0F changes the starting line of the LCD thus allowing you to roll the display vertically. the contrast default is &H08 which is a contrast level of 1. changing &H7300 to &H3300 changes bit RL and consequently mirrors the display. the vertical and horizontal porch timings (pages 40-42 of the HX datasheet). H16 sets up the HX to know that there will be 320 pixels of horizontal data (see page 40 of the HX datasheet-although it calls this register the horizontal porch it is not).e.  The DOTCLK comes from the SSD and is the clock signal for the HX to time all LCD events. sets up some basic parameters for the connection of the LCD. This is 66 in decimal and is measured in pixel clocks. This is 34 in decimal and is measured in lines. the time after HSync goes high and before the next line starts. the range is from &H0(0) to &H1F(3. From the datasheet: the brightness default is &H40 which is a brightness level of 0.  Of the HX setups the most important seem to be registers H16 and H17 in the HX. We set it to the valus &H2122 = &B 0010 0001 0010 0010 The first 2 bits are ignored. e. again to setup the internal electronics to reset the row counter to the top line of the LCD panel ( front and back horizontal porches).  Register &H01. however note that during the visible line time (when LCD_DEN is high) every 4th clock cycle is dropped.

so for 1 count of PCLK at least three cycles of the dotclk must occur. colour. Register &H04 is 0 so MCLK = PLL = 72MHz PCLK is the pixel clock or frequency = MCLK x (registers &H15A.56.625MHz. 159. LShift (dotclk) = MCLK x (PCLK ratio+1) / 218 = 72 x 81920 / 262144 = 22.
SSD Register &H10 is an important setup: It sets the panel type (CSTN delta). 8 bit data width and serial TFT. dotclk is 4 times the freq of PCLK.

  

The SSD generates the PLL clock of 72MHz from the 4MHz crystal using a phase locked loop. The registers in the PCLK calculation are also used in the important LShift (dotclk) calculation.5MHz.16
SSD setups
There are a number of clocks to setup in the SSD to generate all the timing signals. this is necessary because each pixel is actually 3 sub pixels (R-G-B). A PLL is a fancy digital divider network that outputs a higher frequency than the one coming into it. To achieve three cycles the SSD drops one cycle in every four during the actual visible time as shown in the HSYNC and VSYNC timing diagram earlier. Note that dotclk and PCLK are not the same. from page 8 of the SSD application note is the diagram below. The output is 4MHZ x M value / N value = 4 x 180/10 = 72MHz. 158 +1)/ 220= 72 x 81920 / 1048576 = 5.
838
. The M and N values for the PLL are set up in registers &H126 and &H127 in the SSD and described on page 8 of the SSD1928A application note on pages 8 and 9. The next stage in the clock sequence is MCLK.

HPS. Reg&H17 and reg&H16 are set to &H44 = 68 pixels = 68 x 0. HT= 408 pixels (periods of PCLK).178uS before the negative edge of HSync. The diagram on page 24 of the SSD app note shows the timings relative to this point. just 180nSec (0.625MHZ=0.5uS to send. The HSync pulse is very narrow. 12uS is the back porch (blank time after HSync pulse before data) and 3.53uS. HDPW. HDPS = horizontal display period start position and is the back porch timing + HPW + HPS. In our case the registers are set to 0 so HPS=1 cycle of PCLK (0.56. HT = Horizontal total and is set by registers &H12 and &H13.17
SSD line / HSync timing
The actual timing for one line of data from the SSD to the HX as displayed on an oscilloscope is shown below. HDPS and HDP. the register is set to a value of 0 which sets up a negative pulse of 1 PCLK duration = 0.18uSec) and a full line of data takes about 72. of which 57uS is the time taken to send the 320 pixels (960 RGB sub pixels) of data.4uS is the front porch (blank time after data before HSync pulse).
All timing for lines is taken from a reference point and HPS –horizontal pulse start position (registers &H22 and &H23 + 1) is the time in pixels from this point to the negative edge of the horizontal sync pulse. the remaining time is the front porch time. the scope shows a period of 72. HDPW = horizontal display pulse width = LLine pulse width.178uS) so all line timing is relative to 0. Register &H20 also sets up HSync to be a negative pulse. HDP = horizontal display period and is set by register &H14. PCLK period is 1/5.
839
. Note that if HPS is set to more than 0 then it will impact on the other timings as well.178uS = 57uS Having set HT. This is the complete length of time to send 1 full line of colour information to the display. HDP = (&H27+1) x 8 = 320 pixels = 320 x 0.5uS.178uS so HT is set to 0.178uS which was the measured time on the oscilloscope.178 x 408 = 72.178uS = 12uS.

840
.5uS = 17. In the lower part of the diagram note the HSync pulse is continuously sent even during the times when there is no pixel data.5uS = 1308uS. From the previous measurements we know 1 line is HT (horizontal total) and is 72.01899 = 52 frames per second.400uS. VPW is vertical pulse width and is register &H24 value + 1 = 2 lines (145uS). Note that a complete frame takes 18.53 = 19mS. These registers are all set to 0. so VDP = &HEF+1 = 240 lines. This is set by registers &H1F and &H1E. &H1C. this was measured as 1174uS+143uS = 1317uS. All these values are shown on Page 25 of the SSD app note. Reg &H24 also sets VSync to be a negative pulse. VT = vertical total is the values of registers &H19 and &H18 plus 1 and is measured in lines. In the previous diagram we can see that it takes about 72. so VT is 262lines. so the LCD refresh rate is 1/0. 18 x 72. VDPS = vertical display period start position (VSync pulse width + vertical back porch). &H05.5uS to send 1 row of data. These registers are setup with the values &H01. so for 240 rows it should take 240x72. VDP = vertical display period and is set by registers &H1D. The oscilloscope picture below shows the measured values.99mS to send. &H0105 = 261.56.
All timing for frames is taken from a reference point and VPS –vertical pulse start position is set in lines (registers &H31 and &H30) and pixels (registers &H31 and &H30) and is the time from this point to the negative edge of the vertical sync pulse. These have the value &HEF. on the scope it was measured as 17379uS.53uS therefore VT = 262 x 72. These are set to &H12 = 18 lines. so all timing can be taken from the negative edge of VSync.18
SSD row / VSync/ frame timing
Having generated the HSync pulses the next step is to setup the VSync or row timings.

841
.This timing diagram has been taken from the SSD application note and modified to show the clocks
The following code is responsible for all these setups.

$nocompile '******************************************************************** ***
56. at &H60 Dim _mem_wrd2 As Word At _mem_lng + 2 Overlay 'so at &H62 Dim _mem_wrd1 As Word At _mem_lng Overlay 'so at &H60 Dim _mem_b4 As Byte At _mem_lng + 3 Overlay 'so at &H63 Dim _mem_b3 As Byte At _mem_lng + 2 Overlay 'so at &H62 Dim _mem_b2 As Byte At _mem_lng + 1 Overlay 'so at &H61 Dim _mem_b1 As Byte At _mem_lng Overlay 'so at &h60 '******************************************************************** **** 'write an address in memory to the SSD before sending data Sub Setaddress(byval Address As Long) 'Datdir = &HFF Rd = 1 Wr = 0 Rs = 0 _mem_lng = Address 'send first byte.56. We only have an 8bit databus however between the AVR and the SSD1928. however this is too slow even long (4 bytes) using a 20MHZ AVR when we 0000 0001 0000 0002 0000 0003 0000 0004 want to draw lines and fill boxes in the colour data word1 (2 bytes) word2 (2 bytes) memory so to improve the 0000 0001 0000 0002 0000 0003 0000 0004 speed of these routines it is quicker to use the BASCOM byte1 byte2 byte3 byte4 overlay function where a byte 0000 0001 0000 0002 0000 0003 0000 0004 or word can be accessed which is part of a larger Address Address +1 Address +2 Address +3 variable in memory. When using these the address is sent first using one routine and then the pixel data is sent using a second routine.23
Accessing the SSD1928 colour memory
These routines are used to access the 256K byte colour data ram. If the var is a long then the 2 words sized vars that make it up can be accessed as also can the 4 byte size vars. and make bit7 = 1 because we are accessing memory Datout = _b3 Or &B10000000 'third byte Cs = 0 Cs = 1 Datout = _mem_b2 'second byte Cs = 0 Cs = 1 Datout = _mem_b1 'first byte Cs = 0 850
.bas
'routines that allow access to the 256K ram in the SSD1928 Dim _mem_lng As Long 'e. This is the process used in the previous routines to access the control registers in the SSD. so usual practice would be to get 8 bits at a time from a 16bit (word) or 32 bit(long) variable by rotating the var 8 times for each byte.g.24
'SSD1928_Memory_Routines.

0 (top left) 0 x 640 + 0 x 2 0 1.20 clip region 150.239
Finally we have the SSD1928 and the HX8238 set up correctly.0 is the top left coordinate (note that this is different from a line or bar graph that we might draw which has the bottom left corner as 0.150 319. 239.1 1 x 640 + 1 x 2 642 0. Byval _y As Word .960 319 . Byval _color As Word) Local _address As Long Local _draw As Byte Local _temp As Long 'work out position of lcd pixel in SSD1928 ram _address = Page_mem_size * _page _temp = _line_mem_pitch Shift _temp . draw lines and boxes. 239 (bottom left) 239 x 640 + 0 x 2 152.Y) RAM address calculation RAM address Y x 640 + X x 2 0. 0 0 x 640 + 2 x 2 4 319.Y of the LCD. 0 0 x 640 + 1 x 2 2 2. 1 _temp = _temp + _x _address = _address + _temp Call Setaddress(_address) Call Writedata(_color) End Sub 852
. Left .598 '******************************************************************** ***
56.
We may already have previously defined a clip region. Left . we have the ability to put colour data into the SSD1928 RAM now we need some routines to draw some simple graphics like place a pixel. Typically with an LCD 0.0 20.0).26
'SSD1928_Simple_Graphics_Routines. and we first test to see if it is defined and then if it is whether the pixel falls within it.bas
$nocompile Sub Putpixel(byval _x As Word . Here are some sample calculations. note that we need to store 2 bytes at once so we multiply X by 2 and also need to offset Y by 640 bytes in RAM each time we come to a new line on the LCD. The first routine allows us to set a pixel in the LCD at the coordinates X.25
Drawing simple graphics
LCD 0. this is a smaller area of the screen that we might set aside as ok for drawing graphics. 1 _temp = _temp * _y Shift _x .0 1 * 640 + 0 x 2 640 1. 0 (top right) 0 x 640 + 319 x 2 638 1. The bottom right corner is 319. The next step is to locate where in the RAM the pixel data should actually be.56. LCD location (X.239 (bottom right) 239 x 640 + 239 * 2 153.

_yval . _textlen As Word . Forecolor) Else 'pixel not set so clear pixel to backcolor Call Putpixel(_xval . Fontv) _lookuppos = _lookuppos + _lookuppos_b _lookuppos = _lookuppos + 1 'lookup addr in the font table _temp = _xpos + _charwidth 'check there is room for the whole character to be displayed If _temp > 319 Then _xpos = 0 _ypos = _ypos + 16 End If 'display the character For _line = 1 To 2 'there are 2xlines(8rows) for each character _yval = _ypos _xval = _xpos For _columns = 1 To _charwidth 'get data for each character _columndat = Lookup(_lookuppos . Fontv) Incr _letter 'move to addr of letter data 'get hundreds of letter data lookup address _lookuppos_b = Lookup(_letter . _temp As Word Local _charwidth As Byte . _yval . _char As String * 1 . Fontv) 'looks up byte For _pixel = 0 To 7 'looks at each bit in byte If _columndat._pixel = 1 Then 'turn on pixel Call Putpixel(_xval . _xval As Word . Fontv) _lookuppos = _lookuppos_b * 100 Incr _letter 'move to second part of lookup addr _lookuppos_b = Lookup(_letter .32 'printable chars start at ascii 32 _letter = _letter * 3 'each letter in font table has 3 bytes 'first byte is how many pixels wide the character is _charwidth = Lookup(_letter . _columndat As Byte _textlen = Len(_text) 'this process is different to the 16x16 font 'write top line of a charater then the bottom line of the character 'before going on to the next character For _charcount = 1 To _textlen 'for each char in string _char = Mid(_text . 1) 'get one character _letter = Asc(_char) 'find its pos in the ascii table _letter = _letter .Sub Verdana(byval _text As String ) Local _yval As Word . _lookuppos As Word Local _line As Byte . _charcount As Byte . Backcolor) End If Incr _yval 'next pixel Next Incr _lookuppos 'increase column position for next loop _yval = _yval . _letter As Word Local _columns As Word . _charcount . _lookuppos_b As Byte . _pixel As Word .8 857
.

the second look up is the actual font data for displaying. 9 . 5 . The first character is 7 pixels wide and at location 284 in the table The second character is 2 pixels wide and at position 298 in the table The third character is 5 pixels wide and at position 302 in the table. etc Each ine after the first line is an actual line of font data The third line in the font table is the exclamation mark it contains 16 vertical bits of data and takes up only two pixels width of the LCD. 27 .8 Next _ypos = _ypos + 8 'now writing the lower row If _line = 1 Then _xval = _xpos 'resetting the x position Next Incr _xval _xpos = _xval _ypos = _ypos . Here is some of the first line of the font table . 52 ………. 02 . All the upper line (8 bits) of data are stored in the table first then the lower line The exclamation mark is stored as . 12 . _yval . 2 . 2 . The first lookup finds the number of bytes for each character that need to be retrieved from the table and their starting position in the table.Incr _xval For _pixel = 0 To 7 backcolor
'insert 1 column betwen characters 'fill space column with
Call Putpixel(_xval . Backcolor) Incr _yval Next _yval = _yval . 254 . 34 . 3 .db 7 .2pix
The first column of the first line is 254 = &B11111110 The second column repeats the first The first column of the second line is 27 = &B00011011 The second column repeats the first
858
. 27 . ! .db 254 . 18 . 84 .16 Next End Sub 'set x for next character 'back to top
Because each character in a true type font is not a fixed width as in the 8x8 and 16x16 font tables the lookup scheme for each character requires us to make 2 lookups. 2 . 11 . 3 . 3 . 98 . 3 .

57 Traffic Light help and solution
Now here is some assistance for the traffic light exercise from early in the book
859
.

4
860
.Wiring stage 4: the ‘C’ set of lights are wired up
For the last set of lights ports A.7 are used as well as portB.6 and A.

58. High level languages are written using text editors such as Programmers Notepad or within an IDE such as Eclipse or Visual Studio or… These languages are typically easy for us to understand. The AVR machine code to add the numbers in 2 memory registers is 0001 1100 1010 0111. Haskell.
863
. Lisp. HEX uses numbers 0 to 9 and the letters from a to f.hex file (ignore the colon and the first 8 digits in each line.58 Computer programming – low level detail
We refer to programming languages as either HIGH LEVEL languages or LOW LEVEL. for example: add r12 .1
Low level languages:
Machine code for all microcontrollers and microprocessors (all computers) are groups of binary digits (bits) arranged in bytes (8 bits) or words of 16. r7 instead of 1C A7 Assembler is much easier to understand than machine code and is in very common use for programming microcontrollers. You can also see it when you go to manual programming mode its all the hexadecimal in the program window. It looks like this 1CA7 which is easier to read than is 0001 1100 1010 0111. abbreviations called mnemonics are used and we call it assembler or assembly language or. C++. C# and many more. 32 or 64 bits. However microcontrollers do not understand these words they only understand binary numbers which are called Machine Code. Prolog. Understanding a program in machine code is not at all easy. Commands written in high level languages must be compiled into these binary codes. A computer program is ultimately a file with a . but no easier to understand! Program code for micros is never written today directly in machine code. however It does take more effort to understand the microcontroller internals when programming in assembler. assembly code which is more readable. Java. It is easier on the eyes than machine code but still very difficult to read.hex extension containing machine code. C. High Level Languages include Basic. To make machine code a little easier to understand we can abbreviate every 4 bits into hexadecimal numbers. the rest is the actual program).
You can see the machine code in BASCOM by going to the directory where your programs are stored and opening the .

There are memory.58. calculation. control and I/O components.
864
.2
AVR Internals – how the microcontroller works
The AVR microcontroller is a complex integrated circuit. with many features as shown in this block diagram of the AVR’s internal architecture.

Note that with 8 bits (1 byte) only numbers up to 255 may be transmitted at once. Memory
There are three separate memory areas within the AVR. At any one time only one section of the 8535 is able to transmit on the bus.3
1. Each device has its own address on the bus and is told when it can receive and when it can transmit data.
58. larger numbers need to be transferred in several sequential moves. these are the Flash. the Data Memory and the EEPROM. When 865
.
In the 8535 the Flash or program memory is 4k of words (8k bytes) of program. The 8bit data bus
This is actually 8 parallel wires that interconnect the different parts within the IC. Flash Memory is like a row of lockers or pigeon holes.4
2.58. The AVR stores program instructions as 16 bit words.

it will then add the 2 numbers and the result will go into one of the registers. The Static RAM is a volatile store for variables within the program.5
3. ALU The arithmetic logic unit carries out mathematical operations on the binary data in the registers and memory. it carries out that instruction then gets the next one.6
A simple program to demonstrate the AVR in operation
Lets take a simple program in Bascom then analyse the equivalent machine code program and then what happens within the microcontroller itself. then counts binary in a never ending loop on the LEDs on portc. shift. NOR the data.
58. this keeps track of which instruction in flash the microcontroller is carrying out. multiply. Special Function registers
There are several special high speed memory registers within the microcontroller.g. The 32 general purpose registers are used by your programs as temporary storage for data while the microcontroller is working on it (in some micros these are called accumulators). Equivalent machine code to the Bascom code above is: EF0F (1110 1111 0000 1111) 866
. it can add. when you change something in a register the hardware attached to it changes. If you had a line on your code to add 2 numbers e. The micro will get the contents of ram location X and store it in a register. it is shorter to use hexadecimal notation. it then writes the answer from that register into memory location Z.
58. * Instruction register: As a program instruction is called from program memory it is held here and decoded. This program below configures all of portc pins as outputs. However we don't normally view the numbers as binary. it is here that you access the ports. z=x+y. did the addition overflow? 4. OR. The 64 I/O registers are memeory locations with special hardware abilities. The EEPROM is a non-volatile store for variables within the program. * Status Register: holds information relating to the outcome of processing within the microcontroller. test. which is a long line of binary numbers. subtract. AND.the micro starts it goes to the first one to fetch an instruction.g. Config Portc = Output 'all of portc pins as outputs Dim Temp As Byte 'set memory aside Temp = 0 'set its initial value to 0 Do Incr Temp 'increment memory Portc = Temp 'write the memory to port c Loop 'loop forever End This is compiled into machine code. it will get the contents of ram location Y and puts it into a second register. After completing an instruction it will be incremented to point at the next location. e. * Program counter: 16 bits wide. ADC etc and their control them. compare.

R16 INC R16 RJMP -0x0003 set all bits in register 16 store register 16 at address 14 load immediate register 16 with 0 store register 16 at address 15 increment register 16 jump back 3 steps in the program
(portc = output) (temp=0) (port C = temp) (incr temp) (back to BB05)
1. 3. CF FD is decoded and the program counter has 3 subtracted from it (It is 0x06 at the moment so it becomes 0x03).R16 LDI R16. This operation requires the use of the ALU as a mathematical calculation is involved. The instruction is decoded and R16 contents are copied to address 0x14 (0x means hex). The instruction is decoded and the contents of register 16 (0) are copied to address 0x15 this is the i/o register address for portc itself – so all portc goes low.BB04 E000 BB05 9503 CFFD These program commands are programmed into the microcontroller starting from the first address of the FLASH (program memory). The next cycle of the clock occurs and BB 05 is moved into the instruction register from the flash. 6. The next cycle of the clock occurs and E0 00 is moved into the instruction register from the flash. The program counter is then incremented by one to 0x01. The instruction is decoded and Register 16 is loaded with all 0's. The next cycle of the clock occurs and CF FD is moved into the instruction register from the flash. The first instruction is EF 0F and it is transferred into the instruction register. The sequence jumps back to number three causing a never ending loop. The equivalent assembly language to the above machine code EF 0F BB 04 E0 00 BB 05 95 03 CF FD SER R16 OUT 0x14.0x00 OUT 0x15. 4. When the micro is powered up (or reset) it starts executing instructions from that first memory location. The program counter is incremented by one (to 0x05). The program counter is incremented by one (to 0x04). The program counter is incremented by one to 0x02. The instruction is decoded and the contents of register 16 are incremented by 1 (to 01). The program counter is incremented by one (to 0x06). 5. so now all pins of portc are outputs.
867
. the first location in the flash (program memory). The next cycle of the clock occurs and BB 04 is moved from the flash into the instruction register. this is the i/o register that controls the direction of port c. The microcontroller powers up and the program counter is loaded with address &H000. The program counter is incremented by one (to 0x03). The instruction is decoded and register 16 is set to all ones. 2. The next cycle of the clock occurs and 95 03 is moved into the instruction register from the flash.

fischl.59 USB programmer .de/usbasp/ Using this PCB design
And layouts
870
.USBASP
More recently we have been building the USBASP programmer from http://www.

0 of Bascom allows you to select USBASP as a programmer.4. Its actually not worth making one of these as there are some real cheap and good USBASP programmers on EBAY!!.I am currently using version 2. so make sure you are using the latest version of Bascom.
Installing drivers on Windows 7 use to be a real pain. however the latest version libusb is great.0. this has only worked in the later versions.
871
.

From Bascom-AVR menu select Options – Compiler – Output tab and make sure hex file is selected From Bascom-AVR menu select Options – Programmer and setit up as per the following
When you have compiled your program press F4 and it should work fine.adafruit. 2.ladyada. The default option (not using –u) reads the fusebits and rewrites them again.net/make/usbtinyisp/download. 3.com/ or it can be built from scratch from circuits at http://www. or within the workshop we have eagle files for the programmer and we can program the chip. Install the latest version of winavr and the programming software avrdude will be installed with it. 1. Notes: the –u option has been specified.net/make/usbtinyisp/. When you plug in the programmer it will ask for drivers. this tells AVRDUD