Silicon ChipThe USB Flexitimer: accurately timed switching - June 2018 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: I, for one, welcome our new farm robot overlords
  4. Feature: AgBots – robots working on the farm of tomorrow! by Dr David Maddison
  5. Project: The USB Flexitimer: accurately timed switching by John Clarke and Nicholas Vinen
  6. Project: Wide-range digital LC Meter by Tim Blythman
  7. PartShop
  8. Project: Switch on or off anything with a Temperature Switch by John Clarke
  9. Subscriptions
  10. Serviceman's Log: Repairing ‘proper’ stereo gear is satisfying by Dave Thompson
  11. Project: 800W (+) Uninterruptible Power Supply (UPS) Part II by Duraid Madina and Tim Blythman
  12. Review: Degen’s wind-up or solar-powered AM/FM/SW radio by Ross Tester
  13. Feature: El Cheapo Modules 17: 4GHz digital attenuator by Jim Rowe
  14. PartShop
  15. Vintage Radio: 1952 Astor GP/PS Hybrid Portable by Associate Professor Graham Parslow
  16. Product Showcase
  17. Market Centre
  18. Advertising Index
  19. Notes & Errata: 6GHz+ Touchscreen Frequency Counter / 800W+ Uninterruptible Power Supply / Deluxe Frequency Switch / USB Port Protector
  20. Outer Back Cover

This is only a preview of the June 2018 issue of Silicon Chip.

You can view 38 of the 104 pages in the full issue, including the advertisments.

For full access, purchase the issue for $10.00 or subscribe for access to the latest issues.

Articles in this series:
  • AgBots – robots working on the farm of tomorrow! (June 2018)
  • The farm of the future . . . Part II (July 2018)
Items relevant to "The USB Flexitimer: accurately timed switching":
  • USB Flexitimer PCB [19106181] (AUD $7.50)
  • PIC16F1455-I/P programmed for the USB Flexitimer [1910618A.HEX] (Programmed Microcontroller, AUD $10.00)
  • Firmware (C and HEX) files for the USB Flexitimer [1910618A.HEX] (Software, Free)
  • USB Flexitimer PCB pattern (PDF download) [19106181] (Free)
Items relevant to "Wide-range digital LC Meter":
  • Wide-range digital LC Meter PCB with stackable headers [04106181] (AUD $7.50)
  • Wide-range digital LC Meter PCB [04106181] (AUD $5.00)
  • Pair of PCB-mounting right-angle banana sockets (red/black) (Component, AUD $6.00)
  • 1nF ±1% polypropylene (MKP) or C0G/NP0 ceramic capacitor (Component, AUD $2.50)
  • 20x4 Alphanumeric serial (I²C) LCD module with blue backlight (Component, AUD $15.00)
  • Case pieces for the Wide-range Digital LC Meter (PCB, AUD $7.50)
  • Arduino Sketch (.ino) and libraries for the Wide-Range Digital LC Meter (Software, Free)
  • Wide-range digital LC Meter PCB pattern (PDF download) [04106181] (Free)
Items relevant to "Switch on or off anything with a Temperature Switch":
  • Temperature Switch Mk2 PCB [05105181] (AUD $7.50)
  • PIC12F617-I/P programmed for the Temperature Switch Mk2 [0510518A.HEX] (Programmed Microcontroller, AUD $10.00)
  • Firmware (ASM and HEX) files for the Temperature Switch Mk2 [0510518A.HEX] (Software, Free)
  • Temperature Switch Mk2 PCB pattern (PDF download) [05105181] (Free)
Items relevant to "800W (+) Uninterruptible Power Supply (UPS) Part II":
  • 800W+ Uninterruptible Power Supply control shield PCB [11106181] (AUD $5.00)
  • Arduino Sketches (.ino) and library for the 800W+ Uninterruptable Power Supply (Software, Free)
  • 800W+ Uninterruptible Power Supply control shield PCB pattern (PDF download) [11106181] (Free)
  • 800W+ Uninterruptible Power Supply front panel artwork (PDF download) (Free)
Articles in this series:
  • 800W (+) Uninterruptible Power Supply (UPS) (May 2018)
  • 800W (+) Uninterruptible Power Supply (UPS) Part II (June 2018)
  • 800W (+) Uninterruptible Power Supply (UPS) Part III (July 2018)
Articles in this series:
  • El Cheapo Modules From Asia - Part 1 (October 2016)
  • El Cheapo Modules From Asia - Part 2 (December 2016)
  • El Cheapo Modules From Asia - Part 3 (January 2017)
  • El Cheapo Modules from Asia - Part 4 (February 2017)
  • El Cheapo Modules, Part 5: LCD module with I²C (March 2017)
  • El Cheapo Modules, Part 6: Direct Digital Synthesiser (April 2017)
  • El Cheapo Modules, Part 7: LED Matrix displays (June 2017)
  • El Cheapo Modules: Li-ion & LiPo Chargers (August 2017)
  • El Cheapo modules Part 9: AD9850 DDS module (September 2017)
  • El Cheapo Modules Part 10: GPS receivers (October 2017)
  • El Cheapo Modules 11: Pressure/Temperature Sensors (December 2017)
  • El Cheapo Modules 12: 2.4GHz Wireless Data Modules (January 2018)
  • El Cheapo Modules 13: sensing motion and moisture (February 2018)
  • El Cheapo Modules 14: Logarithmic RF Detector (March 2018)
  • El Cheapo Modules 16: 35-4400MHz frequency generator (May 2018)
  • El Cheapo Modules 17: 4GHz digital attenuator (June 2018)
  • El Cheapo: 500MHz frequency counter and preamp (July 2018)
  • El Cheapo modules Part 19 – Arduino NFC Shield (September 2018)
  • El cheapo modules, part 20: two tiny compass modules (November 2018)
  • El cheapo modules, part 21: stamp-sized audio player (December 2018)
  • El Cheapo Modules 22: Stepper Motor Drivers (February 2019)
  • El Cheapo Modules 23: Galvanic Skin Response (March 2019)
  • El Cheapo Modules: Class D amplifier modules (May 2019)
  • El Cheapo Modules: Long Range (LoRa) Transceivers (June 2019)
  • El Cheapo Modules: AD584 Precision Voltage References (July 2019)
  • Three I-O Expanders to give you more control! (November 2019)
  • El Cheapo modules: “Intelligent” 8x8 RGB LED Matrix (January 2020)
  • El Cheapo modules: 8-channel USB Logic Analyser (February 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules (May 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules, Part 2 (June 2020)
  • El Cheapo Modules: Mini Digital Volt/Amp Panel Meters (December 2020)
  • El Cheapo Modules: Mini Digital AC Panel Meters (January 2021)
  • El Cheapo Modules: LCR-T4 Digital Multi-Tester (February 2021)
  • El Cheapo Modules: USB-PD chargers (July 2021)
  • El Cheapo Modules: USB-PD Triggers (August 2021)
  • El Cheapo Modules: 3.8GHz Digital Attenuator (October 2021)
  • El Cheapo Modules: 6GHz Digital Attenuator (November 2021)
  • El Cheapo Modules: 35MHz-4.4GHz Signal Generator (December 2021)
  • El Cheapo Modules: LTDZ Spectrum Analyser (January 2022)
  • Low-noise HF-UHF Amplifiers (February 2022)
  • A Gesture Recognition Module (March 2022)
  • Air Quality Sensors (May 2022)
  • MOS Air Quality Sensors (June 2022)
  • PAS CO2 Air Quality Sensor (July 2022)
  • Particulate Matter (PM) Sensors (November 2022)
  • Heart Rate Sensor Module (February 2023)
  • UVM-30A UV Light Sensor (May 2023)
  • VL6180X Rangefinding Module (July 2023)
  • pH Meter Module (September 2023)
  • 1.3in Monochrome OLED Display (October 2023)
  • 16-bit precision 4-input ADC (November 2023)
  • 1-24V USB Power Supply (October 2024)
  • 14-segment, 4-digit LED Display Modules (November 2024)
  • 0.91-inch OLED Screen (November 2024)
  • The Quason VL6180X laser rangefinder module (January 2025)
  • TCS230 Colour Sensor (January 2025)
  • Using Electronic Modules: 1-24V Adjustable USB Power Supply (February 2025)

Purchase a printed copy of this issue for $10.00.

By John Clarke and Nicholas Vinen USB   Flexitimer This very flexible timer can switch its relay at intervals from milliseconds up to many days. It can be triggered by an external pulse or set to run continuously, switching its relay on and off at a particular interval to turn an external device. It’s easy to build and you can set it up with two onboard trimpots or configure it with your laptop PC via its USB port. W e have published a number of Flexitimers over the years, the last one being a PIC-based unit described in June 2008. It was programmed with an array of jumper links which gave a lot of flexibility but it required some mental agility to get the timing intervals you wanted and it has now been discontinued. Our new Flexitimer also uses a PIC microcontroller but you can program its various time intervals with two onboard trimpots or with your laptop PC via the USB port. That makes it easy to set precise intervals and allows those intervals to vary over a very 24 Silicon Chip wide range, from milliseconds to days. Timers like this one are popular because they can be used in so many different situations. For example, they can be used to switch on a light or a fan for a fixed period with the single press of a button. Or it can be used to switch power on to a device periodically, eg, open a solenoid valve for a minute every hour or power up a radio transmitter for a few minutes now and then. It’s also suitable for automotive uses, for example, as a turbo timer, to keep the engine run- Celebrating 30 Years ning for a few minutes after you switch the ignition off, allowing the turbo to cool down. In fact, we won’t even try to think of all the different uses you could put it to because there are simply too many to list. It has an onboard DPDT relay, with 5A-rated contacts, which is switched on and off at the programmed intervals. It can run in a continuous loop, switching on and off at pre-defined intervals, or it can be triggered by an external switch, relay or digital signal. There are various options to control how long the relay remains on when it’s triggered externally. siliconchip.com.au Previous Flexitimers: Flexitimer by Rob Evans – Electronics Australia, March 1991 Flexitimer Mk2 by Rob Evans – Electronics Australia, August and September 1995 Flexitimer Mk3 by Jim Rowe – SILICON CHIP, August 2005 (siliconchip.com.au/Article/3145) PIC-based Flexitimer Mk4 by Jim Rowe – SILICON CHIP, June 2008 (siliconchip.com.au/Article/1847) These are detailed below. The two trimpots are optional and if fitted, you can use them to adjust the time periods without needing a computer. The functions and ranges of both potentiometers are configurable via the USB interface. You can leave them off the board if you prefer to use the USB interface to change the timings. While we’ve tried to make the unit easy to set up, we also wanted to make it truly flexible so that it can be used in the widest possible range of applications. So it has quite a few different options which should allow you to set it up to suit virtually any circumstance. But you don’t have to use them all; you can keep the settings simple if that suits you. This is actually the fifth iteration of the Flexitimer – the first one was published in the March 1991 issue of Electronics Australia, with the most recent being the Flexitimer Mk.4, as noted above, published in the June 2008 issue. (See the panel above for a list of all the previous Flexitimer projects.) This one is better in just about every way, having a wider range of time settings, better accuracy, easier set-up and much more flexible options. It uses a similar number of components and is around the same size. The power consumption of the new unit is lower, especially when the relay is not energised and it includes extra indicator LEDs. Circuit description As shown in Fig.1, the circuit is based around PIC16F1455 microcontroller IC1 which has a built-in USB interface for programming it. It also has an internal analog-to-digital converter (ADC) to sense the position of the optional trimpots, VR1 and VR2, which can be used to adjust the timings. The USB D+ and D- data pins (pins 13 & 12) are connected directly to the USB socket, CON4. The USB +5V rail siliconchip.com.au is connected to the micro’s 5V supply rail via 1N4148 diode D3, allowing the unit to be powered by the connected computer for set-up and testing. D3 prevents current being fed back into the USB port if power is simultaneously applied to CON1. The coil of DPDT relay RLY1 is driven by NPN transistor Q2 which in turn is driven by the micro’s RC0 digital output (pin 10) via a 1kΩ current-limiting resistor. When pin 10 goes high, the relay is energised and the pairs of COM and NO terminals on CON3 are connected together. When pin 10 is low, the relay is deenergised and the COM and NC terminals are connected instead. When the relay is de-energised, the collapsing magnetic field in its coil causes a voltage to be induced across it and this is fed back into the 11.4V supply rail by diode D2, protecting Q2. LED4 is connected in parallel with the relay coil, along with a 10kΩ resistor and indicates when it is energised. The trigger input at CON2 drives the base of NPN transistor Q1 via a 2:1 voltage divider comprising two 10kΩ resistors. The first 10kΩ resistor limits the base current of Q1 to a safe level while the second one acts as a pulldown, keeping it switched off if no voltage is applied at CON2. Q1’s collector is pulled up to the +5V rail via a 10kΩ resistor, so it operates as an inverter – when the voltage at the trigger input is above 1.6V, input pin RC2 (pin 8) of IC1 is pulled low and when the trigger input is below 1.0V, pin 8 is high. The software compensates for this inversion. A 100nF capacitor from pin 8 to ground prevents any brief spikes or glitches at the trigger input from being detected as a trigger event. It has a time constant of around 1ms in combination with the 10kΩ pull-up resistor. A further trigger delay can be configured in the software, as described below. The 10kΩ resistor from pin 6 (digital output RC4) to the trigger input at CON2 gives the option of pulling the trigger input high, to +5V when it is not driven. This allows you to connect a relay or switch across CON2 and when it closes, it will pull the input low. If the input is being actively driven high/low then it will trigger the unit regardless of the state output pin 6 but setting it low will save a little bit of power. On the other hand, if you have a trigger source which actively pulls the input high but does not actively pull it low, you would need to switch Features & specifications • Function: monostable or astable timer controlling a DPDT relay • Timing period: on and off times programmable from 100ms to 50 days • Timing adjustment: programmed over USB or using two trimpots (optional) • Timing accuracy: typically ±0.25% • Relay contact ratings: 30V DC/AC at up to 5A (8A with the Altronics relay) • Trigger input: digital input (<1V low, >1.6V high) with pull-down or pull-up • Trigger modes: trigger on high level, low level, rising edge, falling edge or state change with option to reset timer on re-trigger • Power supply: 12-15V DC; 2mA with relay off, 45mA with relay on (or USB 5V for setup and testing) • Indicator LEDs: four LEDs including power and relay state; two have adjustable time-outs • Trigger delay: optional, can be set with 1ms resolution, min/max option Celebrating 30 Years June 2018  25 Fig.1: the heart of the USB Flexitimer is microcontroller IC1 and it is programmed by a computer connected using USB port CON4 or using trimpots VR1 and VR2. Transistor Q1 provides signal conditioning for the trigger input while transistor Q2 drives the coil of RLY1. the pull-up off for it to work properly. That can be done via the USB interface. Trimpots VR1 and VR2 are connected across the 5V supply rail so that their wipers sweep over a 0-5V range and they can be monitored at TP1 and TP2. These voltages are filtered by a 100nF capacitors (to keep the source impedance low, for maximum ADC accuracy) and then applied to analog inputs AN7/AN3 of IC1 (pins 7 and 3). By default, trimpot VR1 adjusts the on time over a range of 1-60 seconds and VR2 the off time over a range from zero to 60 seconds. You can use the USB interface to change this. You can set the minimum and maximum time for each trimpot and you can also set them to control different parameters such as the trigger delay, rather than the on and off times. The various options will be described later. The power supply is quite simple but designed to be rugged for vehicular use. The 12-15V DC supply is applied to CON1 and passes through reverse polarity protection diode D1. The re26 Silicon Chip sulting 11.4V (nominal) supply is filtered by a 100F capacitor and fed directly to the coil of relay RLY1. This supply rail is then further filtered by a 47Ω series resistor and 10F capacitor and spikes are clamped by 16V zener diode ZD1. This filtered supply then feeds low quiescent current 5V regulator REG1 which supplies microcontroller IC1. LED1, the power indicator, is connected across the 5V rail with a 3.3kΩ current limiting resistor, giving an operating current of around 1mA. There is a 10F filter capacitor on the 5V rail and a 100nF bypass capacitor close to IC1, while IC1 also has a 10kΩ pull-up resistor for its MCLR reset input so that it is reset at power-up and then operates continuously. LEDs 2 & 3 are driven from outputs RA5 (pin 2) and RC5 (pin 5) of IC1, with 3.3kΩ current-limiting resistors, giving them a similar brightness to LED1 and LED4. These can be set up so that they are lit for a limited time period after the relay switches, to save power, as described below. Celebrating 30 Years Basic operation Fundamentally, the USB Flexitimer operates as follows. Initially, it waits for the trigger condition to be met, eg, for the trigger input to go high or low. There are five different trigger options as described in the options panel. There is also an optional trigger delay. If enabled, the input must remain stable in this condition for that period to trigger the timer. Once triggered, the relay is energised and the timer runs for the specified on time. The relay is then deenergised and the timer runs for the specified off time. Once the off time expires, it will go back into the initial state, waiting for a trigger event at the input. By default, with nothing connected to CON2, the timer will run continuously, switching the relay on and off in a pattern. This is because (also by default) pin6 is held high and the trigger condition is a high level at CON2. Thus the timer is automatically triggered at the start of the process. Note that the relay is not energised siliconchip.com.au Parts list – USB Flexitimer Fig.2: use this PCB overlay diagram as a guide for building the Flexitimer. The USB socket CON4 is the only surface-mounting device. IC1, D1-D4, VR1, VR2 and the electrolytic capacitors are polarised and must be installed as shown here. It can be fitted into a USB plastic Jiffy box or mounted in any other suitably sized enclosure. during the off time and for the trigger delay time, so if you need a precise offtime and have a trigger delay time, you should subtract the delay time from the off time that you set. Construction The USB Flexitimer is built on a double-sided PCB coded 19106181 and measuring 104 x 58.5mm. This can be installed in a standard UB3 Jiffy box or any other enclosure with suitable internal dimensions. Use the PCB overlay diagram, Fig.2, and photo as a guide while fitting the components. Pre-programmed microcontrollers are available from the SILICON CHIP Online Shop or you can program one yourself, if you have a suitable programming device, using the HEX file downloaded from www.siliconchip. com.au Start by mounting the micro USB socket. Apply some flux paste to the five small pads and the two larger mounting pads. Place the part on the board, ensuring the two small plastic posts go into the corresponding holes in the PCB. Check that the five small signal pins line up with their matching pads and then solder one of the side mounting tabs to the board. Now re-check the alignment of the signal pins. If it’s off, re-melt that solder joint and nudge the part into it’s correct position. Then solder the five signal pins. It’s very difficult to avoid bridging them, so it’s easier to simply make sure all of them are soldered to the pads on the board and then apply some extra flux paste and use a piece of solder wick to remove the excess solder. Next, solder the second mounting tab so that the socket is held rigidly into place. 1 double-sided PCB, 104 x 58.5mm, coded 19106181 1 DPDT 12V DC coil relay (RLY1) [Jaycar SY-4052 (5A), Altronics S 4270A (8A)] 2 2-way terminal blocks, 5.08mm pin spacing (CON1,CON2) 2 3-way terminal blocks, 5.08mm pin spacing (CON3) 1 SMD micro USB socket (CON4) 1 14-pin DIL socket (optional, for IC1) 1 UB3 Jiffy box (optional) 4 short M3 tapped spacers and 8 short M3 machine screws (optional, for mounting in box) 2 cable glands (optional, for wiring when mounted in box) Semiconductors 1 PIC16F1455-I/P microcontroller programmed with 1910618A.hex (IC1) 1 LP2950ACZ-5.0 micropower linear 5V regulator (REG1) 1 BC547 NPN transistor (Q1) 1 BC337 NPN transistor (Q2) 1 3mm green high-brightness LED (LED1) 1 3mm blue LED (LED2) 1 3mm red high-brightness LED (LED3) 1 3mm yellow high-brightness LED (LED4) 1 16V 1W zener diode (ZD1) 2 1N4004 1A diodes (D1,D2) 1 1N4148 small signal diode (D3) Capacitors 1 100F 25V PC electrolytic 2 10F 16V PC electrolytic 1 1F 50V multi-layer ceramic or 63/100V MKT 5 100nF 63/100V MKT Resistors (all 0.25W, 1% metal film) 6 10kΩ 3 3.3kΩ 1 1kΩ 1 47Ω 2 10kΩ 25-turn vertical trimpots (VR1,VR2) This same-size photograph of the assembled PCB, in conjunction with the component overlay above, shows where each of the components goes. siliconchip.com.au Celebrating 30 Years You can then move on to the resistors. It’s best to check their values with a DMM before soldering them in place. Follow with the diodes. There are three different types so don’t get them mixed up and make sure the cathode stripes are orientated as shown in Fig.2. If using an IC socket, solder it in place now, ensuring that its notched end is orientated correctly. Otherwise, June 2018  27 mount IC1 directly to the board with the same orientation. Then install the 100nF and 1F capacitors, followed by transistors Q1 and Q2 and regulator REG1. The small capacitors are not polarised. You may need to bend the leads of the transistors out slightly to fit the PCB pad locations before fitting them. Don’t get the transistors and regulators mixed up as they are in similar packages. Next, fit terminal blocks CON1CON3. CON3 consists of two 3-way terminal blocks which are dovetailed together before soldering. In each case, make sure that the wire entry holes face the nearest edge of the PCB. If you are installing the optional trimpots (VR1 & VR2), do it now. Make sure you insert them into the PCB with the adjustment screw orientated as shown in Fig.2. Now fit the electrolytic capacitors, ensuring that their longer lead (+) goes into the pads marked positive on the PCB. The striped side of the can indicates the negative lead. You have the option of mounting LEDs1-4 right down on the PCB, as we have done on our prototype, or mounting them on longer leads so that they will protrude through the lid of the case. Alternatively, you can chassismount some or all of them and wire them to the board with flying leads. You can leave LED1 and/or LED4 off if you need to minimise current consumption. Regardless of how you mount the LEDs, make sure that their longer (anode) leads connect to the pads marked “A” on the PCB. Now push the relay down fully onto the PCB in the location provided and solder its pins. Finally, if you have fitted an IC sock- et for IC1, straighten its pins and insert it into the socket now, taking care that you don’t fold any of the leads under the package when doing so. Testing The easiest way to test the completed board is to plug it into a USB port on your computer using a standard type A to micro type B cable. LED1 should light up immediately and your computer should identify a new USB device. Most operating systems (including Windows 10) should not need a driver as it appears as a standard serial device. Note that the USB cable powers the PCB at this point. There is no need to connect a DC power supply. That step comes later. In Windows 10, you can verify that it is working by opening Device Manager and expanding the “Ports (COM & LPT)” section. It should appear as Software details You might think that the software for a timer would be simple. But due to the USB interface and the flexibility of this design, we were barely able to squeeze the required functions into the 14KB (8K words) of flash memory available. The firmware is written in the C language rather than assembly language for two reasons: one, it would have taken a lot longer to write in assembly language and two, the Microchip USB sample code is in C. It is converted to a HEX file using the Microchip XC8 compiler. The free version lacks full optimisations so you can’t use it to compile this code as the result will not fit in the available flash memory. The source code can be downloaded from the SILICON CHIP website if you are interested in how it works. To start with, we took the Microchip CDC (USB serial) sample program and stripped out all the parts we didn’t need. This resulted in a program that simply echoed back what you type into the terminal and that code already took up around 30% of the available flash memory. Given the number of “strings” (ie, sequences of characters) required for the command line interface in this project, we quickly realised that we would have to devise a custom method of storing these strings in flash. That’s because the default behaviour of the XC8 compiler is to store each character in one flash word (14 bits). So the ~1000 characters we ended up needing would take up 1K words, or 12.5% of the available flash. But since we’re not using accented characters, just basic ASCII, all our characters have codes in the range of 0-127. That means they will fit in 7 bits and hence, each 14-bit flash word could be used to store two characters, not one. So we wrote a little program that took a list of strings and packed it into 14-bit program words, then produced an ASM file to link in with the C file. We also needed two new routines, one to unpack the words and write the strings into a memory buffer (identified by their offset in the “blob”) and another to compare the packed 28 Silicon Chip words to the contents of a memory buffer, for parsing commands typed by the user. Overall, this freed up about 5% of the flash memory for extra code. And the program takes up over 99% of the flash so we certainly needed that breathing room. We also wrote our own functions to convert numbers to and from ASCII strings, also for the command line interface, as they turned out to be smaller than the equivalent C library functions (although we do make use of the “strtoul” built-in function, to convert a string to a 32-bit integer). Timing is based on the micro’s internal oscillator which runs at 12MHz and uses “active clock tuning”, to lock it to the USB host’s clock so that it meets USB timing specifications. This is used to increment a 16-bit variable in memory at 1ms intervals using the internal TIMER1 hardware with a pre-scaler value of 16 and pre-loading the TMR1 register with the value 64786, which causes the timer 1 roll-over interrupt to trigger 750 intervals later. 750 x 16 = 12,000, giving us our 1ms interval relative to the 12MHz system clock. This millisecond counter variable is then used by the logic in the main loop of the software to determine how long to wait and when to change the relay state based on the trigger input logic level. It also makes use of the configuration data, which is copied from the high-endurance area of flash memory to RAM at start-up. Much of the time spent developing this software consisted of finding ways to re-write code to take up less flash space. Many of these optimisations involved moving commonly used code sequences into functions to avoid them having to be stored in multiple locations in flash. But this didn’t always help since function call overhead on the PIC16 is fairly high. In fact, we found the results of the XC8 compiler to be somewhat unpredictable; one seemingly inconsequential change could result in a 15% increase or decrease in flash memory utilisation! So a lot of experimentation was required to find the best combination of code to achieve the desired result. Celebrating 30 Years siliconchip.com.au Configuration options There are six settings that control the operation of the timer. They are: the trigger condition, four timing values (with some extra options) and whether the input pull-up resistor is enabled. Each is explained below. The four timing values are: the on time, the off time, the trigger delay time and the indicator LED on-time. When reading the following explanation, keep in mind that the relay is energised while the main (on) timer is running and deenergised the rest of the time. Trigger conditions There are five possible input trigger conditions which will start the timer. These are when the input is a high level, low level, on a rising edge, on a falling edge or on either edge (input state change). The high level and rising edge settings operate in a very similar manner, as do the low level and falling edge settings. The difference is what happens after the timer has elapsed. If you have the input trigger condition set to high level and the input is still high after the timer has elapsed, it will start again. But if you have it set to rising edge, it will not. The input will have to go low and then high again to re-start the timer. It doesn’t matter whether it goes low during the on time and then high later, or low after the timer has expired and then high again; what matters is the low-to-high transition must occur after the timing period has expired. Similarly, in the input state change mode, the transition must occur after the timing period has finished to start a new one. Having said all that, there is a separate option to reset the timer if a trigger condition occurs during the timing period. If this is enabled and the trigger conditions are met during the timer period, it will start over. That option is explained below. The on time This controls how long the relay is energised. While the resolution is 1ms, the minimum practical value is around 100ms, given that the relay will take around 10ms to switch on and off. The maximum time is 1193 hours which works out to almost 50 days. Like the other time options, the on-time is set using a string which looks like one of the following: “1h15m23.572s” or “1500ms” or “75m”. If you specify an exact on time then each time the unit is triggered, the relay will be on for exactly that period. However, you can also specify it as a minimum or maximum on time. If specified as a maximum, the timer will be cancelled and the relay de-energised if the input changes state before the timer has expired. So the timing period will range from a few milliseconds up to the period specified. Conversely, if specified as a minimum, the relay will be energised for the time period specified and then, if the input has not changed state during that period, it will remain energised until the input does change state. So the timing period ranges from the time specified up to the length of the input trigger pulse. Finally, there is the option to make the on time “resettable”. This means that if the input trigger condition is met during the on time (including any delay, as described below), the timer starts again from zero. So if the input is repeatedly triggered, the on time will be extended each time. This does not make sense to specify with a maximum on time but it can be used in combination with an exact or minimum on time. Off time As soon as the timer expires or is cancelled, the relay is de-energised. You can set the off time to zero, in which case, as soon as the trigger conditions are met again, the timer will start again from zero and the relay will be re-energised. siliconchip.com.au However, if you specify a non-zero off time, then another timer is started and nothing will happen until it expires. You can use this to enforce a minimum time between the relay being de-energised and then re-energised. It’s also useful in a situation where you want the relay to be switched on and off at a particular interval or cadence. In this case, you can set the on time and the off time and arrange for the trigger condition to always be true. The relay will then continually switch on and off at the specified intervals. As with the on time, the off time can range from 1ms up to nearly 50 days but again, the minimum practical off time is around 100ms. Trigger delay time If the trigger delay time is set to zero then the timer will start and the relay will be energised as soon as the trigger conditions are met (either immediately after power-on or after the off time has elapsed). However, you can specify a non-zero trigger delay time, in which case the input level will need to be stable for this period before the timer will actually start, and the relay will remain de-energised during this time. You can also use this as a way to purposefully insert a delay between the trigger signal and the relay being energised. The range of the trigger delay time is the same as the other times, however, it would generally be a shorter period, from a few milliseconds to a few seconds. It’s also possible to have a fixed trigger delay period, which simply means that it doesn’t matter what the trigger input does during the delay period; as long as it initially met the trigger conditions, after the fixed delay, the relay will be energised. This would be useful, for example, if you want to trigger the timer with the push of a momentary pushbutton but have a delay between that button press and the relay switching. There’s also a third option for the trigger delay and that is to specify it as a maximum time. In this case, once the trigger condition has been met, the unit waits for the input to change state and if the period of this trigger pulse is less than or equal to the specified maximum, the on timer starts and the relay is energised. Otherwise, the trigger pulse is ignored. For example, if you were using a photo interrupter to trigger the unit, this would allow you to set it up to be triggered by fastmoving objects but not slow-moving ones. LED on time By default, LED2 lights while ever RLY1 is energised and LED3 lights while ever RLY1 is de-energised. However, you can specify a finite LED on time. In this case, LED2 lights as soon as RLY1 is energised and then switches off after the LED on time has elapsed. Similarly, LED3 lights as soon as RLY1 is de-energised, for the same time period. If running the USB Flexitimer off a battery, you may want to minimise its power consumption, in which case you could set the LED on time to be quite short and leave LED1 off entirely. In this case, its standby current will be around 1mA without VR1 and VR2, or 2mA if they are fitted. Celebrating 30 Years June 2018  29 Changing the configuration via USB With the unit plugged into your computer and the terminal emulator connected as per the testing instructions, you can issue the following commands (shown here in red) to change the unit’s configuration. Note that the changes will not be retained after power is switched off unless you issue a “save” command. Also, you need to press Enter/Return after typing a command and check that you get a positive response. set led timer <time> pull-up (on|off) Sets whether the input pull-up resistor is driven or not. For example:   pull-up on Sets how long LED2/LED3 stay on once the relay state changes. Instead of a time value, you can specify “infinite” so that they are continuously lit. For example:   set led timer 30s    Done.    Done. set trigger on (high|low|rising|falling|change) Issue this command to set the trigger condition to one of the five possibilities listed. For example: set led timer VR(1|2) <time> to <time>    set trigger on rising Sets the on time for LED2/LED3 to a variable value controlled by either VR1 or VR2, over the specified range. For example: set on time [min|max] [resettable] <time>    Done.    Done.    set led timer VR2 1s to 10s Sets the on time to a fixed value. The “min”, “max” and “resettable” keywords are optional and must be provided in that order (if using both). The time is specified as stated earlier, for example:    set on time min resettable      1h15m10.5s    Done.     set on time [min|max] [resettable] VR(1|2) <time> to <time> Sets the on time to a variable value controlled by either VR1 or VR2, over the specified range. For example:    set on time max VR1 1m to 1h    Done. set off time <time> set off time 30s    Done. set off time VR(1|2) <time> to <time> Sets the off time to a variable value controlled by either VR1 or VR2, over the specified range. For example:   set off time VR2 100ms to 1500ms    Done. set trigger delay [min|max|fixed] <time> Sets the trigger delay to a fixed value. If you don’t specify “min”, “max” or “fixed”, the default is “min”. For example: set trigger delay 25ms    Done. set trigger delay [min|max|fixed] VR(1|2) <time> to <time> Sets the trigger delay to a variable value controlled by either VR1 or VR2, over the specified range. For example: set trigger delay fixed VR1    10ms to 100ms 30 Silicon Chip Shows the unit’s current configuration, ie, that which it is actively using to control the relay. Includes any changes you have made since power was applied, even if they haven’t been saved yet. For example: show config     On when input is high for at least 50ms (pull-up on).     Stays on for 1s to 1m (VR1).     Off for: 0ms to 1m (VR2).     LED timer: infinite. show status Displays the current input state, whether the relay is energised, the current timer value, the positions of the trimpots and the corresponding time values. Can be helpful as a debugging aid if the unit is not doing what you expect. For example:    show status Sets the off time to a fixed value. For example:    Done. show [active] config   Input: high.   Relay: energised.    State: relay on for 31.226s/1m.    VR1 controls relay on-time (now 100% = 1m).    VR2 controls off-time (now 51% = 30.600s). show saved config Shows the unit’s stored configuration, ie, that which is loaded at power-up. Does not include any unsaved changes you have made. save Saves any changes made to the configuration into the EEPROM. They will, therefore, be applied each time the unit is powered up. revert Discards any changes made to the configuration and loads the previous configuration from the EEPROM. Has the same effect as power cycling the device without saving the changes. help Displays a short list of these commands. Celebrating 30 Years siliconchip.com.au Resistor Colour Codes     No. Value 6 10kΩ 3 3.3kΩ 1 1kΩ 1 47Ω 4-Band Code (1%) brown black orange brown orange orange red brown brown black red brown yellow violet black brown “USB Serial Port (COMx)”, where x is a number. Next, open a terminal program like Tera Term Pro and set it to use that serial port (in the Setup → Serial Port menu). The baud rate and other settings do not matter. Then return to the terminal emulator and type “help” and then press Enter/Return. You should see the help command echoed back to you as you type and a list of commands should then be displayed when you press Enter/Return. This verifies that the USB interface and microcontroller are working. The default configuration results in the unit being self-triggered because the input pull-up resistor is active and the trigger condition is on a high input. As a result, you should see LED4 flashing at a rate determined by the positions of VR1 and VR2 (or at random intervals if those potentiometers have not been fitted). You should also see LED2 and LED3 switching on and off at the same time as LED4 changes state. If you have fitted VR1 and VR2, adjust them and check that the on time and off time of LED4 vary as expected. Otherwise, you can issue commands such as “set on time 1s” and “set off time 1s” to change the on and off time and check that they vary as expected. If you short the terminals of CON2 then LED4 should stay off once it switches off as the unit is no longer being triggered. At this point, you could hook up a 1215V DC supply to CON1 and check that the relay clicks on and off at the same time that LED4 lights up or goes dark. Setting it up Now that you have it connected to your PC, this is a good opportunity to set up the configuration to your requirements. See the panel opposite on changing the configuration for the list of commands that you can use to set it up. It’s a good idea to start by issuing the “show config” command to see the current (default) settings. Don’t forget to use the “save” command when you siliconchip.com.au 5-Band Code (1%) brown black black red brown orange orange black brown brown brown black black brown brown yellow violet black gold brown have finished. You’ll probably want to read through the panel on timing options first, to understand how the unit works, so that you can figure out how best to set it up for your particular application. If you’re setting it up to activate with an external trigger, you can simulate this by shorting the trigger pin on CON2 to either +12V or GND, to pull the input high or low. The default configuration is as follows. The input trigger condition is on a high level with a 50ms (minimum) trigger delay. VR1 varies the on time over the range of 1-60s, which is set in exact mode (not minimum or maximum). VR2 controls the off time over the range of 0-60s. LED3 and LED4 are constantly illuminated. The pull-up resistor is enabled and timer resetting by the trigger input is disabled. If you’re having trouble getting the timer to operate in the intended manner, you can plug it into the USB port of a computer and use the “show status” command to see what it is doing. The result includes information on whether the device has been triggered, which timer is currently in operation, how long it has been running for and when the next state change will occur. Housing it The PCB is designed to fit inside a UB3 Jiffy box (130 x 67 x 44mm). It has a mounting hole in each corner so that it can be attached to the base of the box using M3 tapped spacers and short machine screws. Alternatively, you can mount it inside some other piece of equipment, possibly that which it is switching on and off. If you do decide to mount it in a UB3 Jiffy box, you could fit cable glands at either end for power wires and for the wires which connect to the relay contacts. If you want to be able to re-program it while inside the box, you will also need to make a rectangular cut-out in the side to access the USB socket. SC Celebrating 30 Years June 2018  31