## Sunday, May 29, 2011

### DAC using the FVR as voltage source

Continuing with the DAC tests over the last two days, I wanted to see the DAC using the internal fixed voltage reference instead of VDD. This would allow VDD to vary (with the condition that VDD > FVR output) without affecting the DAC operation. So I loaded the PIC18F1822 with the firmware below. Note that the internal oscillator frequency has been set to 31kHz to provide a delay between increment/decrement of DACCON1 value.

void InitRegisters()
{
PORTA = 0;
ANSELA = 0;
TRISA = 0;
OSCCON = 0b1000;            // run internal oscillator at 31kHz LF
FVRCON = 0b10001000;        // enable fixed voltage reference for DAC, set gain = 2 to give a ref volt of 2.048V
}

void main()
{
InitRegisters();
DACCON0 = 0b10101000;       // DAC enabled, DAC output available on DACOUT pin, FVR as positive voltage source
DACCON1 = 0x1F;
while(1)
{
while (DACCON1-- >1);     // go from DACCON1 = 31 to DACCON1 = 0
while (DACCON1++ < 30);   // go from DACCON1 = 1 to DACCON1 = 31
}
}


And here are the oscilloscope readings:

### Checking the DAC unit on another PIC

Using the same hardware setup as in the PIC12F1822 DAC test I dropped a PIC16F1827 into the breadboard and checked how its DAC would perform, given that the 12F1822 flunked horribly. The data below says it all. The 1827's DAC performed as it should

 DACCON1 VOUT measured (volts) VOUT computed (volts) 0x00 0.008 0 0x01 0.113 0.106 0x02 0.222 0.213 0x04 0.435 0.427 0x08 0.855 0.855 0x10 1.704 1.710 0x1F 3.303 3.313

The firmware was as follows:

void InitRegisters() {   PORTA = 0;   ANSELA = 0;   TRISA = 0; } void main() {   InitRegisters();   DACCON0 = 0b10100000;  // DAC enabled, DAC output available on DACOUT pin, Vdd as positive voltage source, Vss as negative voltage source   DACCON1 = 0x10;        // change value of DACCON1 as required   while(1); } 

After going over the firmware I used for the 1822 test I realized that I had inadvertently turned on the global weak pull-up--I cleared the WPUEN bit in OPTION_REG. Since all the bits of the individual weak pull-up register WPUA are high upon reset, the pull ups are then all enabled. This was the cause of the erroneous DAC output. So while pull ups may be enabled for other pins, if and when required, pull-up for RA0/DACOUT pin must be disabled if that pin will be used as DAC output.

After I burned the above firmware in the 1822, the DAC output instantly became as it ought to be, as the table below shows.

 DACCON1 VOUT measured (volts) VOUT computed (volts) 0x00 0.028 0 0x01 0.134 0.106 0x02 0.239 0.213 0x04 0.451 0.427 0x08 0.874 0.855 0x10 1.717 1.710 0x1F 3.292 3.313

## Saturday, May 28, 2011

### Test driving the PIC12F1822's DAC

Trying out the digital to analog converter (DAC) of the PIC12F1822. The most current datasheet (DS41413B) has bugs. The DAC block diagram (Fig.17-1) and description in Section 17 both indicate the existence of a negative voltage source (VSOURCE-) which is selectable via the DACNSS bit. But neither of the two DAC registers--DACCON0 and DACCON1--has the DACNSS bit.

On the other hand, in the datasheet (DS41441B) for the PIC12F1840 the DAC block diagram (Fig. 17-1) does not show DACNSS; however, register DACCON0 contains the DACNSS bit.

So does the DACNSS bit exist in the 1822 or not?

A search in the Microchip forum reveals that the DACNSS bit isn't available on the 12F1822 and that the negative voltage source defaults to VSS.

Okay, so the 1822 is referenced to ground. According to the datasheet, output voltage of the DAC is determined via the following equation:

VOUT = (VSOURCE+  -  VSOURCE-)(DACCON1 / 25) + VSOURCE-

This means that if DACCON1 = 0, then VOUT = VSOURCE- = VSS.

But that isn't what I get while measuring the output at the DACOUT pin (enabled by setting the DACOE bit in DACCON0). Using the PICkit2 (with the ICSPDAT disconnected since that pin is also DACOUT) to power the 1822 and setting its VDD = 3.3 and with DACCON1 = 0 and DACPSS configured to use VDD, the Fluke 8842A DMM and Rigol DS1102E oscilloscope both measured DACOUT voltage at 332 to 333mV. It should read zero. 333mV is what we'd expect if DACCON1 is loaded with 0x03. Incidentally using the Fluke 8842A VDD was measured to be 3.42V.

With DACCON1 = 0x1F (decimal 31), VOUT = 3.32V. This is as expected as per the equation above. A summary of DACCON values tested are shown below.

 DACCON1 VOUT measured (volts) VOUT computed (volts) 0x00 0.333 0 0x01 0.760 0.106 0x02 1.074 0.213 0x03 1.328 0.320 0x04 1.533 0.427 0x08 2.093 0.855 0x10 2.640 1.710 0x1F 3.320 3.313

Clearly, computed and measured values are planets apart.

Just to make sure the high impedance DACOUT wasn't being loaded, an op amp configured as a voltage follower (unity gain buffer) was used to buffer the DAC output, but the values obtained were the same as above.

Setting or clearing ANSELA has no effect on DACOUT output either.

I also tested the DAC "low power voltage state" by clearing DACEN, clearing DACLPS, and clearing DACCON1. Output at DACOUT was 313mV. It should be zero.

With DACCON0 cleared--i.e., DAC is completely disabled--and RA0/DACOUT pin configured as digital output and PORTA cleared, voltage reading was 2.5mV. So RA0 works as expected and voltage on this pin can in fact go down to practically zero.

So is there something very wrong with the DAC unit or have i missed some SFR setting?

## Friday, May 20, 2011

### Push-pull output using complementary bipolar transistors

Over the past several years I've been using a transistor push-pull configuration as in Circuit B, with the NPN acting as a current sink for one of the loads and the PNP as current source for the other load. This to me is the "normative" way of using NPN and PNPs. And it's worked fine for me.

The transistors are driven to saturation and are operated such that when one is on the other is off. In Circuit B for instance net NR12 is either at VDD or at ground. When at VDD Q2 is switched on and Q1 off. With the NPN providing a path to ground LED1 then turns on. On the other hand because Q2 VCE is just a couple of hundred mV, current is shunted away from LED2 and thus cannot turn on.

When NR12 is pulled to ground, Q1 is turned on and Q2 off. As such, current is supplied to LED2 which then turns on. Q1 VCE is just several hundred mV, acting almost like a short circuit, and hence diverts current away from LED1 which then switches off.

There is also a push-pull configuration whereby the emitters, instead of the collectors, are tied together and become the output. This is illustrated in Circuit A. This configuration is  known as a Class B amplifier. The advantage of this setup is that only one base resistor is required. Two for each of the bases are needed for Circuit B. Using just one results in both transistors turning on and creating a short circuit path. Trust me. I've tried it and the transistors got searing hot.

To find out if the Class B kind would be a suitable alternative I breadboarded Circuits A and B and took various measurements which I've compiled in this Google spreadsheet.

The most important values of note are the comparative VCE figures. Even with very low base current limiting resistors (100 ohms) the VCE would not drop below ~0.7V for both the NPN and PNP. Circuit B was very different with VCE for the NPN ten times less at 70mV. Although the datasheet lists the S9015 PNP as having a current gain (hFE) of >100 I had to increase the base current by using a 1K resistor to bring down its VCE to a level comparable to the S9014 NPN.

My verdict? I'll stick to the configuration I've used all these years. Class B amplifiers are good for circuits that need the transistors working in the linear region. But for digital circuits the high VCE makes the transistors  inefficient switches which ideally should have zero voltage drop across the contacts (collector and emitter in this case) when they're closed.

## Wednesday, May 18, 2011

### In electronics we trust

Having measured the LDR resistance from dusk to night I also wanted to find out the dawn values. I managed to actually hear the alarm on my cell phone and the alarm clock and got up quarter to five today. It was still dark. Turned on the Fluke 8842A which was already hooked up to the breadboarded LDR circuit outdoors.

I was gazing at the DMM. I was puzzled. Instead of giving me a stable reading, the numbers on the readout kept creeping upwards. I thought it would settle after a few seconds--after whatever capacitance had fully charged/discharged--but it didn't.The reading started at around 350mV and just kept climbing by a couple of millivolts per second. What the ...

After some 10 minutes--when the sky visibly began to light up--only then did I realize that photons from the sun had already began to trickle in even before I woke up. That would explain the gradual increase in voltage. The LDR circuit was actually doing its job and doing it well. It was picking up the minute traces of sunlight at that fuzzy divide between night and dawn.

Lesson: Trust your instruments more than your oh so fallible and insufficiently sensitive senses.

Lesson #2: Wake up even earlier to do the measurements!

I've created a Google spreadsheet which includes graphs of the morning and evening LDR values. I will be updating the spreadsheet with new data as they come in. There are two "sheets" in there labeled "dusk to night" and "predawn to sunrise." The sheet tabs are at the bottom left of the page. Click to move from one sheet to the other.

## Monday, May 16, 2011

### Getting zapped isn't an option

Stupid me. Had already swapped a different value resistor into the breadboard before realizing the circuit was hot! With 220volts! No, I didn't get electrocuted. Didn't even feel a thing. That's because I was drawing the 220VAC from a homemade isolation transformer*. With such a transformer even grasping one of the lines (uninsulated of course) and standing barefoot on wet earth is absolutely safe. Getting grounded isn't an issue. Guess I was smart after all  :p

What would be a memorable (and no doubt traumatic) experience would be to touch both lines. 220 volts is 220 volts, transformer or no transformer. If the isolation transformer has sufficient power rating (greater than a couple of watts) then a nasty shock will be inevitable.

Years ago I was also working on a 5VDC + 220VAC circuit. I had the misfortune of accidentally grounding something. BANG! The acrid smell of toasted electronics. If I remember correctly all three ICs got fried. Luckily I wasn't part of any collateral damage. With this isolation transformer working with DC+AC circuits (either VDD or VSS and one of the AC power lines are part of the same net--they're electrically connected together) has become much much safer.

* It consists of two center-tapped 220V to 24V step down transformer connected back to back. So what happens is that mains voltage of 220VAC is stepped down to 24VAC by the first xformer then stepped up again to 220VAC by the second. 220VAC in 220VAC out, with the output completely electrically isolated from the power company's lines, making grounding an impossibility, as well as limiting the amount of current/power that can be supplied to the circuit--which is good when testing a new circuit you're not sure is bug-free!  The labels on the xformers say each has a rating of 1 ampere. Ergo, this isolation xformer has a maximum power rating of 24V x 1A = 24 watts

## Sunday, May 15, 2011

### Automatic night light circuits

I've been googling and the half dozen designs or so of automatic night light circuits I've seen have been very basic--low parts count and usually use only discrete transistors--and, more critically, are prone to at least two conditions:

1. "Chattering", whereby when ambient light level is at or is crossing the trip point for the load switching, the relay/load can rapidly turn on and off, the reason being that there’s no hysteresis built into the circuit. Hysteresis in this case means that the ambient light level at which the load is turned on is slightly lower than the level at which it is switched off. This difference in trip points eliminates any oscillations when the trip point is crossed, specially considering that sunlight / sky light level increase/decrease extremely slowly relative to electronic switching speeds.

2. A transient, high amplitude and fast rising/falling ambient light level will make the circuit switch the load on/off (depending on whether the light level change is positive or negative). For example, at night, lightning and head lamps of passing vehicles can fool the circuit into interpreting the brightness as indicative of daytime and turn off the load for the duration of the high ambient light level. In light of this (pun intended), there’s a need for a low pass filter so that the circuit rejects such transients. An RC network of sorts will thus be necessary.

The very first viable automatic night light switch (ANLS) I designed back in 2002 already incorporated both these features. That is, it had hysteresis and a low pass filter. The circuit is based on a quad NOR CMOS IC, with two of the gates configured as an RS flip flop. Another gate is used an inverter and the other hooked up to the output of the flip flop and functions as an inverter buffer. NAND gates would function just as well. I chose NOR because they were slightly cheaper. All circuits that I've installed (controlling the perimeter lights of my home) which use this flip flop design employ NOR gates.

I used CMOS instead of TTL for the very important reason that CMOS gates have very high input impedance [Note 1]. Given that the LDR voltage divider will have a very high impedance (Mohms) it is necessary that the gate not load it down. The essentially open circuit of CMOS inputs accomplishes this well. CMOS also has an elegant feature--its output changes state when the voltage at the input is exactly half the supply voltage [Note 2]. This makes designing and calculation of the voltage divider a breeze.

In 2003 I wrote a couple of papers documenting the circuit. I'm reproducing both below with slight editing.

Notes:

1. "The inputs to all [CMOS] devices are open circuits." (Lancaster, D., and H. M. Berlin. CMOS Cookbook. 2ed. Indianapolis,Ind.: Howard W. Sams, 1988. p.11.)

2. "The output of the [CMOS] inverter will change state whenever Va [voltage of the voltage divider] crosses the (V+)/2 point [V+ = Vdd]." (Carr, Joseph J.. IC User's Casebook. Indianapolis, Ind. USA: Howard W. Sams, 1988. p.235.) "The logic changes from high to low exacly halfway up to the supply voltage." (Lancaster p.11.)

------------

Design of Ambient Light Activated Switches
January 2003

The following document describes the operation of a circuit first designed in May 2001 as well as derivatives of that circuit. All the circuits are designed to switch a load on when ambient light condition drops to a certain level, and turn off the load when light condition rises to a certain level. The level at which switching occurs is variable. The circuits can be used to automatically switch on outdoor lights at dusk and switch them off at dawn.

Fundamentals

CMOS 2-input NAND or NOR gates are used to create a simple RS latch and inverters. Two gates are used as voltage comparators whose outputs toggle high or low. CMOS gates (CD4000 series) are inherently referenced to 50% of supply voltage such that an input greater than 50% of supply is interpreted as a high, while an input less than 50% is detected as a low.

By using a light dependent resistor (LDR) in series with fixed value resistors a voltage divider can be formed. Since the resistance of an LDR varies in proportion to incident light, we set up the resistor network such that LDR resistance will be 50% of total series resistance at the light level at which the load should be switched on.

To create a practical circuit and one wherein the RS latch does not enter into oscillation, we build hysteresis into the circuit by setting the switch-on light level to be different from the switch-off level. This can be accomplished by adding a small resistance in series with the LDR so that switch-off resistance value (and, therefore, voltage value) is greater than for switch-on.

The only feasible simple circuit with hysteresis is one that turns the load on when ambient light level drops to less than L and can only be turned off when light level becomes greater than L. The difference between these two light levels is the hysteresis band. A representation of the hysteresis curve is given below. Assuming load is off the circuit will switch it on only when light level drops to Lon and thereafter will be on as light level decreases further. When light level increases load will not be switched off until ambient conditions reaches point Loff after which the load will remain off as long as light level does not drop below Lon. It is not possible to build a simple circuit wherein the load is switched on a certain light level and then switched off at an even darker condition.

Below is a basic sense and control circuit of a light activated switch using CMOS gates (NOR gates in this case). A voltage divider network formed by reference resistance RR, hysteresis resistance Rh, and LDR.

Given the above voltage divider, reset point is given by the equation:

$V_{off} = \frac {R_h + R_L} {R_R + R_h + R_L} > 0.5$

where

RR = Reference resistance
Rh = Hysteresis resistance
RL = LDR resistance

But because of NOR.a is configured as an inverter, NOR.b actually senses a low when Voff is greater than 50% voltage.

Set point is the voltage at which the load is turned on and is given by:

$V_{on} = \frac {R_L} {R_R + R_h + R_L} > 0.5$

Because of inverter NOR.a set input of the latch will be low when reset input is high and vice versa, except when ambient light conditions fall within the hysteresis band. In that transition period both inputs will be low. Thus, the latch outputs will be locked and cannot change.

By increasing the value of Rh the difference between light level at which the circuit turns on and off increases, i.e., the hysteresis band widens. However, this also means that the load will be switched off at higher ambient light conditions. Because of this Rh would be, for practical purposes, less than 10% of RR, with a value between 1% to 5% being sufficient.

By increasing RR the circuit is forced to turn on at darker ambient condition. For outdoor ambient lighting detection RR may take on a value between 500K to 1Mohm given the particular LDR used. Other types of LDRs may necessitate different RR values. By using a variable resistor, field adjustment of the circuit is possible.

IMPORTANT: RR should be such that ambient light has not reached its minimum level, else the circuit will become too sensitive to slight increases in ambient conditions (even with Rh) which may then trigger the circuit to turn off the load.

One important consideration in building a practical outdoor ambient light-activated switch is the occasional occurrence of large and abrupt but transient variations in light level. For instance, such phenomena as lightning may trigger the circuit to turn on for the duration of the lightning flash and then turn off again immediately thereafter. It is, therefore, necessary to shield the circuit by adding an RC network to buffer such changes. This is the purpose of capacitor C3 in the circuit below. C3 is charged via RR and remains at a voltage level determined by Rh + RL. As LDR resistance varies with light level C3 charges/discharges. When light condition changes gradually (the normal state) C3 charges/discharges only by a small amount and so voltage across C3 follows that across Rh + RL nearly instantaneously. But during an abrupt change--say, LDR resistance changes by a factor of 10 or more in a fraction of a second--voltage across C3 will not immediately drop or increase. There will be a time lag before voltage across C3 will settle. This lag prevents the voltage at NOR.a input from changing immediately.

The problem with the above design is that it creates a much greater time lag for the load to be turned on again than for it to be turned off. Thus, during, for instance, a lightning flash at night, LDR will drop to a low value such that LDR + Rh resistance will be a fraction of RR. This means that capacitor discharge RC time is shorter than charging RC time. Yet what we require is for discharge time to be significant to prevent the circuit from reacting to sudden increases in ambient light level.

To remedy this lopsided (and undesirable) response/performance of our circuit we need to find a way to increase the amount of resistance through which C3 is discharged without affecting the voltage divider and without increasing (if possible) the resistance through which C3 is charged. This can be accomplished by using the setup below.

A resistor and a signal diode in parallel have been added. In this arrangement C3 is charged via RR but discharges through Rd + Rh + RL. Hence, the minimum resistance by which C3 can discharge is Rd + Rh. By simply increasing Rd we can "desensitize" our circuit to large, abrupt and transient increases in light level however much we want to.

Here is how the circuit works:

When light level has settled C3 is neither charged nor discharged. When light level decreases C3 is charged via RR. Because of diode D2 Rd is shunted. Therefore, the time for C3 to charge is a function of RRC3. When light level increases LDR resistance decreases forcing C3 to discharge. In this case D2 is reverse biased and so C3 discharges via Rd. The discharge time is a function of (Rd+Rh+RL)C3.

When there is a sudden increase in ambient light conditions LDR will dip to a very low resistance level. Without Rd capacitor discharge would be very fast since the only resistance left would be Rh; hence, the load will be turned off soon thereafter if ambient condition does not return to "normal" quick enough. Without Rd and with C3 = 100uF load turn off occurs within a second or two when light level condition varies from very dark to very bright. By choosing Rd to be approximately equal to RR the charge and discharge times of C3 can be made roughly equal. Or by making Rd very large the circuit can be made insensitive to ambient conditions suddenly getting very bright for a long period of time. For example, given C3 = 47uF and Rd = 1Mohm and a sudden transition from near total darkness to midday light level, tests show that the circuit will not turn off the load until after around 30 seconds of continual exposure to the light source. With such capacitor and resistor values the circuit will be totally immune to false turn-offs even during the severest lightning storms.

While the circuit above uses NOR gates, NAND gates may also be employed to the same end. When using NOR gates the inputs to the RS latch must both be low when within the hysteresis band. In a NAND-based circuit on the other hand both must be high when ambient light conditions are within the dead band. These conditions are necessary for these two respective latches to operate properly. Inputs to a NOR latch cannot both be high simultaneously, while inputs to a NAND latch cannot both be low at the same time. In the circuit above such a condition cannot arise because of NOR.a inverter and Rh.

Operation of NOR-Based Circuit

The operation of the NOR-based switch has been covered in detail above. To recapitulate: RR, Rh and RL form a resistor network and, hence, a voltage divider. NOR.a is used as an inverter. NOR.b and NOR.c gates form an RS latch. Assume that output of NOR.b is initially low (load is off). When light level falls such that LDR resistance is just over 50% of RR+Rh+RL (= Rtotal) NOR.c output goes low and forces NOR.b to output high, thus turning the load on. NOR.b output will remain high as light levels decrease. Thereafter, when ambient light level begins increasing LDR resistance will decrease to below 50% of Rtotal. Output of NOR.b, however, will not go low until Rh+RL goes below 50%. Therefore, a higher light level is necessary for load turn-off than for load turn-on. This hysteresis is necessary to avoid latch race conditions and to prevent rapid switch on-off of load during the 50% mark crossover.

Operation of NAND-Based Circuit

A NAND-based switch is analogous to a NOR-based circuit but a NAND latch needs low inputs to force output latch high, while race condition occurs when both inputs are low simultaneously. Because of these characteristics the inverter is connected to the LDR instead and output is drawn from NAND.c when an NPN transistor is used (output of NAND.b can be used if a PNP transistor is used).

In the circuit below RR, Rh and RL form a resistor network and, hence, a voltage divider. NAND.a is used as an inverter. NAND.b and NAND.c gates form an RS latch. Assume that output of NAND.c is initially low (load is off). When light level falls such that LDR resistance is just over 50% of RR+Rh+RL (= Rtotal) NAND.a output goes low and so NAND.c output goes high, thus turning the load on. NAND.c output will remain high as light levels decrease. Thereafter, when ambient light level begins increasing LDR resistance will decrease to below 50% of Rtotal. Output of NAND.b, however, will not go high until Rh+RL goes below 50%. Therefore, a higher light level is necessary for load turn-off than for load turn-on.

Output of either NAND or NOR gate based circuit is used to turn on a transistor which then triggers a triac to turn on. Attention should be paid to the required gate trigger current of the particular triac used. Enough current should be delivered to the triac gate to assure full switch-on of the triac even in the 4th quadrant which usually requires a much higher gate current. Transistor should be a high gain type so as not to unduly load the CMOS gate if output is obtained from one of the gates that form the latch.

One important consideration when using triacs is the quadrants in which the triac will be operating (see diagram below). With triac optocouplers the triac is triggered by alternating positive and negative currents. This is called "in-phase triggering" since gate polarity with respect to MT1 always follows that of MT2 polarity vs. MT1. Therefore, the triac operates in Quadrants 1 and 3.

With DC triggering, gate voltage with respect to MT1 will either be always positive or always negative. If positive, the triac will be operating in Quadrants 1 and 4. If gate to MT1 voltage is always negative then triac will be working in Quadrants 2 and 3. In other words, when the gate is sourcing current (trigger current always flows from gate to MT1) then the triac is operating in Quadrants 1 and 4. When the gate is sinking current (current flows the more positive MT1 to gate) then the triac is operating in Quadrants 2 and 3.

We can design our ambient light-activated switch to trigger the triac with either positive or negative DC gate current. The circuits below show how an NPN and a PNP transistor can trigger a triac given a logic high or low respectively. With a logic high the collector to emitter junction of the NPN transistor conducts and triggers the triac. With a logic low the emitter to collector junction of the PNP transistor conducts and triggers the triac. Because the gate in either configuration is always positive with respect to MT1 the triac in both circuits will be operating in Quadrants 1 and 4.

According to Teccor's data sheet its Q401E3 1A 400VAC triac needs typically 50mA for Quadrant 4 operation. Our transistor must thus be able to source at least this much current, preferably more. In the circuit S9013 and S9012 transistors are assumed to have an hFE of 100 at collector currents less than 100mA. Therefore, a minimum base current of 0.5mA is required for collector to source at least 50mA. R1 is chosen to provide this minimum base current. R2 on the other hand limits the actual current that is fed to the triac gate.

Because triacs require substantially greater gate current in Quadrant 4 it is best to operate a triac only in Quadrants 1, 2, and 3. Current requirements is of great concern in our circuit because the power supply can source only around 80mA maximum. Therefore, operating the triac in Quadrants 2 and 3 via negative DC gate current is very much preferred. This can easily be achieved by making the positive side of the DC supply the common leg for DC and AC supplies and tying MT1 to it. The net effect is that triac gate will be sinking current to trigger the triac instead of sourcing it--the reverse of the preceding circuits. The circuits below illustrate how this can be achieved using transistors. Using an NPN transistor a logic high will trigger the triac. With a PNP transistor a logic low will trigger it.

Any triac may be used which requires a maximum gate trigger current of less than 80mA--the approximate upper limit of the power supply. TO-220 packaged triacs may need a heat sink.

The Teccor Q401E3 needs a maximum of 25mA gate trigger when the triac is operated in Quadrants 1 to 3. This must be the minimum current supplied to the triac to ensure proper turn-on. Supplying a current greater than this is preferred.

The relationship between collector and base current is given by the following equations:

$I_C = I_B h_{FE}$

$I_B = \frac {V_S - V_{BE}}{R_B}$

Therefore:

$I_C = \frac {V_S - V_{BE}}{R_B} h_{FE}$

where

IC= collector current
IB = base current
hFE = minimum transistor current gain
RB = current limiting resistance for base
VS = input voltage at base, usually power supply voltage
VBE = voltage across base and emitter with base saturated

Assuming collector current provided by base current is greater than current needed by load, current limiting resistor for fixed-voltage load that requires a current source (e.g., the triac gate) is derived as follows:

$I_L = \frac {V_S - V_{CE}}{R_L}$

where

IL = current required by load
VS = power supply voltage
VCE = voltage across collector and emitter with base saturated
RL = current limiting resistor in series with load

Given a S9013 NPN or S9012 PNP transistor as output amplifier to switch the triac on, we can derive the necessary resistor values.

To make 50mA available to the triac gate we choose the base current limiting resistor as follows:

IC = 50mA
S9013 minimum hFE = 60
VS = 5.6V
VBE = 1V

Using the above equations base resistor RB = 5.5Kohm. We choose a standard 5.1Kohm resistor

To limit the actual current supplied to the triac gate to 50mA we choose the collector current limiting resistor as follows:

IL = 50mA
VCE = 0.6 (max.)

Using the above equations RL = 100 ohms

LED's are shown in the circuit but are optional. They provide visual feedback as to the state of the RS latch. Since NOR/NAND gates can only source or sink very small currents, the current limiting resistors for the LED's must limit current to less than 2mA.

Power Supply

The circuit utilizes a half-wave transformerless power supply with one leg of the AC line common with DC positive supply.  Filter capacitor C2 must be large enough to supply enough gate trigger current to the triac during the negative half cycle.  The working DC voltage should be above 3V for the CMOS gates to work properly but should be low enough so that Zener diode Z1 does not dissipate too much power during the positive half cycle when it is reversed biased, during daytime when load is turned off and practically all current is being dissipated by the Zener.

It is important to note that when reverse biased D1 is blocking the full AC line voltage. Therefore, for a 240VAC line it must have a peak inverse voltage (PIV) rating greater than 340V. A 1N4004 will suffice. But using a diode with a much higher PIV rating--600V 1N4005, for example--may be a better idea to provide added protection for the other devices in the circuit from voltage spikes during the negative half cycle.

Adding a fuse in series with the AC line offers added protection in case of overload, shorts or breakdown of C1.

References:

Triac Operation:
Motorola Thyristor Device Data, 2ed. Motorola Inc. 1988.
Teccor triac catalog

Transistor as Switch:
David A. Bell. Solid State Pulsed Circuits, 2ed. Reston. 1981.
Robert Boylstad & Louis Nashelsky. Electronic Devices, 4ed. Prentice-Hall. 1987.

------------

Mathematics of CMOS NOR Latch Based Auto Night Light Switch
July 2003

The design of an auto night light switch based on CMOS NOR gates was discussed in a January 2003 paper. The mathematics involved in the voltage divider is discussed in further detail here.

The following circuit shows the voltage divider network and the latch composed of 2-input NOR gates. NOR.a is used an inverter, while NOR.b and NOR.c are wired as a latch. Rd, D2 and C2 form a dampening RC network that prevents the circuit from reacting to abrupt and transient changes in light levels.

We will determine the LDR resistance at which the output of NOR.b goes high and low, i.e., when the load is turned on (output high) and when NOR.b output goes low, i.e., when the load is switched off (output low). We will also determine the hysteresis band between turn on and turn off.

We know that the inputs of the 4000 series CMOS gates are referenced to 50% of supply voltage (V+), meaning that voltages < 0.5V+ are interpreted as low, and voltages > 0.5V+ are interpreted as high.

In the above circuit RR, Rh and LDR form a voltage divider.

Let
RL = resistance of LDR
RLon = resistance of LDR at the instant RL = 50% of total  resistance (load is switched on)
RLoff = resistance of LDR at the instant RL + Rh = 50% of total resistance (load is switched off)

Because NOR.b and NOR.c are wired as a latch the circuit will turn on the load (NOR.b output goes high) when voltage at the input of NOR.c becomes greater than 50% V+, or in other words RL is greater than 50% of total resistance (input of NOR.b must be low or a disallowed state ensues). The transition point is therefore:

$\frac {R_L_{on}} {R_R + R_h + R_L_{on}} = \frac {R_R + R_h} {R_R + R_h + R_L_{on}} = \frac {1}{2}$

$R_L_{on} = R_R + R_h$

On the other hand, the circuit will turn off the load (NOR.b output goes low) when input at NOR.a (used an inverter) goes below 50% V+, or in other words RL+Rh is less than 50% of total resistance (input of NOR.c must be low or a disallowed state ensues). The transition point is thus:

$\frac {R_L_{off} + R_h} {R_R + R_h + R_L_{off}} = \frac {R_R} {R_R + R_h + R_L_{off}} = \frac {1}{2}$

$R_L_{off} = R_R - R_h$

The hysteresis band is the difference between and RLon and RLoff :

$h = R_L_{on} - R_L_{off}$

$h = 2R_h$

-------

Note: LaTeX math code was embedded using mathcache

### Measuring LDR resistance from dusk to night

[May 17 2011: I've created a Google spreadsheet and pasted the values for 3 days of measurement. Includes charts. If I can force myself to wake up before dawn I'll measure predawn to dawn LDR resistance as well and update the spreadsheet.]

I'm in the process of designing my latest model of automatic night light circuit (it turns on the lights at dusk and switches it off at dawn) and I want to measure the resistance of the light dependent resistor (LDR) with respect to ambient light level. But lacking a light meter I did the only thing I could and measured the LDR resistance with respect to time of day.

To do this I cobbled up the following circuit on a breadboard which I placed outdoors. It's an LDR voltage divider which is buffered by a single-supply op amp. I ran an unshielded twisted pair (UTP) cable from the circuit  to my workbench power supply and Fluke 8842A DMM. The goal was to record the voltage output of the unity gain buffer every five minutes and then derive the LDR resistance.

Circuit was provided 10VDC. Output of the 78L05 (in circuit) was measured to be a stable 4.987V under bright and dark ambient conditions. The 1Mohm resistor measures 1.014Mohm

The following graph shows the measured voltage output of the op amp versus time. Since it's configured as a voltage follower (unity gain buffer) it merely translates the very high impedance input to a very low impedance output; hence, the output would be the voltage across R2.

This graph shows the computed resistance of the LDR versus time.

Equation is derived from voltage divider rule: VS [R2 /(R1 + R2)] = VO

where
VS = VDD = 4.987V
VO = op amp output voltage
R2 = resistance of resistor in series with the LDR forming a voltage divider = 1.014 Mohm

Solving for R1 we obtain: (VS - VO)R2 / VO

LDR resistance was 8Kohm at 17:40. It increased exponentially for an hour but then began plateauing by 18:50 because residual sunlight was ebbing to nil rapidly. By that time my own home and the neighbor's lights as well as sky/cloud reflected city lights began to account for most of what the LDR was picking up. By 19:00 measurement shows there was absolutely no sunlight. City lights must've increased or cloud cover increased since resistance dipped a bit. Maximum resistance was at 18:55 at 15.142Mohm.

The MCP6232 is a rail-to-rail I/O op amp so its output can go very near ground. Just to make sure we haven't reached the op amp's "floor" (VOL in the datasheet, i.e., the minimum voltage above ground which it can output), I covered the LDR with a black opaque plastic can (old Kodak 35-mm film canister). The circuit didn't instantly provide a value; rather the voltage gradually (exponentially) decreased. After about a minute the op amp output was down to 10mV which translates to an LDR resistance of 500 Mohm! After several more minutes it crept further down still to 7.5mV or 665Mohm.

## Saturday, May 7, 2011

### Trip me once shame on you. Trip me twice shame on me.

I don't believe it. I just realized I got bogged down by the same bug twice. In both cases it took me hours to hunt down the cause. First time around it was with the PIC12F1822 last March while developing the toy traffic light.  And now with the PIC16F1827 for the kitchen timer. In both cases I was having a problem getting the MCU to sleep. And in both cases it was because I was clearing the interrupt-on-change interrupt flag bit IOCIF (which is read-only) in the INTCON register when what should be cleared is IOCxF register (where x = A or B depending on the PORT where IOC is present).

From the PIC12F1822 datasheet: "The IOCIF Flag bit is read-only and cleared when all the Interrupt-on-Change flags in the IOCAF register have been cleared by software." (DS41413B-page 91)

And from the PIC16F1827 datasheet: "The IOCIF Flag bit is read only and cleared when all the interrupt-on-change flags in the IOCBF register have been cleared by software." (DS41391D-page 86)

Because the IOCxF register remained non-zero, INTCON.IOCIF remained set and the MCU kept waking up immediately after the sleep command was executed.

This is just unbelievable. I actually completely forgot about the 12F1822 debugging nightmare I had just two months ago. And repeated the very same mistake and had to grope around for the cause all over again. My brain needs a tune up badly.

## Monday, May 2, 2011

### I guess I'm big on timers

This is a variant of the 99-minute timer. It has two keys for incrementing and decrementing the countdown time (green buttons). And it has a third key (the yellow one) for countdown time recall (and/or some other function which I have yet to come up with). Instead of a common anode, I've used a common-cathode two-digit seven-segment display. The reason is that I can use N-channel MOSFET transistors and dispense with transistor base current-limiting resistors. Three 2N7000 MOSFETs are used here--two for the display and one to switch the buzzer which is off-board.

MCU is a PIC16F1827, a relatively new model in the enhanced mid-range line of PICs. All I/O pins are used. VPP pin is dedicated to ICSP. The green pushbuttons use the ICSPDAT and ICSPCLK pins. Since the buttons are normally open and use the MCU's weak pull ups, the pins are effectively unconnected when the buttons aren't pressed. Thus, serial programming is possible.  [May 3 edit: What the heck was I thinking when I wrote that?! The pushbuttons are NOT connected to the data and clock lines of the ICSP. Rather a 32.768kHz crystal and its two 18pF capacitors are, since those pins are also for timer 1 (pin labels T1OSI and T1OSO). I had previously tested whether there would be any problem with those programming pins being connected to a crystal and found that ICSP was unaffected.]

There are four jumper links (three are visible in the photo)--two for VDD and two for ground. I don't know if I could've eliminated the jumpers had I placed the components differently and routed differently. I tried. I really tried to minimize the number of jumpers.

As with the water heater timer board I've again left the photoresist on the traces. Only the photoresist on pads were cleaned off using acetone. And this was done immediately prior to soldering to prevent oxidation buildup. No further preparation of the pads was necessary. The freshly exposed copper took on solder easily.

The components of course were a different story. All leads which showed signs of tarnishing/oxidation were cleaned using the gray (abrasive) end of a Faber-Castel 7061B-50 rubber eraser. After which leads of all components were wiped down with isopronanol soaked cotton to remove oils and eraser debris.

Unfortunately I don't have any solder that's less than 1mm in diameter so the joints tend to have excess solder on them. The copper pour areas are the pads for the 78L05 voltage regulator. The larger copper area will aid in heat dissipation since the input voltage to the regulator is 12V and so there's a large headroom of 7 volts. Given approximately 50mA maximum current through the display, the 78L05 will be dissipating some 350mW. With a junction-to-ambient thermal resistance of 200C°/W for the TO-92, the regulator would reach a temperature of 0.35 x 200 = 70° above ambient. With an ambient of 30° the junction could reach 100° when "8" is being displayed. This is still below the absolute maximum of 125° but the lower the junction temperature the better.

## Sunday, May 1, 2011

### Not so classic electromagnet for kids

Promised my nephew we'd make an electromagnet. So I cobbled up one using the entire coil (6.5 meters) of enamel wire from the inductor of a burnt out compact fluorescent lamp, a 1/4" x 2" zinc-plated bolt, and a couple of 15ohm 3watt resistors from some old busted I don't remember what appliance. Juice provided by a power supply.

I measured the enamel wire's resistance at 2.5ohms. I could've used a single dry cell (say, a D battery) to power the EM but at 600mA current draw it would run out pretty quickly. So I decided on using a power supply. Unfortunately the PS's minimum output is several volts which meant I had to add some resistance to decrease the current flow or the EM would get too hot to hold!

To build the EM I just coiled the wire around the bolt, going back and forth its length a couple of times till the wire ran out, leaving the two ends of the wire sticking out to make electrical connection with the resistors and power supply. The two 15ohms were paralleled (to decrease resistance and increase power dissipation capacity) and the pair connected in series with the enamel wire. With wire resistance of 2.5ohms and the paralleled resistor value of 7.5 ohms, the total resistance was a nice round figure of 10ohms.

I soldered the resistors on a piece of stripboard and added two PCB terminal blocks on both ends to connect wires to so that when this electromagnet circuit is scrapped I'll still be able to use those porcelain-encased resistors. The resistors are paralleled with jumper wires on the terminal blocks.

I initially powered the circuit using 3.3VDC from a regulated supply. That's gives 330mA of current. Magnetic flux was fine but not at all strong. Once nothing blew up or got fried I increased the supply to 5VDC. With half an amp the resistors were dissipating almost a watt each [(0.5A/2)^2*15ohms] and the electromagnet (the enamel wire), 625mW.

Increasing the current through the coil would increase the magnetic flux but will proportionally increase the heat dissipation of the circuit as well.

Optimally of course I shouldn't have to resort to adding resistors. As the above computations show I was throwing away 2W as heat while less than a watt was doing useful work. Well I do have more dead CFLs whose circuit boards still have to be salvaged from the lamps. If the 5-year old brat doesn't get bored with the EM after just a few minutes and ends up wanting to play with it some more in the coming days I'll crack open (literally) those lamps and splice more enamel wire to the EM to bring the total wire resistance to 10 or more ohms. May have to use a larger bolt. And have to check that it doesn't become too warm to handle comfortably!