# EC 4 Evil Genius: Project 1 – Lesson 12

I finally had some spare cycles this past weekend. This allowed for me to work on 1 of 2 final projects for section one of Electronic Circuits for the Evil Genius. Lesson 12 provides the reader with an opportunity to leverage the knowledge and skills gained thus far. Once the circuit for this project is constructed, it creates an automatic night light that dims in the light and brightens in the dark.

The components used in the circuit include various resistors, a diode, 100k pot, LDR, 5mm LEDs, and a NPN transistor. When attached to a power supply (9v) and with the pot set to around 50k ohms, the LEDs will remain dark/dim in lighted areas and transition to a full glow in a darkened area.

Depending on how much resistance is provided by the pot will determine how much voltage is present in the circuit. Such as, if the pot is set to a low resistance, more voltage is registered, allowing the NPN transistor to be easily activated. Circuit analysis reveals that the LDR is incapable of dumping all of the voltage sent its way.

Although simple in nature, this was an interesting project overall. The knowledge exercised is from the previous sections that dealt with transistor and LDR coverage. This information comes in handy if you attempt to step outside of the suggested components.

For example, the circuit calls for two 5mm LEDs. However, I wanted to use blue LEDs of which require almost double the voltage of red LEDs. Therefore, with the working knowledge of transistors and OHMs Law, I was able to easily determine what type of resistance was necessary to power the two blue LEDs in my circuit.

This project also required some soldering of components which at least for me is the fun part. The kit associated with the book actually provides you with a ready-to-go PCB. That said, obviously soldering anything worth while is fun; however, experiencing a working circuit when finished is definitely gratifying too.

Lastly, I would recommend keeping the bread boarded circuit as a reference. This way, if you get stuck while putting together the PCB, or if it doesn’t work after the soldering is complete, you have a working physical representation as a reference.

Next up is project #2; post to follow.

# EC 4 Evil Genius: Lessons 9, 10, & 11

Electronics Circuits for the Evil Genius lessons #9 and #10 cover the operation of both the NPN and PNP transistors. Specifically speaking the NPN-2N3904 and the PNP-2N3906. The lessons demonstrate how each transistor type reacts when voltage is applied to the base of the transistor.

The demonstration circuit for lesson #9 reveals how the voltage held in a capacitor is used to power the transistor and subsequently allow the LED to turn on.

Moreover, the base of the transistor requires less power than the load required for the LED; through observation you determine that the capacitor drains the stored voltage very slowly. Further circuit analysis indicates that the capacitor in the circuit is the sole power source for the transistor, and it is the transistor that ultimately provides power to the LED.

Pressing the pushbutton plunger allows the voltage and current to flow through the circuit from the main source. However, when the pushbutton is open, the current and voltage is cutoff resulting in no voltage being sent to the base of the transistor.

I decided to have a little fun and developed a simulated SPICE circuit prior to breadboarding. The video here shows the simulation in progress.

The circuit for lesson #10 demonstrates how the NPN and PNP transistors differ in operation. Once the capacitor is fully charged, voltage is applied to the base of the transistor causing an interruption in current flow. When applying the battery to the circuit the first thing you notice is that the LED is immediately handling a voltage load – the result of a lack of voltage pressure at the base of the transistor.

The valve of the transistor is open, allowing current to flow from the emitter onward to the collector. Once the plunger of the pushbutton is pressed, voltage is instantly sent to the base of the transistor, closing its internal valve. This blocks the flow of current and causes the capacitor to charge.

However, once the pushbutton is released, the voltage from the capacitor applies pressure on the base of the transistor, closing the valve and restricting current flow from the emitter to the collector.

Next up is lesson #11 which demonstrates the capabilities of the phototransistor, using both the clear and darkened glass versions of the component.

This lesson is quite interesting as you develop a combination circuit in which have there is an input, processor, and output component.The objective here is to observe how each input component affects the processing component (light spectrum dependent). This circuit however requires that the experiment be conducted away from sunlight. You will also need to print out a disc provided by the text to properly complete the experiment.

The overall purpose is to see how fast or slow the processing component is affected when the (input) light source is blocked. The inputs used are a yellow LED and the clear IR phototransistor. The processors use are an LDR and the dark IR phototransistor.

Up next is the first of two main projects for this section. Putting it all together.

Looking forward to it.

# Review: Electronic Circuits for the Evil Genius

Electronic Circuits for the Evil Genius has been on my list to review for a while. So I decided to finally crack it open and see what it was all about. As with most books of the this type, project based. I typically will look for any available ready-made kits, and luckily for me ABRA Electronics already had one made. The bonus of these kits is simply that of saving the reader the hassle of tracking down components needed for the circuits in the book.

From what I can tell thus far, the book is geared towards the beginning “Evil Genius”, someone with basically no exposure to electronics whatsoever. However that being said, this is not your typical beginners text. The approach of the author appears to be that of introducing new components via a series of simple circuits as a foundation for the section project(s) at the end of each section. Basically you develop just enough knowledge to be dangerous and have somewhat of an idea of how the main project works.

Of course, the first circuit, or the hello world of electronics is the typical flasher. Of note, I like the early introduction of the diode here. Something not typically seen. It never hurts to learn the value of the diode early on. The beginner will be presented with data involving how to read a DMM, measure voltage at various points, learning how to read resistor values, how to identify electronic components, and much more. My only suggestion would be that of having a supplemental electronics text-book near by for additional informational purposes.

The next circuit covers the use of a potentiometer and provides additional exercises and measurements to be completed by the reader to further develop your knowledge.

The LDR is introduced in the next circuit. Again, the reader is encouraged to experiment, and take additional measurements for continued knowledge development.

What should be noted thus far, are the components being presented. Although the LDR falls under the category of resistor, it is not your typical resister and is seldom seen (in my experience) so early in a beginners electronics book for one to bread board. That being said, this speaks to the approach of the text. The author is introducing components that will be used in targeted projects, but in a manner suitable for a beginner to grasp. Different….but cool and makes sense.

The last circuit I completed, not the last circuit for the section mind you, introduces push buttons and capacitors. Notably, the author does a good job at reaching his target audience through the use of everyday items in his analogies to describe the function of electronic components. A definitely plus for the beginner who may find it difficult to grasp what is occurring at subatomic level as a result of the high-level presentation of the material (not a necessarily a bad thing).

Overall, my first impression of the book is that it is targeted towards the beginner. That being said, a true beginner may struggle with the text as there is no hand holding here per se. If your circuit does not work, the use of a supplemental text may prove to be beneficial in a pinch. On the other hand, this book is very much hands on and that is one of the best ways to learn and stay engaged. Time will tell if the pace remains at a beginners level or if it teeters between beginner and that of advanced beginner. So far, I can’t see the subject matter drifting towards an intermediate level but I could be wrong.

As I continue through the book I will blog when I can.

It’s definitely worth a look based on the projects inside. The authors approach to the subject matter is easily understandable and pleasant.

Side note: The kit comes with preprinted circuit boards for the main projects which is quite nice. Therefore, it should be noted that some soldering skills are required.

# How to estimate a delay cycle for the HCS12

Creating a delay and estimating how much time the delay takes is a straightforward process. I’ll show you how to create a delay routine in assembly, in addition to estimating how much time the routine actually takes.  In order to estimate the delay cycle, we will need to determine the amount of time spent in clock cycles for each instruction inside the delay routine.

By obtaining a datasheet for the HCS12, we can find out the amount of clock cycles for each HCS12 instruction.  Look for the “access detail” column, it will display characters that may look like rPf, P, rPo, etc.  Regardless of character type, what we are interested in is the amount of characters in the column for that instruction. The amount of characters are equal to the amount of clock cycles.

Calculating CPU Instruction Time

The HCS12 has an 8 MHz crystal. However, only half of the crystal’s oscillator frequency is used for CPU instruction time. Normally, time is calculated as T = 1/F. In the case of the HCS12, we will need to halve the frequency provide by the crystal before calculating the actual time:
8 MHz / 2 = 4 MHz;  T = 1 / 4 MHz = 0.25 us

Now we can estimate the time delay with this formula
(COUNTER_VALUE x NUM_OF_INSTRUCTION_CYCLES) x CPU_CYCLE_TIME

But first, let’s take a look at the example code below.

```COUNTER_LOC EQU #\$1200
--
--
DELAY LDAA #300
STAA COUNTER_LOC
LOOP  NOP
NOP
DEC COUNTER_LOC
BNE LOOP
RTS
```

Breaking Down the Instruction Cycles

The actual loop inside the DELAY subroutine has a total of four instructions. The NOP instruction requires only one instruction cycle. The DEC instruction takes four instruction cycles. BNE requires three instruction cycles if looping back and only one instruction cycle if falling through the loop.

To determine the amount of delay time for the function above, we simply plug the values into our formula:
(COUNTER_VALUE x NUM_OF_INSTRUCTION_CYCLES) x CPU_CYCLE_TIME
(300 x 9) x 0.25E-6 = 0.000675 us seconds

# AVRISP MKII Tutorial – The setup

So, you finally got a hold of an AVRISP MKII and have no idea what to do next .  Well lucky for you the setup and overall configuration is a lot easier than you might think. This mini tutorial will demonstrate how to flash an AVR chip via the Atmel Studio 6 IDE.  If you do not have Atmel Studio installed you can download the IDE from here.

Of note, Elliot Williams just released an excellent book titled Make: AVR Programming. I highly recommend his text if you are serious about AVR programing; especially if you are new to the embedded world. The book provides excellent coverage on setting up a robust tool-chain. In addition to setting up a development environment for several platforms, i.e. Windows, Linux, and MAC.

Build of Materials:

Hardware:
2 – 200 Ohm Resistors
2 – LEDs
1 – 0.1 uF Capacitor
1 – AVR Chip: ATMEGA168PA
– AVRISP MKII
– Jumper Wires
– 5v Power Supply

Software:
– Amtel Studio 6.2

LED Flasher Circuit:

The circuit used in this tutorial is a LED Flasher.  Note that the LED connected to pin 15 is affected by the code flashed to the chip. The LED connected to VCC is simply used as an indicator of the 5v running across the rails of the board; unaffected by flashing the chip.  The Mini Red 0.36 ” LED Digital Volt Voltage Panel Meter Voltmeter attached to my circuit is optional and a personal preference.

If you do not have a 6 pin connector for your programmer no worries, just plug jumper wires into the holes.  I recommend using  Premium 6″ M/M jumper wire .  Most people [me] have a healthy supply of the cheap jumpers, the ones were the metal connectors fall out more times than you would like. After switching to a more sturdier jumper wire, there is something to be said about the expectations of quality. Trust me, spend the coin on a pack of premium jumpers and live a happier life.

Here are a few notes on the behavior of the AVRISP MKII, prior to flashing the chip for the first time. When the programmer is connected to the USB port on your computer. A green LED will flash near the USB connection inside the device. However, if you attach the programmer to the bread board [VCC & GND only] and supply 5v of power. You may see a flashing orange indicator light. If the programmer is fully connected to the circuit, the USB port, and VCC = 0v.  The indicator light should be red. If the programmer is fully connected to the circuit, the USB port, and VCC = 5v. The indicator light should be green. Green is good.

Complete Schematic:

Constructed Circuit:

Now that you have the circuit constructed lets get ready to flash the chip. Launch Atmel Studio and follow the steps below:

STEP 1: Create a new GCC C Executable Project

STEP 2: Select your device (I’m using the Atmega168pa)

STEP 3. Open the file in the Solution Explorer window and overwrite it’s contents with the source code below

```// ------- Preamble -------- //
#include <avr/io.h>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* Defines pins, ports, etc */
#include <util/delay.h>&nbsp;&nbsp;&nbsp; /* Functions to waste time */

int main(void) {

// -------- Inits --------- //
DDRB |= (1 << PB0);&nbsp; /* Data Direction Register B:
writing a one to the bit
enables output. */

// ------ Event loop ------ //
while (1) {

PORTB = 0b00000001; /* Turn on first LED bit/pin in PORTB */
_delay_ms(500);&nbsp;&nbsp;  /* wait */

PORTB = 0b00000000;&nbsp;&nbsp; /* Turn off all B pins, including LED */
_delay_ms(500);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* wait */

}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* End event loop */
return (0);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /* This line is never reached */
}
```

STEP 4: Compile the Source Code

*Results of a successful build

STEP 5: Select your target device for programming (Click Device Programming)

STEP 6: Select the AVRISP MKII in the “Tool” drop down and your chip in the “Device” drop down then hit the “Apply” button

STEP 7: Leave the the ISP Clock at the default setting of 125 kHZ

STEP 8: *Make sure your power supply is turned on with power going to the board. Click the “Read” buttons to validate voltage and the device signature

STEP 10: *If you run into this message it means we need to select the MKII as our target debugger. Proceed to STEP 11

STEP 11: Select the AVRISP MKII  as the debugger

STEP 12: *Attempt to flash the chip again. From the Debug Menu select “Start Without Debugging” and Flash the Chip

End Result:

# MAKE ELECTRONICS – CHP 2 EXERCISE 10

Exercise ten, “Transistor Switching”.  This exercise introduces a very important component which has characteristics similar to the relay.  Whereas both components can switch the flow of electrical current. That said, the documentation explains the ins and outs of transistors, in that they are naturally off until turned on; considered a limitation.  Relays on the other hand offer more switching options, i.e., can be normally open, normally closed, or utilize a double-throw switch. When it comes to determining which component to choose for your needs it will always come down to the requirements for your application.

The construction of the discrete components for this exercise requires that you pay close attention to which way the transistor is facing.

Through observation you will note that the LED is off (not lit).  Voltage travels through R1 and arrives at the collector pin of the transistor.  There is a small amount of voltage leakage but not enough to light the LED. When the push-button is depressed voltage also travels through R2 and reaches the base of the transistor.  The voltage that arrives at the base causes the transistor to open its solid state switch – current flows down to the emitter of the transistor as a result.  R3 is in place to prevent the LED from receiving too much voltage and burning out.

Overall, this was another fun chapter that covers the necessary basics of transistors (NPN and PNP). In addition to topics related to current.  The author continues to do a great job making the information provided accessible for those willing to attempt understanding.

Also, I was able to simulate this circuit demonstrating the LED lighting up when engaging the push-button. In the video, the “Green Arrows” represent the LED receiving voltage.

Required Components:
-LED
-Resistors
-Push-button SPST
-Transistor 2n2222

# MAKE: ELECTRONICS – CHP 2 EXERCISE 9

Exercise nine, “Time and Capacitors”.  This exercise demonstrates how one can measure time by simply placing a capacitor in series with a resistor.  The importance of this concept is related to the “time constant”.  That said, by placing a capacitor and resistor in series, the amount of time it takes for the capacitor to charge will be much longer than if both components were placed in parallel.

To fully implement this exercise you will need a multimeter. I would suggest getting some alligator leads instead of using the traditional probes as it makes for easier measuring.

Upon observation, you should notice that the 100K resistor causes the capacitor to charge much slower compared to the 100 ohm resistor when added to the circuit.  In going back to the “time constant” or TC as it’s known; TC = R x C.  In this formula TC is the time constant and a Capacitor C is being charged through resistor of R ohms. The author does an excellent job of walking the reader through the time constant theory in this chapter.

As for the construction of the circuit, it’s straight forward and is simple to bread board. The main take-away from this exercise is obviously the concept of time.  Apply your focus to the theory and circuit observation via the multimeter results.

Lastly, I also simulated the circuit. See attached video below.  When applicable I will attempt to simulate the circuits to demonstrate how they perform in simulation prior to rendering them via hardware.

Required Components:
-Multimeter
-Push-button SPST
-Resistors and Capacitors

# MAKE: ELECTRONICS – CHP 2 EXERCISE 8

Exercise eight, “A Relay Oscillator”. This exercise is a slightly revised version of exercise seven in which the direct connection was between the push button and the coil.  In exercise eight, the voltage arrives at the coil as a result of traveling through the contacts of the relay.  Therefore, when the push button is depressed, the contacts of the relay feed the voltage to both the coil and the leftmost LED.

The idea here is that when the coil is energized, it opens up the contacts of the relay.  This causes an interruption of power being sent to the coil allowing the relay to relax the state of the contacts – closing them.  The cycle repeats by sending another pulse of voltage to the coil that in turns opens the relay contacts again.

A capacitor is introduced to provide assistance in slowing down the oscillation process and assist in the visual observation of the cycling process – LED flicker.

This chapter provided some decent background information on capacitor basics  in addition to learning how to breadboard a circuit. Speaking of which, initially the exercise called for building the circuit without a breadboard. A beginner will definitely begin to appreciate the idea of the bread board after attempting to build this circuit without one.

Required Components:

– AC Adapter or Power Supply, wire, wire cutters and strippers
– DPDT relay
– LEDs
– Push button, SPST
– Alligator Clips
– Resistors 680 ohm
– Capacitor (electrolytic) 1000uf

# Make: Electronics – Chp 2 Exercise 7

Exercise seven “Relay-Driven LEDs”.  This experiment introduces the Relay component and is used to drive two LEDs.  The heart of a relay is basically an iron core wrapped around wire.  The electricity running through the coiled wire will produce a magnetic reaction,  triggering an internal lever that closes two contacts.  During this process the relay is said to be energized, allowing a low voltage signal or low current to travel through the circuit – lighting the LEDs.

The author is very specific about the type of relay required for the experiment.  When shopping for your materials pay special attention to the model number in addition to coil voltage, set voltage, operating current, and switching capacity.  All of which is explained nicely in the text.

Also be prepared to pull out the utility knife for the deconstruction of one of your relays.  Although I am not a fan of ruining perfectly functioning components. I can appreciate the idea behind demystifying their inner workings for the sake of education.

The actual experiment itself, at least for me was sort of tedious when it came to construction.  The major difficulty was attempting to fasten the hook up wire to the spikey legs of the relay.  My advice: use a pair of needle nose pliers and bend the ends of the hook up wire into a small loop prior to placing it on the relay legs.  Once the wires are in place, use the needle nose pliers to close the loop.

Lastly, this is the first experiment that required more than 6 volts; the requirement is 12 volts.  However, the author has a great section on hacking an AC Adapter by cutting off the ends and using the wires to drive the circuit.  For some, this may seem a little hairy. No worries though, the instructions are clear, concise,  and there are listed precautions to ensure that using the AC Adapter is safe.

Overall, this was another fun experiment with excellent background information to drive the material home.  I even enjoyed the tedious aspect of putting the circuit together. Sometimes it’s the little  things [challenges].

Required Components:
AC Adapter, wire cutters and strippers
DPDT Relay (2)
LEDs (2)
680 ohm Resistor
Push button SPST
Hook up wire (22 gauge)
Alligator Clips
Utility Knife

# Make: Electronics – Chp 2 Exercise 6

Exercise six “Very Simple Switching”.  Looking back to exercise four we covered how to turn electricity into a functional property and lit an LED.  This exercise follows up that concept and is the beginning stages of controlling electrical power via switches.

Putting together the discrete components is quite simple but can feel a little tedious without using a bread board.  I could imagine that someone who has not done this before may find themselves frustrated; wires popping of the switch connections. Patience grasshopper …. patience.  Also, the beginner will more than likely get their first crack at using wire strippers. My advice. Invest in a high quality pair of wire strippers.

The main emphasis of this exercise is to develop a understanding of  what makes a switch an SPDT or DPST, etc.  More or less understanding the on and off states of the switch types.

Overall, another interesting and high quality exercise. The author continues to do an excellent job providing just the right amount of technical information relative to each exercise.

Required Components:
AA Batteries (4)
Four Battery Carrier
LED
SPDT Toggle Switches
220 Ohm Resistor
Wires
Alligator Clips
Wire Cutters

*Note regarding Exercise 5 “Let’s Make a Battery”*.  The exercise requires the reader to attempt the creation of a battery using lemons or lemon juice. Been there, done that, failed each time.  I have never been able to get an LED to light via a lemon. However, the background information found in that section is of high quality and definitely deserves a read through, especially if you are beginner e.g., the nature of electricity, positive and negative charges, etc.