Thursday, May 3, 2012

Measuring the current draw of the liquid level indicator

I breadboarded the liquid level indicator circuit to measure its current draw when operating in its different modes. I powered it using the PICkit2 set to 3.0V. I ran out of 1µF capacitors so C1 = 1.5µF. To simulate immersion in a water-based liquid I used 1K resistors.

VDD was measured using a Fluke 8842A. All current measurements were taken using a Fluke 87V set to high resolution, with MIN-MAX enabled, and with selector knob set to µA when measuring standby mode current and to mA range for all others. Reading was nulled (REL button pressed) before measurements were taken. The 87V probes were connected on the high side in series with the PICkit 2 VDD. The last significant digits of the average values when the transducer was buzzing kept jumping around--that's the reason for the approximation sign.  

Current draw @VDD = 3.01V, ambient temp. = 31°C
Mode/Condition Min Max Ave units
Standby mode 12.65 15.55 13.08 µA
only low probe immersed 0.137 3.827 ~2.01 mA
low and high probes immersed 0.328 3.654 ~2.00 mA
only high probe immersed 0.139 3.855 ~1.28 mA


Since WDT is always on and since it runs off the 31kHz LFINTOSC, both of these modules are always enabled in all modes even during sleep. Therefore the minimum current consumption of the circuit is the sum of these two. According to the datasheet typical current for the LFINTOSC is 4.0µA with a maximum of 22µA. WDT typical current is around 0.5µA. [See very important current measurements for these two and discussion below].

As I pored over the datasheet I noticed the brownout reset consumes a hefty amount of current--6.9µA typical. It also occurred to me that since I had disabled the MCLR (in the configuration word) this means pin RA3 is configured as a digital input, but is floating--it has no pull-up or pull-down resistor--which can only mean that it's drawing more current than it should. So I checked how the current consumption would change by first enabling MCLR and then disabling BOR. The following are the results. Values in the first row is just a control since the measurements below were made several hours after I had performed the ones above.

Current draw @VDD = 3.01V, ambient temp. = 30°C
Mode/Condition Min Max Ave units
Standby mode, MCLR disabled, BOR enabled 11.73 14.27 12.12 µA
Standby mode, MCLR enabled, BOR enabled 7.47 9.66 7.93 µA
Standby mode, MCLR enabled, BOR disabled 0.23 2.57 0.75 µA

Clearly, the reduction in power consumption is just incredible. From the averages we can infer that a floating RA3 pin wastes around 4µA, while BOR guzzles some 7µA--just as the datasheet says. With MCLR enabled and BOR disabled, I measured the currents for when low and high probes are immersed and they're practically the same as in the first table above.

With all these data we can now compute battery life. The Maxell CR2032 coin cell I'm using has a nominal capacity of 220mAh. Given the average current of  0.75µA when in standby mode the battery should be able to last for 220mAh / 0.75µA = 33.5 years! But of course I built the circuit to be used not displayed on the shelf. So let's say it's used thrice daily and its probes are immersed in liquid for 30 seconds each time. That's 1.5 minutes every 24 hours. In those 90 seconds the circuit is drawing an average current of 2.0mA. Therefore, everyday, the average current is:

(1.5 min / 60 min x 2000µA + 24 hrs x 0.75µA) / 24.025 hrs = 2.8uA

If you look at the graphs in the Maxell datasheet you'll see that the discharge capacity declines as the discharge current increases. Let's be conservative and take the 2.0mA as our discharge current. According to the graph discharge capacity will now only be around 200mAh. Thus the discharge duration of the liquid level indicator given our hypothetical conditions is:

200mAh / 2.8µA = 8 years.

Not bad. Even derating that by 50% still gives a very good battery lifespan.

----

With MCLR enabled and BOR disabled I proceeded to comment out void main() and used the following instead:

void main()
{
  IniReg();
  WDTCON = wdt512ms;
  while(1)
  {
    asm sleep
  }
}

With the voltage comparator, DAC, and weak pull-ups out of the picture average current dropped to 0.48µA.

Using the same main() I then disabled WDT in the configuration word. Average current fell to a mere 0.02µA (pretty much just as Microchip boasts). 20nA is practically the threshhold of the Fluke 87V's measurement capability!


Still with MCLR enabled and BOR disabled I tried the following to determine the amount of current the LFINTOSC uses while the MCU is continually awake.

void main()
{
  IniReg();
  WDTCON = wdt512ms;
  while(1) 
    asm clrwdt;
}

Average current was 4.11µA with WDT enabled. This agrees well with the datasheet spec for LFINTOSC current. Disabling WDT brought the average current marginally down to 4.03µA.

From the above measurements I gather that the LFINTOSC current of 4µA in the datasheet refers to when the MCU is awake. However, during sleep and if WDT is running this 4µA no longer applies. As we saw above it was a mere 0.48µA--the WDT current as per datasheet spec.

Sunday, April 29, 2012

Liquid level indicator for the visually impaired

My dad has had glaucoma for about a decade now and in the last 7 or so years has been nearly completely blind. He's been able to cope to a large extent, including making coffee (instant) on his own. Lately, however, he's been having difficulty judging whether his cup is nearly full. On several occasions he's overfilled his cup with piping hot water. Fortunately he hasn't scalded himself (yet). At over 80 years old and given his disability, we can expect things to get worse.

So to at least aid him in making his drinks I decided to build him a liquid level indicator (LLI) similar to the following.



I could've bought him any one of the various commercially available units out there, but hey this is such a simple circuit and I couldn't resist the challenge of designing a circuit for which a single coin battery would last for months. But not being the creative sort I've patterned the look of my gizmo after those on the market.

The principle behind detecting water or water-based liquids using metal probes is pretty straightforward. Since ordinary water is partially conductive we can set up a voltage divider using the liquid and a pull-up resistor of fixed value. (We can reverse the set up using a pull down resistor instead but as we'll see in a moment the former has an advantage given the microcontroller I'm using). A voltage comparator can then be used to detect the change in voltage when the liquid bridges the fixed resistor to ground.


Low power specification

Since this is a battery-operated unit power consumption is a big deal. I'm using a Microchip PIC and in order to have the least consumption possible I had to use an LF version. I opted for an 8-pin PIC12LF1840 (the 12LF1822 would do as well and is slightly cheaper but I haven't used the 1840 and wanted to try it out and up until recently didn't have any known silicon issues; it does now--yeah, drats!). According to the datasheet its typical sleep current @3.0V is a mere 20nA with all peripherals shut down and 500nA with the watchdog timer on (the LLI circuit needs WDT to be on at all times). Compare that with the F version of the 1840 which draws 5600nA and 5900nA, respectively, at 3.0V.

Another way to minimize consumption is by judicious manipulation of oscillator frequency. It's a truism that the higher the clock frequency the higher the power consumption. So whenever possible this circuit uses the the low power 31kHz LFINTOSC (low frequency internal oscillator). The only reason I use the medium frequency MFINTOSC is because the piezoelectric transducer needs a constant 2kHz square wave to make it beep. The typical current consumption at 500kHz MFINTOSC is 124µA versus a mere 4.0µA using the LFINTOSC.

According to the datasheet the on-board voltage comparator in low power mode draws around 4.9µA. During standby--when no liquid is detected--the circuit could go to sleep with the comparator enabled. The MCU would then wake up when the comparator interrupt flag gets set--liquid has been detected. But given that the watchdog timer uses only about 0.5µA, it's more economical to disable the comparator, put the MCU to sleep, let a WDT timeout (>100ms) wake the MCU, power up the comparator, check the probes, and then go back to sleep if no liquid is detected.


Schematic

I initially used an external pull-up resistor for each for the high and low probes. It then occurred to me I might be able to use the weak pull-ups of the microcontroller. Tried it and it worked and so I was able to dispense with two discretes. Note that the datasheet says the weak pull-ups typically guzzle a massive 100µA. I'm not sure if this is true whether or not there is an external path to ground. Just to be sure, in the firmware, the pull-ups are enabled only when the probes are being checked.

The buzzer is not a Sonalert alarm. It's a simple piezoelectric transducer in a Sonalert-like black plastic housing. The transducer will not sound if it is simply connected to a power source. It needs a constant square wave to produce sound. I tested the transducer using a function generator and to my ear it was loudest at a frequency of around 2.15kHz. So this is the frequency of the square wave I feeding it in the LLI.
Connecting the transducer directly to the MCU pin does work but the sound level is very low. Increasing the value of C3 more than 2µF does not make the sound any much louder. 1µF seemed sufficient.

Firmware

I initially used the following structure to store the values of the instantaneous comparator readings, level, and edge detect.

struct
{
  val: 5;
  edge: 2;
  level: 1;
} PLO, PHI;

But the amount of compiled assembly instructions was scandalously high compared to having separate 8-bit and one-bit variables. Since every instruction adds to processing time and therefore time when MCU is awake instead of asleep using the least current, it simply was unthinkable to employ structures, however more elegant they may be from a programming standpoint. (It can be argued, rather successfully, that given my goal of maximum power efficiency, I should've written the firmware in pure assembly rather than C. But my skill in assembly is rusty and right now I'm not ready for a grueling punishment.)

The MCU regularly checks the status of the probes (time between checks depends on whether no liquid has been detected--standby mode--or if liquid has already been sensed) with the instantaneous one-bit readings stored in a 5-bit variable. The bits in this variable are left shifted each time the probes are read. Thus it stores the five most recent readings. A debounce routine then simply checks if the variable contains all ones or all zeroes. If it's all ones then level = 1, and if it's all zeroes level = 0. A rising edge is defined as the level transition from 0 to 1, and a falling edge the level transition from 1 to 0. Rising and falling edges are not used so the edge variables and statements have been commented out to reduce the size of the assembly and therefore reduce time when the MCU is awake when in standby mode. Again, slashing power consumption is good.

A probe error is defined as the state where the high probe detects liquid but the low probe doesn't. It may be that the probes have shorted out in his pocket for instance. When this happens the a characteristic audible pattern is sounded to alert the user. Shorting of the high and low probes does not require any alarms to go off.

The reference voltage for the comparator is derived from the on-board digital-to-analog converter (DAC). I initially set the DAC output voltage to 50% of VDD, but increased to 75% in the hopes that even a liquid with an unexpectedly high resistance will be detected. Thus, if the voltage detected by the comparator is less than 0.75VDD  this is taken to mean that liquid has been detected.

Global weak pull-up (found in the OPTION register) is always enabled. However, individual weak pull-ups for the two probes are enabled only just after the DAC and comparator are turned on. The pull-ups are turned off right after the particular probe has been read. The comparator and DAC are disabled right after reading both probes.

Timer 0 is used to set the interval between probe reads when the 500kHz MFINTOSC is being used. When the LFINTOSC is active timer0 is ignored.

Timer 1 is used to create the three different audible alert patterns. When liquid has been detected at the low probe the pattern is a continuous loop of 500ms beep --> 500ms silence. When liquid has also been detected at the high probe the pattern becomes a continuous loop of 120ms beep --> 120ms silence. When a probe error is sensed the alarm pattern is a continuous loop of 250ms beep --> 150ms silence --> 250ms beep --> 1000ms silence.

Timer 2 is dedicated to producing the 2.15kHz square wave for the piezoelectric transducer.

When in standby mode the watchdog timeout is 512ms, meaning the MCU wakes up every half second and checks the status of the probes then goes back to sleep for another half a second. Assuming the current mode is standby (ie., variables PXXlevel for both probes = 0) then once the instantaneous reading of either the low or high probe is high (meaning liquid has been sensed), the WDT timeout is changed to 8ms with the MCU going back to sleep and waking up 8ms later. If the instantaneous reading now becomes low (zero) then WDT timeout reverts back to 512ms, else WDT remains at 8ms. If five consecutive instantaneous readings are all high then PXXlevel goes high, the MCU remains awake, begins using the 500kHz clock, and the appropriate audible alert is sounded.

Once PLOlevel and PHIlevel both go low and instantaneous readings are zero, the MCU returns to standby mode and reverts to the 31kHz clock.

/*

Liquid Level Indicator
April 2012

processor = PIC12LF1840
compiler = mikroC v5.6.0

configuration word: 
  INTOSC with I/O on clk pin
  enabled: power up timer, brownout reset low trip point, WDT via SWDTEN, stack over/underflow
  all else disabled

CONFIG1   :$8007 : 0x0F8C
CONFIG2   :$8008 : 0x1613
*/

#define  int1                bit
#define  int8                unsigned char
#define  int16               unsigned int
#define  int32               unsigned long

#define  on                  1
#define  off                 0

#define  input               1         // for TRISx
#define  output              0         // for TRISx

#define  analog              1         // for ANSELx
#define  digital             0         // for ANSELx

#define  hi                  1         // switch level high
#define  lo                  0         // switch level low

#define  buzz                LATA.f2

#define  an_plo              ANSELA.f1
#define  an_phi              ANSELA.f4
#define  tris_plo            TRISA.f1
#define  tris_phi            TRISA.f4
#define  wpu_plo             WPUA.f1
#define  wpu_phi             WPUA.f4

#define  ch_plo              0         // comparator input channel
#define  ch_phi              1         // comparator input channel

#define  t1h_fill            256-30    // TMR1H initial value, for audible indicator when low probe submerged or low and high probe submerged
#define  t1h_beep1           256-31    // TMR1H initial value, for audible indicator when probe error
#define  t1h_pause1          256-19    // TMR1H initial value, for audible indicator when probe error
#define  t1h_beep2           256-31    // TMR1H initial value, for audible indicator when probe error
#define  t1h_pause2          256-122   // TMR1H initial value, for audible indicator when probe error

#define  osc500khz           0b111000  // 500kHz MFINTOSC, for use with OSCCON
#define  osc31khz            0b0       // 31kHz LFINTOSC, for use with OSCCON

#define  wdt8ms              0b111     // value for WDTCON
#define  wdt16ms             0b1001    // value for WDTCON
#define  wdt32ms             0b1011    // value for WDTCON
#define  wdt128ms            0b1111    // value for WDTCON
#define  wdt256ms            0b10001   // value for WDTCON
#define  wdt512ms            0b10011   // value for WDTCON

#define  rising              1         // rising edge detected.
#define  falling             2         // falling edge detected.
#define  none                0         // no edge.

int8 PLOval;                           // values of last five low probe readings
int8 PHIval;                           // values of last five high probe readings
//int8 PLOedge;                          // edge detected?, 0 = no edge detect, 1 = rising edge, 2 = falling edge; other values = Not Used / Undefined for now
//int8 PHIedge;
bit PLOlevel;                          // voltage level of probe when not bouncing (hi = 1, lo = 0)
bit PHIlevel;

bit plo;                               // comparator reading of low probe. 1 = liquid detected, 0 = no detection
bit phi;                               // comparator reading of high probe. 1 = liquid detected, 0 = no detection
bit buzzing;                           // buzzer status flag; 1 = buzzer is on, 0 = buzzer off

enum {_begin, _standby, _insta_plo, _immersed_plo, _insta_phi, _immersed_phi, _probe_error}
     STATE = _begin,         // current state
     PREVSTATE = _begin;     // previous state

enum {_beep1, _pause1, _beep2, _pause2} STATEPERROR;


// ===========================================================================================
//       Functions
// ===========================================================================================

void IniReg()
{
  ANSELA = digital;
  TRISA = output;
  PORTA = 0;

  an_plo = analog;
  an_phi = analog;
  tris_plo = input;
  tris_phi = input;

  PLOval = 0;
  PHIval = 0;
  PLOlevel = lo;
  PHIlevel = lo;

  DACCON0 = 0;               // DAC off, DAC is not output on DACOUT pin, Vdd as positive source
  //DACCON1 = 0b10000;         // 0x10, Vref = 16/32 = 50% of Vdd
  DACCON1 = 0b11000;         // 0x18, Vref = 24/32 = 75% of Vdd

  CM1CON0 = 0b10;            // comparator off, comp output polarity not inverted, comp output internal only,
                             // comparator in low power low speed mode, hysteresis enabled
  CM1CON1 = 0b10000;         // comparator interrupts disabled, C1VP connected to DAC, C1VN connected to C1N0-

  WPUA = 0;                  // disable individual pull ups
  OPTION_REG = 0b00000010;   // global pull ups enabled, timer0 prescale = 1:8
                             // given clock = 500khz, TMR0 increments from zero to 255, prescale = 1:8, timer0 tick = 256*8 / (500kHz/4) = 16.384ms

  // timer2 initialize
  // piezoelectric buzzer toggled on and off at 2.15kHz -- loudest sound is at this frequency (empirically determined)
  // with timer2 prescale = 1:1, postscale = 1:1, PR2 = 29, Fosc = 500kHz, timer2 tick = 29 /(500khz/4) = 232us
  // buzzer is on 232us and off 232us. Period therefore = 464us. Freq = 2.155khz
  PR2 = 29;
  T2CON = 0;                 // prescale = 1:1, postscale = 1:1, timer2 off
  
  buzzing = 0;

  INTCON.GIE = 0;
  INTCON.PEIE = 1;

  OSCCON = osc31khz;         // default INTOSC frequency = 500khz. Change to 31kHz LFINTOSC after initialization.
                             // in all probability when coin battery is inserted and circuit powered up, the probes are not immersed in liquid and so the MCU will be put to sleep
} // void IniReg()


// turn on buzzer
// piezoelectric buzzer needs constant square wave to produce sound
// timer2 provides this square wave with a frequency of 2.15kHz
void BuzzOn()
{
  buzz = on;
  buzzing = 1;
  TMR2 = 0;
  PIR1.TMR2IF = 0;
  PIE1.TMR2IE = 1;
  T2CON.TMR2ON = 1;
}

// turn off buzzer
void BuzzOff()
{
  buzz = off;
  buzzing = 0;
  T2CON.TMR2ON = 0;
  PIE1.TMR2IE = 0;
}

// audible indicator is armed and the specific sequence of sounds emitted depends on
// whether liquid has reached low probe or high probe or whether a probe error has occurred.
void EnableAudible()
{
  TMR1L = 0;
  PIR1.TMR1IF = 0;
  PIE1.TMR1IE = 1;
  INTCON.GIE = 1;
  BuzzOn();
}

void DisableAudible()
{
  BuzzOff();
  T1CON.TMR1ON = 0;
  PIE1.TMR1IE = 0;
  INTCON.GIE = 0;
}

// voltage comparator reads the probes
// DAC, weak pull ups, and comparator are turned on before reading and then turned off afterwards to minimize power consumption
void ReadProbes()
{
  // OPTION_REG.NOT_WPUEN = 0;
  DACCON0.DACEN = 1;         // turn on DAC
  CM1CON0.C1ON = 1;          // turn on comparator

  wpu_plo = 1;               // enable low probe weak pull up
  CM1CON1.C1NCH = ch_plo; // PIC12F1840
  if (CMOUT)
    plo = 1;
  else
    plo = 0;
  wpu_plo = 0;               // disable low probe weak pull up

  wpu_phi = 1;               // enable high probe weak pull up
  CM1CON1.C1NCH = ch_phi;  // PIC12F1840
  if (CMOUT)
    phi = 1;
  else
    phi = 0;
  wpu_phi = 0;               // disable high probe weak pull up

  CM1CON0.C1ON = 0;          // turn off comparator
  DACCON0.DACEN = 0;         // turn off DAC
}


void Debounce()
{
  // shift all bits to the left
  // if probe reading is high then PXXval bit 0 = 1
  PLOval <<= 1;
  if (plo)
    ++PLOval;
  PLOval.f5 = 0;             // only bits 0 to 4 (5 least significant bits) are used so bits 5 to 7 must be cleared
                             // need only clear bit 5 because this zero will eventually be left shifted into bits 6 and 7
  PHIval <<= 1;
  if (phi)
    ++PHIval;
  PHIval.f5 = 0;             // only bits 0 to 4 (5 least significant bits) are used so bits 5 to 7 must be cleared

  //PLOedge = none;
  //PHIedge = none;

  // if level is low and all bits of PXXval are now high then
  // a rising edge has been detected
  // switch is considered just released when rising edge is detected
  // switch level is now high
 if ((!PLOlevel) && (PLOval == 0b11111))
  {
    PLOlevel = hi;
    //PLOedge = rising;
  }

 if ((!PHIlevel) && (PHIval == 0b11111))
  {
    PHIlevel = hi;
    //PHIedge = rising;
  }

  // if level is high and all bits of PXXval are now low then
  // a falling edge has been detected
  // switch is considered just pressed when falling edge is detected
  // switch level is now low
  if ((PLOlevel) && (!PLOval))
  {
    PLOlevel = lo;
    //PLOedge = falling;
  }

  if ((PHIlevel) && (!PHIval))
  {
    PHIlevel = lo;
    //PHIedge = falling;
  }
} // void DebounceSwitch()


void Standby()
{
  if (PREVSTATE != _standby)
  {
    STATE = _standby;
    OSCCON = osc31khz;     // 31kHz LFINTOSC
    DisableAudible();
    WDTCON = wdt512ms;
  }
  asm sleep
}


void InstaPLO()
{
  if (PREVSTATE != _insta_plo)
  {
    STATE = _insta_plo;
    OSCCON = osc31khz;   // 31kHz LFINTOSC
    DisableAudible();
  }
  asm clrwdt             // this clrwdt is absolutely necessary or there will be a wdt timeout every time plo is high
  WDTCON = wdt8ms;       // since plo is high (liquid has been detected during this pass) shorten sleep and check plo more often than during standby mode
  asm sleep
  WDTCON = wdt128ms;     // return wdt period to at least 32ms-- one loop through void main() at clock = 31khz LFINTOSC takes around 10 to 14ms
}


void InstaPHI()
{
  if (PREVSTATE != _insta_phi)
  {
    STATE = _insta_phi;
    OSCCON = osc31khz;   // 31kHz LFINTOSC
    DisableAudible();
  }
  asm clrwdt             // this clrwdt is absolutely necessary or there will be a wdt timeout every time phi is high
  WDTCON = wdt8ms;       // since phi is high (liquid has been detected during this pass) shorten sleep and check phi more often than during standby mode
  asm sleep
  WDTCON = wdt128ms;     // return wdt period to at least 32ms-- instructions in void main() during 31khz LFINTOSC take around 10 to 14ms
}


void ImmersedPLO()
{
  if (PREVSTATE != _immersed_plo)
  {
    OSCCON = osc500khz;     // 500kHz MFINTOSC
    STATE = _immersed_plo;
    INTCON.TMR0IF = 0;
    TMR0 = 0;
    WDTCON = wdt128ms;
    TMR1H = t1h_fill;
    T1CON = 0b110001;       // Timer1 clock source is instruction clock (FOSC/4), prescale = 1:8, timer1 oscillator off, timer1 on
    EnableAudible();
  }
}


void ImmersedPHI()
{
  if (PREVSTATE != _immersed_phi)
  {
    OSCCON = osc500khz;    // 500kHz MFINTOSC
    STATE = _immersed_phi;
    INTCON.TMR0IF = 0;
    TMR0 = 0;
    WDTCON = wdt128ms;
    TMR1H = t1h_fill;
    T1CON = 0b10001;       // Timer1 clock source is instruction clock (FOSC/4), prescale = 1:2, timer1 oscillator off, timer1 on
    EnableAudible();
  }
}


void ProbeError()
{
  if (PREVSTATE != _probe_error)
  {
    OSCCON = osc500khz;  // 500kHz MFINTOSC
    STATE = _probe_error;
    INTCON.TMR0IF = 0;
    TMR0 = 0;
    WDTCON = wdt128ms;
    TMR1H = t1h_beep1;
    T1CON = 0b100001;    // Timer1 clock source is instruction clock (FOSC/4), prescale = 1:4, timer1 oscillator off, timer1 on
    EnableAudible();
    STATEPERROR = _beep1;
  }
}


void Status()
{
  if (!PHIlevel)
  {
    if (!PLOlevel)
    {
      if (plo)               // current pass through comparator has detected liquid at low probe but there is no confirmation of submersion yet (PLOlevel is low), and hi probe not submerged
        InstaPLO();
      else if (phi)
        InstaPHI();
      else
        Standby();
    }
    else
      ImmersedPLO();
  }
  else // if (PHIlevel)
  {
    if (PLOlevel)
      ImmersedPHI();
    else
      ProbeError();
  }
  PREVSTATE = STATE;
}


void interrupt()
{
  if (PIE1.TMR2IE && PIR1.TMR2IF)
  {
    if (buzz)
      buzz = off;
    else
      buzz = on;
    PIR1.TMR2IF = 0;
  } // if (PIE1.TMR2IE && PIR1.TMR2IF)

  else if (PIE1.TMR1IE && PIR1.TMR1IF)
  {
    if (STATE == _probe_error)
    {
      if (++STATEPERROR > _pause2)
        STATEPERROR = _beep1;

      switch (STATEPERROR)
      {
        default:

        case _beep1:
          BuzzOn();
          TMR1H = t1h_beep1;
          break;

        case _pause1:
          BuzzOff();
          TMR1H = t1h_pause1;
          break;

        case _beep2:
          BuzzOn();
          TMR1H = t1h_beep2;
          break;

        case _pause2:
          BuzzOff();
          TMR1H = t1h_pause2;
          break;
      } // switch
    } // if (STATE == _probe_error)
    else // if (STATE == _immersed_plo || STATE == _immersed_phi)
    {
      TMR1H = t1h_fill;
      if (buzzing)
        BuzzOff();
      else
        BuzzOn();
    }
    PIR1.TMR1IF = 0;
  } // if (PIE1.TMR1IE && PIR1.TMR1IF)
} // void interrupt()


void main()
{
  IniReg();

  while(1)
  {
    if (OSCCON != osc31khz)            // this conditional is equivalent to "if (STATE == _immersed_plo || STATE == _immersed_phi || STATE == _probe_error)" since these states run at 500kHz
    {
      while (!INTCON.TMR0IF) ;         // do nothing until one timer0 tick has elapsed
      INTCON.TMR0IF = 0;
    }
    asm clrwdt
    ReadProbes();
    if (STATE == _standby)             // during standby there is no need to run the debounce routine. Just record the instantaneous value of the probes
    {
      PLOval.f0 = plo;
      PHIval.f0 = phi;
    }
    else
      Debounce();
    Status();
  }
}

The build

Wanted to make the pcb as small as possible and so I used an SOIC package for the MCU. Unfortunately I don't keep surface mount caps and resistors (cost is prohibitive for me at the moment) and so I had to use throughholes. It seemed like a grievous sin not to place the MCU in the large unused space on the copper side of the board beneath the battery holder and so that's just what I did even if I had already drawn a previous layout that situates the MCU partially underneath the terminal block.

I scoured shops for a plastic box that would house the circuit board and found this near perfect cream-colored plastic box that's in fact a portable USB power supply that uses 2 x AA  batteries. I simply removed the small DC-to-DC converter pcb and the metal spring contacts for the batteries. Having found a suitable container I proceeded to finalize the PCB size and layout. The biggest component is the CR2032 battery holder, taking up half the real estate! I intentionally did not include a polarity reversal protection Schottky diode since that immediately slashes 0.3V off the power 3-volt supply. User will just have to be extra careful when changing batteries. Yeah, relying on user competence is a recipe for disaster. Hey, I'm talking about myself too you know.


Below is the freshly etched panel which I scored and snapped into two. You will notice the track on the right side of the board is right at the border. The track is a ground trace from the negative terminal of the battery holder to one of the pins of the terminal block as well as to one of the header pins. Had little choice since I didn't have enough board width. Of course I made sure I didn't commit the same booboo that caused a short between the power supply rails. I added the triangles just to keep more copper on the board and to complement the diagonal circuit tracks. It kinda looks good I think.


Even while laying out the board I knew the headers wouldn't have enough leeway on either side. The battery holder on one side and the terminal on the other would prevent the PICkit2/3 programmer from plugging in properly. So I bent the header pin by almost 30 degrees. Simple fix. I wanted to use a right angle header but the pins would end up extending beyond the board perimeter and the board wouldn't fit the plastic case. 


I had to sand down the top of the (green) terminal block because it was sticking out about a millimeter preventing the plastic cover from sliding in and locking. 



For the SOIC pads and those alone I used a Multicore "VOC-free No-clean" flux pen. The usual flux paste I use leaves a messy unsightly residue which is hard to clean off an SMD and could cause a high resistance bridging between the closely spaced pins--something that could contribute to unnecessary battery drain. Nevertheless, after all the soldering was completed, I used isopropanol and acetone to clean the solder joints of all the components including the MCU.  




The probes (metal wires) are just nickel-plated paper clips. For now these will have to do since I haven't found any stainless steel wires yet. I don't have a photo of it, but after screwing down the probes onto the terminal block, I encased the three in hot melt glue to give the set of probes some rigidity.


The liquid level indicator at work. Just hang it over the lip of the cup, mug or tumbler. No switches to flip, no buttons to push.





Even during the breadboard stage of design the liquid level indicator was showing signs of having some difficulty detecting water. Reason? I thought it might be the nickel plated probes. But ohmmeter readings show their resistance to be in the milliohm range. And more importantly because the LLI detected coffee, chocolate and juice the instant these liquids reached the tips of the probes, those metal wires can't be the problem.

Now I'm inclined to believe it may be due to the fact that Microchip explicitly recommends an input signal impedance of less than 10 kilohms when using the analog peripherals such as the voltage comparator. Coffee et al. of course have a relatively low resistance because of the solutes, and that translates to, I reckon, a liquid resistance of less than 3K. Plain potable water has a higher resistance which could be anywhere along the spectrum depending on how pure it is or how much minerals are dissolved. To make the battery last as long as possible and because of printed circuit board real estate constraints, I intentionally decided not to design in a unity gain buffer to provide the comparator a low impedance signal which I definitely would in a circuit that had little power consumption concerns. Will have to test a breadboarded version of the LLI and see how the inclusion of the buffer will affect water-detection performance.

If the voltage follower licks the problem then a future version 2.0 of the gizmo will include a dual op amp which gets powered up only when probe readings are being taken. Power consumption is still my major concern given that the circuit is using a single CR2032 3-volt lithium cell which I want to last for months and hopefully--FSM willing--years.


Dad has already used the gizmo and he seems to like it. Told him to inform me immediately if the unit starts acting up.

Monday, April 2, 2012

Equation for determining belt size of a three-pulley system

April 3 Erratum: Thanks to rickets007 I spotted several egregious errors! I had used pulley diameter in some parts when clearly I was intending to use radius. Utter carelessness on my part. I have already corrected the blunders. The equations below are now (hopefully!) free of mistakes.


This is off-topic, but I've been googling and thus far haven't found any page that has the equation for computing the belt circumference given pulley diameters and distance between three pulleys. So I'm posting mine. I've tested my equation against an online 3-pulley calculator and while they don't give exactly the same numbers for some input values, they're close enough (there might be rounding errors in the webpage or my spreadsheet). You will note that the calculator necessitates the user inputting three angles. My equation below has no such requirements.

When I'm looking for formulas online I frequently just want a plug and play equation without any of the mathematical esoterica and history. So for those who couldn't give a rat's bleep about the derivation here's the formula up front.




For my sake (so I don't have to do it all over again!) and for skeptics who want to make sure I didn't make any booboos here's the derivation.

In Fig.1 we have three circles representing three pulleys. Pulley A has its center marked as point A. Pulley B has its center marked as point B. Pulley C has its center marked as point C.


We are given the diameters of each of the three pulleys and the distance between their centers. We need to find the belt length.

Let
DA = diameter of pulley A
DB = diameter of pulley B
DC = diameter of pulley C

Let
a = distance between centers of pulleys B and C = segment BC
b = distance between centers of pulleys C and A = segment CA
c = distance between centers of pulleys A and B = segment AB

L = belt length = segments HJ + DE + FG + arc lengths FE + GH + DJ

Let
a' = segment HJ
b' = segment DE
c' = segment FG

Let
α = ∠CAB
β = ∠ABC
γ = ∠BCA

Let
α' = ∠FAE
β' = ∠GBH
γ' = ∠DCJ

Let
lα' = arc length of the belt looping around pulley A = arc FE
lβ' = arc length of the belt looping around pulley B = arc GH
lγ' = arc length of the belt looping around pulley C = arc DJ

Note: All angles and arcs are less than π radians (180 degrees).

Rewriting the equation for belt length we have:

L = a' + b' +c' + lα' + lβ' + lγ'


In order to find the arc lengths we need to first determine the angles α', β',  and γ'. To achieve this we shall, for each pulley, find the values of all the other angles in the pulley and then subtract them from 2π radians (360 degrees).

For triangle ABC we are given the values of all the sides (a, b, c). Therefore, we can determine all three angles of the triangle using cosine law:

α = arccos[(b2+c2-a2)/(2bc)]
β = arccos[(c2+a2-b2)/(2ca)]
γ = arccos[(a2+b2-c2)/(2ab)]


As we know if a line is tangent to a circle then a radius of the circle drawn to the point of contact of the tangent line with the circle will be perpendicular to the tangent line. Thus, ∠AFG, ∠BGF, ∠BHJ, ∠CJH, ∠CDE, ∠AED are all right angles.


In Fig.2 we have segment BK drawn parallel to FG. Since ∠AFG is a right angle, therefore, ∠AKB is also a right angle. It follows that triangle AKB is a right triangle. Because BK is parallel to FG and FK is parallel to GB, segment AK = difference in the radii of pulleys A and B = DA/2 - DB/2.

Likewise, we draw segment CL parallel to DE and obtain right triangle ALC. LE = CD and so AL = DA/2 - DC/2.

Our objective is to find the value of ∠KAB and ∠LAC. Because we know the values of the hypotenuse and the adjacent side of both right triangles we can use the cosine function for right triangles:

∠KAB = arccos[(DA/2-DB/2)/c]
∠LAC = arccos[(DA/2-DC/2)/b]

We now have all the angles to compute for α'.

α' = 2π - arccos[(DA/2-DB/2)/c] - arccos[(DA/2-DC/2)/b] - α

We use the same method above for pulleys B and C to obtain:

β' = 2π - arccos[(DB/2-DC/2)/a] - arccos[(DB/2-DA/2)/c] - β
γ' = 2π - arccos[(DC/2-DA/2)/b] - arccos[(DC/2-DB/2)/a] - γ

Note that the fact that (DC/2 - DA/2) is negative is not an error. In fact it provides the correct answer--an obtuse angle which is the ∠ACD in this case. We don't need to know which pulleys are bigger and which are smaller. The equations will always give us the correct values.

We now turn to finding the arc lengths. The arc length of the belt looping around a pulley is the angle subtended by the belt divided by the angle measure of an entire circle (2π) multiplied by the circumference of the pulley:

lα' = (α'/2π)(πDA) = α'DA/2
lβ' = (β'/2π)(πDB) = β'DB/2
lγ' = (γ'/2π)(πDC) = γ'DC/2

Let's return to triangle AKB. Notice that segment FG and KB are not only parallel but also equal in length (because quadrilateral BKFG is a rectangle). Above we let c' = segment FG. It follows that c' is also = segment KB. We can get the value of KB using the sine or tangent function, but to minimize trigonometric functions we will apply the Pythagorean theorem, with c (segment AB) as the hypotenuse:

c' = √[c2-(DA/2-DB/2)2]

The same applies to the other two segments of the belt.

a' = √[a2-(DB/2-DC/2)2]
b' = √[b2-(DC/2-DA/2)2]

And at last we have all the values needed to compute for belt length.

Monday, March 12, 2012

I2C dual voltage mystery solved

Remember that strange phenomenon on the dual voltage I2C bus where I was getting 3.4V on the 2.8V bus and 4V on the 5V bus? Well, I finally found the culprit. Turns out that I had, with breathtaking unparalleled stupidity, plugged the two TO-92 2N7000 MOSFETs the wrong way around! The drain and source pins got reversed! So all the while when the bus was idle, current was flowing from the 5V rail to the 2.8V I2C bus (due to the inherent diode in MOSFETs). Almost certainly protection diodes on the MMA7660FC accelerometer chip were conducting, thus giving that extra 0.6 to 0.7V excess voltage reading. Because the chip is still ticking the current flowing through it must've been within limits. Had I decreased the pull-up resistors to below 1kohm, it (and therefore I) may not have been so lucky.

Interestingly, as we've seen, I2C communication works even with this reversed set up--with the lower voltage on the MOSFET drain side and the higher voltage bus on the source side. Let's analyze the circuit to see how and why it works. (We'll consider only one line since the explanation applies to both SDA and SCL.)


A. When neither the 7660 nor the MCU is pulling the line low--i.e., Q1 and Q2 are off--then MOSFET Q0 is off--because its source pin is at a higher voltage than the gate. Points V1 and V2 ought to be pulled up to VDD1 and VDD2, respectively. But due to Q0's internal diode--with the anode at VDD2 (5-volt) side--current flows from VDD2 toward VDD1 side. Since VDD2 > (VDD1 + diode voltage drop), the accelerometer's protection diode D1 conducts and so at point V1 we get a voltage less than VDD2 but greater than VDD1. We expect V1 = VDD1 + VFD1, where VFD1 = D1's forward voltage.

Because of Q0's diode we expect the voltage at point V2 = V1 + VFD0, where VFD0 = forward voltage of Q0's diode. End result is that both V1 and V2 are at logic high. Note that V2 may not reach a logic high if the voltage difference between VDD1 and VDD2 is large. For instance if VDD1 = 2.8V and VDD2 = 15V then, assuming the accelerometer hasn't been fried, the voltage at V2 would still be around 4V which may not be sufficient to meet the minimum voltage required for a logic high. 

B. When Q2 turns on V2 is pulled to ground. Q0 source is likewise pulled to ground. Because the voltage difference between Q0's gate and source exceeds the gate threshold voltage VGS(th), Q0 switches on causing V1 to be pulled to nearly to ground as well. So both V1 and V2 are at logic low.

C. When Q1 turns on, V1 is pulled to ground. Because of Q0's internal diode V2 gets pulled down close to ground  as well. (V2 will be approximately 0.7V, with the exact value depending on the voltage across Q1's drain and source). V1 and V2 are at logic low. [March 13 edit: V2 will actually be very close to ground because as in B above the voltage difference between Q0's gate and source exceeds the gate threshold voltage VGS(th) and thus Q0 turns on. With less than a couple of milliamps of current Q0 drain-source voltage is in the order of millivolts.]


I want to post the screenshots of the oscilloscope readings of the dual voltage I2C with the error corrected, but I still don't have my USB flash drive so I'll put the images up when I finally get it back.

Quirks on dual voltage I2C bus / Using a 5V LCD with an MCU at less than 5V

[Update: I know what's causing the overvoltage condition on the I2C. Find out over here.]

Previously I talked about how a MMA7660FC accelerometer was supplied with 2.8V while the microcontroller was run at 5.2V. Because the two chips communicate via I2C a voltage level shifter using MOSFETs was employed. To make sure the voltage levels on the bus were within specs I took some oscilloscope readings .Unfortunately, unlike the scope readings in the AN97055 Bi-directional level shifter for I²C-bus and other systems, mine show that the 2.8V side of the I2C is at around 3.4V while the 5V bus is at 4.0V. This is strange and I have yet to find an explanation for this. Intriguingly the voltage difference between 2.8V and 3.4V is the forward voltage of a diode.

Here are screenshots of the readings. I've also taken shots of the rise/fall times.

A. 2.8-volt I²C






B. 5-volt I²C.






Pull resistors are 4.7K on both the 2.8V and 5V bus. I also tested 10K pull ups. As expected rise time increased.

As stated in the previous blog entry the reason I ran the MCU at 5V is that I'm using a 5V LCD. It turns out, however, that the LCD is fine with signals way below its minimum required VDD of 4.5V. According to the Displaytech 162F datasheet the minimum voltage for a logic high  (VIH) is 2.2V. So running the MCU at 2.8V and feeding the LCD a signal of 2.5-2.8V would be acceptable. Thus, if there are no other hardware on the circuit which requires the MCU to run at a higher voltage than 2.8-3.0V then the following simpler circuit (than the one with MOSFETs and additional pull ups) can be used.


Notice that the LCD's RW pin is connected to ground. RW is kept at logic low when writing to the LCD or issuing commands to it. It is only brought high when reading from the LCD. The most important use of the read operation is to check whether the LCD is busy--we cannot write or issue a command while it's still processing. To read the LCD, the MCU pins connected to DB4 to DB7 must first be tristated--the pins configured as inputs. We then poll DB7 until it goes low--signifying the LCD is ready. However, in lieu of reading the LCD, we can just wait a few milliseconds so the LCD can finish whatever it's doing. This is the method the mikroC compiler employs. It does not tristate the PIC pins. It just issues a delay of 5.5ms. Apparently this is the maximum amount of time generic LCDs need. So with RW tied to ground, this is the only method of ensuring we don't write to the LCD while it's still busy.

Besides freeing up one MCU pin, using this delay method ensures no overvoltage condition will exist on the MCU pins. Remember that in our circuit MCU VDD < LCD VDD. When the MCU pins are tristated and the LCD is read from the signals from the LCD are close to LCD VDD of 5V. As per datasheet PIC pins are not supposed to have voltages > MCU VDD.

So what happens if we have signal voltages on the PIC pins greater than its VDD? Well the protection diodes start conducting. The following schematic is from the PIC16F1828 datasheet and clearly shows the diodes on the I/O pins.


Actually the voltage on the MCU pins can exceed MCU VDD. But the current through the diodes has to be limited so as not to fry the chip. In fact even mains voltages of 110 or 220V can be applied to the MCU so long as a resistor of at least 1Mohm is placed in series to severely limit the current flowing into the chip.

To test how the MCU will stand up to the 5V signal voltages from the LCD--without any series current-limiting resistor--I had the MCU use the polling method for determining the busy status of the LCD. The RW pin is connected to the MCU of course. Firmware is as follows.

#define  en        PORTA.f2
#define  rs        PORTC.f1
#define  rw        PORTC.f0
#define  db7       PORTC.f4
#define  db6       PORTC.f3
#define  db5       PORTC.f6
#define  db4       PORTC.f7
#define  trisdb7   TRISC.f4
#define  trisdb6   TRISC.f3
#define  trisdb5   TRISC.f6
#define  trisdb4   TRISC.f7

#define  clearlcd            0x1

#define  int1                bit
#define  int8                unsigned char
#define  int16               unsigned int
#define  int32               unsigned long

#define  on                  1
#define  off                 0

#define  hi                  1
#define  lo                  0

#define  input               1         // for TRISx
#define  output              0         // for TRISx

#define  analog              1         // for ANSELx
#define  digital             0         // for ANSELx

 //************************************************************************************************
 //    LCD subroutines
 //************************************************************************************************

void DelayMillisec(int8 ms)
{
  int8 i;
  for (i=0; i<=ms; i++)
    Delay_ms(1);
}

void PulseEN()
{
  en = hi;
  asm {nop}            // one cycle delay
  en = lo;
}

void CheckLCDbusy()
{
  bit lcdbusy;

  en = lo;
  rs = lo;
  rw = hi;

  // change data bits to input
  trisdb7 = input;
  trisdb6 = input;
  trisdb5 = input;
  trisdb4 = input;

  lcdbusy = 1;
  while(lcdbusy)
  {
    en = hi;
    if (!db7)
      lcdbusy = 0;
    en = lo;
    PulseEN();                // dummy read lower nibble; this is necessary since both nibbles must be read
  }

  // change data bits back to output
  trisdb7 = output;
  trisdb6 = output;
  trisdb5 = output;
  trisdb4 = output;

  rw = lo;
}

void SendNibbles(int8 text)
{
  db7 = text.f7;
  db6 = text.f6;
  db5 = text.f5;
  db4 = text.f4;
  PulseEN();

  db7 = text.f3;
  db6 = text.f2;
  db5 = text.f1;
  db4 = text.f0;
  PulseEN();
}

void WriteTextLCD(int8 text)
{
  CheckLCDbusy();
  en = lo;
  rs = hi;
  SendNibbles(text);
}

void SendCommandLCD(int8 text)
{
  CheckLCDbusy();
  en = lo;
  rs = lo;
  SendNibbles(text);
}

void IniLCD()
{
  DelayMillisec(15);
  en = 0;
  rs = 0;
  rw = 0;
  db7 = 0;
  db6 = 0;
  db5 = 1;
  db4 = 1;
  PulseEN();

  Delay_ms(5);
  PulseEN();

  Delay_us(160);
  PulseEN();

  Delay_us(160);
  db4 = 0;
  PulseEN();

  // lcd now in 4-bit operation mode
  // the SendCommandLCD() function can now be used to send all other initialization instructions
  SendCommandLCD(0b101000);            // Function Set: 4-bit data bus, 2-line display, 5x7 dots
  SendCommandLCD(0b1000);              // Display: display off
  SendCommandLCD(clearlcd);            // clear lcd screen-- clears DDRAM
  SendCommandLCD(0b110);               // Entry Mode: increment, display shift off
  SendCommandLCD(0b1100);              // Display: display on, cursor off, cursor blink off
  asm {clrwdt}
}

//************************************************************************************************


void IniReg()
{
  // set internal clock frequency to 4MHz
  OSCCON = 0b1101000;

  TRISA = output;
  TRISB = output;
  TRISC = output;
  ANSELA = digital;
  ANSELB = digital;
  ANSELC = digital;
  PORTA = 0;
  PORTB = 0;
  PORTC = 0;
} // void IniReg()


void main()
{
  IniReg();
  IniLCD();
  while(1)
  {
    WriteTextLCD('T');
    WriteTextLCD('e');
    WriteTextLCD('s');
    WriteTextLCD('t');
    WriteTextLCD(' ');
    WriteTextLCD('P');
    WriteTextLCD('I');
    WriteTextLCD('C');
    WriteTextLCD(' ');
    WriteTextLCD('p');
    WriteTextLCD('i');
    WriteTextLCD('n');
    WriteTextLCD('s');
    DelayMillisec(200);
    SendCommandLCD(clearlcd);
  }
} // void main()


With the circuit powered up I probed DB4 to DB7 using a Fluke 87V with its PEAK MIN MAX voltage detect enabled. As expected the voltage was significantly above its VDD of 2.81V. I recorded a maximum of 3.53V. The difference between VDD and the peak voltage is the voltage drop across the protection diode which is conducting due to the excess voltage on the I/O pin. I didn't bother measuring the current. I just left the circuit running for several minutes and from the looks of it, the MCU can take it.

I've also used the oscilloscope to measure the voltages and the waveforms are rather intriguing. Unfortunately I don't have my USB flash drive right now. I'll post screenshots when I get it back.

Sunday, March 11, 2012

MMA7660FC Accelerometer on dual voltage I2C bus

I recently got a Freescale MMA7660FC accelerometer already soldered on a breakout board. It's made by made by Tautic and comes complete with decoupling capacitors. I soldered a header to the board and plugged in a 5-pin connector. The connector wires plug into the breadboard. This way I can freely rotate the accelerometer.

To make sure the communications between the microcontroller and the accelerometer was going well and to view the values of X, Y, Z axes, I initially relied on the Saleae Logic. After the bugs had been ferreted out I wired in an LCD so I can get a real time feedback as I rotated the board.

Note that Tautic has opted to tie the analog (AVDD) and digital (DVDD) supply together. This means the chip cannot be set to OFF MODE wherein only the digital part of the circuit is powered. According to the datasheet in this mode the "MMA7660FC will not respond, but I2C bus can be used for other devices (MMA7660FC does not load I2C bus)." This mode has the least power consumption and would be useful in handheld devices which need to conserve as much power as possible.

While I'm quoting the datasheet, a caveat is in order. To have absolute faith in the 7660 datasheet is to court misery--as I learned. Even as it's already in its 7th revision it still has at least two egregious errors which caused me confusion, not to mention wasted time in getting this chip up and running.

The first brick wall I crashed into: "During the Active Mode, continuous measurement on all three axes is enabled. In addition, the user can choose to enable: Shake Detection, Tap Detection, Orientation Detection, and/or Auto-Wake/Sleep Feature..." Well I tried to change a few registers in Active Mode and it wouldn't let me. So I did it in Standby Mode. I'm not sure if none of the registers--save for MODE register 0x07--can be edited in Active Mode.

Second Freescale booboo: "In order to enable Tap detection in the device the user must enable the Tap Interrupt in the INTSU (0x06) register...." No! I disabled all interrupts and tap detection still works. Of course there won't be any interrupts sent via INT. But the tap detection bit in TILT register 0x03 still gets set when the chip is tapped.

Can Freescale engineers please get their documentation right? This isn't a 300-page doc. It shouldn't be that hard to finally--after so many revisions--get rid of all the errors.

The MMA7660 has a maximum VDD of 3.6V and a recommended VDD of 2.8V. Maximum voltage on any other pin should not exceed VDD. Since it communicates with the microcontroller via I2C the MCU must either run at the same voltage or if the MCU runs at a higher voltage then voltage level shifting hardware has to be present on the I2C bus.

The microcontroller I chose is the 20-pin PIC16F1828. Because I'm using a 5V Displaytech 162F LCD I wanted the MCU to run at 5V. This meant I had to find a way to have a dual voltage I2C bus. Fortunately, the engineers at Philips devised a very simple way to realize this years ago. Check out the following application notes:

AN97055 Bi-directional level shifter for I²C-bus and other systems 
AN10441 Level shifting techniques in I2C-bus design

We need only connect two MOSFETS to the bus and we automatically have a bidirectional voltage translator, with electrical isolation between the two voltage levels. In the breadboarded circuit I had an LM317 voltage regulator supply 2.8V to the 7660 while the MCU and LCD were run at 5.2V. The MOSFETs were 2N7000.
The comparator isolates the INT pin from the MCU. It also provides either 0V or 5V signal to the MCU. Note that the accelerometer's INT pin is configurable either as open drain or push-pull. In this set up it should be set as push-pull. In the test circuit I didn't use a comparator. Instead I employed a simple diode to isolate and protect the accelerometer. The pull down resistor prevents the MCU input pin from floating when INT is low. The voltage output at the INT pin is actually above the minimum of 2.0V required by the TTL input of the MCU. Note that given an INT max output of 2.8V this diode method will not work with Schmitt trigger inputs on the microcontroller since they require a logic high to be at least 80% of VDD.

For this test circuit I've added a 3.3V Zener diode and a 27-ohm current limiting resistor to protect the accelerometer from any accidental overvoltages.

Here are screenshots of samples taken by the Saleae Logic analyzer on both the 5V and 2.8V I2C bus. You'll  notice that the sampling rate is a mere 500kHz. This is a limitation of my computer. I don't have a USB 2.0 connection and therefor--according Logic--condemns me to this max rate. Else I'd definitely be sampling at >1MHz.





The following vid shows how the accelerator's measured values change as it's tapped, turned on its sides, and flipped over. The XYZ values shown on the LCD are in the range of -31 to +31. They are not percentages of g.




I've already tested the tap interrupt function but have yet to try the other interrupts as well as shake detection and auto-sleep / auto-wake functions.

In the firmware I rely on mikroC's built-in functions for accessing the I2C bus and the LCD. The splash screen routine wasn't installed in the firmware I used in the vid.

/*

Displaying the measurements of the Freescale MMA7660FC Accelerometer on an LCD

Created:        March 2012
Processor:      PIC 16F1828
Compiler        mikroC Pro 5.0.0
Configuration:  power up timer, brownout reset (set to 2.5V), stack over/underflow reset -- all enabled, all others disabled
                internal oscillator with clk pins as I/O

*/


#define  t1h_ini   256 - 122           // value loaded into TMR1H every time it rolls over to zero for timer1 to count 0.25sec
                                       // at a prescale = 1:8 and clock of 4MHz

#define  I2Cclock 100000               // mikroC needs to know the desired I2C clock frequency (in Hz) in order to compute baud rate generator values for PIC registers

// MMA7660FC 7-bit address = 0x4C, left shift by one bit to become 0x98 in 8-bit format. 
// LSB = 0 to read slave, 1 to write to slave
#define   ACCwr    0x98 + 0
#define   ACCrd    0x98 + 1


int8 XOUT, YOUT, ZOUT;                 // X,Y,Z axis values from accelerometer - register addresses 0x00, 0x01, 0x02 respectively
                                       // values range from -31 to +32, with negative values in 2's complement
                                       // if bit 5 = 1 then number is negative. To retrieve the value, get the complement and then add 1
                                       // if bit 6 = 1 then value is not accurate because accelerometer was writing to register when it was read

int8  TILT;                            // contains the value of register address 0x03 of accelerometer

bit tap;                               // flag for tap detect


// following are needed by mikroC for built-in LCD functions

// Lcd pinout settings
sbit LCD_RS at RC1_bit;
sbit LCD_EN at RA2_bit;
sbit LCD_D7 at RC4_bit;
sbit LCD_D6 at RC3_bit;
sbit LCD_D5 at RC6_bit;
sbit LCD_D4 at RC7_bit;

// Pin direction
sbit LCD_RS_Direction at TRISC1_bit;
sbit LCD_EN_Direction at TRISA2_bit;
sbit LCD_D7_Direction at TRISC4_bit;
sbit LCD_D6_Direction at TRISC3_bit;
sbit LCD_D5_Direction at TRISC6_bit;
sbit LCD_D4_Direction at TRISC7_bit;


// **************************************************************************
/*
   for LCD with Hitachi HD44780 (or compatible) controller chip
   c1 = is the address of line 1 column 1 of the LCD
   l2c1 = line 2 column 1
*/
// **************************************************************************

#define  c1                  0x00 + 0x80
#define  c2                  0x01 + 0x80
#define  c3                  0x02 + 0x80
#define  c4                  0x03 + 0x80
#define  c5                  0x04 + 0x80
#define  c6                  0x05 + 0x80
#define  c7                  0x06 + 0x80
#define  c8                  0x07 + 0x80
#define  c9                  0x08 + 0x80
#define  c10                 0x09 + 0x80
#define  c11                 0x0a + 0x80
#define  c12                 0x0b + 0x80
#define  c13                 0x0c + 0x80
#define  c14                 0x0d + 0x80
#define  c15                 0x0e + 0x80
#define  c16                 0x0f + 0x80
#define  c17                 0x10 + 0x80
#define  c18                 0x11 + 0x80
#define  c19                 0x12 + 0x80
#define  c20                 0x13 + 0x80
#define  c21                 0x14 + 0x80
#define  c22                 0x15 + 0x80
#define  c23                 0x16 + 0x80
#define  c24                 0x17 + 0x80
#define  c25                 0x18 + 0x80
#define  c26                 0x19 + 0x80
#define  c27                 0x1a + 0x80
#define  c28                 0x1b + 0x80
#define  c29                 0x1c + 0x80
#define  c30                 0x1d + 0x80
#define  c31                 0x1e + 0x80
#define  c32                 0x1f + 0x80
#define  c33                 0x20 + 0x80
#define  c34                 0x21 + 0x80
#define  c35                 0x22 + 0x80
#define  c36                 0x23 + 0x80
#define  c37                 0x24 + 0x80
#define  c38                 0x25 + 0x80
#define  c39                 0x26 + 0x80
#define  c40                 0x27 + 0x80

#define  l2c1                0x40 + 0x80
#define  l2c2                0x41 + 0x80
#define  l2c3                0x42 + 0x80
#define  l2c4                0x43 + 0x80
#define  l2c5                0x44 + 0x80
#define  l2c6                0x45 + 0x80
#define  l2c7                0x46 + 0x80
#define  l2c8                0x47 + 0x80
#define  l2c9                0x48 + 0x80
#define  l2c10               0x49 + 0x80
#define  l2c11               0x4a + 0x80
#define  l2c12               0x4b + 0x80
#define  l2c13               0x4c + 0x80
#define  l2c14               0x4d + 0x80
#define  l2c15               0x4e + 0x80
#define  l2c16               0x4f + 0x80
#define  l2c17               0x50 + 0x80
#define  l2c18               0x51 + 0x80
#define  l2c19               0x52 + 0x80
#define  l2c20               0x53 + 0x80
#define  l2c21               0x54 + 0x80
#define  l2c22               0x55 + 0x80
#define  l2c23               0x56 + 0x80
#define  l2c24               0x57 + 0x80
#define  l2c25               0x58 + 0x80
#define  l2c26               0x59 + 0x80
#define  l2c27               0x5a + 0x80
#define  l2c28               0x5b + 0x80
#define  l2c29               0x5c + 0x80
#define  l2c30               0x5d + 0x80
#define  l2c31               0x5e + 0x80
#define  l2c32               0x5f + 0x80
#define  l2c33               0x60 + 0x80
#define  l2c34               0x61 + 0x80
#define  l2c35               0x62 + 0x80
#define  l2c36               0x63 + 0x80
#define  l2c37               0x64 + 0x80
#define  l2c38               0x65 + 0x80
#define  l2c39               0x66 + 0x80
#define  l2c40               0x67 + 0x80


#define  int1                bit
#define  int8                unsigned char
#define  int16               unsigned int
#define  int32               unsigned long

#define  on                  1
#define  off                 0

#define  input               1         // for TRISx
#define  output              0         // for TRISx

#define  analog              1         // for ANSELx
#define  digital             0         // for ANSELx

// ************************************************************************************************
//       I2C
// ************************************************************************************************

// initialize the accelerometer
void ACCini()
{
  // upon power up the MMA7660 defaults to Standby Mode
  // apparently the MMA7660 registers can only be changed when it's in Standby Mode
  I2C1_Init(I2Cclock);       // mikroC needs to set up PIC I2C registers given the user desired I2C frequency
  I2C1_Start();
  I2C1_Wr(ACCwr);            // transmit MMA7660 address and write command
  I2C1_Wr(0x6);              // point to register address 0x06
  I2C1_Wr(0b0);              // [reg addr 0x06] all interrupts disabled
  I2C1_Wr(0b0);              // [reg addr 0x07]
  I2C1_Wr(0b0);              // [reg addr 0x08] set to 120 samples/sec -- required for tap detect
  I2C1_Wr(0b01101111);       // [reg addr 0x09] set
  I2C1_Wr(0x0F);             // [reg addr 0x0A]
  I2C1_Stop();

  // after registers have been initialized it can be put in Active Mode where it can start measuring values
  I2C1_Start();
  I2C1_Wr(ACCwr);            // issue MMA7660 address and write command
  I2C1_Wr(0x7);              // point to register address 0x06
  I2C1_Wr(0b11000001);       // [reg addr 0x07] put MMA7660 in Active Mode. Upon power up chip enters Standby Mode
                             // interrupt is push-pull, interrupt is active high
  I2C1_Stop();
} // void ACCini()


// VAL contains the value of accelerometer value of the axes
void DispAxis(int8 row, int8 col, int8 VAL)
{
  #define          pos       1
  #define          neg       0
  bit sign;                  // 1 = number is positive; 0 = number is negative

  sign = pos;
  if (VAL.f5)                // if bit5 is high then axis value is negative -- in two's complement
  {
    VAL.f6 = 1;              // this bit is not part of the axis value so make it high so that when it's compelemented it'll be zero
    VAL.f7 = 1;              // this bit is not part of the axis value so make it high so that when it's compelemented it'll be zero
    VAL = ~VAL + 1;          // get the absolute value from the twos complement
    sign = neg;
  }

  if (sign == pos)
    Lcd_Chr(row,col, '+');
  else
    Lcd_Chr(row,col, '-');

  // display the tens and ones digit of the axis value
  Lcd_Chr_CP(VAL/10 + 0x30); // the ASCII code of a number is the number + 0x30
  Lcd_Chr_CP(VAL%10 + 0x30); // the ASCII code of a number is the number + 0x30
}


// read and display measurements from the accelerometer
void ACCread()
{
  int8 VAL;
  
  do
  {
    I2C1_Start();
    I2C1_Wr(ACCwr);            // issue MMA7660 adddress and write command
    I2C1_Wr(0x0);              // point to desired register adddress
    I2C1_Repeated_Start();
    I2C1_Wr(ACCrd);            // issue MMA7660 adddress and read command
    XOUT = I2C1_Rd(1);
    YOUT = I2C1_Rd(1);
    ZOUT = I2C1_Rd(1);
    TILT = I2C1_Rd(0);
    I2C1_Stop();
  } while (XOUT.f6 || YOUT.f6 || ZOUT.f6 || TILT.f6);     // if bit6 of these registers is high then the registers were read while the chip was updating them
                                                          // read the registers again since the values will be unreliable

  // X Y Z axes output
  DispAxis(1, 3, XOUT);
  DispAxis(1, 9, YOUT);
  DispAxis(1, 14, ZOUT);

  // Back / Front orientation
  VAL = TILT & 0b11;
  Lcd_Cmd(l2c1);
  if (!VAL)
    Lcd_Out_CP("  ?  ");
  else if (VAL == 1)
    Lcd_Out_CP("FRONT");
  else if (VAL == 2)
    Lcd_Out_CP("BACK ");
  else
    Lcd_Out_CP("error");

  // Portrait / Landscape orientation
  Lcd_Cmd(l2c7);
  VAL = (TILT & 0b11100) >> 2;
  if (!VAL)
    Lcd_Out_CP("  ?  ");
  else if (VAL == 1)
    Lcd_Out_CP("LEFT ");
  else if (VAL == 2)
    Lcd_Out_CP("RIGHT");
  else if (VAL == 5)
    Lcd_Out_CP("DOWN ");
  else if (VAL == 6)
    Lcd_Out_CP("UP   ");
  else
    Lcd_Out_CP("error");

  // check for tap detect
  // single tap = (a tap is detected in the current I2C read) && (no tap was detected during the last I2C read || a double tap was detected during the previous read )
  // double tap = a tap is detected in the current read && a single tap was detected in the last I2C read 
  Lcd_Cmd(l2c13);
  if (TILT.f5)
  {
    if (!tap)
    {
      tap = 1;
      Lcd_Chr_CP('1');
    }
    else
    {
      tap = 0;
      Lcd_Chr_CP('2');
    }
  }
  else
  {
    Lcd_Chr_CP('-');
    tap = 0;
  }
} // void ACCread()


// Splash screen and permanent text on LCD
void DispIniText()
{
  Lcd_Cmd(_LCD_CLEAR);               // Clear display
  Lcd_Cmd(_LCD_CURSOR_OFF);          // Cursor off

  // splash screen upon power up
  Lcd_Out(1, 1, "FreescaleMMA7660");
  Lcd_Out(2, 2, "Accelerometer");
  Delay_ms(3000);
  Lcd_Cmd(_LCD_CLEAR);               // Clear display

  // Text that will always remain on screen
  Lcd_Out(1, 1, "X=");
  Lcd_Out(1, 7, "Y=");
  Lcd_Chr(1, 13, 'Z');
  Lcd_Out(2, 14, "TAP");
}


// ************************************************************************************************
//       other functions
// ************************************************************************************************

void IniReg()
{
  // set internal clock frequency to 4MHz
  OSCCON = 0b1101000;

  TRISA = output;
  TRISB = output;
  TRISC = output;
  ANSELA = digital;
  ANSELB = digital;
  ANSELC = digital;
  PORTA = 0;
  PORTB = 0;
  PORTC = 0;

  TRISB.f7 = input;
  IOCBP.IOCBP7 = 1;
  IOCBF = 0;

  // Timer 1
  TMR1L = 0;
  TMR1H = t1h_ini;
  PIR1.TMR1IF = 0;
  T1CON = 0b110001;          // prescale = 1:8, timer1 clock = Fosc/4, timer1 oscillator off, timer1 on

  // Timer2 is used for state machine and switch debouncing timing tick
  // with clock = 2MHz, PR2 = 125, prescale = 1:16, postscale = 1:1
  // TMR2 will count from zero to PR2 and timer2 interrupt occurs every 125*16 / (2MHz / 4) = 4ms = timer2 tick
//  T2CON = 0b110;             // postscaler = 1:1, prescaler = 1:16, timer2 on
//  TMR2 = 0;
//  PR2 = 125;

  WDTCON = 0b1000;           // prescale = 1:512 (16ms typical)
                             // WDTE in configuration word is configured so that WDT enabled when MCU awake and disabled when MCU asleep

  tap = 0;
} // void IniReg()


// ************************************************************************************************
//       main
// ************************************************************************************************

void main()
{
  IniReg();
  Lcd_Init();
  DispIniText();
  ACCini();
  while(1)
  {
    if (PIR1.TMR1IF)
    {
      TMR1H = t1h_ini;
      ACCread();
      PIR1.TMR1IF = 0;
    }
  }
} // void main()

Thursday, March 1, 2012

TNG traffic light - epilogue

Each of the two LED boards on top of the signal tower traffic light are joined to the "platform board" via 9 solder joints. I certainly would not rely on them to hold the boards together nor am I deluded enough to think the corners of the boards won't chip off when the kids start playing with the toy and quite predictably knock it over ... and over. Those boards simply aren't going to survive this school of--literally--hard knocks. So as was planned I've potted the copper side of the boards with clear epoxy. Not only will the plastic make the whole three-board structure rigid and strong, the epoxy will also seal the copper tracks, solder connections and component leads and protect them from corrosion as well as minimize if not prevent possible injury to the kids if they go about running their fingers on the LED pins.

The two sort of cream colored rings are more than conspicuous. For aesthetic reasons I actually would rather not have them except that they're absolutely necessary to soften the impact of any falls. Without them the canister and its cap and maybe even the colored acrylic(?) lenses will surely crack/break/shatter. The rings are made of soft rubber tubing (silicone I think) with an outer diameter of 10mm. To build and install the rings I first cut one piece equal to the circumference of the canister--50mm. I then glued the ends with cyanoacrylate superglue. After letting the glue set for a couple of minutes I coated the sides of the canister where the ring will be positioned with superglue. I slipped the ring on the canister and pressed the ring inwards to make sure there's good contact between the ring and canister. After it was securely bonded, I coated the top portion of that ring with superglue and placed the second ring on top of it. Hence, the upper ring is bonded only to the lower ring, not to the canister. This way I can push that top ring down when the canister cap has to be screwed off. The rings have to be as close to the cap as possible to make sure the face of the 7-segment LED does not hit the ground when the tower tips over. 





I've tested the light with power on and knocked it down a couple of times and for now at least it can take a lickin' but keeps on tickin.

Just a couple of facts I failed to mention in the previous blog entry.

The green/ed on-time can be changed any time--in any mode. However, after doing so the light will immediately enter normal traffic light mode.

You'll notice the 5-pin header around the center of the main board. That's for the ICSP connection to a PICkit 2 or 3. I foresee the kids wanting some changes to how the light works--a max green/red on-time of 90 seconds perhaps, or different non numeric characters when the amber/red lights are flashing. The ICSP connection will make firmware updates a breeze. I've actually used it already. The firmware I initially uploaded to the MCU (whilst on the breadboard) had a tiny bug--upon power-up the bulbs aren't all off and so--since the circuit defaults to a flashing amber upon turn-on--either or both the red and green lights are also on. Fail! After inserting a call to the function turning all bulbs off, I used the PICkit 2's Programmer-To-Go feature by uploading the firmware to the PICkit 2 and then plugging it into the board's ICSP headers and pressing the PICkit's red button to upload to the MCU. Note the board has to be powered up when uploading.

While breadboarding the circuit I discovered that the resistors pulling the bases of the PNPs to the 12VDC supply were actually unnecessary. The LED display works fine without them. But I retained them anyway just to make sure the transistor bases aren't floating.