Samstag, 29. Oktober 2016

Garmin Connect IQ on Linux

Introduction

Many Garmin devices like heart rate monitors or bike computers support the download and execution of apps. These enable custom watch faces, additional data fields during activities, and stand-alone apps and widgets.

Garmin offers the Connect IQ SDK free of charge to develop your own apps. However, the SDK is only offered for Windows and Mac OS. Fortunately, it mostly relies on Java and two simple platform-dependent applications which are simple enough for Wine.

More Information

Installation

The  shown installation instructions were used for Debian (sid) in October 2016 on an Intel Core i7 PC. If you have a different Linux distribution, your steps might differ.

1) Download the Connect IQ SDK

Use the version for Windows (!) from https://developer.garmin.com/connect-iq/sdk/. These instructions were tried with version 2.1.4.

2) As root, extract the package

su -
mkdir /opt/Garmin-ConnectIQ
cd /opt/Garmin-ConnectIQ
unzip /path/where/you/stored/connectiq-sdk-win-2.1.4.zip

This will result in an installation of 123M.

3) For Linux, a few minor adaptions are necessary

To start the two Windows .exe programs with Wine, the shell scripts "shell" and "simulator" are created. Further, all scripts are made executable and Unix line end convention is ensured.

cd bin/
echo -e '#!/bin/bash\n\nwine $(dirname "$0")/shell.exe "$@"' > shell
echo -e '#!/bin/bash\n\nwine $(dirname "$0")/simulator.exe "$@"' > simulator
chmod a+x monkeyc monkeydo monkeygraph connectiq connectiqpkg simulator shell
sed -i 's/\r//g' monkeygraph

4) Make the executables callable from everywhere

You have to add the bin directory to your path.

export PATH="$PATH:/opt/Garmin-ConnectIQ/bin"

Unfortunately, the scripts don't support to be symbol-linked from e.g., /usr/local/bin/, because they use $0 to determine their base directory.

5) Install Java and Wine

Debian Packages wine32:i386 and default-jre and their dependencies work fine.

6) As user, create a developer key

See the explanation at https://developer.garmin.com/connect-iq/programmers-guide/getting-started/

mkdir ~/.ciq
openssl genrsa -out ~/.ciq/developer_key.pem 4096
openssl pkcs8 -topk8 -inform PEM -outform DER \
    -in ~/.ciq/developer_key.pem \
    -out ~/.ciq/developer_key.der -nocrypt

Test

7) Test

Setup the path

export PATH="$PATH:/opt/Garmin-ConnectIQ/bin"

Copy and compile a sample program

mkdir /tmp/ciqtest
cd /tmp/ciqtest
cp -r /opt/Garmin-ConnectIQ/samples/ProgressBar/ .
cd ProgressBar/
monkeyc -y ~/.ciq/developer_key.der -o ProgressBar.prg \
    -m manifest.xml -z resources/resources.xml \
    -z resources/strings.xml -z resources/bitmaps.xml \
    source/ProgressBar.mc source/ProgressBarView.mc

Start the simulator in the background

connectiq &

Start your program

monkeydo ProgressBar.prg

This will upload the program and then execute it. You can stop the application using File → Kill App or by pressing the back button at the start screen of the app.

8) Another Test

Copy the source code of the example program

cd /tmp/ciqtest
cp -r /opt/Garmin-ConnectIQ/samples/Picker/ .
cd Picker/

Create a new file "build.sh" with the content:

#!/bin/bash

# result/output
OUT=Picker.prg

# developer key
DEVEL_KEY=~/.ciq/developer_key.der

# MonkeyC compiler
CC=monkeyc

# declare an array for all arguments
declare -a args

# developer key
args+=('-y' "$DEVEL_KEY")
# output
args+=('-o' "$OUT")
# manifest
args+=('-m' 'manifest.xml')
# resources
for i in resources*/*.xml resources*/*/*.xml ; do
  args+=('-z' "$i")
done
# sources
for i in $(find source -iname '*.mc') ; do
  args+=("$i")
done

# compile
$CC "${args[@]}"

Make it executeable and execute it

chmod a+x build.sh 
./build.sh

Finally run the program and click on the buttons

monkeydo Picker.prg fr920xt

If you press the back-button in the intro screen, the program exits.

The color picker doesn't work but crash because it can't find the resource. I don't know if this is my fault or theirs.

Additional Notes

  • Attention: The simulator will always use the extension ".prg", regardless of what you specify with "monkeydo". If it can't find your executable, "monkeydo" will display a "System Error" (very informative!)
  • The uploaded apps are placed in .wine/drive_c/users/<username>/Temp/GARMIN/APPS/
  • The upload and the start are executed in two steps, i.e., shell.exe is executed twice. See the script monkeydo for more details on the parameters of shell.exe.
  • The tool "connectiqpkg" doesn't work because the Java file pkgtool.jar is missing.
  • You can start "monkeydo" with a second parameter to specify the watch or watch type. Possible values are "square_watch", "round_watch", "semi_round_watch", "tall_watch", "fr920xt", "fr735xt", "fr230", ...
  • For a complete list, see the "id" attribute of the "device" entries in /opt/Garmin-ConnectIQ/bin/devices.xml
  • Attention: If you use an invalid watch type, nothing is displayed and "monkeydo" simply hangs. You have to kill "shell.exe".

Mittwoch, 21. Mai 2014

Including ADC+DSP+DAC in SPICE Simulation

Ever wanted to include an ADC + DSP/MCU + DAC chain in your SPICE analog circuit simulation? Here is an approach where you can directly use the program code of your DSP or microcontroller (MCU) firmware. You only have to program a small adapter routine to simulate ADC and DAC behavior. Then all this can be integrated in the SPICE simulation.

How does it work?

Ngspice is the next generation of the SPICE analog circuit simulator. It includes XSPICE which supports custom so called "Code Models", i.e. models for circuit element which are provided by the user as C routines. I've developed such a Code Model which simulates periodic ADC sampling and DAC output updates. For every period the adapter routine is executed which itself can execute the original DSP/MCU firmware code. So, the DSP/MCU firmware is an actual component in the SPICE simulation.

Example: FIR Filter

Consider a finite impulse response (FIR) Filter implemented in a DSP or MCU, e.g. as an audio processor.

As an example, an 11-th order FIR low-pass filter was implemented as a simple C function. The input signal was provided by another custom code model. This was configured to generate a sweep from 100Hz to 22kHz with logarithmic increments within 220ms. The sampling rate of the FIR filter was set to 44.1kHz. The following image shows the input and output signal (orange in1 and blue out1, respectively) as well as the output signal filtered by a 10kHz RC low-pass reconstruction filter (red vout). The amplitude of out1 clearly shows the filter characteristics with stopband ripples as predicted by Matlab's fvtool.

Application: Source Measurement Unit

A Source Measurement Unit (SMU, also called SourceMeter) is an instrument which does precise voltage and current measurements as well as constant voltage or constant current supply. It can operate in all four quadrants (source and load for positive and negative voltages and currents). The main application of the above mentioned Code Model is the development of an SMU with a fully digital control loop. The only analog part is a Class AB push-pull output stage, everything else, especially the control algorithm, is implemented by software.

Note that this enhances the above FIR filter example to a closed loop setup.

To be precise, there will be more analog components: translate DAC output voltages to the FET gate voltages, translate actual output voltage to ADC input voltage, shunt resistors for current measurement, ... BTW, the shunt in the positive supply is necessary to set a small but controlled quiescent current through both FETs.

The above mentioned Code Model will be used to test and optimize the control algorithm together with the analog circuitry in a SPICE simulation. The source code can then be used without modifications when compiling the DSP firmware. An ARM Cortex-M4F with floating-point support will be used as DSP. These are readily available with 120MHz, which allows roughly 1200 instructions for the control algorithm at a sampling rate of 100kHz.

Donnerstag, 26. September 2013

LED Tubes

Retrofit LED lamps for light bulbs in E27 and E14 screw sockets and for halogen bulbs are easily available, even at food discount stores. Lately, also LED tubes as replacement for fluorescent tubes are available, sometimes at suprisingly low prices.

How do they work? First, how do fluorescent tubes work? The tube has four contacts, two on both ends, between each there is a filament. In the figure below the full circuit is shown: There is a series connection of the inductor as ballast, the right filament, the starter, and the left filament.

When switched on, the full 230V AC are across the starter. "[...] There will be a glow discharge across the electrodes in the starter lamp. This heats the gas in the starter and causes one of the bi-metallic contacts to bend towards the other. When the contacts touch, the two filaments of the fluorescent lamp and the ballast will effectively be switched in series to the supply voltage. The current through the filaments causes them to heat up and emit electrons into the tube gas by thermionic emission.

In the starter, the touching contacts short out the voltage sustaining the glow discharge, extinguishing it so the gas cools down and no longer heats the bi-metallic switch, which opens within a second or two. The current through the filaments and the inductive ballast is abruptly interrupted, leaving the full line voltage applied between the filaments at the ends of the tube and generating an inductive kick which provides the high voltage needed to start the lamp."

The current flows through the inductor and through the ionized gas inside the tube. The filaments are now used as mere electrodes. Due to the voltage drop across the inductor, the starter (which is in parallel to the lamp) sees a lower voltage (approx. 110-150V) which is below its ignition voltage.

"The lamp will fail to strike if the filaments are not hot enough, in which case the cycle repeats; several cycles are usually needed, which causes flickering [...]" (quoted from http://en.wikipedia.org/wiki/Fluorescent_lamp).

For the LED tube you have to replace the starter with the supplied replacement starter, which is a simple short. One end of the LED tube itself is also a short. Therefore the full 230V AC are seen on the other end of the LED tube. This is where the internal power supply is located. This is smart, because you can install the LED tube in either way, it will always work.

Note that with this simple replacement starter, the inductor is still in series, which causes ohmic losses. Most LED tubes also allow the direct application of 230V AC to the power supply pins. Be sure to measure the resistance on both ends to tell the short from the power supply apart. The short should be near 0 Ω (I measured 0,3 Ω including contact resistances), the power supply of my tube varies strongly around 900 kΩ, and the resistance between both ends is too high to measure. If you modify a whole luminaire, be careful not to insert the LED tube with swapped sides, because this will short circuit the 230V line voltage.

Donnerstag, 3. Januar 2013

Measurement Framework for GPIB, USB-TMC, LAN, ...

The GPIB bus is used to connect and control measurement instruments like multimeters, spectrum analyzers, scopes, ... Most professional measurement instruments offer a GPIB connector, and sometimes additionally Ethernet (LXI), USB (USB-TMC) and RS232 connectors, which offer the same remote control functionality.

Setups with one or more measurement instruments and remote controlled sources are used in production test, device characterization, ... Therefore a controller, usually a PC, sends commands to all instruments and queries measurement results. The test and measurement procedure is implemented as a custom program, which links to libraries to send the commands and receive the results.

The measurement framework pas-gpib provides such libraries to communicate via GPIB, LAN, USB and RS-232 with measurement instruments. It is an open source project hosted at GitHub fully implemented with FreePascal. It was successfully tested with Agilent 34410A multimeter, LeCroy WaveJet 354A and 324 scopes and Keithley 2602A SourceMeter. Demo programs how to use the framework with these instruments are included.

All interested users are invited to test pas-gpib and to contribute more functions, more devices and even more communication protocols. Your feedback is very welcome! Let me know, how you could solve your test and measurement requirements using pas-gpib!

Samstag, 29. Dezember 2012

SVF Interpreter for VHDL Testbench

Digital chips often contain a JTAG port, which is used to implemente boundary scan and to access internal functionality of the chip, like programming and debugging.

One widespread "standard" to specify JTAG operations is SVF (Serial Vector Format). Many tools can generate SVF files which are then used to operate the JTAG signals of a chip, e.g. with Lib(X)SVF.

As everything in chip design, the JTAG functionality also has to be verified during development. At this time, all modules as well as the whole chip are simulated. vhdl-svf provides an SVF interpreter, written in pure VHDL, which reads a SVF file and exercises the JTAG signals. It is inteded to be integrated in a testbench to verify the chip design.

Donnerstag, 4. Oktober 2012

MSP430 LaunchPad with Debian

The TI MSP430 are ultra-low-power 16-bit RISC microcontrollers. Since a while, TI sells eval kits called "LaunchPad" for $ 4.30 for their "value line" (i.e. cheap) MSP430 products. These have a debugging and programming interface (USB).

To use the LaunchPad with Debian GNU/Linux (sid, as of 2012-10-04), some packages have to be installed

aptitude install gcc-msp430 gdb-msp430 \
  msp430-libc msp430mcu mspdebug binutils-msp430

Debugging

mspdebug supports the LaunchPad for programming and debugging using its rf2500 driver (which is also used for the eZ430-RF2500 and Chronos watch). It is started with

mspdebug rf2500

This program offers a powerful command line interface for memory dump, programming and debugging. It also has a GDB remote stub, so you can debug your programs with GDB. Connecting via the debugger stops the currently running program (presumably the preloaded demo program). To continue execution, type

run

and press ^C to stop again. This will show the current register values and a short disassembly.

(mspdebug) run
Running. Press Ctrl+C to interrupt...
^C
    ( PC: 0fc86)  ( R4: 00282)  ( R8: 0ab57)  (R12: 00000)  
    ( SP: 0027a)  ( R5: 05a08)  ( R9: 0fb5b)  (R13: 0fd90)  
    ( SR: 000dd)  ( R6: 0adff)  (R10: 0aee2)  (R14: 00000)  
    ( R3: 00000)  ( R7: 0fa3f)  (R11: 0bf73)  (R15: 0ffff)  
0xfc86:
    0fc86: 30 41                     RET     
    0fc88: f2 40 0a 00 00 02         MOV.B   #0x000a, &0x0200
    0fc8e: 03 3c                     JMP     0xfc96
    0fc90: 92 42 70 01 72 01         MOV     &0x0170, &0x0172

You can switch on beautifully colorized output:

opt color true

My LaunchPad came with a MSP430G2231. It seems that newer LaunchPads come with a different device. Features of the MSP430G2231:

  • 1.8-3.6V
  • 16MHz
  • 2kB Flash, 128B RAM
  • 10-Bit ADC, 8 IOs, WDT, Timer, USI (SPI, I2C)

Memory map:

  • F800h-FFFFh: Flash, 4 segments of 512 bytes
  • 1000h-10FFh: Information Memory, 4 segments of 64 bytes, stores calibration values!
  • 0200h-027Fh: RAM
  • 0000h-01FFh: SFR, Peripherals
  • FFC0h-FFFFh: Interrupt Vectors, Reset = FFFEh

The LaunchPad has a red LED (connected to P1.0) and a green LED (P1.6) and a button (P1.3).

After reset, the 16-bit value at FFFEh is read. This is used as initial value of the PC register to start execution. Let's examine the boot process!

(mspdebug) md 0xFFFE 2
    0fffe: c2 fc                                           |..              |
(mspdebug) dis 0xFCC2
0xfcc2:
    0fcc2: 31 40 7e 02               MOV     #0x027e, SP
    0fcc6: b2 40 6e fd 36 02         MOV     #0xfd6e, &0x0236
    0fccc: b2 40 6e fd 38 02         MOV     #0xfd6e, &0x0238
    0fcd2: b0 12 66 fd               CALL    #0xfd66
    0fcd6: 0c 93                     TST     R12
    0fcd8: 02 24                     JZ      0xfcde
    0fcda: b0 12 8e fb               CALL    #0xfb8e
    0fcde: 0c 43                     CLR     R12
    0fce0: b0 12 00 f8               CALL    #0xf800
    ...

Before our own program is programmed, we should save the Flash memory content. The following command will save 2048 bytes, starting at F800h, to the Intel HEX file MSP-EXP430G2-2231.ihx.

hexout 0xF800 2048 MSP-EXP430G2-2231.ihx

During playing, I had an accident, inadvertently typing "mw 0xFFFE 2" instead of "md 0xFFFE 2" which overwrites the value C2h at FFFEh with 02h. It was not possible to correct this with "mw 0xFFFE 0xC2" because the Flash is initialized to all logic 1s and can be set bit-wise to 0. Writing the memory to an Intel HEX file, correcting the value at FFFEh to C2h (and correcting the checksum), and reprogramming the device with "prog MSP-EXP430G2-2231.ihx" restored the old contents. BTW: The "prog" command complained for the invalid checksum and also said which value it expected. So no hand calculation of the value was necessary. :-)

Compiling

As first example program, let's use the blinking LED proposed by TI at http://processors.wiki.ti.com/index.php/Blink_your_first_LED (you have to scroll down a bit). Copy-paste the example program to a file called blink.c and change the included .h-file to the device you own. Then compile using

msp430-gcc -mmcu=msp430g2231 -o blink.elf blink.c

The result can be examined (and disassembled) using

msp430-objdump -d blink.elf

Back in the mspdebug commmand line, program the new firmware to the MCU and start it:

prog blink.elf
run

Nice blinking should be visible.

MSP430 FRAM Devices

The MSP-EXP430FR5739 Experimenter Board with an MSP430 FRAM MCU can also be programmed. It comes with an MSP430FR5739 soldered to the board. Its features are

  • 2-3.6V
  • 24MHz
  • 16kB FRAM, 1kB SRAM
  • 10-BIT ADC, 32 IOs, Comparator, Timer, USCI (UART, IrDA, SPI, I2C)

The memory map is as follows:

  • C200h-FFFFh: FRAM
  • 1C00h-1FFFh: RAM
  • 1A00h-1A7Fh: Device Descriptor Info (FRAM)
  • 1800h-19FFh: Information memory (partly mirrored, FRAM)
  • 1000h-17FFh: Bootstrap loader (ROM)
  • 0000h-0FFFh: SFRs, Peripherals
  • FF80h-FFFFh: Interrupt Vectors, Reset = FFFEh

The MSP-EXP430FR5739 Experimenter Board is a bit more expensive than the LaunchPad (but has a similar form factor). It comes with 8 blue LEDs (everything needs blue LEDs!), an accelerometer, an NTC, two buttons, ... These are connected as follows:

  • LED0..3: PJ.0 .. PJ.3
  • LED4..8: P3.4 .. P3.7
  • S1: P4.0
  • S2: P4.1
  • Accel X: P3.0/A12
  • Accel Y: P3.1/A13

Simple alternate blink program

#include  <msp430fr5739.h>

unsigned int i = 0;

void main(void) {
  // Stop watchdog timer.
  WDTCTL = WDTPW + WDTHOLD;

  // enable PJ.0 and PJ.1 as outputs
  PJDIR |= 0x01 | 0x02;
  // switch on first LED and switch off second LED
  PJOUT = (PJOUT & ~(0x01 | 0x02)) | 0x01;

  // main loop
  for (;;) {
    // toggle LEDs
    PJOUT ^= 0x01 | 0x02;
    // delay
    for(i=0; i< 20000; i++);
  }
}

Save this to a file blink-fram.c and compile with

msp430-gcc -mmcu=msp430fr5739 -o blink-fram.elf blink-fram.c

Important: To download, the mspdebug command "prog" cannot be used, because it issues a Flash erase command. The FRAM devices don't need an erase, because it can be written like normal RAM. Therefore program the device with the "load" command. But first, the FRAM contents should be backuped:

hexout 0xC200 0x3E00 MSP-EXP430FR5739-Demo.ihx
load blink-fram.elf
run

And again, nice blue blinking should be visible

This was only a very coarse run through the tools, but the usage is really astonishing simple, yet powerful. More to come (GDB, Makefile, Eclipse, ...)

Sonntag, 23. September 2012

libusb 1.0 for Pascal

This is a follow-up post to LibUSB for Pascal on 2012-07-15. I've now added header translations for the newer version libusb 1.0 (as well as its fork libusbx) including an object-oriented wrapper and a few examples to be used with Pascal.

Please find the source code in the libusb-1.0 branch at https://github.com/hansiglaser/pas-libusb.