Menu Close

Category / How and Why

How to Deal with Badly Written Code

Sadly there is a ton of badly written code out in the wild. Hardware related code, seem to suffer more in this regards. I imagine, many developer in this segment are unwillingly to invest time in quality or are just inexperienced.

Even if you are dedicated in reliable and high quality code, you will probably run into the situation, where you have to use a library with really low standards.

Strategies

There are a number of strategies to deal with this code:

  1. Rewrite the library.
  2. Refactor the code.
  3. Wrap the library.
  4. Wrap the interface.

Rewrite the Library

This is actually the best you can do and it is also the most time-consuming approach. Yet, write the code from scratch will give you several benefits:

  • You will perfectly understand how the original library and the accessed hardware works. Actually you have to understand it, otherwise you are unable to rewrite the code.
  • The new code will be modern, fast, reliable and in your coding style.
  • If you open source the new code, you will give people an alternative and a better example how to implement something the right way.
  • You can also selectively remove unwanted/bloated parts from the original code, which can reduce the overall binary size of the final project.
  • It will also give you the option to implement a proper error handling in the new code.

If you have the time and motivation to rewrite the code, do it!

Refactor the Code

Changing the code, without changing the functionality is called code refactoring. This is a good strategy, a compromise, between rewriting and wrapping. Usually you will just go, line by line, through the original code, modernise it and cleaning it up.

Continue Reading

How to Design a Cheap Plant Watering Sensor (Part 5)

This is the fifth part of the meta-tutorial, where I talk about designing a cheap plant watering sensor. If you did not already read the firstsecondthird and fourth part, please do it now. These parts contain a lot information which lead to this point of the tutorial.

The fourth part ended with step 20, where I did usability tests and stability tests using the preliminary firmware. This article will focus on designing the final board for the project.

Step 21: Design the Final Board

Designing a good board is like one of these puzzles with quadratic tiles, where you try to lay down a 3✕3 set where all edges match. Often a small change result in many follow up changes, so you have to rip-up a lot of routes and design them in a new way.

My goals for the board were:

  • Everything, except the two LEDs, should go to the top side of the board.
  • Reduce the amount of vias to the absolute minimum.
  • Create a ground pour, especially around the oscillator part, to reduce noise.
  • Move the button as far as possible from the oscillator to minimise the influence if the user presses the button.
  • Make it as small as possible.

I worked with small iterations, checking the design after each iteration and checked the design against my goals. To keep track of the changes, I versioned each larger iteration. This way I could go back at a later stage for comparison or if a change did not turn out well.

The Tools

I worked with Autodesk Eagle to create the board. This tool is in the current state far from perfect, but it is cheap and has all required features for the task. For me personally, these are the features I need to design a board:

  • Smart routing editor which is linked to the schema.
  • Quick and easy way to create vias and see the required connections.
  • Good library support for symbols and packages.
  • Design rule checks.
  • Quick board preview to check label placement and design.

I described some issues of Eagle in this post:

12 Time Wasting Issues in Autodesk EAGLE

As you can see, these are not very advanced features and are supported by almost all good board editors. I never use the auto router, because I do not have time pressure or have to do repetitive tasks. Continue Reading

How to Design a Cheap Plant Watering Sensor (Part 4)

This is the fourth part of the meta-tutorial, where I talk about designing a cheap plant watering sensor. If you did not already read the firstsecond and third part please do it now. These parts contain a lot information which lead to this point of the tutorial.

The third part ended with step 18, planing the final firmware. There a decision was made about the language and style of the firmware. This article will focus on the code of the firmware itself.

Step 19: Write a Preliminary Firmware

In order to be able to do some final tests with the prototypes and be able to work on the final PCB, I need a firmware which is is very close to the final one. In the Atmel Studio, I start a new C++ project in a new folder.

The first thing I do is checking the chosen compiler options for the project. Everything looks reasonable, I just add the option --std=c++11 to the C++ compiler options to get the latest language features.

In a section below I will describe all modules I wrote and will point details about the functions. I obviously did not wrote the whole firmware sequentially in that order, instead I use a incremental approach to develop the software:

  1. Create empty frameworks for all modules.
    • Create a header and implementation file for each module with the correct name.
    • Add the header comments, the namespace, #pragma once and the #include for the own header file.
    • At this point, each module should be ready, so I can easily add new functions to each module.
  2. Start with the hardware module.
    • Write the initialisation for the hardware, like CPU speed, port directions and other important stuff.
    • Layout the interface for the hardware module and prepare empty implementation blocks to be filled with code.
    • At each place where code is missing, I write a comment // FIXME!! to be reminded that there is something missing.
  3. Start the logic module.
    • Write the main entry point of the logic.
    • Call this entry point in the main() method of the firmware.
    • Add the hardware initialisation to the logic.

At this point, I have the structure of the firmware prepared as planed. This structure will lead me through the development process. Continue Reading

How to Design a Cheap Plant Watering Sensor (Part 3)

This is the third part of the meta-tutorial, where I talk about designing a cheap plant watering sensor. If you did not already read the first and second part, please do it now. These parts contain a lot information which lead to this point of the tutorial.

The second part ended with step 14, designing a first prototype PCB. So let us start with the next steps in this journey. This article will be the smooth transition from prototyping to the initial planing for a final design.

Step 15: Assemble and Check the Prototype

After receiving the prototype PCBs from OSH Park, I assemble one completely, including the cable and with one of the sensor plate prototypes as foot part.

Set the Fuses of the Microcontroller

The microcontroller ATtiny13A requires programming using SPI before it can be soldered to the board. There are special bits in the memory, called “fuses”, which control very basic settings of the chip. One of this fuse controls if the chip can be programmed and debugged via the debugWire protocol. This protocol just uses one single wire to program and debug the chip, bus has to be enabled first.

So I put the microcontroller into the programming adapter and connect everything via the Atmel ICE to the computer.

lucky-resistor-1 Continue Reading

How to Design a Cheap Plant Watering Sensor (Part 2)

This is the second part of the meta-tutorial, where I talk about designing a cheap plant watering sensor. If you did not already read the first part, please do it now. It contains a lot information about constraints and decisions made which lead to this point.

The first part ended with step 11, building a working prototype with the selected key components. So let us start with the next steps in this journey.

Step 12: Analyse and Measure the Prototype

Never forget why you actually built a prototype. It is your tool to verify all assumptions you made in the design phase. To do this you need the right measuring instruments.

The Power Usage

I start measuring the current of the circuit. This will show if my assumptions about the battery life will be true. For this test I use a multimeter which has a good resolution measuring in the µA range. The multimeter I use is the Testo 760-3 which is not a very well known brand. Multimeters are usually really poor at measuring low currents on low voltages, so let us see if this will work.

I also use a Fluke 114, but this one has no current measurement. It is sometimes very handy to have two multimeters, one to measure the voltage and a second one to measure the current.

For the first test I program the MCU to do all the tests in a loop and connect the power directly to the second part of the circuit. Now the power is always on and I can measure the current used by the MCU while doing the measurement.

lucky-resistor-1

Just running, doing the measurement of the oscillator, the second part of the circuit uses at maximum ~1.2mA. This measurement phase should be as short as possible. Later we will analyse the timing. Continue Reading

How to Design a Cheap Plant Watering Sensor (Part 1)

In this article I will talk about how I designed a cheap plant watering sensor. My goal is some kind of meta tutorial, where you can see the steps involved from the initial idea to the final sensor. If you ever planed to create a own device, I hope this article give you some inspiration to start your own project soon.

Why a Plant Watering Sensor?

I have a couple of plants in flowerpots and this plants not only like some light, they also need water from time to time. Watering this plants is something I often forget, with sad results. There are ready made solutions for this, but I have some objections with all of them. To be clear: There are really smart products out there – it is absolutely nothing wrong with them. It is just as I like to build my own fan controller, I like to build my own plant watering sensor in my very own fashion.

Here a list of already existing projects and devices I own or checked out:

Step 1: Define the Expectations and Goals

After deciding to create a own plant watering sensor, I spend some days to think about my expectations and goals for this sensor.

For my personal case, I like to put a small sensor in each flowerpot. There will be five and more pots, therefore that number of sensors are required. A single sensor should be really cheap, so I can distribute as many of them as I like. Battery life should be at least one year, better two years. I collected all this thoughts into the following list:

  • Cheap: Ideally less than €5 including the PCB.
  • Visual Signal: A flashing LED, simple to notice but easy to ignore.
  • Simple: Easy and simple to build with few components.
  • Beautiful: It should ideally look like a decoration.
  • Long Battery Life: The battery should last at least 1 year or longer.
  • Small: The sensor should be almost invisible from far away.
  • Reliable: The measurement should be reliable and the sensor must not corrode or degrade over years.
  • Safe: The sensor must be safe for the plant and environment.
  • Low Battery Indicator: The sensor should detect if the battery is at end of life and signal this.

Continue Reading

How to use the Scripts in the Cat Protector Project

It seems the cat protector project documentation has a small gap. There is just a hint that you have to use some scripts to prepare the SD card to play the audio files, but no details about this.

To use the scripts you need some knowledge how to use a command line interface on your operating system. The scripts are very simple to use on Linux and Mac OS X, but on Windows it is very tricky. I strongly advice you to use either Linux or Mac OS X. If you are working on Windows, just use a free virtual machine application and install a Linux (I suggest Ubuntu) or a Linux live CD where you don’t have to install anything.

Why? …. Why … that … complicated

The used microcontroller is not very fast, if the software on the microcontroller also has to deal with a complicated filesystem, no sequential blocks and other obstacles, changes are small to produce sound output in a good quality. Therefore I prepare the samples in a very simple format and instead of a complicated file system, I just store the blocks with the audio data sequentially onto the SD card.

Continue Reading

All Meggy Jr RGB Colors

I created a complete color table with the impression of all possible 4096 Meggy Jr RGB colors. The green LED is much brighter than the other two LEDs, the first tables used blue as base which does not make much sense. So I created a second set of tables which use the bright green as base.

If you like to create own tables or if you try to create something like a simulator or color lookup, here a ZIP file with all colors as individual PNG images: MeggyJrColorLEDs.zip

MeggyColorGreen_0

Continue Reading

How to Debug Time Critical Code using an Oscilloscope

From time to time you have to debug time critical code. If you are using interrupts, you are interested in the actual performance on the code. This is especially true, if you are using timed interrupts.

In this cases, using the serial interface is impossible. If you write to the serial interface, the whole timing of your application changes and you will get no usable results.

If you own an oscilloscope, there is a really simple way to debug many applications. I used this technique many times, for example with projects featured on these pages: For the timing of the sound output of the cat protector, or the timing of the display interrupt of the Meggy Jr library.

This technique is obvious ans simple. Nevertheless I hope this article will give some inspiration to help solving timing problems.

Continue Reading

How and Why to Avoid Preprocessor Macros

While most naming conflicts in C++ can be solved using namespaces), this is not true for preprocessor macros.

This post is outdated. You will find an updated version here:
How and Why to Avoid Preprocessor Macros

Macros can not be put into namespaces. If you would try to declare a new class called Stream, but somewhere in a header you include would be a macro called Stream, things would break. While compiling your code, the preprocessor would simply replace the Stream in your class Stream { declaration. You could get a really confusing error message, and it would take time and energy to find the actual problem.

Especially people developing software for controllers, often overuse macros for almost everything. They believe it will save RAM, speed up the code or make it more flexible. Often none of these three things are true. Actually each additional macro is a risk for name conflicts and makes the code less readable. You should reduce the use of macros to the absolute minimum, and especially avoid macros in your header files.

Continue Reading

Older Posts