Simple method to make ternary full adder

My fresh invention is ternary full adder design. First of it’s kind in the World. Very much all search result from Internet are wrong and doesn’t work. This is first known design which truth table is right. And design uses simple MOSFET transistors. Not any nano carbon tube or other weird futuristic materials seen on Internet search result.

Ternary half adder truth table

SUM  A B C | S C
0+0  0 0 0   0 0
0+1  0 1 0   1 0
0+2  0 2 0   2 0
1+0  1 0 0   1 0
1+1  1 1 0   2 0
1+2  1 2 0   0 1
2+0  2 0 0   2 0
2+1  2 1 0   0 1
2+2  2 2 0   1 1

New method

Ternary full adder is possible to construct from one half adder. If carry-in is 1 then invert inputs and outputs. Result is rest of the full adder truth table below. This is tested with simulation software and it’s works!

SUM  A B C | S C
0+1  0 0 1   1 0
1+1  0 1 1   2 0
2+1  0 2 1   0 1
1+1  1 0 1   2 0
2+1  1 1 1   0 1
3+1  1 2 1   1 1
2+1  2 0 1   0 1
3+1  2 1 1   1 1
4+1  2 2 1   2 1

There is no need for C=2 condition because it’s not newer two.

Design and more design…

Mechanical design

Image is from USB side of The Mystery Box. It’s my designed SDR radio. Other end has SMA for antenna. PCB’s are ordered with assembly service. Them should be ready on next week and arrive to me about three working days later from that.

I intentionally selected round connectors for USB and antenna. It should be easy to drill holes for them altough case is aluminum. Possibly even easier when case ends are connected to center piece. USB connector hole size is 12.7 mm but it can be round to 14 mm so that I can use standard drill bit. SMA connector hole size is 6.5 mm which is already standard size.

Software design – Mbed OS and Tiny IIO Daemon

After massive amount of research I think I can at least try to set up Arm Mbed operating system and Tiny IIO Daemon to The Mystery Box device. Mbed OS consumes about 55kB of flash memory. The onboard STM32L476RG MCU has 1MB of flash memory so there is plenty of room for custom program.

Guide to porting Mbed OS to new device is there:
https://os.mbed.com/docs/mbed-os/v6.9/porting/porting-custom-boards.html

Porting process is even easier because The Mystery Box is designed on top of Nucleo development board which is already supported by Mbed OS. Some minor configuration might be only thing that must be done before it is possible to use Mbed Studio to program and upload programs to the device.

There is only one code example for Tiny IIO Daemon on the Internet:
https://github.com/analogdevicesinc/libtinyiiod/blob/master/example.c

However it is enough. Running Tiny IIO Daemon continuously is very easy and program is quite simple. This is taken from above link:

int32_t main(void) {
	struct tinyiiod *iiod = tinyiiod_create(&ops);

	set_handler(SIGHUP, &quit_all);
	set_handler(SIGPIPE, &quit_all);
	set_handler(SIGINT, &quit_all);
	set_handler(SIGSEGV, &quit_all);
	set_handler(SIGTERM, &quit_all);

	while (!stop)
		tinyiiod_read_command(iiod);

	tinyiiod_destroy(iiod);

	return 0;
}

I have an idea how IIO daemon could work. I will test it as soon as I receive The Mystery Boxes from prototype manufacturer. Idea is that receiver and transmitter are turned off by default. Only when data is requested receiver is turned on momentarily and when data is about to send transmitter is turned on momentarily. Only parameter is frequency.

Frequency is controlled with local oscillator through SPI port. I haven’t found yet any example about how to control SPI with IIO daemon. In theory it is possible with GNURadio from Linux computer when IIO daemon is running.

The Mystery Box

The Mystery Box – A multiband software controlled receiver-transmitter for 50MHz…6GHz frequency range.

This is my latest project. Main feature will be simplicity. Only one USB connector for computer and one SMA connector for antenna. Other key features are small size 120*54 mm and wide operational temperature range. It will be also cheaper and more hackable than it’s competitors because there is no any FPGA’s.

https://www.xilinx.com/products/silicon-devices/fpga/what-is-an-fpga.html

I’ll probably program my own controlling software to that radio. Other alternatives are for example popular GNURadio, but it’s design is very complicated and there is not enough information on how to implement IIO environment to embedded system without before mentioned FPGA. I think IIO forms some kind of ring buffer to device, but this is where information ends.

There is however a plenty of information how to render audio stream on Linux operating system. For example on this page.

https://github.com/scottstensland/render-audio-openal

Then I only need to parse received audio from quadrature and in-phase signals from ADC. Unfortunately Wikipedia is very cryptic about these signals and so are most web search results. However there is I/Q data for dummies.

http://whiteboard.ping.se/SDR/IQ

This is one of rare pages that clearly states that I and Q signals are 2D representations of 3D world from side and from above. Very simple to understand. Worth reading!

Butterworth filter design

One new thing that I learned during development was calculating correct component values for Butterworth lowpass filter. I found almost perfect calculator from RF-Tools.com website.

https://rf-tools.com/lc-filter/

That was good starting point for filter design. Input values for that calculator that I use was following. Response: “lowpass”, type: “Butterworth”, topology: “Series First”, order: “8”, cutoff frequency: “57MHz”, input and output impedances: “50 ohm” and component values: “exact”.

My circuit uses 50MHz local oscillator. That’s why I selected 57MHz cutoff frequency so that only at most 50MHz signal goes through it without any attenuation. All received signals is downmixed to that frequency before filter. After filter there is quadrature demodulator circuit.

Back to filter design. From Wikipedia I found important information how to convert that filter circuit to it’s balanced version.

https://en.wikipedia.org/wiki/Balanced_circuit

Capacitors are untouched but inductors are doubled for both sides of circuitry and their values are divided by two. This topology is yet verified with CircuitLab.com circuit simulator and it works as expected. Frequency response is identical with original results.

Balanced-T attenuator design

That was easy part. All component values and circuit design was ready on that web page.

https://www.electronics-tutorials.ws/attenuators/t-pad-attenuator.html

I needed only to select component values from table with desired attenuation and then choose correct circuit version to have balanced design. Attenuation is needed because MCU’s ADC uses 1.8 volts analog voltage and quadrature demodulator outputs 2V p-p signal levels.

Arbitrary Transmission Line Calculator

http://atlc.sourceforge.net/

Atlc is a program which can be used to calculate differential PCB traces impedance among many other things. It seems to be very accurate when compared to other calculators on the Internet and I think it’s result is most accurate of them all. That’s why I selected it to be my main tool when calculating PCB traces.

First thing when using Atlc from command line is to produce data file which is then used to calculate result. Data file is actually a BMP bitmap and Atlc comes with several helper programs to make them.

I needed to design 50 ohm coupled lines so I used my favorite method that is trough trial and error and come to these values below.

create_bmp_for_microstrip_coupler -b 8 1.4 0.2 0.2 0.36 0.035 1 4.3 out.bmp

BMP size is selected with b option to be 8. It’s default value is 4 so now result accuracy is doubled. Trace width is 1.4mm and spacing between them is 0.2mm and spacing between traces and surrounding ground plane is 0.2mm. There is also ground plane below traces on the first inner PCB layer and that thickness between these layers is 0.36mm. Copper thicknesses are 0.035mm and air permittivity is 1 and PCB’s is 4.3.

Result is calculated by Atlc with this way.

atlc -d 0xac82ac=4.3 out.bmp<br>
out.bmp 3 Er_odd=   2.912 Er_even=   3.355 Zodd=  24.866 Zeven=  31.882 Zo=  28.156 Zdiff=  49.732 Zcomm=  15.941 Ohms VERSION=4.6.1

We can see from that result that Zdiff is 49.732 ohm which is almost perfect for our target use.

Simple analog sequencer and synthesizer

generate neat music with only five basic IC’s

Sample audio is available on Youtube. https://youtu.be/91aFLi7b4vM

Very easy to build and funny to use. Just turn potentiometers and hear how resulting music alters. You can also start to recording your music with computer. It is super easy for example a program called Audacity. Just plug in audio cable and press record.

Building tips

Building is very straightforward. Put components to their places on to the circuit board and solder in place. Potentiometers needs to be assembled with wires. Length is not critical. Watch correct placement and polarity with reference markings from circuit schematics and printed circuit board.

Technical description

Sequencer part of this device is based on classic Baby-10 sequencer. It uses logic 4017 counter and one adjustable low frequency oscillator made from very basic NE555 timer circuit with fixed 50% duty cycle to generate tempo. There is also two other timer used to produce sound frequencies. To save board space one NE556 dual timer is used along with one ordinary NE555.

4017 counter outputs is connected to first of two sound frequency oscillators with 500k adjustable resistor. Outputs is also connected to rotary switch so user can select how many channel is used to produce sound. Common pin of rotary switch is connected to 4017 reset pin. Every output has it’s own adjustable resistor so there is maximum of ten independently controlled frequencies. Them are tied together through diodes. This output is called control voltage. Second sound frequency oscillator is also adjustable with one 500k resistor. It is connected in series with sequencer control voltage so it’s frequency is also based on that.

These two adjustable sound frequencies is mixed together with XOR gate which is made with diode bridge and one BC557 transistor to save board space from yet another logic IC. With this dual tone and mixer combination it is possible to generate classic cowbell sounds. Low frequency oscillator output is called gate and mixed output of two other oscillator is called tone.

Gate pulse is used to generate envelope with adjustable attack and decay times for tone signal. These are controlled by two 500k adjustable resistor. It is buffered with one half of LM358 dual operational amplifier. Other half is unused and it’s inputs are connected to ground. This envelope signal is then used to control tone and these to waveforms are then combined with one BC547 transistor. Finally there is passive low pass filter to filter out unwanted high frequency clicks.

Now our audio signal is ready to be amplified with LM386. At this point there is also signal level output connector for audio. Power amplifier is made with basic circuit with bass boost because we use small speaker. Output level is suitable for 1W, 8ohm speaker. Volume is adjustable with one 10k potentiometer.

Device works with voltages between 5…9 volts. Transformer is not included. Printed circuit board is designed to fit in CP-18-5 enclosure. It is not included. Basically you can use any suitable enclosure.

Setting up LoRa-GPS Tracker

Installing bootloader

Bootloader is pre-installed on board. This information is given if you want to make changes to it. You will need Segger J-Link programmer to follow these instructions and custom adapter to connect with Tag-Connect cable to board.

Clone UF2 repository and make a copy of /boards/feather_mo directory.

clone https://github.com/adafruit/uf2-samdx1
cd uf2-samdx1
cd boards
cp -r feather_m0 tracker_m0

Go to that directory and edit board_config.h file as following:

#ifndef BOARD_CONFIG_H
#define BOARD_CONFIG_H

#define VENDOR_NAME "Juha-Pekka Varjonen"
#define PRODUCT_NAME "LoRa-GPS-Tracker"
#define VOLUME_LABEL "TRACKERBOOT"
#define INDEX_URL "https://locateworld.net/"
#define BOARD_ID "SAMD21G18A-Tracker-v1"

#define USB_VID 0x1209
#define USB_PID 0x0005

#define LED_PIN PIN_PA17

#endif

You can fill it with your own data if you want. Note that volume label must be 11 character long uppercase string.

Build bootloader with command:

make BOARD=tracker_m0

Go to newly created directory ‘build’ and it’s subdirectory ‘tracker_m0’. If not yet installed, download and install J-Link software from here. Install with this command:

sudo dpkg -i ~/Downloads/jlink_package.deb

To enable/disable bootloader protection you must create two files accordingly to same directory with bootloader.

set.mot:

S214804000FAC7E0D85DFCFFFFFFFFFFFFFFFFFFFF63
S9030000FC

clear.mot:

S214804000FFC7E0D85DFCFFFFFFFFFFFFFFFFFFFF5E
S9030000FC

Start J-Link Commander.

JLinkExe

Type ‘connect’ to make connection to microcontroller. It follows with three question. To first question press enter and then ‘S’+enter and then enter again. Default settings are ok.

J-Link>connect
Please specify device / core. : ATSAMD21G18
Type '?' for selection dialog
Device>
Please specify target interface:
  J) JTAG (Default)
  S) SWD
TIF>S
Specify target interface speed [kHz]. : 4000 kHz
Speed>
Device "ATSAMD21G18" selected.

Clear bootloader protection fuse:

loadfile clear.mot

Reset the target:

r

Upload the bootloader:

loadbin bootloader.bin,0

Set the bootloader fuse:

loadfile set.mot

Now it should be visible as USB mass storage device and serial port.

Installing CircuitPython

CircuitPython is pre-installed on board. These instructions is given if you want to make changes to it. Clone Adafruit CircuitPython repository:

git clone https://github.com/adafruit/circuitpython

An ARM compiler is required for the build. It can be installed as follows:

sudo add-apt-repository ppa:team-gcc-arm-embedded/ppa
sudo apt-get install gcc-arm-embedded

Install necessary submodules before continue:

git submodule update --init --recursive

Next commands must be executed in subdirectory ports/atmel-samd/. Create copy of directory boards/feather_m0_basic and edit file mpconfigboard.h as follows:

#define MICROPY_HW_BOARD_NAME "LoRa-GPS-Tracker"

Then edit file mpconfigboard.mk as follows:

USB_VID = 0x1209
USB_PID = 0x0005
USB_PRODUCT = "LoRa-GPS-Tracker"
USB_MANUFACTURER = "Juha-Pekka Varjonen"

Compile MicroPython cross-compiler:

make -C mpy-cross

To build give this command:

make BOARD=tracker_m0

It creates a lot of files and directories in to directory ‘build-tracker_m0’. We only need one with name firmware.uf2. Easiest method to install it is to drag and drop it in to previously created USB device TRACKERBOOT.

After dropping it takes about 15 seconds and device name changes to CIRCUITPY and it’s ready to use.

Setting up development environment

This step is necessary when programming and testing with Mu-editor. Clone Mu-editor repository and edit mu/modes/circuitpython.py file.

git clone https://github.com/mu-editor/mu
nano mu/mu/modes/circuitpython.py

Under ‘valid boards’ add VID and PID to the list. PID 0x0005 is only for testing. Do not use it in production.

valid_boards = [
...
(0x1209), (0x0005), # LoRa-GPS Tracker development
]

Run Mu-editor from it’s root directory with command:

python run.py

Now it should detect LoRa-GPS Tracker automatically. You will need also Adafruit library bundle. Download it from here.

Testing GPS receiver

At first you need to copy adafruit_gps folder from Adafruit library bundle to lib folder on CIRCUITPY device.

Open Mu editor and create new CircuitPython project with code.py filename. File content should be this:

import board
import busio
import adafruit_gps
import time

RX = board.RX
TX = board.TX

uart = busio.UART(TX, RX, baudrate=9600, timeout=30)
gps = adafruit_gps.GPS(uart, debug=False)
# Turn on the basic GGA and RMC info (what you typically want)
gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
# Set update rate to once a second (1hz) which is what you typically want
gps.send_command(b'PMTK220,1000')

while True:
    gps.update()
    if not gps.has_fix:
        # Try again if we don't have a fix yet.
        continue
    # We have a fix! (gps.has_fix is true)
    # Print out details about the fix like location, date, etc.
    print('=' * 40)  # Print a separator line.
    print('Fix timestamp: {:02}:{:02}:{:02}'.format(
        gps.timestamp_utc.tm_hour,  
        gps.timestamp_utc.tm_min,   
        gps.timestamp_utc.tm_sec))
    print('Latitude: {0:.6f} degrees'.format(gps.latitude))
    print('Longitude: {0:.6f} degrees'.format(gps.longitude))

That code prints out to serial port current coordinates. You can watch serial port communication by pressing Mu editor button ‘serial’.

Testing LoRa radio

At first you need to copy adafruit_tinylora and adafruit_bus_device folder from Adafruit library bundle to lib folder on CIRCUITPY device.

Open Mu editor and create new CircuitPython project with code.py filename. File content should be this:

import busio
import digitalio
import board
from adafruit_tinylora.adafruit_tinylora import TTN, TinyLoRa
import time
import microcontroller

# Create library object using our bus SPI port for radio
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
 
# RFM9x Breakout Pinouts
cs = digitalio.DigitalInOut(microcontroller.pin.PA06)
irq = digitalio.DigitalInOut(microcontroller.pin.PA09)
rst = digitalio.DigitalInOut(microcontroller.pin.PA08)

# TTN Device Address, 4 Bytes, MSB
devaddr = bytearray([0x00, 0x00, 0x00, 0x00])
 
# TTN Network Key, 16 Bytes, MSB
nwkey = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
 
# TTN Application Key, 16 Bytess, MSB
app = bytearray([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
 
ttn_config = TTN(devaddr, nwkey, app, country='EU')
 
lora = TinyLoRa(spi, cs, irq, rst, ttn_config)
 
# Data Packet to send to TTN
data = bytearray(4)
 
while True:
    # Encode payload as bytes
    data[0] = 0xff
    data[1] = 0x01
    data[2] = 0xff
    data[3] = 0x01
 
    # Send data packet
    print('Sending packet...')
    lora.send_data(data, len(data), lora.frame_counter)
    print('Packet Sent!')
    lora.frame_counter += 1
    time.sleep(15)

Important thing is that TTN device address, network key and application key should be your own unique numbers from TTN Console. More detailed instructions can be found from Adafruit site.

After code is copied to CIRCUITPY drive it runs automatically and starts sending data to internet. You can follow it with TTN Console. If there is no gateway in your area you need one own. Next is described how to setup one.

Setting up LoRaWAN gateway

I have Raspberry Pi with GW-01-RPI LoRa Shield. Start with downloading Rasbian img file from Raspberry Pi’s web site. Extract it with unzip command and transfer to SD card with dd command.

unzip your_image_file_name.zip
sudo umount /dev/sdx*
sudo dd bs=1M if=your_image_file_name.img of=/dev/sdx

Make sure to replace /dev/sdx with correct device name. You can check it with command sudo fdisk -l

Finally put a empty file named ‘ssh’ to the root directory of SD card. This way you enable ssh connection. Insert card to Raspberry Pi and connect power and LAN. Login with default username and password (user: pi, password: raspberry). With remote computer:

ssh pi@192.168.0.6

Change IP address accordingly. It is recommended to change password at this point. Use command passwd.

First enable onboard SPI connection. Go to raspi-config.

sudo raspi-config

Select interfacing options and there is SPI. Enable it by pressing enter and choosing enable.

Create directory and clone and make two necessary repositories on to it.

cd ~
mkdir lora
cd lora
git clone https://github.com/Lora-net/lora_gateway.git
cd lora_gateway
make

cd ~/lora
git clone https://github.com/Lora-net/packet_forwarder.git
cd packet_forwarder
./compile.sh

Then edit config files:

cd ~/lora/packet_forwarder/lora_pkt_fwd
nano global_conf.json
nano local_conf.json

Local config contains only one line for gateway ID. Change it’s value to same than in global_conf.json. You can make up that ID to be anything you like. It must be 8-bit hexadecimal number. Example settings:

gateway_ID: "0102030405060708"
server_address: "router.eu.thethings.network"
serv_port_up: "1700"
serv_port_down: "1700"

One last thing is to make startup file.

cd ~/lora
nano reset.sh

That file should contain following lines:

#!/bin/sh
echo "25" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio25/direction
echo "1" > /sys/class/gpio/gpio25/value
sleep 3
echo "0" > /sys/class/gpio/gpio25/value
sleep 1
echo "0" > /sys/class/gpio/gpio25/value
cd /home/pi/lora/packet_forwarder/lora_pkt_fwd/
./lora_pkt_fwd &

Set that file to be executable and run it:

sudo chmod +x reset.sh
sudo ./reset.sh

If you see line with following text then setup is succesfull.

INFO: [main] concentrator started, packet can now be received

Break that by pressing Ctrl-C. Next thing is to modify rc.local file.

sudo nano /etc/rc.local

Just before ending “exit 0” line, add following:

/home/pi/lora/reset.sh || /bin/true &

And on the beginning of the file change “#!/bin/sh -e” to “#!/bin/sh”. Save and close file. Then set executable bit and enable it:

sudo chmod +x /etc/rc.local
sudo systemctl daemon-reload
sudo systemctl enable rc-local.service

Now it should start every time when Raspberry starts. Restart to confirm that by typing ‘sudo reboot’ and pressing enter. When restarted look with top command if lora_pkt_fwd is running.

Setting up TTN

Start by logging in to TTN console and choose Gateway -> register gateway. Select “I’m using the legacy packet forwarder”. Important thing is that gateway EUI must be same than previously selected Gateway_ID. Also router needs to be same than in gateway settings. Other settings are self-explanatory.

LoRaWAN GPS Tracker

Image is coming as soon as first devices arrives from manufacturer…

Only 20 different component. What could you except for that?

For use in EU and India. Suitable band is software controlled. Fully hackable open source software design with CircuitPython language. Ready to use. Program includes advanced power saving techniques. Extreme small physical size yet powerful tracking device. Free subscription to mapping service. And there’s more!

Includes panic button which can send GPS coordinates to pre-selected recipients through SMS and email. Includes battery level monitoring service through LoRaWAN uplink. You can select where and how to send that data. It is automatically saved to database like all other messages from device. Only you have access to that data from backend which is password protected web site.

Tri-color LED indicates when battery is fully charged and when there is GPS fix. Red color is programmable and by default it is showing operational status of the device. Battery charging and programming through micro USB port.

Device is water resistant to IP65. It can be used outdoor. GPS position accuracy < 3 meters. Stand alone operation time from days to week depending on how often GPS tracking is made.

Advantages to use CircuitPython includes but not limited to:
Perfect choice for data logging applications. Internal storage is seen as USB storage device. Easily update your code. Since your code lives on the disk drive, you can edit it whenever you like. And Python is fastest-growing programming language. It’s taught in schools and universities.

Internal battery voltage 3.7V, battery type LiPo and capacity 105mA. Integrated charging circuit from USB port whenever USB is connected to computer. Over and under voltage protected. Automatic switch between USB and battery depending on USB connection.

Physical dimensions of durable black ABS plastic enclosure are 36mm x 66mm. Height only 17mm. It includes a key fob ring so you can connect it to keys and never lose those keys again!

Usage examples includes ofcourse person tracking obviously but also a industrial logistics tracking applications. And many more. It can freely adopted to different usages by simply changing Python code inside it. And it’s easy than plugging it into computer. It shows up a external drive where you can put your code and it is run instantly!

Welcome to Juvar.fi!

I’m 35 years old programmer from Tampere, Finland.

This is my personal web site. 

I work on electronic design, construction and programming. It is also my hobby. On this site I will present some of the hobby projects I have made. I also have a radio amateur qualification. Self-learning and experimentation through hobby has since taught much more.

Embedded systems have always attracted me. Nowadays they are everywhere. It refers to a device with a microprocessor and program code in it. Almost all my hobby projects are like that.

RF Power Meter V1.1

This device is part of my APRS radio transmitter backpack rig published later on.

PCB layout file, schematic diagram and AVR program available on GitHub: https://github.com/Juvar1/RFPowerMeter
It is designed with KiCad.

Improvements

Here is second version of my RF power meter device. It has improved RF shielding and noise immunity. A little bit more expensive to make but quality pays.

C14 is also added for improving noise immunity from supply line.

C14 added and other SMA connector removed. It’s replaced with T splitter externally.

Casing

Case is bought from Digi-Key. It’s part number is PIP-11766-C. DC jack outer diameter is 5.5mm and inner 2.5mm.