FireFly Solar / 日輪蛍 – Circuit & PCB – The Art of Living on Sunlight

夏の日を
器に宿し
闇を待つ

Natsu no hi o
Utsuwa ni yadoshi
Yami o matsu

Holding the summer sun
within a vessel,
waiting for the dark.


Or in cold engineering terms, it is 50 farads of energy storage. In another sense, it is simply a vessel built to hold a piece of the day.


In my previous blog article, I described the firmware of FireFly Solar. An ATtiny85, a few registers, and the art of doing almost nothing. But even doing almost nothing requires energy. In this post, I want to look at the hardware behind the firefly: How it collects sunlight, stores energy, and turns it into little messages in the darkness.

As always, FireFly Solar is my “technology playground”. The goal is not simply to build something that works, but to learn something along the way. All Files for this projects are in my Gitea repository.

1. The Idea

The original idea was quite simple: build a small autonomous electronic firefly that sends out a Morse code message during the night. No disposable batteries. No external power supply. Just sunlight during the day and a little light during the night.

Ideally, it should be able to live somewhere in a garden or balcony for years, without requiring any attention. The software takes care of the Morse code, the detection of darkness, and, most importantly, keeping energy consumption as low as possible. I have already described the firmware in my previous article “FireFly Solar – Inside the Firmware”.

However, the electronics also need a home outdoors. For the enclosure, I decided to use a PET bottle preform. A preform is the small, thick-walled plastic object from which a PET bottle is manufactured. Before being heated and blown into its final shape, it looks a little like a test tube with a bottle thread. More about plastic bottles and their preforms on Wikipedia. For a small outdoor electronics project, these preforms are quite interesting. They are mechanically robust, transparent – essential for a LED blinker – inexpensive, and already come with a thread for a standard bottle cap. They are also used widely for small electronic projects or geo caches. Of course, the cable entry and the cap still need to be properly sealed against moisture.

The other important design decision was to use through-hole technology (THT) instead of surface-mounted components (SMD). Because I want this little project to remain accessible also for beginners. With a small soldering iron, a little patience, and some basic soldering skills, almost anyone should be able to assemble a FireFly. I also have the idea of a small DIY kit in mind.

Perhaps a future version will use SMD components. Learning to design and assemble an SMD version would be another interesting step for my technology playground.

A small mechanical challenge: There is one little conflict between these design decisions: through-hole components need space, and a PET bottle preform does not offer much of it. The width of the PCB is only one part of the problem. The height of the components, particularly the supercapacitor, is equally important. One of my lessons learned was that the PCB needed a cutout to accommodate the supercapacitor. Instead of placing the entire capacitor on top of the PCB, part of its body can sit within the PCB outline.

I just finieshed the 1st version, and it is running for testing at my balcony:

FireFly full assembled, ready for action
FireFly full assembled, ready for action

2. Storing the Sun

The most important question behind the FireFly is how to store enough energy during the day to keep it alive throughout the night. The obvious solution would be a small rechargeable battery.

But I wanted to try something different, also because of the size limitations: a supercapacitor. Supercapacitors can be charged and discharged repeatedly, generally tolerate a large number of charging cycles, and can provide relatively high currents when required. For a small device that consumes very little energy and is recharged every day, they are an interesting alternative to conventional rechargeable batteries.

For FireFly Solar, I selected an Abracon AHCR-S04R0SA506Q, a 50 F / 4 V lithium hybrid supercapacitor in an 8 mm × 25 mm radial package (AHCR-S04R0S — Abracon datasheet). The datasheet specifies more than 50,000 charge cycles.

50 farads sounds quite impressive when you are used to dealing with capacitors in the microfarad range. So how much energy does it store? The energy stored in a capacitor can be estimated using:

E = ½ × C × U²

For 50 F at 4 V:

E = ½ × 50 F × (4 V)² = 400 J

That is about 0.111 Wh, which matches the maximum stored energy in the datasheet. Not very much compared to a rechargeable battery, but FireFly does not need much energy.

There is, however, an important detail. The selected component is a lithium hybrid supercapacitor, not a conventional capacitor that can simply be discharged down to zero volts. Its datasheet specifies a lower voltage threshold of 2.5 V, and the datasheet itself points out that the usable energy is less than the stored energy because of it. You can see this during discharge below 2.5V at the Supercap. Voltage will drop during load sharply, but recovery mostly to the previous voltage. On the upper end, the maximum charging voltage is 4.2 V. In FireFly Solar, a 3.9 V Zener diode limits the charging voltage, a little below the 4.0 V rating. Taking this into account, the theoretical usable energy between 3.9 V and 2.5 V is approximately:

E = ½ × 50 F × [(3.9 V)² − (2.5 V)²]
E ≈ 224 J ≈ 0.062 Wh

This uses the nominal 50 F. The capacitance tolerance is −10 % / +30 %, so a real part holds between about 45 F and 65 F. That moves the usable energy between roughly 200 J and 290 J (0.056 to 0.081 Wh). It is also the energy before any losses in the DC/DC converter. This is before accounting for conversion losses, leakage current, and the energy required by the electronics themselves.

The principle of the complete FireFly circuit is quite simple. It consists of three functional blocks:

  1. Energy harvesting and storage: Solar modules, charging protection, and the supercapacitor.
  2. Power conversion: A DC/DC converter that provides the operating voltage.
  3. The firefly itself: An ATtiny85 and an LED that acts both as a light source and a light sensor.

Sunlight goes in at one end, and a little Morse code comes out at the other.

3. The Circuit

The complete schematic was designed in KiCad. It is available, together with the other project files, in my Gitea repository. FireFly Solar — KiCad Schematic. Also a PDF Version of the Circuit.

Screenshot for this blog:

FireFly Circuit
FireFly Circuit

3.1 Harvesting the Sun – Energy Storage and Protection

The first part of the circuit collects and stores the energy. The PCB provides connections for up to three small solar modules. Alternatively, another suitable low-voltage, current-limited DC source can be used.

I use three small solar modules of approximately 60 × 60 mm, nominally rated at 5 V, connected in parallel, one per input. They face in different directions, so there is no need to align them to the sun. The flip side is that only one or two of them see the sun at any moment.

In real outdoor conditions, the values are somewhat different from the numbers printed on the modules. For my initial calculations, I used approximately 4.5 V and 10 mA per module as representative working values. Of course, the actual output depends on the weather, the position of the sun, the orientation of the module, and its electrical operating point.

Each solar input is connected through a Schottky diode (D1–D3). These diodes allow the modules to feed a common charging circuit while preventing reverse current into the modules. This is particularly useful when one module is illuminated and another one is in the shade. It also prevents the supercapacitor from discharging back into the solar modules during the night. I chose Schottky diodes because of their relatively low forward voltage drop. With only a few volts available, every unnecessary voltage drop matters.

FireFly Circuit solar cell input supercap and protection
FireFly Circuit, solar cell input supercap and protection
Protecting the energy storage

The solar modules can generate a higher voltage than the supercapacitor should be exposed to. Therefore, the charging circuit needs some form of overvoltage protection. My solution is deliberately simple:

The Zener diode is connected in parallel with the supercapacitor. As the capacitor voltage approaches its breakdown voltage, it starts to conduct, and once the capacitor is full, the surplus current from the modules flows through the Zener instead of raising the capacitor voltage further.

The modules limit their own current to roughly 10 mA each, so with solar input alone R1 dissipates only about 30 mW at most. [Reason for 33 Ω / 2 W, e.g. headroom for a stronger external DC source, or the Zener operating point.] The price is a voltage drop of about 0.33 V at 10 mA.

One detail deserves attention. The datasheet specifies the BZV85-C3V9 at 3.7–4.1 V, measured at 60 mA and 25 °C. So a 3.9 V Zener may clamp a little above the 4.0 V rating of the supercapacitor. This is still below the 4.2 V maximum charging voltage in the datasheet, and my modules deliver much less than 60 mA, which lowers the clamp voltage in practice. The temperature coefficient of this Zener is negative, so the clamp voltage rises slightly on cold days.

If this is a concern for your build, the next lower type is the BZV85-C3V6. It keeps the capacitor safely below its rating, but it costs energy. With the 2.5 V lower threshold of the supercapacitor, the usable energy drops from about 224 J to about 168 J, roughly 25 %, and that translates directly into less Morse time per night.

Why this big 2 W resistor?

Let’s look at a few numbers. The current through the charging resistor can be estimated with Ohm’s law:

I = (Usolar − Udiode − Ucap) / R1

Assuming a solar voltage of 4.5 V, a Schottky forward voltage of 0.3 V and an almost full capacitor at 3.9 V:

I = (4.5 V − 0.3 V − 3.9 V) / 33 Ω ≈ 9 mA

That is close to the 10 mA I assumed for one module. The power dissipated by the resistor is:

P = I² × R ≈ (9 mA)² × 33 Ω ≈ 2.7 mW

With a lower capacitor voltage, the formula gives a higher current. At 2.5 V it would be about 50 mA. But the formula assumes a stiff 4.5 V source, and my solar modules are not: each delivers about 10 mA, so three modules give at most 30 mA, and the module voltage sags instead of the current rising. With solar input alone, R1 therefore never dissipates more than:

P = (0.03 A)² × 33 Ω ≈ 30 mW

So why 2 W? Because of a possible DIY kit: someone may connect stronger solar modules or another DC source, and the resistor should survive that. The worst case for R1 is an empty supercapacitor, the worst case for the Zener a full one.

For example, with a charging current of 100 mA (this needs a stiff source of about 7.5 V at a capacitor voltage of 3.9 V):

P = (0.1 A)² × 33 Ω = 0.33 W

R1 reaches its 2 W limit at about 246 mA. For my own three modules, a 0.5 W resistor would be enough (good up to about 120 mA). It is also worth noting that once the supercapacitor is full, the surplus current flows through the Zener diode. At a Zener current of 30 mA:

PZ = 3.9 V × 0.03 A ≈ 0.117 W

The Zener is actually the weaker component. The BZV85 is rated for 1 W (25 °C ambient, 10 mm leads) up to 1.3 W with the leads held at 55 °C. At 246 mA it already dissipates about 0.96 W, so resistor and Zener reach their limits at roughly the same current. For 33 Ω that corresponds to an input of about 12 V. I checked this at the workbench and the resistor got really hot. That is why I stay with the 2 W type for a future DIY kit.

This circuit is simple, but it is not an unlimited power-input stage!

How long does charging take?

The basic relationship between charging current, capacitance and voltage is:

I = C × ΔU / Δt

Or, rearranged:

t = C × ΔU / I

Charging the 50 F capacitor from 2.5 V to 3.9 V with a constant current of 10 mA would theoretically take:

t = 50 F × 1.4 V / 0.01 A = 7,000 s ≈ 1.9 hours

Put differently, the capacitor has to take up a charge of 50 F × 1.4 V = 70 C, which is about 19.4 mAh. I checked this at the workbench with a 4.5 V source limited to 10 mA, and it took about 2 hours, very close to the calculation. This works so well because the charging current stays at the 10 mA limit almost all the way up. R1 only starts to reduce it at about 3.87 V, where (4.5 V − 0.3 V − 3.87 V) / 33 Ω falls below 10 mA.

In reality, the charging current is not constant. It changes with sunlight and decreases as the capacitor approaches its final voltage. With only 3 mA, for example under a thick layer of clouds, the same charge takes about 6.5 hours. The capacitance tolerance of −10 % / +30 % (45 F to 65 F) moves the 10 mA figure between about 1.75 and 2.5 hours.

Nevertheless, this gives a good idea of the order of magnitude. A few hours of useful sunlight can be sufficient to prepare the FireFly for another night.

Design decisions and lessons learned

This simple charging circuit is not designed to extract the maximum possible energy from the solar modules. It is a compromise between simplicity, component count, efficiency, and ease of assembly.

One important consideration is the accuracy of the Zener voltage. A 3.9 V Zener diode does not necessarily clamp at exactly 3.9 V. Its voltage depends on current, temperature, and manufacturing tolerances. For this reason, the actual maximum capacitor voltage should be measured under the brightest expected conditions. A 3.6 V Zener diode is another possible option if a larger voltage margin is required, but this will limit the morse time during night dramatically.

Another lesson is that the solar module’s nominal voltage alone tells you very little about its performance in the real world. What matters is how much energy it can actually deliver to the storage capacitor during the day.

3.2 Making Every Joule Count – The DC/DC Converter

A supercapacitor has one characteristic that makes it rather different from a conventional battery. Its voltage decreases continuously as energy is removed.

Connecting the ATtiny85 directly to the supercapacitor would be possible within certain voltage limits. However, the LED brightness would change with the supply voltage, and the circuit would eventually reach the minimum operating voltage of the microcontroller.

To make better use of the stored energy, I decided to use a DC/DC converter. The component I selected is the MAX756CPA, a step-up switching converter from Maxim Integrated, now Analog Devices:

The MAX756 is not exactly a new component. Its design dates back to the 1990s. But it has one very important advantage for my project: it is available in a classic 8-pin DIP package. When looking for a suitable DC/DC converter, I found many modern components with excellent efficiency and extremely low power consumption. Unfortunately, most of them are only available in SMD packages.

The MAX756 fits my through-hole design philosophy much better, but yes it sometimes hard to get.

The basic MAX756 circuit

There is nothing particularly exotic about my implementation. It is based on the typical operating circuit described in the MAX756 datasheet.

FireFly Circuit MAX756 DC/DC part
FireFly Circuit MAX756 DC/DC part

The main components are:

  • U1: MAX756CPA
  • L1: 22 µH inductor
  • D5: Schottky diode
  • C3: 100 µF output capacitor
  • C4: Reference bypass capacitor

The basic operating principle is that the converter temporarily stores energy in the magnetic field of the inductor and then transfers that energy through the Schottky diode to the output capacitor. By repeating this process, the converter can produce an output voltage higher than its input voltage.

The MAX756 uses pulse-frequency modulation (PFM). The switching activity changes according to the energy required by the load, which makes it useful for applications with varying power consumption.

In FireFly Solar, the load changes considerably between the short periods when the LED is illuminated and the much longer periods when the ATtiny85 is asleep.

3.3 V or 5 V?

The MAX756 offers two selectable output voltages: 3.3 V and 5 V. I included a selection connection, J3, on the PCB so that both options are available for experimentation.

For normal operation, I use the 3.3 V setting. There is simply no need to run the ATtiny85 and the LED at 5 V in this application. A lower voltage saves energy: the microcontroller draws less, and for the same LED current the power taken from the supply scales with the voltage, so 5 V would cost about 50 % more (5 V / 3.3 V ≈ 1.5). It also means less voltage is burned in the LED series resistor.

One important detail is that the MAX756 is a boost converter, not a buck-boost converter. If the supercapacitor voltage is higher than the selected output voltage, the converter cannot reduce it. The output then simply follows the input through the inductor and the Schottky diode, lower by the diode’s forward drop. With the supercapacitor at its Zener-limited 3.9 V and a drop of about 0.3 V, the output sits at roughly 3.6 V instead of 3.3 V. Maxim’s evaluation-kit notes recommend keeping the input below the output voltage plus 0.5 V (about 3.8 V in the 3.3 V mode), so a full supercapacitor is slightly above that recommendation. But bench test showed it worked well enough. Also with full supercap at 4V I have a stable voltage of 3.3V for the ATtiny.

For the ATtiny85 this is harmless, since it is specified up to 5.5 V. For the LED it matters: the voltage across the series resistor changes by about 0.3 V between a full and a partly discharged supercapacitor. If about 1 V drops across the resistor at 3.3 V, it is about 1.3 V at 3.6 V, which means roughly 30 % more LED current. That is why I did not calculate the resistor on paper, but tested different LEDs and resistors at the bench, with a full and a low supercapacitor.

So why 5 V at all?

The only reason for the 5 V setting is a blue LED. The forward voltage of an LED depends on its color, because it is set by the band gap of the semiconductor. Typical values at 10 to 20 mA (check the datasheet of your LED):

  • Red, Green: about 2 V
  • Yellow / amber: about 2.1 V
  • Blue (and white): about 3.0 to 3.2 V, within a range of roughly 2.8 to 3.4 V

At a few milliamperes the voltage is lower by about 0.2 to 0.3 V. The LED is driven directly by two ATtiny85 pins, and each of them loses a few tenths of a volt at LED current. At 3.3 V, well under 3 V therefore remain for the LED and its series resistor. A red LED leaves about a volt for the resistor, which keeps its current well defined. A blue LED has no headroom at all: either it barely lights, or the resistor must be tiny and the current then depends strongly on the LED tolerance, the temperature and the supply voltage. It would also be brighter with a full supercapacitor (about 3.6 V at the output) than later in the night, when the converter regulates 3.3 V.

At 5 V, about 4.4 V remain. A blue LED of 3.1 V leaves about 1.3 V for the resistor, roughly the headroom a red LED has at 3.3 V. The price is energy: about 50 % more for the same current, and an ATtiny85 running at 5 V. I have not tested the 5 V setting yet. One more caveat: a blue LED only responds to short wavelengths, so as a light sensor it behaves differently from a red one, and the darkness threshold “darkSteps” in the firmware has to be recalibrated.

The cost of doing almost nothing

The MAX756 itself needs energy, even when the ATtiny85 is asleep. Its datasheet specifies a typical quiescent current of 60 µA. That is quite low for a switching converter of its generation, but in a system where the microcontroller spends most of its life asleep, even 60 µA becomes significant. This is one of the interesting aspects of low-power electronics: once you reduce the consumption of the microcontroller, other components that previously seemed insignificant suddenly become important. Another important point is that the MAX756 can continue operating at input voltages well below the minimum voltage of my hybrid supercapacitor.

The current circuit does not include a dedicated undervoltage disconnect. Adding one to protect the supercapacitor during extended periods without sufficient sunlight would be a worthwhile improvement for a future revision. Simply putting the converter into shutdown is not necessarily sufficient, because the boost circuit still provides a passive current path through the inductor and diode. There are certainly more efficient solutions available today. But all in SMD…

But for this version of FireFly, the MAX756 offers a nice combination of simplicity, understandable operation, and through-hole assembly.

3.3 The ATtiny85 – One LED, Two Jobs

The final part of the circuit is the firefly itself. Compared to the energy harvesting and power conversion stages, this part looks almost disappointingly simple. An ATtiny85, an LED, a resistor, and a few additional passive components.

But there is a little trick behind it. The LED does not only produce light. It also acts as a light sensor. An LED is a semiconductor junction. Just as electrical current can cause it to emit light, incident light can generate a small electrical response within the junction. The ATtiny85 uses this effect to determine whether it is day or night.

During light detection, the firmware changes the configuration of the GPIO pins and measures the behavior of the LED junction. During Morse transmission, the same LED is operated normally as a light-emitting diode. This means I do not need a separate phototransistor, photoresistor, or other light sensor.

The details of how this works, including the watchdog timer and the sleep modes of the ATtiny85, are described in my firmware article.

Selecting the LED resistor

This sounds like one of the easiest parts of the circuit. Choose an LED, calculate a resistor with Ohm’s law, and you are finished. Well, not quite. The basic equation is simple:

R = (Usupply − Uf − Upins) / ILED

Upins is the voltage lost in the two ATtiny85 pins that drive the LED directly, a few tenths of a volt in total. The forward voltage of an LED depends on its semiconductor technology, the operating current, the temperature and manufacturing tolerances. Furthermore, two LEDs with the same current can look very different: the eye is about three times more sensitive to green light (525 nm) than to red light (630 nm), and the dark-adapted eye shifts even further towards green. I experimented with different LEDs and resistor values until I found a good compromise between visibility and energy consumption.

For operation at a nominal supply voltage of 3.3 V, my tested combinations are:

LED Series resistor R2 Calculated current at 3.3 V Remarks
Red 640 Ω about 1.8 mA a little bit dark, but ok in the night
Green 330 Ω about 2.9 mA very bright, especially in the night

The currents are calculated from typical forward voltages (about 1.9 V for red, 2.1 V for green at these low currents) and about 0.25 V lost in the pins. Both LEDs therefore run at less than 15 % of the 20 mA at which their datasheets specify forward voltage and brightness. Strictly speaking, that is outside the specified range, and the exact values vary from piece to piece. For this application that is fine: low current is the whole point. The ATtiny85 pins are comfortably within their guaranteed output levels at these currents. Over one Morse transmission the LED is lit for about 10.85 s, which costs roughly 64 mJ with the red LED and 104 mJ with the green one. Green looks much brighter, but it costs also about 60 % more energy.

These values are not universal recommendations for every red or green LED. They are the results of my experiments with the particular LEDs I selected for the FireFly. And because the LED is also used as a sensor, changing the LED also changes the light detection behavior, so the darkness threshold “darkSteps” in the firmware has to be checked again.

I have not tested blue LEDs or the 5 V setting yet.

Lessons learned

My first assembled PCB was, in the end, a rather messy little object. Different LED versions, different resistor values, modifications, more soldering, and another round of testing. What started as a nice, clean PCB became a record of my experiments. But that is exactly what a prototype is supposed to be.

One important lesson for a possible DIY kit is that the LED and its corresponding resistor should be considered a matched combination. A kit should contain a specific, tested LED together with the appropriate resistor value, rather than leaving the selection entirely to chance.

After a sunny day, my current FireFly prototypes have achieved approximately 14 hours of Morse operation during the night, the green and the red ones.

Better than I originally expected!

4. PCB Assembly – Making It Fit

The PCB was designed in KiCad with through-hole assembly in mind. Most components are relatively easy to solder, and there is no need for a hot-air station, solder paste, or a reflow oven (I alspo not own). Just a soldering iron and some patience. But the PCB is not only an electrical object. It also needs to fit into its little PET enclosure and survive outdoors.

The PCB design is in the KiCad Project at my gitea, also a pdf printout.

The supercapacitor

The largest mechanical challenge is the supercapacitor. Its diameter is approximately 8 mm, but its body is relatively long compared to the other components. Mounting it in the conventional way would increase the overall dimensions of the assembled PCB considerably. Therefore, the capacitor needs to be accommodated within a cutout in the PCB. This reduces the total profile of the assembly and makes better use of the available space inside the preform. It is a small detail, but one that is much easier to solve during PCB design than after receiving the manufactured boards.

Mechanical support – A little wire cage

There is another detail worth mentioning. FireFly is intended to live outdoors. Wind will move it, sometimes gently, sometimes not quite so gently. The supercapacitor has considerably more mass than most of the other components on the PCB. If it is supported only by its electrical leads, every movement creates mechanical stress on the leads, the solder joints, and the PCB pads.

Over time, I think this could become a problem. My solution is a small wire cage around the supercapacitor. The wire provides additional mechanical support and helps transfer forces to the PCB rather than leaving the solder joints to carry the entire mechanical load. The support wire must, of course, be arranged so that it cannot damage the capacitor’s insulation or create an electrical short circuit. Nothing sophisticated, but hopefully effective.

A little lesson from my experience in mechanical engineering: solder joints are primarily electrical connections, not structural mounting points.

FireFly PCB assembly
FireFly PCB assembly

IBN – Assembly Check and First Power-Up

IBN — Inbetriebnahme (German), or commissioning, as we engineers like to call it.

Before releasing a little electronic firefly into the wild, it is worth checking whether everything works as intended. After assembly, I first checked the PCB for the usual suspects: solder bridges, incorrect component orientation, and particularly the polarity of the diodes and the supercapacitor. For the first power-up, I used my laboratory power supply instead of the solar modules, connected to one of the solar inputs:

  • Voltage: 4.5 V
  • Current limit: 10 mA (0.01 A)

This provides a controlled environment for the initial charging of the supercapacitor. With 50 F, charging takes a little patience. The current limitation also helps to prevent damage if something is wrong with the assembly.

While charging, I checked the voltage across the supercapacitor and the output of the DC/DC converter. For the functional test, I used the Lab Bench Mode of the FireFly firmware. There is no need to wait for some time (13 minutes) to find out whether the little creature is alive. More about the FireFly firmware and its operating modes

There is, however, one little challenge: the FireFly is designed to operate in darkness, and my laboratory is usually quite well illuminated. My solution is a small piece of heat-shrink tubing that fits over the LED. For a typical 5 mm LED, a suitably sized tube can simply be slipped over it without shrinking it.

The tube acts as a little light shield, creating an artificial night for the LED. I leave the lower end open so that I can still observe the LED blinking and read its Morse code. Once charging, voltage conversion, light detection, and Morse transmission have all been checked, the FireFly is ready for its first real night outdoors.

In the video you can also see the measuring points for the Supercap at the PCB, just juse the pin of L1, connected to the supercap and ground is the “cage” of the superconductor:

A small recommendation about IC sockets

I use a socket for the ATtiny85. This makes it easy to remove the microcontroller for programming, testing, or replacement. For a project like FireFly, where I frequently experiment with the software, this is very convenient. However, I learned that not all IC sockets are equally good.

Some inexpensive sockets can develop contact problems after months of operation, particularly when exposed to the temperature variations and mechanical movement of an outdoor installation. My recommendation is to use a good-quality IC socket, preferably a precision socket with turned contacts. Saving a few cents on a socket is not particularly useful if you later have to investigate a mysterious microcontroller malfunction caused by an unreliable electrical connection.

Ready for the outdoors?

The PET preform provides a nice little protective enclosure, but it does not automatically make the FireFly weatherproof. Cable entries, condensation, moisture, UV exposure, and temperature cycling all need to be considered. For long-term operation, the enclosure and the temperature limits of the electronic components are just as important as the electrical design.

And this is another aspect of the project that I will continue to observe.

5. Closing Words

FireFly Solar is not the smallest solar-powered circuit possible. It is not the most efficient one either. There are more sophisticated energy harvesting ICs, better DC/DC converters, and much smaller SMD components available today. But that is not really the point of this version. I wanted to build a little autonomous device, using components that I can understand, experiment with, and assemble myself.

Along the way, I learned about solar energy harvesting, supercapacitors, low-power switching converters, LEDs as light sensors, PCB design, and the mechanical challenges of putting electronics into a rather small plastic tube.

And there is still plenty to explore. Perhaps the next generation of FireFly will have a more efficient energy harvesting circuit, a better protection system, or an entirely SMD-based PCB.

But for now, at my balcony, little electronic firefly collects sunlight during the day, waits for the darkness, sends out its little message, and goes back to sleep.

螢火や
闇にひとこと
又消えぬ

Hotarubi ya / A firefly’s glow
Yami ni hitokoto / a single word in the darkness,
Mata kienu / gone again.


Project resources

Tōgō Lab / 塔郷研究所,

FireFly Solar / 日輪蛍 – Inside the Firmware

螢火や
闇にひとこと
又消えぬ

Hotarubi ya (A firefly’s glow)
Yami ni hitokoto (a single word in the darkness)
Mata kienu (gone again.)

Or, in cold engineering terms:
An ATtiny85, a few registers, and the art of doing almost nothing.

1. The Software Concept

FireFly Solar is a solar-powered Morse blinker built around an ATtiny85. This blog post is about the firmware running inside that little ATtiny85.

This tiny 8-pin microcontroller has three simple jobs: notice that it is dark, blink a message in Morse code, and use as little energy as possible in between. The Morse part is one big switch statement — pretty basic coding. The “as little energy as possible” part is where things got interesting and where I learned some of the secrets of the AVR architecture.

I do a lot with Arduinos, and a typical Arduino sketch keeps the CPU spinning even when there is nothing to do. For a device like this one, which has to get through a whole night on a 50F supercap, that is a really bad deal. So the firmware follows one rule:

Wake up. Do the one useful thing. Go back to sleep.

Nearly all of its life is spent in power-down mode, with the watchdog timer as its alarm clock. ATtiny’s are limited, there is no operating system, no real-time clock and no communication stack. but this gives me the most freedom. BTW – the compiled sketch occupies just 1,226 bytes of the available 8 KB of flash. So if you like: Change it, tinker with it & add functions, rewrite everything, but let me know.

One nice thing is: I can still use the familiar Arduino IDE. With an additional board package, I can write and compile programs for the ATtiny85 and other ATtiny microcontrollers, just as I would for a normal Arduino.

For this project, I used ATTinyCore. If you want to get started with these little chips today, I can highly recommend Wolfgang Ewald’s blog post on Wolles Elektronikkiste: TinyCore board package for classic ATtinys. TinyCore is a newer board package based on ATTinyCore, with updated tooling for the Arduino IDE.

I get through some cycles during the last weeks and month, this blog post describes firmware v1.0, dated 2026-11-14. The complete source is available in my Gitea repository.

2. How the Firmware Works

2.1 The Operating Cycle

One normal operating cycle looks like this:

  1. Check whether it is dark.
  2. If it is dark, send the Morse text.
  3. Release both LED pins to high impedance.
  4. Sleep for 5 × 8 s = 40 s.

With the default payload, the Morse transmission takes about 20 s. Together with the darkness measurement and the idle sleep, this adds up to roughly one transmission per minute.

During daylight, the darkness check usually ends after a single 16 ms step. The chip goes straight back to sleep, and the solar cell charges the supercap while the electronics do next to nothing.

After a reset, the firmware first runs through a recovery period before entering normal operation. More on that in chapter 7.

2.2 Morse Code Generation

The default payload is:

const char morseText[] PROGMEM = "TOGO-LAB.IO FIREFLY";

It lives in flash because the ATtiny85 has only 512 bytes of SRAM. There is no reason to copy a constant text string into RAM.

Change the string before programming and each firefly gets its own message.

The character table supports A–Z, digits, spaces and the following special characters:

. , ? ! : ; ( ) " @ & - / ' + = _

Lowercase letters are converted to uppercase. Unsupported characters are skipped without adding a gap.

The timing follows the usual Morse rules:

Element Duration
Dot (dit) 1 unit
Dash (dah) 3 units
Gap between elements 1 unit
Gap between characters 3 units
Gap between words 7 units

One unit is about 96 ms: a 64 ms and a 32 ms watchdog sleep back to back.

The watchdog has fixed timeout steps, so 96 ms is a convenient way to get close to 100 ms without keeping the CPU running. It is slow enough to read by eye.

The payload is also part of the energy budget. The default 19-character text takes 212 units, including the final character gap. That is roughly 20 s on air, with the LED lit for 113 of those units, about 11 s.

Every extra letter costs LED time.

2.3 An LED as a Light Sensor

Using an LED as a light sensor is not realy a new trick. The principle has been known for decades, and in 2003 Paul Dietz and his colleagues at Mitsubishi Electric Research Laboratories published a particularly interesting paper, Very Low-Cost Sensing and Communication Using Bidirectional LEDs. They describe almost exactly the circuit I use here: one LED, a resistor and two microcontroller I/O pins, switching between emitting light and detecting it.

No extra sensor, no extra part on the PCB.

For a more hands-on explanation with Arduino code, I recommend John Graham-Cumming’s blog post Two ways to use an LED as a light sensor with Arduino.

The difference in FireFly Solar is that I do not keep the CPU running while waiting for the LED junction to discharge. I put it back to sleep and let the watchdog wake it up for the next measurement.

The measurement goes like this:

  1. Charge the junction capacitance: cathode pin HIGH, anode pin LOW. The LED is reverse-biased.
  2. Switch the cathode pin to a high-impedance input, with the pull-up off.
  3. Let the photocurrent discharge the junction capacitance. The brighter the environment, the faster it discharges. Check the pin every 16 ms.
  4. If the pin reads LOW within the measurement window, there was enough light. Skip the blink. If it is still HIGH at the end of the window, it is dark enough to start blinking.

The relevant part of isDark():

for (uint8_t k = 0; k < darkSteps; k++) {
  sleepWdt(0);  // ~16 ms
  if (digitalRead(LED_N) == LOW) {
    dark = false;
    break;
  }
}

The measurement window is defined by:

const uint8_t darkSteps = 40; // ~640 ms

The ATTiny’s CPU sleeps through most of the measurement. It only wakes up to check the pin and, if necessary, start the next sleep interval.

One neat side effect I discovered: in power-down, the hardware disables the ordinary digital input buffer of the floating sense pin. The slowly falling voltage therefore does not cause continuous shoot-through current while it passes through the intermediate voltage region. There is no lux value. The only question is whether it is dark enough to start blinking. The threshold can be adjusted with darkSteps:

  • A larger value requires darker conditions before blinking starts.
  • A smaller value makes the firefly start blinking at a higher ambient light level.

The threshold depends on the LED and on temperature. Junction leakage increases at higher temperatures, so the discharge time in darkness becomes shorter. If the firefly blinks in winter but refuses to blink on warm summer nights, darkSteps may need to be reduced.

I’ll find out. It’s getting cold now, so I can’t really test this yet. But this is a long-term project, and there will be another hot summer.

3. Firmware Structure and Functions

The firmware consists of the following functions:

Function Purpose
earlyWatchdogInit() Saves the reset cause and disables the watchdog before normal startup.
setup() Initializes recovery, I/O pins and power management.
loop() Coordinates recovery, darkness detection, Morse transmission and idle sleep.
configureUnusedPins() Configures unused pins as INPUT_PULLUP.
releaseLedPins() Releases both LED pins to high impedance with pull-ups disabled.
sleepWdt() Configures the watchdog and sleeps in power-down until it fires.
waitUnits() Generates Morse timing units using watchdog sleep.
isDark() Measures the LED junction discharge to detect darkness.
morse() Reads the text from flash and translates characters into Morse code.
dit() Generates a short LED pulse followed by a one-unit gap.
dah() Generates a long LED pulse followed by a one-unit gap.
ISR(WDT_vect) Sets the watchdog wake-up flag.

3.1 setup()

The initialization sequence establishes the I/O configuration and switches off the unused hardware.

To be safe, I configure the pins first, before disabling the peripherals. The Arduino core’s digitalWrite() can touch timer registers to disconnect PWM, so I leave the timer clocks enabled during this initial configuration.

The ADC shutdown has a specific requirement: the ADC must be disabled before its clock is gated in the Power Reduction Register (PRR).

The relevant sequence is:

configureUnusedPins();
releaseLedPins(LED1_N_SIDE, LED1_P_SIDE);

cbi(ADCSRA, ADEN);
ACSR |= (1 << ACD);

PRR = (1 << PRADC) | (1 << PRUSI)
    | (1 << PRTIM0) | (1 << PRTIM1);

The ADC, analog comparator, USI and both timers are not needed in this application.

The ADC is disabled by clearing ADEN, and the comparator is disabled by setting ACD. Only then are the unused peripheral clocks stopped.

The reason for this order is explained in section 6.2.

setup() also reads the reset flags saved by earlyWatchdogInit() and initializes the recovery counter.

3.2 loop()

The main loop is short:

if (recoverCycles > 0) {
  recoverCycles--;
} else if (isDark(LED1_N_SIDE, LED1_P_SIDE)) {
  morse(LED1_N_SIDE, LED1_P_SIDE);
}

If a recovery wait is running, count it down. Otherwise check for darkness and send Morse if needed.

In bench test mode, an additional branch generates a short flash when the darkness check returns false.

Afterwards, release the LED pins and sleep:

releaseLedPins(LED1_N_SIDE, LED1_P_SIDE);

for (uint8_t i = 0; i < sleepCycles; i++) {
  sleepWdt(9);
}

In normal operation, sleepCycles is 5 and watchdog timeout code 9 means approximately 8 s.

No scheduler needed.

3.3 sleepWdt()

This is the function everything else hangs on. All timing in FireFly Solar goes through it.

The function accepts a watchdog timeout code from 0 to 9:

Timeout code Nominal duration
0 16 ms
1 32 ms
2 64 ms
3 128 ms
4 250 ms
5 500 ms
6 1 s
7 2 s
8 4 s
9 8 s

The watchdog has its own nominal 128 kHz oscillator, which keeps running when the CPU and main oscillator are stopped.

It is not a precision timebase. Its frequency changes with temperature and supply voltage. The standard FireFly Solar hardware runs at 3.3 V, with a 5 V configuration for the experimental blue LED variant.

So “8 s” means “about 8 s”.

Morse does not need a precision clock. All timing comes from the same oscillator, so the relative duration of dots, dashes and gaps is maintained while the absolute speed can drift.

Configuring the Watchdog

The watchdog prescaler bits are not contiguous in the WDTCR register. WDP0–WDP2 occupy bits 0–2, while WDP3 sits at bit 5.

The timeout code therefore needs a little bit manipulation:

if (ii > 9) ii = 9;

uint8_t bb = ii & 7;
if (ii > 7) bb |= (1 << WDP3);

const uint8_t cfg = bb
                  | (1 << WDIE)
                  | (1 << WDE)
                  | (1 << WDIF);

The configuration sets both WDIE and WDE, enabling the combined interrupt and system reset mode.

Another AVR detail: WDIF is cleared by writing a one, not a zero. The configuration explicitly clears this flag so a pending watchdog interrupt from an earlier operation cannot interfere with the next sleep interval.

Before writing the configuration, the firmware clears the software wake-up flag, disables interrupts and resets the watchdog counter:

f_wdt = false;
cli();
wdt_reset();

The protected register update itself uses two consecutive AVR assembly instructions. See section 7.2.

Entering Sleep Without Missing the Wake-Up

There is a subtle problem with entering sleep.

If an interrupt occurs after interrupts have been enabled but before the CPU executes the sleep instruction, the wake-up could be lost. The processor would then go to sleep after the interrupt had already been serviced.

The solution is a classic AVR trick:

set_sleep_mode(SLEEP_MODE_PWR_DOWN);

while (!f_wdt) {
  sleep_enable();

#if BOD_FUSE_ENABLED
  sleep_bod_disable();
#endif

  sei();
  sleep_cpu();
  sleep_disable();
  cli();
}

sei();

On AVR, the instruction immediately following sei() executes before any pending interrupt is serviced.

Here, that instruction is sleep_cpu().

The CPU therefore enters sleep before the pending watchdog interrupt can be handled.

The interrupt service routine itself does almost nothing:

ISR(WDT_vect)
{
  f_wdt = true;
}

The flag is declared volatile because it is modified by an interrupt service routine.

If something other than the watchdog wakes the CPU, the loop checks the flag and goes back to sleep. The function only returns after the watchdog interrupt has occurred.

This same function produces everything from the 16 ms darkness measurement steps to the 8 s idle sleep intervals.

It re-arms the watchdog on every call. That detail becomes important in chapter 7.

3.4 waitUnits(), isDark() and the Morse Functions

waitUnits()

The Morse timing is defined by two constants:

#define UNIT_WDT_A 2
#define UNIT_WDT_B 1

The function combines the two watchdog intervals:

static void waitUnits(uint8_t n)
{
  while (n--) {
    sleepWdt(UNIT_WDT_A);

#if UNIT_WDT_B != 0xFF
    sleepWdt(UNIT_WDT_B);
#endif
  }
}

For the standard configuration, one Morse unit consists of a 64 ms and a 32 ms watchdog sleep.

The speed can be changed without touching the Morse character table:

UNIT_WDT_A UNIT_WDT_B Nominal unit
2 1 96 ms — standard
3 0 144 ms
3 0xFF 128 ms
2 0xFF 64 ms

0xFF disables the second sleep interval entirely.

A longer unit makes the Morse easier to read but also increases the LED operating time.

While the CPU sleeps in power-down, the port latches keep their state. The LED stays on or off as the firmware left it. The processor does not have to be awake to hold an output HIGH or LOW.

isDark()

The darkness measurement uses plain Arduino calls, not direct register access.

Underneath those calls are three AVR registers:

Register Function
DDRB Selects input or output operation.
PORTB Sets the output level or enables the internal pull-up.
PINB Reads the actual pin state.

The subtle part is releasing the cathode pin without enabling its internal pull-up:

pinMode(LED_N, INPUT);
digitalWrite(LED_N, LOW);

The charged LED junction can now discharge through its photocurrent and leakage paths.

After the measurement, both LED pins are configured as outputs and driven LOW. The calling function then either starts the Morse transmission or releases the pins for idle sleep.

morse(), dit() and dah()

morse() reads the payload directly from flash:

const size_t len = strlen_P(morseText);

for (size_t i = 0; i < len; i++) {
  char c = (char)pgm_read_byte(&morseText[i]);

  // Character decoding ...
}

strlen_P() determines the length of the string in program memory, and pgm_read_byte() reads the individual characters.

A switch statement translates each character into calls to dit() and dah().

The pulse functions are deliberately simple:

void dit(int LED_P)
{
  digitalWrite(LED_P, HIGH);
  waitUnits(1);
  digitalWrite(LED_P, LOW);
  waitUnits(1);
}

void dah(int LED_P)
{
  digitalWrite(LED_P, HIGH);
  waitUnits(3);
  digitalWrite(LED_P, LOW);
  waitUnits(1);
}

Both functions already include one dark unit after each element.

The Morse generator adds two further units after a recognized character, giving the required three-unit character gap. A space adds four more units, extending that gap to seven.

A typical character therefore looks like this:

case 'A':
  dit(LED_P);
  dah(LED_P);
  symbolSent = true;
  break;

The character decoding and pulse timing are separate. I can change the speed in one place or add a character without touching the timing functions.

3.5 The Pin Helpers

The ATtiny85 Arduino pins 0, 1 and 2 are unused and physically open in the FireFly Solar design.

configureUnusedPins() sets them to INPUT_PULLUP:

void configureUnusedPins()
{
  pinMode(UNUSED_PIN_0, INPUT_PULLUP);
  pinMode(UNUSED_PIN_1, INPUT_PULLUP);
  pinMode(UNUSED_PIN_2, INPUT_PULLUP);
}

The LED uses Arduino pins 3 and 4:

#define LED1_N_SIDE 3
#define LED1_P_SIDE 4

releaseLedPins() puts both pins into high impedance:

void releaseLedPins(int LED_N, int LED_P)
{
  digitalWrite(LED_N, LOW);
  digitalWrite(LED_P, LOW);

  pinMode(LED_N, INPUT);
  pinMode(LED_P, INPUT);
}

The order matters. Writing LOW first clears the output latch, so the internal pull-up remains disabled when the pin is switched to input.

There is no deliberately driven voltage across the LED during idle sleep, and no internal pull-up providing an unwanted current path.

4. Compiling and Programming the ATtiny85

4.1 Arduino IDE and ATTinyCore

The firmware is written as an Arduino sketch, using ATTinyCore to support the ATtiny85.

Install the board package through the Arduino Boards Manager, following the installation instructions in the ATTinyCore repository, and select the ATtiny25/45/85 family.

The firmware uses the AVR libraries for sleep, watchdog handling, interrupts and access to program memory:

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <string.h>

No additional third-party Arduino libraries are needed.

The ATtiny85 is programmed directly via ISP. There is no bootloader in the application.

4.2 Board Settings

The following settings are used for FireFly Solar:

Setting Value
Board family ATtiny25/45/85
Chip ATtiny85
Clock 1 MHz internal RC oscillator
Brown-out detection Disabled
millis() / micros() Disabled
Programming ISP
Bootloader None

The exact menu names depend on the installed ATTinyCore version.

1 MHz internal

Morse needs no speed. A lower CPU frequency reduces active current and allows operation at a lower supply voltage than higher clock frequencies.

A factory-fresh ATtiny85 already runs at 1 MHz, using the internal 8 MHz oscillator with the divide-by-eight fuse enabled. BOD is also disabled by default.

BOD disabled

The brown-out detector costs standby current, and a 1.8 V brown-out threshold also limits the useful operating time of the device.

In my tests, disabling BOD allowed the chip to continue operating down to approximately 1 V, giving about 20 minutes of additional blinking time.

This is below the specified operating voltage of the ATtiny85. Correct operation is not guaranteed there.

I accept this limitation for FireFly Solar. Chapter 7 explains how the firmware deals with the resulting recovery problem.

millis() disabled

Nothing in the firmware needs the Arduino timebase. There is no reason to have Timer0 running or to maintain a millisecond counter.

All timing comes from the watchdog.

4.3 Setting the Fuses and Uploading

Changing the clock or BOD settings in the Arduino IDE does not necessarily change the fuse configuration during a normal sketch upload.

The procedure is:

  1. Connect the ATtiny85 to the ISP programmer.
  2. Select the board, processor and settings listed above.
  3. Select the appropriate ISP programmer.
  4. Execute Burn Bootloader to set the fuses.
  5. Execute Upload Using Programmer.

The name “Burn Bootloader” is slightly misleading here. The operation is used to configure the fuse bits. The application itself does not need a bootloader.

With a 1 MHz target clock, the ISP clock must be slow enough for reliable programming. It should not exceed one quarter of the target CPU clock.

An 8 µs ISP bit-clock period, for example, corresponds to 125 kHz and is suitable for a 1 MHz ATtiny85.

4.4 Firmware Configuration

The main configuration parameters are located near the beginning of the sketch.

Parameter Standard value Purpose
DEBUG_TEST 0 Normal outdoor operation.
UNIT_WDT_A 2 First part of a Morse unit, 64 ms.
UNIT_WDT_B 1 Second part of a Morse unit, 32 ms.
sleepCycles 5 Number of 8 s idle sleep intervals.
darkSteps 40 Maximum number of 16 ms darkness measurement steps.
RECOVER_CYCLES 20 Number of recovery cycles after a reset.
BOD_FUSE_ENABLED 0 Optional software BOD disable during sleep.
morseText TOGO-LAB.IO FIREFLY Morse payload stored in flash.

The parameters are defined at compile time. There is no configuration interface or EEPROM configuration to maintain.

Change the payload, adjust the timing if needed, compile and program the ATtiny85.

5. Bench Test Mode

A device that sleeps 40 s per cycle and waits more than 13 minutes after every reset is not particularly convenient to debug on the bench.

That is what the DEBUG_TEST switch is for.

#define DEBUG_TEST 1

The changes are:

Parameter Field mode Bench mode
DEBUG_TEST 0 1
sleepCycles 5 1
Idle sleep 40 s 8 s
RECOVER_CYCLES 20 0
Bright-condition indicator None Short flash

The bench configuration skips the recovery wait, reduces the idle sleep to 8 s and gives a short flash when the firmware decides it is bright.

The bright-condition flash uses a single watchdog interval:

sleepWdt(3); // ~128 ms

That is useful when testing the LED as a light sensor. I can see whether the firmware decided “bright” or whether the LED is simply not being driven.

Cover the LED and the firmware should transmit the Morse text. Expose it to sufficient light and it should produce the short test flash instead.

The 8 s interval is the idle sleep time, not the total time between transmissions. A Morse transmission still takes its normal amount of time.

For outdoor operation:

#define DEBUG_TEST 0

Current measurements should also be made with the field configuration. The bench configuration reduces the idle sleep by a factor of five and adds LED activity during daylight.

6. How to Achieve Minimum Power Consumption

An ATtiny85 is a low-power chip, but it does not become a low-power design by itself.

The gains come from knowing what is running and why.

6.1 Power-Down, with the Watchdog as Alarm Clock

In power-down mode, the CPU clock and main oscillator stop.

The sleep mode is selected using:

set_sleep_mode(SLEEP_MODE_PWR_DOWN);

The AVR sleep library handles the corresponding sleep-mode bits in MCUCR. On the ATtiny85, SM1:SM0 = 10 selects power-down, and the SE bit enables the actual sleep operation.

According to the ATtiny25/45/85 datasheet, active current at 1 MHz is in the range of a few hundred microamperes, depending on the supply voltage. In power-down, with BOD disabled and the watchdog still running, current consumption can drop into the single-digit microampere range under typical conditions.

These are datasheet figures, not measurements on my board.

The watchdog oscillator continues running independently of the CPU clock. It wakes the processor when the selected interval expires.

The firmware uses this for everything:

  • The 16 ms darkness measurement steps.
  • The timing of Morse pulses and gaps.
  • The 8 s idle sleep intervals.
  • The recovery wait after a reset.

Even while the LED is lit during a Morse transmission, the CPU spends most of its time in power-down.

The LED does not need a running processor to stay on.

6.2 Switch Off What Is Not Used

The ATtiny85 has several internal peripherals that FireFly Solar does not need.

The following register operations disable them:

cbi(ADCSRA, ADEN);
ACSR |= (1 << ACD);

PRR = (1 << PRADC) | (1 << PRUSI)
    | (1 << PRTIM0) | (1 << PRTIM1);

ADCSRA — ADC Control and Status Register

Clearing ADEN disables the analog-to-digital converter.

The LED measurement does not require an ADC. It only needs to know when the cathode voltage falls below the digital input threshold.

An enabled ADC remains enabled in all sleep modes, so putting the CPU into power-down is not enough to switch it off.

The ADC is disabled before its clock is gated in PRR.

Disabling a peripheral and stopping its clock are two different things. Clock gating freezes the peripheral in its current state, and any resources occupied by the peripheral remain occupied.

The datasheet therefore requires the ADC to be disabled before its clock is stopped.

ACSR — Analog Comparator Control and Status Register

Setting ACD disables the analog comparator.

The comparator has no dedicated PRR bit. It has its own power control in ACSR.

FireFly Solar does not need the comparator, so I switch it off. This reduces current consumption while the CPU is active.

The comparator is normally disabled automatically in power-down. However, if configured to use the internal voltage reference, it can keep that reference active even during sleep. Explicitly disabling the comparator avoids this.

PRR — Power Reduction Register

The Power Reduction Register gates the clocks of unused peripherals:

Bit Peripheral
PRADC Analog-to-digital converter
PRUSI Universal Serial Interface
PRTIM0 Timer/Counter0
PRTIM1 Timer/Counter1

Clock gating reduces the current consumption of these modules while the CPU is active. In power-down, their clocks are already stopped.

With the ADC, comparator and BOD switched off, the internal voltage reference is no longer needed for these functions.

DIDR0, the Digital Input Disable Register, is not used. The sense pin must remain readable as a digital input when the CPU wakes up, and its ordinary input buffer is already disabled by the hardware during power-down.

For the details, see Power Reduction Register, Minimizing Power Consumption and Analog Comparator in the ATtiny25/45/85 datasheet.

6.3 Pins Are Part of the Budget

Unused inputs should not float. A voltage somewhere between a valid LOW and HIGH can cause unnecessary current consumption in a digital input buffer.

The three unused pins are therefore configured as INPUT_PULLUP.

The LED pins are a different story.

For the darkness measurement, the cathode must be able to float without a pull-up. During idle sleep, both LED pins are released to high impedance.

The output latches are set to LOW before switching the pins to input.

This removes any deliberately driven voltage across the LED and avoids an unwanted current path through the internal pull-ups.

High impedance does not mean zero leakage. The LED junction and the microcontroller pins still have their physical leakage currents.

6.4 No Arduino Timebase

delay() and millis() are convenient, but the normal Arduino timing infrastructure needs Timer0.

FireFly Solar has no delay(), no millis() and no analogWrite().

All waiting is done with sleepWdt().

This allows Timer0 and Timer1 to be disabled completely. There is no periodic timer interrupt from the Arduino timebase, and no reason to keep the CPU running while waiting for the next Morse element.

6.5 Optional BOD Disable During Sleep

The ATtiny85 also allows the brown-out detector to be temporarily disabled during sleep, even when it is enabled by the fuse settings. This feature is supported on ATtiny85 revision C and newer.

The firmware supports this with:

#define BOD_FUSE_ENABLED 0

Inside sleepWdt():

#if BOD_FUSE_ENABLED
  sleep_bod_disable();
#endif

If the BOD fuse is enabled, setting BOD_FUSE_ENABLED to 1 activates this feature.

The sleep_bod_disable() macro handles the timed sequence involving BODS and BODSE in MCUCR. The detector is switched off when the chip enters power-down and automatically becomes active again when the CPU wakes up.

This provides voltage supervision during active operation without paying the BOD current penalty throughout the sleep period.

The startup timing must allow the internal voltage reference and BOD circuitry to become operational before code execution resumes.

BOD_FUSE_ENABLED does not change the fuse itself. It only controls whether the firmware executes the software BOD-disable sequence before sleep.

In the standard FireFly Solar configuration, the BOD fuse is already disabled, so the parameter stays at 0.

The reason is simple: the 1.8 V BOD threshold shortened the useful blinking time by about 20 minutes in my tests. Without it, the ATtiny85 continued operating down to approximately 1 V.

The trade-off is reduced protection against undervoltage.

6.6 Where the Energy Actually Goes

The usual formula applies:

Iavg = Isleep × (1 − D) + Iactive × D

Where D is the fraction of time spent in active operation.

Reducing the duty cycle does more than shaving a few instructions.

The darkness check is cheap. The CPU wakes up briefly, reads the pin and goes back to sleep. In daylight it normally needs just one measurement step, and even in darkness the maximum is 40 steps.

The Morse transmission is where the LED starts to dominate the budget.

For the default payload:

Parameter Nominal value
Morse unit 96 ms
Total transmission 212 units
LED ON time 113 units
Transmission duration 20.35 s
LED ON duration 10.85 s
Darkness measurement 0.64 s
Idle sleep 40 s
Complete night-time cycle ~61 s

Assuming an LED current of 1 mA:

Qled = 1 mA × 10.85 s
     = 10.85 mC per cycle

For comparison, assuming a microcontroller sleep current of 5 µA and using the full cycle duration as an approximation:

Qmcu = 5 µA × 61 s
     = 0.305 mC per cycle

In this simplified example, the LED consumes approximately 36 times as much charge as the sleeping microcontroller.

These are estimates, not measurements. They do not include the additional current during CPU wake-ups or the losses and leakage of the remaining hardware.

The 36:1 ratio is not a figure for the complete device, but it shows where further optimization makes sense.

The main levers are now the payload length, the Morse unit duration and the interval between transmissions.

The complete energy budget also includes the supercap’s leakage, the DC/DC converter’s quiescent current and conversion efficiency, and the solar cell’s charging efficiency.

Optimizing the firmware is only one part of optimizing the device.

6.7 The Result

The current firmware v1.0, tested outdoors in winter at −1 to 8 °C after a sunny day, blinks for well over 12 h on one charge with a 10-character payload.

The actual runtime depends on the payload, the available solar energy, the temperature and the hardware configuration.

7. Autonomous Recovery

FireFly Solar runs outdoors with nobody to press reset.

That is harder than it sounds because the supply is not a bench supply. The energy stored in the supercap increases during the day and decreases through the night.

I also turned the brown-out detector off to reduce standby current and extend the useful operating time.

Without BOD, the chip is no longer reset at the configured brown-out threshold when its supply voltage sags. It keeps running as long as it still can, potentially below its specified minimum operating voltage.

A chip in that range can behave strangely.

I cannot rule out an endless loop, a stuck configuration or a chip asleep with its wake-up source gone.

The latter is a particularly unpleasant case. A supercap that is hardly drained by a sleeping chip may take a very long time to discharge far enough for another power-on reset.

The firmware therefore needs a way to recover without relying entirely on normal program execution.

7.1 The Watchdog as Dead-Man’s Switch

The ATtiny85 watchdog can operate in three active modes:

WDIE WDE Mode
0 0 Watchdog stopped
1 0 Interrupt mode
0 1 System reset mode
1 1 Interrupt and system reset mode

FireFly Solar uses the combined interrupt and system reset mode.

The mechanism works like this:

  1. sleepWdt() sets both WDIE and WDE.
  2. The first watchdog timeout generates an interrupt and wakes the CPU.
  3. When the interrupt vector is executed, the hardware clears WDIE. WDE remains set.
  4. The main code continues and calls sleepWdt() again, re-arming the combined mode.
  5. If the main code does not get there, the next watchdog timeout resets the chip.

The interrupt service routine only sets f_wdt. It does not re-arm the watchdog.

Re-arming it inside the interrupt service routine could allow the main program to hang while the interrupt continued to keep the watchdog satisfied.

Instead, the main program has to reach the next sleepWdt() call.

The firmware keeps its awake intervals short compared with the shortest watchdog timeout, approximately 16 ms. During normal operation, the next call re-arms the watchdog before a reset can occur.

If the main code hangs after waking up, the watchdog resets the chip at the next timeout.

A failure earlier in the watchdog cycle can take up to two timeout periods from the last re-arming, provided the watchdog remains operational.

The timeout depends on which sleep interval was active. It can be anything from milliseconds to several seconds.

The watchdog acts as both the alarm clock and a dead-man’s switch.

7.2 The Timed Sequence

Changing WDTCR is protected against accidental modification.

To change the protected configuration bits, WDCE and WDE must first be written together. The new configuration then has to be written within four CPU cycles.

The limit is four cycles, regardless of the CPU frequency.

I use two adjacent OUT instructions in inline assembly, with interrupts disabled:

const uint8_t unlock = _BV(WDCE) | _BV(WDE);

__asm__ __volatile__(
  "out %[wdt], %[unlock] \n\t"
  "out %[wdt], %[config] \n\t"
  :
  : [wdt]    "I" (_SFR_IO_ADDR(WDTCR)),
    [unlock] "r" (unlock),
    [config] "r" (cfg)
  : "memory"
);

An AVR OUT instruction takes one CPU cycle.

The first instruction unlocks the register. The second immediately writes the new configuration.

The operands use two different types of assembly constraints.

_SFR_IO_ADDR(WDTCR) provides the I/O address as a compile-time constant ("I"). The AVR "I" constraint accepts values from 0 to 63, which matches the I/O address field of the OUT instruction.

For the ATtiny85, that address is 0x21.

The two values, unlock and cfg, are passed in CPU registers ("r").

Both values are therefore ready before the first OUT executes. There is no address calculation or additional operand loading between the two writes.

The resulting instruction sequence could look like this:

out 0x21, r24
out 0x21, r25

The actual CPU registers are selected by the compiler.

Both instructions are part of the same assembly template, so the compiler cannot insert additional instructions between them. Interrupts have already been disabled by cli().

The "memory" clobber tells the compiler that the assembly may access memory beyond the explicitly listed operands. It acts as a compiler-level memory barrier, but it is not what guarantees the timing of the two writes.

That guarantee comes from the two adjacent OUT instructions and the disabled interrupts.

The inline assembly is there for the guarantee, not for speed.

The operand constraints are documented in the GCC manual — Constraints for Particular Machines, AVR.

7.3 The WDRF Trap

After a reset, the MCU Status Register MCUSR contains information about the reset source.

Flag Reset source
PORF Power-on reset
EXTRF External reset
BORF Brown-out reset
WDRF Watchdog reset

WDRF comes with a trap: while it is set, WDE is forced to 1 and cannot be cleared.

After a watchdog reset, the watchdog is still running with its shortest timeout, approximately 16 ms.

If the firmware does not clear the reset flag and disable the watchdog in time, another watchdog reset occurs. Then another, and so on.

A recovery mechanism that creates a reset loop is not much of a recovery mechanism.

The fix has to run before normal application initialization.

The firmware uses a routine in the .init3 startup section:

static uint8_t resetCauseEarly
  __attribute__((section(".noinit")));

void earlyWatchdogInit(void)
  __attribute__((used, naked, section(".init3")));

void earlyWatchdogInit(void)
{
  resetCauseEarly = MCUSR;
  MCUSR = 0;
  wdt_disable();
}

The sequence matters:

  1. Save the reset flags.
  2. Clear MCUSR, including WDRF.
  3. Disable the watchdog.

Only after WDRF has been cleared can the watchdog reset function be disabled.

The attributes are doing some useful work here:

Attribute Purpose
used Keeps the routine emitted even without an ordinary function call.
naked Suppresses the normal function prologue and epilogue.
section(".init3") Places the routine in the early AVR startup sequence.
section(".noinit") Prevents the C runtime from clearing the saved reset flags.

The routine is not called from setup(). It is part of the AVR startup sequence, and execution continues into the following initialization sections.

The saved value survives C runtime initialization because it is stored in .noinit.

This allows setup() to read the original reset cause while the watchdog is already safely disabled.

7.4 The Recovery Wait

A watchdog reset should not immediately be followed by another LED transmission if the reason for the reset may have been a marginal supply voltage.

The same applies after a power-on reset.

The firmware checks the saved reset flags in setup():

if (resetCauseEarly & ((1 << PORF) | (1 << BORF) |
                       (1 << EXTRF) | (1 << WDRF))) {
  recoverCycles = RECOVER_CYCLES;
}

All four reset causes lead to the same recovery procedure. There is no separate watchdog recovery mode.

In field operation:

#define RECOVER_CYCLES 20

During recovery, the main loop simply decrements the counter, releases the LED pins and executes its normal idle sleep.

No darkness measurement and no Morse transmission.

The nominal recovery time is:

20 cycles × 5 × 8 s = 800 s

800 s = 13 min 20 s

The idea is to give the supercap some time to recover before the LED starts pulling energy from it again.

Of course, this only helps with recharging if solar energy is available.

There is no voltage measurement in the firmware, and the end of the recovery period does not mean that a particular charge level has been reached.

It is a very low-energy pause, nothing more.

In bench test mode, RECOVER_CYCLES is 0, so the recovery period is skipped.

7.5 What It Cannot Do

The watchdog cannot repair a damaged part, create energy that the solar cell did not deliver or make a chip run correctly at an arbitrary low voltage.

Below the specified supply-voltage range, nothing is guaranteed.

What I get is a hardware recovery mechanism that does not depend on the main program continuing to work.

As long as the watchdog itself remains operational and correctly configured, a software hang that prevents the next sleepWdt() call can trigger a hardware reset.

After that reset, the early startup routine takes care of the watchdog, and the recovery wait applies before the firefly tries to blink again.

I ran the hardware down on one charge until the supercap voltage was below 0.6 V, measured ahead of the DC/DC converter.

I also have the winter field test, with temperatures between −1 and 8 °C.

What I have not yet confirmed is behaviour on warm summer nights. Higher LED junction leakage may shorten the discharge time during the darkness measurement, requiring an adjustment of darkSteps.

The goal is to avoid a temporary problem turning into a permanently dead firefly.

8. Conclusion

The Morse code was the easy part. Making an ATtiny85 do nothing for 40 seconds, on the other hand, took some work. An LED that works backwards, a watchdog that doubles as an alarm clock and a dead-man’s switch, and two lines of assembly because four CPU cycles matter. This is why I like playing with these little chips.

And now, somewhere on my balcony, a few microamperes keep a tiny firefly asleep until it has something to say.

闇にひとこと — a single word in the darkness.

TOGO-LAB.IO FIREFLY


Sources & Further Reading

FireFly Solar / 日輪蛍 – Nichirin Hotaru

太陽を宿し、夜にモールスを灯す蛍。
Taiyō o yadoshi, yoru ni Mōrusu o tomosu hotaru.
A firefly carrying the sun, lighting Morse in the night.

FireFly Solar is my small solar-powered Morse blinker for outdoors. Think of it as a solar-punk style LED throwie, but without the disposable coin cell.

Some years ago, when I started playing with AVR and ATtiny programming, I built a very simple Morse “throwie”: one ATtiny, one LED, one resistor, and some power-friendly firmware. The goal was to use as few parts as possible while still doing something useful.

The basic behaviour is simple: detect daylight, sleep when it is bright, blink when it is dark. The LED can even be used as a light sensor, which keeps the hardware nicely minimal.

This new version keeps the spirit of that old project, but moves it closer to a small outdoor object. It uses a solar cell and supercapacitor instead of a disposable battery. During the day it charges. At night it wakes up and sends a Morse-style light signal.

So it is no longer really a throwie. It is more like a small pendant or garden signal creature. Hang it somewhere with daylight, keep the electronics protected from direct weather, and let it blink when the sun is gone.

Why this Name?

Why Japanese? Because I want to do so, but the repository name stays simple: FireFly Solar

For blog posts and documentation I use the Japanese name:

FireFly Solar / 日輪蛍 – Nichirin Hotaru

Roughly translated, this means something like sun-disc firefly. This will keep the solar idea for the new design.

About this Project

This is partly a small hardware project and partly a workflow exercise. I want to improve my practical design skills in a few areas:

  • low-power electronics
  • solar charging with supercapacitors
  • simple outdoor mechanical design
  • 3D-printed parts
  • documentation for beginner-friendly DIY kits
  • repeatable project workflow from idea to small kit

The hardware itself should stay simple. The larger goal is to define a clean path from prototype to PCB, enclosure, documentation, BOM, and maybe a small DIY kit later.

Maybe this will end up on Tindie one day. Maybe it will only become a useful internal reference project for future ToGo-Lab hardware. Both outcomes are fine.

Idea behind

The target is a beginner-friendly soldering kit with clear documentation and hackable firmware.

Current idea:

  • MCU: ATtiny45/85, through-hole
  • Power: solar cell plus supercapacitor
  • Behaviour: night-only Morse-style blink
  • Light detection: preferably minimal hardware, using the LED as in the original morse throwie
  • Firmware: editable with Arduino IDE
  • Mechanics: small outdoor-friendly holder or pendant structure

Where to find the Details

The source files and releases live in the ToGo-Lab Gitea repository, https://gitea.togo-lab.io/tgohle/0001-FireFly

Larger internal notes and working documents may live in Nextcloud during development, but the public-facing documentation should stay in the repository as much as possible.

The default licence target for documentation and design files is:

CC-BY-NC-4.0

Firmware licensing will be handled separately if needed.

Project Details & Descriptions:

Project 0003: SDG2042X GUI v0.2.* — first patch round and bug tracker setup

The current work on my Linux GUI for the Siglent SDG2042X is about findig bugs before piling more features on top.

Version 0.1 already did the basics: Waveform control, burst and sweep settings, ARB handling, presets, a small SCPI console, and screenshot support. But no software without bugs. So besides the first code fixes, I also set up a proper issue tracker for the project in Gitea (this was also a point in my gitea learning 2Do List). The repository now has labels, issue templates, a small board workflow, and the first full review list entered as issues. For this first round, I started with the items that looked most worth fixing immediately: #1, #2, & #12. I also did #6 as it was a little bit annoing thing.

The code side for those is already done in v0.2 in this git. What is still open is real verification against the actual SDG hardware before I close them.

Current issue list

Find this in the Gitea: https://gitea.togo-lab.io/tgohle/0003-SDG2042X-PyQt-GUI-for-Linux/issues

Status of the project is now (18.04.2026):

I wrote and ran a small test script for issues #1, #2, #6, and #12, plus a final hardware check on the SDG itself: https://gitea.togo-lab.io/tgohle/0003-SDG2042X-PyQt-GUI-for-Linux/src/branch/master/script/archive/V0.2 That gives me enough confidence to close all four issues and move this first bug-fix round a step further toward done.

  • bug tracker is set up in Gitea, including milestone for v0.2
  • the full first review list is in the tracker
  • the first four fixes (1,2,6 & 12) are already coded and l loaded up to this git
  • tested with script, passed.
  • hardware verification for issue 2 done

Not exciting, but necessary: the tedious grind of bugfix work, so the front end becomes handy enough that it does not get in the way of my other hobby projects.

Further bug and issue work will only tracked in the issue tracker.


Update 20.04.2026 Bug-fix round for the SDG2042X Linux GUI

A productive bug-fix day on the SDG2042X GUI for Linux.
The focus was on medium-severity issues around ARB handling, sweep robustness, preset handling, and input validation.

  • #15 — ARB download response parser fails on real SDG
  • #10 — Sweep fallback from WAV to SPAC is timing-fragile
  • #9 — Preset recall ignores current channel selection
  • #8 — Preset file path selection is not propagated back to Main
  • #3 — human_to_eng() silently accepts ambiguous m suffix

Details in the closed section of the gitea: https://gitea.togo-lab.io/tgohle/0003-SDG2042X-PyQt-GUI-for-Linux/issues?type=all&state=closed

Version progression during this round

  • v0.2.1 → Bug #15
  • v0.2.2 → Bug #10
  • later working copy → Bug #9 and Bug #8
  • v0.2.6 → Bug #3

Summary

This round cleaned up several of the more annoying reliability and usability problems in the GUI: better ARB handling on real hardware, safer sweep fallback, more reliable preset behaviour, and stricter input validation where silent misinterpretation would be risky. Overall, a good step toward making the GUI more dependable as an actual bench tool instead of just a nice front-end.

Setting up Nordic’s Power Profiler Kit II (Linux)

For some of the next TōGō-Lab projects I’m thinking about, I want some gear that lets me look properly into the very low-power usage of my builds instead of just guessing. Besides some more expensive gear like the Joulescope, I finally bought Nordic’s Power Profiler Kit II, which looked like a very good fit for the kind of measurements I want to do. Nordic positions the PPK2 as a standalone power-measurement and power-optimization tool for embedded hardware, with support for real-time current measurements and use with both Nordic boards and external hardware.

As typical for some lab gear, it runs nicely under Windows, in my case in a virtual Win10 setup. But I wanted it on my actual Linux workbench machine, where the rest of the lab IT frontend for my tools lives. That part was a bit more difficult than expected. Nordic gives you an AppImage, but it is a little bit tricky to get it running.

Because the blog will malformat the command lines find the installation lab notes as markdown file in my Gitea as project #0006:
https://gitea.togo-lab.io/tgohle/0006-Setting_up_Nordic_PowerProfilerKitII_Linux

For the official side, Nordic’s product page for the kit is here, the official PPK2 setup documentation is here, and the official nRF Connect for Desktop installation documentation is linked here.


Nordic Power Profiler Kit II Test Setup
Nordic Power Profiler Kit II Test Setup
nRF Connect for Desktop v5.2.1
nRF Connect for Desktop v5.2.1

Test Measurement:

nRF Connect Power Profiler App, working Measurement
nRF Connect Power Profiler App, working Measurement

電力番長 Denryoku Banchō – a MightyWatt Linux CLI

Since I’m currently in the process of redesigning and updating the setup of my electronics lab, I no longer want to keep Windows around just to run my electronic load I own now for 10 years: The famous MightyWatt.

So this fork moves the project where it fits better to my actual lab setup: Into my Linux environment, closer to my usual tools, and I hope much easier to automate. The current focus is the CLI backend. That is the useful part for headless operation, scripting, CSV logging, JSON-driven test runs, and remote access. A GUI may come later, but only as a second layer. First the engine, then maybe the dashboard. The name 電力番長 (Denryoku Banchō) fits that idea well: the CLI sits on the hardware, owns the usb link, and acts as the boss in the background.

But first: A big thank you is due to the original MightyWatt developer, Jakub Polonský (kaktus85) whose MightyWatt repositories remain the foundation this work builds on. The original GitHub project pages are here: MightyWatt (that’s the one I own) and MightyWatt R3.

My Linux-native fork lives here: 0005-DenryokuBancho on ToGo-Lab Gitea which you also can access it via one of my landing pages.

This blog post will be updated as the project progresses. Beta 0.1 is now available in my Gitea repository. It is already running, but it still needs proper testing in the next stages of the project.

電車ベクトル (Train Vector): The Software

Short overview

This is the software description of the 電車ベクトル (Train Vector) project (link to overview). The hardware side (link to description) isolates and prepares the motor signal, but the real decision how to light the LEDs is done in software.

Because the signal comes from a noisy H-bridge motor controller, the software has to do more than just one raw read and one if statement.

The actual Arduino sketch is here in the git subfolder: https://gitea.togo-lab.io/tgohle/0004-DenshaBekutoru/src/branch/master/firmware/ArduinoTest/DenshaBekutoru-0004_Version-0-2_ProMini_PCB2026-2_V01

In Summary

The software is the part that turns the noisy input from the hardware into a stable direction decision. It does that by:

  • averaging the analogue inputs,
  • calibrating itself at startup,
  • building a threshold from the real idle behaviour,
  • using hysteresis,
  • remembering the last valid direction,
  • driving the outputs accordingly,

Basic idea

The software reads two analogue voltages from the optocoupler output stage:

  • ADC_PIN_1 = A0
  • ADC_PIN_2 = A1

These two signals represent the processed motor direction information. If the motor is driven one way, one side will dominate. If the motor is driven the other way, than the other side will dominate. So the basic software idea is to compare both voltages and evaluate the difference:

  • diff = v1 - v2

If diff is clearly positive, the software decides for direction 1.
If diff is clearly negative, the software decides for direction 2.
If the difference is too small, the software does not change direction and simply keeps the last valid state.

That last point is the important one. It means the headlights do not start flickering just because the motor is stopped, the signal is weak, or the input is sitting in some noisy neutral area.

First step: averaging the analogue inputs

The first thing, after power on: The sketch averages the inputs over a time window. This is done in:

  • measureAveragedVoltages()

The code samples both analogue channels repeatedly over:

  • SAMPLE_WINDOW_MS = 100
  • SAMPLE_DELAY_US = 500

So instead of reacting to one random noisy measurement, the software builds an average value for both channels:

  • v1
  • v2

This is one of the most important parts of the program, because the motor signal is not clean. Without averaging, the later direction decision would be much more unstable.

Second step: calibration when nothing happens

At startup, the software assumes there is no real movement yet. That is the moment it uses to adapt itself to the actual build, controller, and wiring. This is done in:

  • calibrateVdiffThreshold()

The sketch performs multiple averaged measurements at boot:

  • AverageRepeat = 100

For each of these measurements it calculates:

  • |v1 - v2|

This gives the natural mismatch between both channels when no real direction decision should happen yet. Because even in the idle case both channels are usually not perfectly identical, the software does not assume zero. Instead, it measures the real baseline. The measured values are sorted, and then the median is taken:

  • VdiffBaseline = median(|V1-V2|)

I think this is a good choice, because the median is less sensitive to single bad spikes than a simple average. From this baseline, the code builds the real decision threshold:

  • VdiffThreshold = max(VdiffBaseline * 1.5, 0.03V)

So the threshold is:

  • adapted to the real hardware setup
  • increased by a margin
  • never allowed to go below a minimum floor

This is exactly the part that should help the board work with different train builds and different controllers without having to hard-code one fixed voltage value.

Third step: threshold and hysteresis

Once the baseline threshold is known, the software creates two limits:

  • T_hold
  • T_enter

These are derived from the calibrated threshold:

  • T_hold = 1.0 * VdiffThreshold
  • T_enter = 2.0 * VdiffThreshold

This creates a small hysteresis system. The idea is:

  • if the signal difference is very small, hold the old direction
  • if the signal difference is clearly strong, allow a direction change
  • in between, still hold the old direction

So the software does not switch direction the moment the signal only barely crosses one border. That makes the behaviour much more stable.

The state machine

The actual state machine is very simple and handled in:

  • updateDirectionFromVoltages()

mainly State machine (direction memory) + Hysteresis (Version A)

I use two thresholds:

  • T_hold (smaller): below -&gt; treat as neutral and HOLD state
  • T_enter (larger) : above -&gt; allow direction change (set by sign)

Behavior:

  • If |diff| = T_enter : set direction by sign
  • Else (between) : hold direction

Presets (implemented as multipliers of the calibrated VdiffThreshold):

  • T_hold = 1.0 * VdiffThreshold
  • T_enter = 2.0 * VdiffThreshold
  • Inputs derived from v1, v2: diff = v1 – v2

This means the software remembers the last valid direction and does not jump around in the weak or noisy range.

Output logic

Once the state machine has decided the direction, the outputs are updated in:

  • applyDirectionOutputs()

The output pins are:

  • LED_DIR1_PIN = 3
  • LED_DIR2_PIN = 9

The code first switches both outputs off and then activates only the matching one:

  • direction 2 -> D3 on
  • direction 3 -> D9 on

So at the moment the output stage is simple:

  • one direction = one output active
  • the other direction = the other output active

This is enough for the basic headlight function.

The sketch also includes a small startup blink sequence in:

  • initBlinkSequence()
  • blinkLED()

That is mainly useful to see directly that the board is alive after power-up.

Main loop behaviour

After setup and calibration, the loop is very simple:

  1. measure both averaged input voltages
  2. update the direction state
  3. apply the outputs
  4. print debug values to serial
  5. wait a short time

The delay at the end is:

  • delay(300)

So this is not written as a super-fast control loop. It is written as a stable and easy-to-observe detection loop, which makes sense for this kind of project stage.

Serial output for debugging

For debugging, the code can print all important values to serial output.

This is controlled by:

  • SerialOutputAllow

The function is:

  • serialPrintAll()

The output includes:

  • v1
  • v2
  • |v1-v2|
  • VdiffBaseline
  • VdiffThreshold
  • T_hold
  • T_enter
  • current direction

For development this is useful, because it makes it much easier to see why the software made a certain decision and how well the calibration worked.

Overview of the used functions

Here is a short overview of the most important functions in the sketch:

  • blinkLED()
    Small helper to blink one output LED

  • initBlinkSequence()
    Startup blink pattern to show the board is alive

  • applyDirectionOutputs()
    Switches the output pins according to the current direction state

  • measureAveragedVoltages()
    Reads both analogue inputs over a time window and calculates averaged voltages

  • sortFloatArray()
    Sort helper used during calibration

  • medianOfSortedFloatArray()
    Returns the median value from the sorted calibration data

  • calibrateVdiffThreshold()
    Measures the idle mismatch at startup and creates the calibrated threshold values

  • updateDirectionFromVoltages()
    The actual direction decision logic with hysteresis and direction memory

  • serialPrintAll()
    Prints all relevant measured and calculated values for debugging

  • setup()
    Initialises serial, pins, calibration, startup blink, first direction update

  • loop()
    Repeats measurement, state update, output update, and debugging output

電車ベクトル (Train Vector): The Hardware

Short overview

This is the HW description of the 電車ベクトル (Train Vector) project I described in this overview.

The main job of the hardware is to retrieve and process the signal direct from the motor, so that it can be used by the Arduino’s analogue input. The Arduino then does the magic and controls 4 LEDs (2 for each direction). The hardware will also have some additional features, so I can send out 2 more signals as a future option and also expose the I2C and TX/RX lines of the Arduino. There will also be a future option to control the brightness of the LEDs via PWM, controlled by a variable resistor or light (LDR). All this has to fit on a very small PCB, using the typical brick size.

The schematic is built around these main blocks:

  • input signal processing
  • Arduino Pro Mini 5V as controller, also providing the 5V needed
  • output section for the headlights
  • test circuit
  • future options
0004-DenshaBekutoru_v0.2_schematics

The PCB is split into 3 sections

  • signal processing and controller board / section
  • future options (light PWM and communication) section
  • test circuit section

All details, including KiCad files, you will find in the ToGo-Lab Gitea.

Input signal processing

To get the signal from the brick-type motor or controller, I adapted this brick wire. In the picture you will see where the supply voltage, ground, and the motor wires are located. This connects to J1 in the schematic.

0004-DenshaBekutoru_v0.2_Connector

The input side reads the motor-related signals and prepares them for the controller. Because this is taken directly from the motor via J1, the signal is neither clean logic nor directly usable by the Arduino analogue inputs. It comes with switching noise, polarity changes, and inductive effects. Also, the voltage is too high to be properly handled later by the analogue inputs.

In the schematic, the parts doing this are: R1, R2, D1, D2 (input protection for the LEDs in the optocouplers) and U1, U2 = PC817 optocouplers.

To keep the controller side safer and cleaner, I used two isolated input channels with PC817 optocouplers (that was also the reason why I built a small tester for optocouplers). These optocouplers will act as rectifiers due to the polarity change (J1-3 and J1-4).

R3 and R4 together with D4 and D5 are used for pull-up, signalling (also for debugging), and of course to deliver voltage to the phototransistor in the optocoupler.

The signals will at the analoge inputs will show like this (slow, mid power, as example):

Arduino Pro Mini 5V as controller

For the controller I used an Arduino Pro Mini 5V / 16 MHz. It is small enough, I have reset logic on it, and also a power supply, so I can use the voltage directly from the remote controller. The on-board power supply will also be used to feed the optocouplers.

The Pro Mini is small, cheap, easy to replace and I understand how to program it because my programming skills are limited, I am more the HW guy, but feel free to use your own prefered µC. It is also more than powerful enough for this job and has everything needed to do analogue measurement and drive some LEDs. Another advantage is that the Pro Mini keeps the design easy to reproduce later for a DIY kit. No special programmer or unusual module is needed.

Output, future options, and test section

On the output side I used Arduino pins D3 and D9 for the two direction outputs. I used D3 and D9 because both pins support hardware PWM. The current version mainly uses them as normal outputs, but this keeps the option open for later LED dimming and other light-control functions without changing the hardware.

At the moment it is not tested; the basic function is only on/off switching of the headlights according to direction. But I wanted to keep the option open to dim the LEDs later. That could be useful for a more realistic light level, different train setups, or later expansion ideas.

Each direction drives two white LEDs in parallel, with each LED (D10, D11, D12, D13) having its own series resistor (R5, R6, R7, R8).

The future options are PWM control by resistor (RV1 and R9). You can replace RV1 with an LDR. There are also connectors for communication: I2C and TX/RX and 2 extra digital outputs to drive LEDs.

The LEDs later will be the ones in the train, so I placed the LEDs you see in the schematic on the test part of the PCB. To connect them from the mainboard I added the connectors J2 and J3.

Main PCB

The main PCB contains the complete working circuit:

  • motor-side input connection
  • isolated signal processing
  • Arduino Pro Mini socket
  • main headlight outputs
  • basic support parts

This is the board that matters. If somebody only wants the core function, this is the section that needs to work. You can detach the future options part and also the test part.

The layout was done with a small footprint in mind, because the board is intended to sit inside a brick-built locomotive, where space is always limited.

0004-DenshaBekutoru_v0.2_PCB

Additional detachable section

There is also an additional detachable PCB section. This part is not required for the core function, but it gives room for expansion without changing the main board concept too much. In the current design this includes optional extra light outputs and an option for brightness control, for example via LDR or potentiometer. This part also expose the pins for communication, I2C and TX/RX.

Test section

I also included a small test section on the PCB. This is simply practical. For a board like this, bring-up is much easier if basic functions can be checked directly on the board before everything is installed in a locomotive. The test section helps to verify that the direction outputs behave as expected and that the board is alive before going into real use. Before installing it, you can cut this away easily.

電車ベクトル (Train Vector): Project Overview and Current Status

What this project does

電車ベクトル (“Densha Bekutoru” / Train Vector) is a small board for LEGO, BlueBrixx, or similar locomotives built from bricks. Its job is to detect the current driving direction and switch the front and rear lights (2 white LEDs for each direction) to match.

That is the whole point of the project: the train changes direction, and the lights should follow automatically. They also stay on if the train stops; only when the direction changes do the lights switch to the correct direction.

This is Project No. 0004 for my Togo-Lab hobby / side project and the first “full-blown” one, meaning the result should be a DIY kit ready for everybody to use.

You will find the project files (schematics, PCB, controller software) in my Git: https://gitea.togo-lab.io/tgohle/0004-DenshaBekutoru

Why detecting the direction from motor input is not as simple as it sounds

In theory, it should be easy: just look at the motor polarity, add a simple state machine in hardware or software, and done. But in reality it is not that simple.

The motor in such setups is driven by an H-bridge circuit to deliver different power levels = different resulting speeds. Therefore, the signal on the motor lines is not a nice, stable DC level. You get switching effects, noise, and inductive spikes from the motor. Depending on the controller, load, and wiring, the signal can look pretty messy.

As an example, the following pictures are oscilloscope readings for one direction, let’s say direction “A”.

minimum power (slow speed):

20251026_Direction_A-Slow

maximum power (high speed):

20251026_Direction-A-Fast

You will notice the noise and, making the problem even worse, the inductive voltage, so you get reverse voltage as well. Simply installing an LED and resistor would result in flickering in each direction, with the level depending on speed. But this is of course not the right thing for a headlight.

So the challenge is not just detecting a direction once and using a state machine. The challenge is to sense the direction only from motor voltage and get rid of flickering, inductive voltages, and reactions to every little disturbance.

The current approach I use

My idea was to use two isolated input channels via optocouplers and a small controller (Arduino Pro Mini 5V type) to evaluate the motor-side signals. This should be small enough to fit the other constraint as well: the small footprint / volume, because this will be installed in the train, meaning there is very little space, and it needs to match the size of typical bricks.

On the software side, I did not go for a super simple “read once and switch” solution. The firmware works with averaging, calibration, and hysteresis so that short spikes or unstable transitions do not immediately flip the detected direction.

I hope this will make it also usable for a wide range of controllers, from low-cost Chinese controllers up to the official ones.

Current status

At this point in March 2026, I have a working design = hardware PCB and a working version of the software. The current version 2 (beta) hardware is built and working. Three PCBs were produced, assembled, and tested. The Arduino code was written to fit the actual HW setup, but so far it shows only the very basic function: switching lights according to direction.

I think the project is in a good beta state: real hardware exists, it works, and it is ready for practical testing. My colleague, who originally asked for this circuit for his hobby use, will show and use it in his model train club. I hope for real-life testing. This will give much better input than bench testing alone.

PXL_20260308_111601647_copy

So the current version 2 works, but it is still beta.

Related posts

In the next blog posts I will describe:

Outlook

Maybe there will be a version 3, depending on the input. I also hope that some of the club members will want this hardware as well, so I will design version 3, and this would also be the first DIY kit and the transition from beta to the first “official” version.

Post-Mortem: Antivirus Integration on a 1 GB Nextcloud VPS (failed due load)

Failing Experiments Are Useful

Today I tried to push my togo-lab.io setup (see 2nd block at my landing page for all services) a bit further than strictly necessary. So maybe you noticed some outages.

Why I did this? Not only for production security reasons, but also out of curiosity: How far can I go with limited resources? I want to understand where the real limits for my setup are.

In this experiment, I wanted to see whether a single small VPS could reasonably host Nextcloud, a Matrix server, and Gitea, and still handle antivirus scanning for file uploads. At first glance it looked tight, but maybe possible. In practice, it pushed this small VPS over the edge.

That outcome was useful for my learning and understanding. When things fail or become unstable, I usually learn much more than when everything works smoothly. As a technician, breaking things on purpose for learning is, for me, typically the fastest way to understand them.

The following section is a post-mortem of that experiment: what it revealed, what I learned from it, and what would be required if I want to add antivirus scanning in the future.


Context:
This server hosts multiple self-managed services on a small VPS (1 GB RAM, 1 vCPU):

  • Nextcloud (primary collaboration platform)
  • Matrix server
  • Gitea
  • Supporting stack (PHP-FPM, MariaDB, Redis, Apache/Nginx, Fail2Ban)

The goal was to add antivirus scanning for uploaded files in Nextcloud, as preparation for future collaborative use.


Initial Goal

Enable server-side antivirus scanning for Nextcloud uploads using ClamAV, with the following constraints:

  • Lightweight
  • Automated
  • No interactive maintenance
  • Suitable for a self-hosted environment

This is a reasonable baseline requirement once multiple external contributors are involved.


Attempted Approaches

1. ClamAV Daemon (clamd) + Nextcloud (Socket Mode)

What was tried

  • Installed ClamAV daemon

  • Tuned clamd.conf aggressively (single thread, reduced parsers, size limits)

  • Added strict systemd memory limits

  • Disabled background scans

  • Socket-based integration with Nextcloud

  • **changes to the default /etc/clamav/clamd.conf

          # === VPS-safe limits ===
          MaxThreads 1
          ConcurrentDatabaseReload no
    
          # File size limits (Nextcloud uploads)
          MaxFileSize 50M
          MaxScanSize 75M
          StreamMaxLength 75M
    
          # Archive / recursion limits
          MaxRecursion 10
          MaxFiles 5000
    
          # Timeouts
          ReadTimeout 120
          CommandReadTimeout 120
    
          # Disable low-value / memory-heavy scanners
          ScanHTML false
          ScanMail false
          ScanSWF false
          ScanHWP3 false
          ScanXMLDOCS false
    
          # Reduce bytecode impact
          Bytecode true
          BytecodeTimeout 20000
    
          # Reduce RAM further (Nextcloud upload use-case)
          PhishingSignatures false
          PhishingScanURLs false
          DisableCache true
          ExtendedDetectionInfo false
  • best I got, via free -h

total used free shared buff/cache available
Mem: 960Mi 926Mi 68Mi 31Mi 101Mi 33Mi
Swap: 1.0Gi 843Mi 180Mi – – –
    $ swapon --show
    NAME      TYPE  SIZE   USED PRIO
    /swapfile file 1024M 848.5M   -2`

Observed behavior

  • clamd resident memory usage: ~500–600 MB
  • Heavy swap usage even after tuning
  • Periodic stalls, SSH lag, partial service unresponsiveness
  • OOM kills during database reload or startup

Conclusion Even heavily tuned, resident ClamAV is not viable on a 1 GB VPS that already runs multiple services.


2. ClamAV Executable Mode (clamscan on upload)

What was tried

  • Disabled clamd entirely
  • Used Nextcloud Antivirus for Files app in Executable mode
  • Scanning only on upload
  • Strict size limits
  • No background scans

FYI Final authoritative configuration in NextCloud App “Antivirus for Files”

  • Mode: ClamAV Executable
  • Path to clamscan: /usr/bin/clamscan
  • Extra command line options (comma-separated): --no-summary,--infected,--max-filesize=50M,--max-scansize=75M
  • Stream Length: 104857600
  • Block uploads when scanner is not reachable: Yes
  • Block unscannable files: No
  • Background scans: effectively off (unchecked)

Observed behavior

  • Technically functional
  • No permanent memory footprint
  • However:
    • Uploads caused noticeable CPU + IO spikes
    • PHP-FPM workers stalled under load
    • Combined service activity still led to instability

Conclusion Even non-resident scanning adds too much peak load for this VPS when combined with:

  • Nextcloud
  • Matrix
  • Gitea
  • Database and cache services

Final Decision

Antivirus disabled (for now)

The Nextcloud Antivirus app is currently disabled.

Reasons:

  • System stability has higher priority than partial security measures
  • Trusted users only
  • Strict file permissions
  • Regular backups
  • No public upload endpoints

After disabling AV and rebooting:

  • System became stable
  • Swap usage normalized
  • All services responsive:
    • Nextcloud
    • Matrix
    • Gitea

Post-Mortem Summary

Item Result
Configuration error ❌ No
ClamAV bug ❌ No
Nextcloud bug ❌ No
VPS resource limit ✅ Yes
Wrong architecture ✅ Yes (for this size)

Meaning:

  • This was not a misconfiguration.
  • It was a capacity mismatch.

Lessons Learned

  1. 1 GB VPS is already at the limit for:

    • Nextcloud
    • Matrix
    • Gitea
      combined.
  2. Antivirus scanning is loadwise not “free”, even in executable mode.

  3. Security features that trigger CPU + IO spikes must be sized for worst-case concurrency, not idle averages.

  4. Adding AV without increasing resources creates negative security by destabilizing the system.


When Antivirus Will Be Re-Enabled

Antivirus scanning will be mandatory once this instance is used for real group collaboration.

That will require one of the following options:

Option A — VPS Upgrade (actual preferred)
  • Upgrade to ≥ 2 GB RAM
  • Re-enable ClamAV (daemon or executable mode)
  • Keep all services on one host
Option B — Service Split
  • VPS 1: Nextcloud
  • VPS 2: Matrix + Gitea
  • Antivirus enabled only on Nextcloud host

Current Security Posture (Interim)

  • If, than only trusted users
  • No public upload endpoints
  • Strict permissions
  • Fail2Ban + firewall
  • Frequent backups
  • Fast restore tested

This is acceptable temporarily, but not a final state.


Closing Notes

This experiment was intentional and valuable, learned a lot, also during configuration and tuning.

It clarified:

  • the real resource cost of antivirus scanning
  • the practical limits of small VPS setups
  • and the architectural decisions required for future growth

When collaboration expands, the infrastructure will be expanded accordingly. So clamav and configuration stays, but Nextcloud App is disabled for now, but not uninstalled.