Category Archives: Technology

Technology and Engineering

LED Christmas Tree 328

Strange things happen during a pandemic shutdown. For some reason, being stuck inside, I got the urge to prepare Christmas gifts for my friends and relatives. I have built LED Christmas Trees for many years from kits and original designs. Here is the latest revision for 2020.

LED Christmas Tree
Finished Tree

General Description

As shown in photo above the LED Christmas Tree consists of a green printed circuit board in the outline shape of a tree decorated with 16 LEDs. A microphone responds to ambient sound to effectively clock a microcontroller (MCU) executing different LED sequence patterns. The unit is powered by a 6VDC, 600mA AC adaptor (wall wart). Overall Dimensions: 6″Hx4″Wx2″D

Features

The ATmega328P microcontroller (MCU) in a 28L DIP package controls the LED action. The Arduino Uno uses this same MCU and indeed the firmware was developed in the Arduino environment.

  • An Electret Microphone connects to the MCU Analog Comparator (AIN0/AIN1) to detect sound and animate the LEDs.
  • A 16 bit Linear Feedback Shift Register (LFSR) creates a Maximal Length Pseudo Random Bit Stream (PRBS) dynamic LED sequence. This produces an eye-catching pattern as the bits shift in order around the 16 LEDs.
  • If no sound is detected for 30 seconds all the LEDs turn off and the Tree enters a low-power stealth mode, ready to resume execution at the next sonic vibration.
  • All through-hole component technology makes or easy assembly. Socketed integrated circuits enable firmware updates. Unit cost is $40-60 depending on quantities.

Hardware

The ATmega328P microcontroller (MCU) in a 28L DIP package controls the LED action. The Arduino Uno uses this same MCU and indeed the software was developed in the Arduino environment.

The Printed Circuit board was manufactured by ExpressPCB and designed using their FREE CAD tools. I used my home shop band saw with a fine toothed blade to cut out the Tree profile.

Microphone Circuit

As shown in the diagram below the electret microphone output is capacitively coupled to a linear op-amp IC (LM358). An LM358 op-amp is biased with 5K ohm resistors producing a voltage gain of 2x, so it mainly functions as an impedance buffer. But this is enough signal to trip the Analog Comparator (AIN0,AIN1). The circuit is shown below.

Microphone Circuit
Electret Microphone Interface Circuit

Firmware Sketch

This sketch is short and very simple, only 1900 bytes are flashed (about 4% of available program and variable space). All the LED dynamics are driven by two Interrupt Service Routines (Analog Comparator and Timer1).

Software Functional Block Diagram

Each time an Analog Interrupt occurs an interrupt counter is incremented. This value, depending on the range, decides which sequence subroutine to execute. The sequence subroutine operates like a Finite State Machine where each call advances the sequence by one clock tick. The LFSR sequence is generated algorithmically but other patterns are defined by a multi-dimensional array. The first dimension defines the sequence step while the second dimension lists the LEDs to turn off and on. A multi-dimensional array allows the programmer to create any LED sequence, in a straight forward manner, limited only by your imagination and MCU memory size.

Timer1 is the MCU’s only 16 bit timer (max. value is 65535 counts). When a timeout occurs all the LEDs are turned off. In order to achieve a 30 second timeout delay, the CPU clock was divided by 16 making the internal CPU clock frequency 1MHz. To avoid premature timeout Timer1 is reset every time an Analog Comparator interrupt occurs.

The sketch includes 5 canned LED sequences and debug compile options for using the Arduino Serial Monitor. Many debug problems required stand-alone, real-time operation without the Serial Monitor.

LFSR

A Linear Feedback Shift Register (LFSR) is a logic configuration often applied in cryptography and authentication, random number generation, logic testing, communications coding, decoding and error correction.

There are 2 main LFSR configurations. In Fibonacci LFSRs, 2 or more Q outputs are Xor’d (logic exclusive OR) to generate feedback (externally) to the first input stage (D0). The other type, named after Evariste Galois, inserts Xor’d feedback (internally) between the D-flop stages.

By taping different output stages for feedback we can create different sequences with different run lengths. With proper choice of feedback stages we can create a Maximal Length Sequence with a run length of 2^n -1 combinations.

Example: 4 bit LFSR

With feedback taps chosen from Q0, Q3, this 4 bit LFSR generates a Maximal Length PRBS of 15 combinations (2^4 – 1).

4 bit LFSR
4 Bit LFSR for PRBS
tD0D1D2D3feedback
011110
101111
210110
301011
410101
511010
601100
700111
810010
901000
1000100
1100010
1210001
1311001
1411101
151111Repeat
160111Repeat
Maximal Length 4-bit LFSR State List

If we count the number of consecutive 1’s and 0’s we find that 1/2 are 1 bit, one-quarter are 2 bits, one-eight are 3 bits etc. up to 1/(2^n) are n bits wide. Thus the distribution nearly equals the statistical expectation value for a truly random distribution.  This type of analysis is shown for our 4 bit LFSR in the Table 2 below. Some difference between Actual versus Ideal Probability Expectation is noted, however for wider LFSRs, with more states, these Expectation values are very close. This is what gives a PRBS its pseudo random quality.

width=
length
4
15
bits
combos.
Random
Prob. Expectation
 
Bit PatternRun Len.#Occur.ActualIdeal
‘b1120.250.25
‘b11210.1250.125
‘b111310.1250.0625
‘b11114000.0625
‘b0120.250.25
‘b00210.1250.125
‘b0003000.0625
‘b0000410.1250.0625
A 4-bit LFSR Statistical Expectation

Stream Cipher

Suppose we want to encrypt the message ‘HI’ which is ASCII Capital ‘H’ (‘b0100 1000) and ASCII Capital  ‘I’ (‘b0100 1001). This makes our Plaintext = ‘b0100100001001001.

Select a 16 bit Key from Table 1, e.g. column D0 from t = 2  to 16 i.e. Key = ‘b1011001000111101. To encode the message, Xor each bit of Plaintext with the corresponding bit of Key. Remember that Xor is like binary addition (without the carry bit).

Encrypt (Encode)

Generate Ciphertext by Xor’ng Key with Plaintext

t0123456789101112131415
Key1011001000111101
Plaintext0100100001001001
Ciphertext1111101001110100

Decrypt (Decode)

Restore Plaintext by Xor’ng original Key with Ciphertext

t0123456789101112131415
Key1011001000111101
Ciphertext1111101001110100
Plaintext0100100001001001

Of course this is a trivial example (so you can follow along). If the key (initial state) were much wider, say 256 bits, the number of possible keys would be 1E+77. If you tried cracking the cipher by guessing 100 trillion keys per second it would still take 2.5E+47 universe lifetimes to try every possible key. Chances of success are very low.

Assembly

To perform the necessary ATmega328P programming I modified an Arduino Uno by replacing the 28 lead MCU DIP (Dual Inline Package) with a narrow 28L ZIF (Zero Insertion Force) socket, and built the Adafruit 462 Standalone AVR ISP Programmer Shield Kit to program bootloaders into raw MCU ICs.

Programming Tools
MCU Programming Tools

Conclusion

This was a satisfying project because it created unique Christmas gifts for my relatives and friends. Children especially, enjoy the voice/audio interaction. No doubt my relatives will not be satisfied unless my next revision is controlled by a Smartphone App and automatically uploads data to the Cloud for real time ambient noise analysis. I kept one Tree for myself to set on my piano so I can entertain guests with a multi-media performance of Christmas Carols.

Programmers are invited to play with LED sequences, switching delays and add digital filters or other functionality.

Building this standalone MCU project extended my development skills in the Arduino environment. 10 Tree units were assembled with 100% yield.

development platform
Development Platform

References

COVID-19 Mortality Risk Given a Positive Diagnosis

Bayes Theorem for conditional probability is applied to Oregon Health Authority COVID-19 reports to calculate the probability of death (Mortality Risk) given a positive infection test result. This same statistical method is commonly used in cancer and pre-employment drug screening. Latest data is available at OHA.

Executive Summary

As of 5/16/20, In Oregon’s population of cases attributed to COVID-19 infection, the probability of death for those testing positive is estimated to be 1.67%. Strangely, more COVID-19 dead patients test negative (78) than positive (59). Also, the probability of false positive (3.77%) is relatively high compared to false negative (0.08%). This begs the question, are so many false positive deaths really due to the virus?

Bayesian Definitions

Empirical Data

Scarce testing resources may not accurately sample asymptomatic infections, in which case the mortality risk here is exaggerated.

Joint Probability Distribution

Arduino PID Temperature Control

Arduino PID Temperature Control
Running PID Unit

Being a dedicated nerd, I’m always fascinated by Proportional Integral Derivative (PID) process control. So when a local farmer asked me to automate a vegetable canning process, I took it as a challenge to physically realize a PID temperature control device. Of course many fine industrial controllers already exist, say from Omega, but I’d already done that so I strived to do it smaller, cheaper. The Arduino product line provides inexpensive hardware for the home Maker. Also, the Arduino development environment is easy to install and remarkably easy to use. For this reason, I decided to build an Arduino PID Temperature Control unit.

Arduino PID Temperature Control
PID Temperature Sampling

About PID
The PID process control method is well researched and commonly applied in modern industry. PID mathematics can be complicated, but (within limits) PID can compensate for thermal resistance and thermal capacitance in a system for precise temperature control. Ideal PID temperature control assumes both a heating and cooling source (with same linear thermal forcing gain). This can be difficult to achieve practically due to different heat/cool technologies. Under-sampling temperature frequently will also increase errors. There are many ways to go wrong. Even when operating correctly, wild oscillations in temperature are possible. Nevertheless PID control can be adapted to many situations.

Many PID controllers claim to autotune the Kp, Ki, Kd PID coefficients to achieve optimal performance. But I suspect these methods are often home-grown and apply only to a narrow set of conditions. PID mathematics is very complicated. Fortunately there are practical manual methods and online simulations to aid in setting these important PID parameters.

For this controller, the PID proportional output uses Pulse Width Modulation(PWM) on 2 pins. Often PWM is used to create a (time-averaged) variable DC voltage, but here the digital signal duty-cycle modulates a SSR power cycle. One pin outputs the plus(+) and a second pin the minus(-) PID output. The PWM resolution for this microcontroller is 8 bits (0-255 values) for each pin.

Simplified Circuit Diagram
Simplified Circuit Diagram

Hardware
This PID controller device is composed of 3 sub-units (Arduino Uno R3, MAX6675 thermocouple temperature sensor, 1602 LCD keypad display).  An Arduino Nano and breadboard was used for testing purposes. Online cost for these units is about $11 + $5 + $4 = $20. Analog pins A1-A5 were converted to digital function for temperature sensor  power and communication. Fortunately this leaves digital pins 3, 11 (both on 16 bit TIMER2) to use for PWM modulation outputs.

Program Features
Using the LCD Keypad Display it would be possible to control every function but this is beyond the project’s scope. So the best way to experiment is through the Arduino IDE environment.

  • PID output range has units of degrees per sample period . It’s very important to set min/max PID limits for actual physical temperature forcing capability. For example, in a heat-only system the negative PID output is theoretically zero, or perhaps slightly negative (-2 degrees/minute maybe) for an ambient cooling system.
  • An over/under temperature Alarm is programmed to terminate execution immediately if min/max temperature limits are exceeded.
  • If either +/- PID output limit is reached an error is displayed on the LCD screen. While not fatal, this should be a clue that K coefficients may need adjusting.
  • The Arduino Serial Monitor tool displays PID data in progress
  • Commenting one line of code switches between PID simulation and live operation

SSR and PWM Problem
A Solid State Relay (SSR) is capable of switching on/off a 120V heavy load. But, like electromechanical relays, the switching speed is slow.  Because common, low-cost SSRs use a TRIAC Thyrister element, the power is not actually switched until the voltage phase of AC power crosses zero. The zero-crossing effect is shown in graphic below.

zero-crossing timing diagram
zero-crossing timing diagram

At a frequency of 60Hz the maximum delay is 1/2 cycle or 8.33ms. Considering that our PWM duty-cycle ranges from 0-255, a single bit of resolution at 8.33ms would imply a full range PWM switching period of 256 * 8.33ms = 2.133 sec. By selecting a PWM switching frequency, the control resolution is determined because the SSR only responds to higher order bits. See table below.

60Hz PWM Table
60Hz PWM Table

Because the ATmega328P master clock operates at 16MHz and the maximum TIMER2 divisor is 1024, the minimum PWM sampling frequency is ~30Hz yielding 4 levels of resolution control.  However if we further divide the ATmega328P master clock frequency by 8, then  PWM frequency is 3.75Hz with 5 bit (32 level resolution) is achieved.

Considering many practical applications, a sampling rate of ~4Hz with 5 bit resolution was an acceptable trade-off.  Implementing both TIMER2 pre-scalar 1024 and master clock divisor 8 is required to reach a PWM frequency of 16MHz/(1024*256*8*2) = 3.83 Hz. The master clock was divided in software with the clock_prescale_set(clock_div_8); instruction which of course has a similar affect on the delay(); instruction and delay values must be divided proportionally. The Arduino standard PID_v1 library was also edited for the same reason and a modified PID_v1R library is included in zip archive link below.

Testing
To debug and validate this design an Arduino Nano and breadboard was used with 2 LEDs, SSR and 60W incandescent light bulb. It was easy to see the LEDs flash at a slow rate (PWM cycle time) and the LED brightness change (PWM duty-cycle). The definitive test was using an SSR to switch a 120V resistive load (60W light bulb) and to my joy, flashing and variable brightness was observed. This was the extent of testing.

Arduino Nano Test Platform
Arduino Nano Test Platform

Discussion
This was a satisfying project because I learned a lot about PID and made a practical PID temperature control unit for very cheap ($20). Almost all the Arduino I/O pins are used and SSR-PWM problems were overcome to a reasonable degree. Adding a menu structure to edit run-time variables from the existing keypad would approach the functionality of a real commercial unit. Adding timer functions could create temperature profiles and recipes(EEPROM). Some practical applications might include a Rice Cooker, Slow Cooker, alcohol fermentation. Some day I’m going to turn the PID problem around and make a device that senses meat temperature and indicates the remaining cooking time. Mom’s Thanksgiving turkey will be cooked perfectly every time.

References
Arduino_PID_Temp_Control_Program.zip
Wikipedia PID
SSR Types

MongoDB C100DBA Exam Study Guide

mongodb_logo_300x100Today I completed my MongoDB C100DBA database administration certificate exam. This proctored exam is taken remotely online through Examity. The exam session duration was 90 minutes which consisted of 60 multiple choice and all-that-apply questions. The way I study is to condense a summary of my knowledge into a single document. Just the act of writing coherent paragraphs about a subject aids in my memory and understanding. For this purpose I prepared MongoDB_C100DBA_Exam_Study_Guide

This study guide expands on topics referenced in MongoDB’s own C100DBA study guide, and the MongoDB online documentation. My exam was related to database v3.2.  I passed my exam and my certificate license is #295-0761-259.

In my opinion, the exam is rather difficult, requiring deeper knowledge and practical experience than what is nominally presented in M102, M202 online courses. Of course the good student will expand on these introductory courses and establish a working platform to explore the syntax, properties and exceptions of CRUD, indexes, replication, sharding, administration etc. of various possible test cases.

This guide is especially recommended for M102 students to find condensed detail notes and documentation links on this subject.

In PDF format, 35 pages. A_MongoDB_DBA_Exam_Study_Guide

$20 VHF 50 Ohm Dummy Load

As a HAM Radio enthusiast I like to think I can design, build and evaluate RF Antennas. To help me calibrate my SWR meter I decided to build a VHF 50 ohm dummy load. Naturally, an ideal dummy load  is purely resistive (no reactive component).

I visited my local Electronics Surplus Store to purchase a 50 Ohm, thin film Beryllium Oxide (BeO) resistive load. Ceramic wire-wound  resistors were cheaper but they react more like RF inductors. In general, BeO loads are rated for 3-20GHz and 5-200W, but of course we must never exceed the max rated temperature, 100C (?), so a Heatsink is required. My surplus shop also sold an SO-239 panel mount connector. This is a common VHF/UHF (0-300MHz) connector used in radio communications. Resistor, connector and heatsink component cost was about $15.

VHF Dummy Load
Front View note: SO-239 Connector

The heatsink is resourced from an SSR (Solid State Relay). SSRs are rated for 40W continuous. Be careful. Watch the temperature! A nearby fan may marginally cool. A flexible thermal pad is installed between resistor body and heatsink for better thermal contact.

Side View
Side View

To complete the ground circuit, 14 gauge multi-strand wire is soldered to  resistor coax shield and PCB (and SO-239 connector shield). Luckily the resistor shield was not Aluminum.

back
Ground Connection

I tested this with my 75W 2 meter ham radio rig. Works well but at full power it gets hot in a few seconds. I’ll use this load to calibrate my SWR meter readings.

Load50-SWR
SWR ranges from 1.0 to 1.3 at 300MHz max freq.

Using a Network Analyzer, I gathered performance data over the frequency range of 0 – 300 MHz. Above is shown Standing Wave Ratio plot. SWR ranges from 1.0 (ideal) to 1.3 (good) at max frequency.

Smith Chart
Impedance barely deviates from 50 ideal resistor over frequency range

Smith Chart above shows that the load impedance (blue curly-q) is close to ideal 50 ohm resistance over the frequency range.

Load50_TDR_553In this Time Domain Reflectometry (TDR) plot  the grossly soldered connector is obvious as it ranges from 30 to 80 ohms near the connector. Nevertheless the performance at lower frequency is OK.

Canning Appliance

Recently I toured a farm’s harvest processing facilities and mentioned to the farmer that I thought I could automate one of his processes. He challenged me to build such an appliance, so I did.

Using a commercial 1500W hotplate and an Omega temperature controller I fabricated the appliance shown below. A Solid State Relay (SSR) switches power to the hotplate to modulate temperature. The controller operates in four modes (temperature display, constant temperature and ramp/soak program, PID). Since the hot plate operates only in on/off mode I couldn’t use the PID (Proportional Integral Differential) mode.

Front view testing
Front view testing

 

 

 

 

 

 

Top View
Top View

 

 

 

 

 

 

More Testing
More Testing

 

 

 

 

 

 

 

 

Wiring in Bottom
Wiring in Bottom

 

 

 

 

 

 

After using my canning appliance, the happy farmer reported that he was able to control temperature within a +/- 3F range. And this resulted in shortened process times and more uniform product.

Download Design Docs in PDF Format