Saturday, May 16, 2015

Direct Digital Synthesizer based on plain Arduino

Microcontroller is meant to control stuff and not to generate periodic signals - for this propose we would use a dedicated hardware - something like Atmega328 and AD9850.
But on the other side this might be an interesting project - not very useful, but at least we can manually build DDS and get good understanding of its functionality. The basic idea of such synthesizer is to create a software loop where each iteration will output single point of particular wave. Higher amount of points within single period increases resolution and reduces frequency - due to limited processing power.
There is also a good motivation to optimize the code - each extra operation consumes CPU cycles and decreases maximal output frequency.

Generated wave signals

Sine with 120 probes per period

Sine with 360 probes per period
Max frequency is limited to 1.8Khz where sine with 120 steps reaches 5.58Khz

Signal at 10Hz is smoother when compared to sine with 120 steps.



Wave Generator

Arduino does not have Digital to Analog Converter - there is only PWM generator, but in order to generate smooth wave we need stable analog voltage. Common pattern to solve this problem is to take a few digital outputs and connect them together trough voltage divider - you can see that on schematics in the right bottom corner. We are using Arduino's digital output D0-D7 because they are all managed by single register (Port D). This means that we can change value of all 8 bits (D0-D7) with single assignment, for example: PODTD = B10000001 would set D0 and D7 to 1. This also means that mapping between byte value and analog output is linear, here are few examples that I've measured using oscilloscope:

B00000001 22 mV
B00000010 38 mV
B00000100 73 mV
B00001000 140 mV
B00010000 276 mV
B00100000 545 mV
B01000000 1.08 V
B10000000 2.18 V

B00000001 22 mV
B00000011 56 mV
B00000111 125 mV
B00001111 265 mV
B00011111 543 mV
B00111111 1.1 V
B01111111 2.23 V
B11111111 4.47 V
Each generated wave consist of few steps - for example sine has 120 (or 360 because there are two versions). Each step is pre-calculated and stored in an array - main loop simply goes over this array and assigns value from it to PORTD.

To smooth out generated signal I've used capacitor 470pF on the output. The op-amp works as a buffer so that resistance of a device connected to the output cannot influence generated wave - capacitor would discharge faster and we would change characteristics of voltage divider.


There are four buttons:
  • Frequency Up - increase frequency
  • Frequency Down - decrease frequency
  • Delay Step - value of the step for frequency change
  • Select Wave -  you can choose from from sine 120, sine 360, square and saw
Reaction on buttons is handled by interrupts, so that the main loop can concentrate on generating high frequency wave.

Frequency adjustment

There is a small catch... single press on Frequency Up does not necessary change the frequency by one hertz, but it changes the amount of wasted CPU cycles per step .... I will try to explain this from the beginning:
as you remember we are generating wave by going over pre-calculated table - each byte in such table will be assigned to PORTD and this happens within a single "step". In order to plot wave we have to go over whole table, once we are done, we have to start from the beginning. In order to change frequency, we have to alter time for each step - this is the only possibility to proportionally scale up he whole wave. The smallest amount of delay in our case is the single CPU operation - it's called NOP and it takes 1327 nano seconds - NOP itself is quicker but I've also considered time required to call a method.
For example single period of sine consist of 120 steps, increasing delay by one, would add one NOP operation to each step, meaning that single period would take additional 120 * 1327ns.
The good news is, that LCD display always displays correct frequency in hertz, only pressing Up and Down buttons changes it by few hertz. The bottom line of LCD display shows period time in nano seconds.

Code Optimization

My first version has used Arduino API and I was getting about 150Hz for sine with 120 steps - final optimization went up to 5,6KHz. I've used interrupts to handle input from buttons,  direct registry access, removed all unnecessary method calls, reduced size of a variables  - like from 16 to 8bits and finally exchanged floating points with integers.

There is always a tradeoff - code readability had decreased, direct access to  registers is also tricky, because they can be used for different proposals. Arduino API takes care of all those problems, but it need few extra CPU cycles.

Source Code

is on github

Monday, February 16, 2015

Simple plant monitor based on Arduino

The goal of this project is to build a controller that will inform you when your plant needs watering. You will see the maximal and current moisture level and the time passed since last watering. Finally when moisture level drops below defined threshold the alarm will rise - in form of LED flashing SOS signal.


 I will go over some not obvious parts:
  • you will find fritzing project here
  • 4 PIN socket in the left bottom corner is meant to be connected to moisture sensor. It's be cheap one that you can get on ebay
  • photo resistor regulates insensitivity of LCD backlight
  • R1 regulates LCD brightness
  • R5 regulates backlight insensitivity for LCD display
  • R10 sets alarm threshold
  • R3 value is not 220 ohm but 10k (I have to correct schematic)

Software design

I've used Eclipse, source code is here . Whole project is divided into modules, each one in separate class file.

I dis not use interrupts, so every module is controlled from main loop in PlantMonitor.cpp.

Each module has to be initialized and has to execute some operations once in a while. For this propose each module defines two functions: abc_setup() and abc_cycle() - abc would be a module name. The setup method has to be called only once and this happens in PlantMonitor#setup(). The cycle method will be called on every loop. Each cycle method internally measures time and runs only when it should (like every 100ms) without blocking.

The method Util#util_millis() is used by each module to measure time. This method caches current time and returns this cached value - internally it obtains time at the beginning of each cycle.
Using the same time during each cycle not only reduces amount of calls going to the timer, also each log statement within the same loop contains identical time, so we can logically connect events.


The log module will produce messages over COM port. It cannot be disabled because ... there is no reason to do so -  we do not have any other usage for COM port and sometimes it's useful to see what is happening.
There are a few variable resistors, that can be used to set up things like alarm threshold. Those changes will be also printed over COM port, so that you can actually see how they effct functionality. Here is a log example:

>>[000-00:00:00,000]-> Initializing LCD module >>[000-00:00:00,000]-> Initializing hygrometer module
>>[000-00:00:00,038]-> Adopting LCD backlight. Sensor: 519, LCD: 177, Adjust(def 500): 605 
>>[000-00:00:00,038]-> Adjusted alarm sensitivity. 370 = 36% 
>>[000-00:00:01,000]-> Status -> Free RAM: 1270 
>>[000-00:00:12,000]-> Moisture has changed = 30%, Max: 30%, Status: 3 
>>[000-00:00:12,000]-> Recognised plant watering, status: 3 
>>[000-00:00:18,000]-> Reseting max proc based on adoption time after watering 
>>[000-00:00:18,000]-> Moisture has changed = 24%, Max: 24%, Status: 1 
>>[000-00:00:36,000]-> Reseting max proc based on adoption time after watering 
>>[000-00:00:36,000]-> Moisture has changed = 19%, Max: 19%, Status: 1 
>>[000-00:00:49,013]-> Adopting LCD backlight. Sensor: 559, LCD: 169, Adjust(def 500): 605 
>>[000-00:00:57,000]-> Reseting max proc based on adoption time after watering 
>>[000-00:00:59,169]-> Adopting LCD backlight. Sensor: 679, LCD: 145, Adjust(def 500): 605 
>>[000-00:01:12,139]-> Adopting LCD backlight. Sensor: 639, LCD: 153, Adjust(def 500): 604

Moisture - Hardware

We are using cheap moisture sensor that consists of two plates that you have to stick into a soil. The sensor delivers 0-5 volts based on moisture level. This means that we can directly connect it to Arduino analog input (A0).
Sensor plates corrode quickly, so it's a good idea to cover them with tin. Without this fix your sensor will last at most few weeks, or maybe you can get one that is already resistive to corrosion (one with gold surface). Applying extra tin will unfortunately increase current flow and influence readings, but we will correct this in a software (Hygrometer#MOISTURE_PROC_ADOPT).

Moisture - Software (Hygrometer.cpp)

The method hygro_sample(Moisture) returns current moisture level and status: "no change", "small change" and "level increased".
hygro_sample(Moisture) is being called on every loop, internally it executes only every 100ms, otherwise it returns "no change". With each run (every 100ms) it probes moisture level, but it does not return it immediately, it stores it in internal array and returns "no change". First after collecting 30 probes, it finds the median and returns proper status. It's worth mentioning, that moisture change is being recognized with tolerance of 5% - just to avoid bouncing.

LCD Display - Hardware

LCD display is connected in a standard way, variable resistor R1 can be used to adjust brightness.

The insensitivity of LCD backlight is controlled by photo resistor. Photo resistor is connected to analog input A1 over voltage divider - this is a common pattern used to archive stable readings that are independent from current changes.
Software calculates insensitivity of backlight based on reading from photo resistor - this is a linear function. Additionally variable resistor R5 connected to A2 is used to calculate constant for our function: lower resistance increases measured voltage on A2 and increases backlight. This means, that resistance change proportionally influences backlight for all light conditions (readings of photo resistor).
Resistance changes on R5 are logged over COM, so you can exactly see it's influence on backlight.

The LCD backlight is connected to PWN output on D9, but it does not go directly to LCD input, instead it goes trough RC filter and op-amp. The RC filter uses large capacitor, this gives us smooth changes of backlight insensitivity.
Actually we would not need this whole RC filter, because PWM frequency it to high to observe flickering and smoothness could be archived in software, but I just wanted to solve this in hardware and have nice constant voltage.

You can see on screenshots below dependency between PWM duty (blue) and constant voltage (yellow).

The time required  to change LCD backlight from maximal brightness to minimal takes 440 ms.

LCD Display - Software (Lcd.cpp)

The initialization phase (lcd_stup()) prints all static characters - those will not change any more,  all other characters will be printed only if they have changed - this reduces flickering.
The lcd_cycle() will get called on every loop from PlantMonitor#loop() and it adopts LCD backlight for changing enviorment.
Lcd.cpp contains also one function that prints time and another function that prints moisture - that's all.


It's just a LED connected to A10. The Sos.cpp controls the blinking frequency. The sos_setup() is called only once and it configures PIN A10 for output. sos_cycle() has to be called on every loop - it's non blocking method and it will switch the LED on and off in SOS rhythm. You can configure all possible time periods by changing corresponding variables in Sos.h. There are two more methods, that play significant role: sos_on() will enable SOS signal and respectively sos_off() will disable it. The cycle method have to be called on every cycle, even when SOS is disabled - in this case it returns immediately.

Low moisture level alarm

When moisture gets below defined level the LED controlled by Sos.cpp will start flushing. This is being controlled by Alarm.cpp. This module knows when the alarm has to be raised and when it stops, it also controls kind of alarm - currently it's a LED signal, but you could connect something else. In this case you have to only plug it on the right place in Alarm.cpp.
Alarm starts when moisture drops below level defined by variable resistor connected to PIN 3. The resistance will be mapped to percentage and changes to this resistor are printed to COM port - when you change the resistance you can read the threshold for alarm.

Getting up and running

Download latest release from here and compile cpp files, PlantMonitor.cpp contains main loop. I've used Eclipse, but importing this project makes no sense, because it contain hardcoded paths.

Optionally you can directly upload compiled hex file:

sudo avrdude -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -Uflash:w:PlantMonitor.hex:a