# Code and Life

Programming, electronics and other cool tech stuff

Time for something completely different from my usual electronics projects. This morning I started to wonder (don’t ask why) a couple of fundamental questions:

• If you’d convert the planet Mercury to a huge solar panel, would it cover the sun as viewed from earth?
• How large portion of sun’s energy you’d get for the project if you started by covering the surface of Mercury with solar panels?
• Assuming hyper advanced technology that could do this, would Venus or some other planet in our solar system perhaps be a better target?

The thought experiment initiated from some Science podcast, probably from Anatomy of Next scientist interviews (or BBC’s Tomorrow’s World), which talked about turning Mercury into solar panels or mirrors — essentially a Dyson Swarm.

Mercury is close to sun, so it’s a clear candidate, but I started thinking “If you were an alien (or future human race) with super advanced technology arriving to solar system, which planet would you pick?”. You could of course harvest gas giants for Helium-3 and use fusion energy to do stuff, or have some not-yet-invented energy source. But let’s focus on the giant fusion reactor in the center of our solar system, and look at some numbers.

## Basic Data for Planets

If we think of sun as a perfect sphere putting out energy in form of solar radiation to pretty much uniformly to all directions, the amount of radiation reaching a certain planet is a simple function of the planet’s radius and it’s distance from sun (π*r^2 / d). Surely you can quickly google which planet gets the most radiation? Turns out most articles on the internet for laymen focus on energy per unit of area (square feet or meters), and leave out the size of the planet completely. Well, easy to fix! Let’s start with some basic data from NASA’s planetary factsheet:

Planet Mass (10^24kg) Diameter (km) Distance from Sun (10^6 km)
Mercury 0.33 4,879 58
Venus 4.87 12,104 108
Earth 5.97 12,756 150
Mars 0.642 6,792 228
Jupiter 1898 142,984 779
Saturn 568 120,536 1,434
Uranus 86.8 51,118 2,873
Neptune 102 49,528 4,495
Pluto 0.0146 2,370 5,906

## How Big Do Planets Look From The Sun?

Now as all planets are really far away from the sun compared to their radius and diameter, I’m just doing a shortcut and calculating their angle from sun as just the ratio of diameter and distance, owing to the fact that sin(x) ≈ x for very small values of x (second coefficient of Taylor series expansion is x^3/9 so with these numbers we’ll get about 20 significant digits correct). Calculating diameter/distance shows that even the largest planet from the sun, Jupiter, is just 184 microradians, that is 0.000184 radians wide when viewed from the sun! Full sky would be 3.14 radians, so there’s some way to go!

You could get an excellent Bluetooth keyboard controller from Adafruit called Bluefruit EZ-Key which allowed super easy creation of projects that sent keyboard presses (for example a gamepad) just by connecting some switches to the pins. However, the EZ-Key cost \$20 and is now discontinued. And in any case, Bluetooth-capable devboards are now available from AliExpress for a few dollars, so \$20 today feels on the steep side. “Could it be done cheaper?” I wondered…

I have honestly about a dozen cheap wireless devboards lying around, many based on ESP8266 which only have Wi-Fi, but some also with ESP32 which includes Bluetooth. I spent some time trying to configure a Chinese ZS-040 serial Bluetooth module to function as a keyboard, but the AT command set was a very small subset of what the similar HC-05 / HC-06 modules have. After an evening of trying, I decided to give up on that. There are instructions how to flash HC-05 modules with RN-42 firmware to get Bluetooth HID capability, but it will require quite a few steps.

I also took a look at esp32_mouse_keyboard project, but for some reason or another, abandoned that avenue. Don’t recall if there were obstacles or the project was still incomplete a year ago, might also be that the ESP32 only had BT LE which technically didn’t support HID (Human Interface Device). Throw me a comment if you have that working!

Meanwhile, another idea dawned to me:

## A Cheap Bluetooth Keyboard Must Contain A Bluetooth Module

Enter the wonders of AliExpress: While you cannot source an easy BT keyboard module from US under \$20, you can get a full mini Bluetooth keyboard for \$9.50 (at time of writing) including postage! This package ought to contain:

• A fully compliant Bluetooth board that pairs with iOS, Android and PC devices
• Full functioning keyboard and case
• Presumably, a battery and a way to charge it

Sounds a too good deal to be true? Well, let’s find out! The keyboard has a solid metal backplate that is easily screwed open with micro cross head screwdriver. Once inside, it reveals a very professional layout with a flat ribbon cable (or “FCC cable”) coming from the mechanical part into the controller module, And a small (most likely LiPo) battery.

Taking the tape off and turning the board around reveals a bit spacious, but very professional looking PCB with clear markings. There are easily usable on/off switch and connect button on the PCB, a connector for the keyboard switches, and obviously some kind of microcontroller wired to the connector, as well as another smaller chip that is most likely a voltage regulator or charging chip.

I Googled around to find out if the “YC1026” MCU would have a datasheet to help me along the way, but unfortunately I only got Chinese web pages (most likely the manufacturer) without any documentation. Time to dig out my trusty Picotech 2000 scope and do some old-fashioned reverse engineering!

This project was born as a sidetrack of another one (I’m planning on building a \$10 DIY Bluetooth page turning pedal for my piano and iPad sheet music app, similar to PageFlip Butterfly). I was looking if AliExpress would have bluetooth pedals, which they don’t — it seems Chinese vendors are REALLY good at copying products but there is little new product innovation combining something as simple as a bluetooth keyboard sending one or two keys with a pedal (two items that they do have)! But while searching, I found this inexpensive gadget (in case the product is removed, you might just search for “bluetooth remote” at AliExpress.com):

So what is it? It’s an \$8 disc with multimedia buttons that pairs with your smartphone and you can use it for example in car to control your music. But maybe it would pair with my Raspberry Pi W which has integrated bluetooth as well? Well it costs about nothing to find out!

Fast forward about two weeks and it arrived. I did not try to use it for its intended purpose, but instead went straight to pair it with my Raspberry Pi Zero W. Turns out the pairing process was quite painless, you can follow for example LifeHacker’s tutorial for pairing quite easily. And it goes a little something like this (your MAC address might vary, just look for output after “scan on”):

``````# bluetoothctl
power on
agent on
scan on
connect FF:FF:00:45:8D:FF
trust FF:FF:00:45:8D:FF
``````

Most electronics DIY projects I’ve worked in the past have involved digital communication protocols such as USB, UART or PS/2. Sometimes when first twiddling with a new protocols, everything works nicely. Other times, things don’t quite work the way they should. In the latter case, a logic analyzer is an invaluable tool, essentially a multi-channel logger of digital signals, which you can use to hopefully pinpoint where things are not going as they should. Nowadays most of these are connected to PC, so you can capture a piece of communications between two devices, and analyze what is happening with a dedicated software.

I started my logic analysis with the inexpensive Bus Pirate, but after a while also got Saleae Logic unit I used to view the PS/2 traffic in my knock sensor project. Later on, I have gotten the PicoScope 2208B which has both analog oscilloscope functionality, as well as digital logic analysis capabilities.

So when I was contacted by IKALOGIC, the makers of ScanaQuad series of logic analyzers, who offered to send me a unit to try out in return for a review, I though I was in a good position to give it a spin and also have previous experience to compare it against. I also had a project in mind to test drive the SQ200 unit I got: my recent MIDI-USB adapter, which is a combination of slow 32 KHz serial signals, and quite fast USB signalling.

Note: I received the review unit from Ikalogic without cost, but with freedom to form my own opinion about the device. I’m giving praise where it’s due, but not pulling any punches where something will nag me or compare unfavorably against the devices I’ve had first-hand experience in the past!

The unit arrived well packaged, and inside the plastic wrapping I uncovered a matte black cardboard box with the unit name. A grade above no-name Chinese vendors, but of course not an iPhone “unwrapping ceremony” kind of thing either. Inside, there was the unit, USB cord and logic probes neatly packed (click for larger images).

There’s nothing complicated in taking the unit into use: Just attach the USB cable, the probes, and you’re set. Build quality of the unit is very good, with grey matte surface with nice finishing, four screws and a product spec sticker on the backside, and logo, markings and a power/activity LED on top.

Size-wise, the SQ200 is slightly larger than the very compact Logic unit I have from Saleae (it’s an old model, don’t recall the exact model code), which I rate as the gold standard in product casing, with Apple-esque metal feel (aluminum?) and solid construction. The Saleae unit actually has 8 channels despite it’s smaller size. On the comparison image you can also see PicoScope 2208B with 16-channel MSO capability. Compared to that, both IKALOGIC and Saleae units are quity tiny (still, the palm-sized 2208B is extremely compact as well, given the 2 high frequency analog channels and waveform generator).

This article will detail how to build a USB MIDI adapter (one-directional: you connect the adapter with USB cable to your computer, and it receives notes and pedal data from your keyboard’s MIDI OUT and transmits them to your computer) with ATmega32u4, 6N137 optocoupler, a few resistors and spare MIDI connector or cable. Read on for details!

## Preamble

Last year I wrote how you can turn Teensy LC into an inexpensive USB MIDI adapter. I used it to replace a non-working Chinese MIDI-USB adapter that did not send controller messages (i.e. piano pedal) properly to PC.

However, since the Teensy still costs \$12, and you have to get some additional components, it doesn’t make sense to use it in a dedicated MIDI adapter, since you can get a working USB MIDI adapter for around \$15 from Thomann and probably many other places.

But how about other boards? After making my Teensy LC adapter, I actually tinkered with Adafruit Pro Trinket, and got that working as well (the standard Trinket does not have hardware UART so V-USB and software UART is somewhat risky). But there is even a better board for this: The ATmega32u4 board I previously showed how it can be made into USB HID mouse. Let’s see how to turn it into a USB MIDI adapter!

## Required hardware

To build this, you will need roughly \$5.40 worth of components:

• SparkFun Pro Micro (clones with ATmega32u4 can be had for \$3.50 from AliExpress, eBay, etc.)
• 6N137 optocoupler, which can be had for ~\$0.30 a piece (I suggest sourcing a couple in case you burn one by accident)
• 330 ohm and 2 kohm resistors (\$0.10) and 1N4148 diode if you want to be safe
• MIDI connector or alternatively you can just cut a short cheap MIDI cable and wire it to your project, let’s say \$1.50

In my previous post I showed how to use Raspberry Pi to automatically record MIDI files from digital piano whenever you turn it on. However, if you sit down and play for an hour, and get one big MIDI file, it is not very useful. So what to do?

Pianoteq has a feature that splits your playing session based on breaks you take between playing notes. So I decided to mimick this feature with a simple Python script that:

1. Keeps tab on keys and pedals pressed
2. Whenever X seconds elapse without any keys or pedals down, a new MIDI file is started
3. Additionally, if user presses and releases sustain pedal several times in the end, filename for that MIDI is altered to “highlight” that file

I first thought to learn enough of MIDI file format to do everything from scratch, but there’s quite a bit of small details to handle, so in the end I decided to use an external toolkit from Craig Stuart Sapp called midifile to do the heavy lifting. You should be able to just clone the Git repo and make it with Raspberry Pi:

pi@raspberrypi:~ \$ git clone https://github.com/craigsapp/midifile pi@raspberrypi:~ \$ cd midifile pi@raspberrypi:~/midifile \$ make

You should now have two useful commands in `~/midifile/bin`: `toascii` to read a MIDI file and dump an ASCII (text) version of it, and `tobinary` to do the reverse. With Python’s `Popen` and smart piping, we can read and write the binary MIDI files as they were in this text format. You can check out how the format looks like with some MIDI file you have:

~/midifile/bin/toascii somemidi.mid | less

Here’s a sample of a MIDI file recorded by `arecordmidi` (I added the note in square brackets):

"MThd" 4'6 2'0 2'1 2'384

;;; TRACK 0 ---------------------------------- "MTrk" 4'50044 v0 ff 51 v3 t120 v0 ff 58 v4 '4 '2 '24 '8 v7147 90 '58 '29 v88 b0 '64 '5 v1 b0 '64 '7

[LOTS OF MIDI EVENTS]

v0 ff 2f v0

There’s some header data in the beginning, and each MIDI event is comprised of a deltatime field starting with ‘v’, and then fairly standard MIDI events in straightforward syntax. I hardcoded my program to expect single track which starts with tempo and speed data (ff 51 and ff 58 lines) which I use to calculate how many deltatime units is one second. I copy this header part to start of every MIDI file, and append the final “ff 2f v0” (END TRACK) event to the end. Here’s the full code: