halfbyte

compact musings of a multi faceted geek

As I wrote in my last post one of the things I wanted to try with the Agon was to build a MIDI interface for it and write some software to use it.

I started with a tiny prototype where I would simply connect the Agon Light's serial lines to an FTDI usb adapter so that I could open up a terminal on my desktop computer to see if I could get serial comms to work at all.

It was a bit of a steep learning curve but looking at a lot of other people's examples, I finally got it to work.

Frames shifting and other issues

Kind of. A bunch of weird things happened all at once and it made debugging really hard. At low baud rates (And low in that case meant MIDI speed and downwards), for the most part only the first byte would transfer correctly, everything after that would be mangled. I only later noticed that my terminal (RealTerm is a really great open source program for debugging serial connections) complained about so-called “frame errors”.

Also, even at higher baud rates, where I didn't get these frame errors, the last byte of my transmission would always be cut short. And with that I mean, literally, electrically. The transmission would just stop after 3 bits.

The latter one was easy to diagnose: I simply closed down the serial port too quickly and the UART part of the eZ80 would just stop pushing out the bits. Took me a while but I got there eventually.

The frame errors were a bit more complicated. My hunch was that somehow, something with the baud rate generation went wrong at lower baud rates. Didn't make a ton of sense to me but if you know how serial comms ala RS232 work, you know that one of the few things that can really throw it of is frequency drift.

This type of serial communications works with a single line (plus a ground connection for good measure). There is no additional clock signal. Instead both sender and receiver rely on somewhat stable timing of the signal. (Ben Eater, as usual, does a pretty good job of explaining this in one of his videos).

I didn't have any good tools to diagnose the signals. My analog oscilloscope would probably have trouble properly putting the bits on the screen to measure the timing and the only other alternative I had was my tiny DSO scope, where I was also struggling to get good measurements.

Proper measurements

So I finally caved in and ordered one of these relatively cheap USB scopes, in my case the Hantek 6022BL. People hate these scopes for their shoddy quality but I'd argue that for the kind of stuff I usually do they are actually quite sufficient. The BL variant additionally has a logic analyser (16 channels) built in that luckily works with a chipset that is compatible with the Saleae logic analyser software, which is one of the better tools and one of the things you can do with Logic is automatically decode serial comms. I tried this with my code and Logic complained about frame errors as well. In Logic I was now able to measure the length of individual bits. If you do the math, at 9600 baud (Which I was testing with), each “bit” should take roughly 104 microseconds. “My” bits were consistently around 112 microseconds, so somewhere around 8% off.

So I asked on the AgonLight group if someone could explain this. At the same time, I dug into the source for the AgonLight firmware, called agon-mos to see how the calculation works and if I can find something there.

You see, with a microcontroller like the eZ80, which has two UARTS on board, you cannot simply say to the chip, hey, use 9600 baud. Instead, you have to calculate the ratio between the baud rate you need, the frequency the microcontroller is driven with and a factor of 16.

And there I saw something. The header file defining the constants used in that calculation had the processor clock defined as 20 MHz. But the oscillator that generates the clock runs at 18.4320 Hz. (A very interesting number, as we will see in a sec). If you do the math, the difference between these two numbers is, oddly enough, roughly 8%. Could it be?

I did some quick maths and tried to adjust in my requested baud rate for that specific error and got it to work reliably. So I made a comment to that effect on the group – Dean Belfield, the author of agon-mos was a bit dismissive at first, and rightly so, as we'll see, but later he confirmed that indeed, this was a mistake and he would fix it for the next version.

The fun of integer maths

Now, there's some interesting questions to be asked: The AgonLight heavily relies on UART usage. The ESP32 which acts as Agon Lights main I/O processor talks to the eZ80 via UART0. So why wasn't this noticed earlier? Shouldn't the error be present there as well?

Here we need to get into the details of the calculation I mentioned above: At the end of that calculation you end up with a number you'll write into a register on the processor. The higher your baud rate, the lower that number will be. And it will always be rounded to an integer number, of course. And, of course, agon-mos is trying to communicate with the ESP32 as quickly as possible which means that given the baud rates and the CPU frequency, that number will be either 1 or 3 (depending on how well that link works) and it really doesn't matter if you start with 20 MHz or 18.4320 MHz. Here's where that 18.4320 number has some interesting properties: It makes it so that all commonly used baud rates result in a non fractional number for this calculation. (This unfortunately isn't true for MIDIs odd baud rate, but I think we can make it work with the tiny error we'll get).

So, for very large baud rates, the error introduced by using 20 MHz is either non existing or neglegible and it was easy to overlook. I guess I was just the first one to try out lower baud rates.

Onwards

I now have a test build in my hands and will do some additional testing to see if the baud rate error I'm getting for the MIDI baud rate has any real life effects. I hope it is not the case and I can continue with the project. The next steps are going to be both in hardware and software: I want to try to write a piece of assembler that will receive MIDI. for that I'll need to build a receiver circuit as well, which is a bit more involved than the sending circuit.

And then the next step would be to build a first version of the MIDI circuit on perfboard, after which I will hopefully be able to turn it into a real circuit board design. I will try to document by code and hardware design on this github project

I watch a lot of Youtube videos about retro computing. I am not a huge retro computing person myself, after all, I gave away all of my old computers to a friend when I last moved (they were just taking up shelf space in our basement), but I am a fan.

Every now and then, when watching these videos, you come across some new “old” computer projects, like the Retrogames TheC64 (which is, unfortunately, essentially just an emulator running on an SBC like thing), the ZX Spectrum Next and then completely new designs like the Commander X16. If you look deeper, there are a ton of these projects, but a lot of them have really small communities or are just someone's pet project. This seems to now radically change for one particularly interesting platform: The Agon Light, designed by Bernado Kastrup aka TheByteAttic, Dean Belfield and Jeroen Venema. One of the reason their community is currently exploding is because Olimex, the Bulgarian electronics powerhouse, decided to build a cost optimised version of it you can buy for 50 EUR.

Introducing the Agon Light

A photo showing the Agon Light 2 board inside the Olimex metal case with VGA, USB keyboard and USB power connected and two LEDs showing the status of the board

The Agon Light is a very interesting platform. It uses a modern derivate of the Z80 processor that runs at much faster speeds. But that's not even the most interesting thing about it. Because it runs an ESP32 (yes, that big brother of the ubiquitous ESP8266 internet-of-shit microcontroller) sans the antenna (So no built in Wifi, unfortunately) as the universal I/O controller, sort of. The ESP32 runs a software called VDP (Video Data Processor) that is based on an almost magical open source project called FabGL that, among other things, implements a full graphics processor capable of running VGA output. It also does sound and is responsible for keyboard input as well.

In other words, the ESP32 is AgonLight's VIC/SID/CIA (you can probably tell I grew up with a C64 as my main machine?) and the cool thing about it is that it's all defined in software. Basically, a very cheap version of what most projects try to solve with FPGAs.

The Agon Light runs BBC Basic, a very good basic dialect, ported over from 6502 assembly to Z80 by R.T.Russell and adapted by Dean Belfield to the AgonLight.

Keyboard Error, press any key to continue...

The biggest issue with the AgonLight currently seems to be to find a compatible keyboard, it only supports PS/2 keyboards. Interestingly, the Olimex variant (which I have) comes with a USB port, so it only supports keyboards that have a USB plug but can fall back to PS/2 (which was a very helpful feature of USB keyboards back when they were uncommon).

The Agon Light software side is currently improving quickly. You can now flash the Z80 ROM in situ (no need for Zilog tooling anymore) and the ESP32 can be updated via the USB port (otherwise only needed to power the device) via the Arduino IDE.

People are working on getting various games to run on the machine. People have made the VDP work with CP/M as well which opens up a huge world of retro software.

And me? I have a couple of ideas, which I'll list here for future reference:

MIDI

The Agon Light exposes (similarly to the RaspberryPI) GPIO pins through a pinheader. Among other things, this exposes the second UART of the eZ80 (the first one is used to communicate with the ESP32) which should be MIDIfiable with a fitting interface. I have already looked up how to build such an interface and ordered a couple of missing parts. On the software side, the second UART is already exposed via the system software (called MOS) and should be callable via BASIC, probably with a bit of inline assembler. All in all, this should be doable in 1-2 days.

After that it would be interesting to try to build something on top of that, like maybe a simple MIDI based tracker or so.

Sound

If I can, I would love to help with the software side of exposing more of the sound features of FabGL in the VDP so that it's accessible from the main processor. I assume that designing an interface that will allow expressiveness while not overloading the serial bus will be tricky, but it's worth a shot. There are people already working on that so'll try to chime in there if I can find the time and I think I have something to contribute.

A simple sprite editor

I would love to dip my toes back into BASIC to see if I can build a simple sprite editor. My idea would be to build something similar to the tooling Pico-8 has built in, sans mouse support, of course.

Conclusion

This looks like a fun retro computer. A throwback to simpler times. An interesting target for experiments. Let's see how it goes.

Okay, that's probably an exaggeration. I am neither in the Ukraine nor am I part of the Russian troops, so unless something goes extremely sideways within the next few weeks, I'm probably fine for now.

The reason for this drastic, probably a bit clickbaity headline is a serious one, though. The very thinly veiled threat of Putin to use his (to be fair, so far rather underutilised nuclear arsenal) did trigger some deeply ingrained fears in me. I grew up in the 80's (Born 1976) and as a rather astute (If I do say so myself) and curious young child, I unfortunately was a bit more influenced by the cold war antics of the day when a nuclear meltdown was essentially on the table on a day to day basis than you would think. So deeply ingrained were those fears, in fact, that my subconcious transported me directly into the centre of a nuclear explosion one morning in a dream when in fact, the only thing that happened was that some rather noisy construction work had started on the roof I was directly sleeping under. I was probably 14 or so and the risk of a sudden nuclear war was suddenly very low after the collapse of the soviet union and the german reuinfication. Still.

All goes to say, of course I am relatively safe here in Germany, all things considered, especially in contrast to my Ukrainian brothers and sisters but that doesn't mean that this doesn't trigger traumata in many of us born before the official end of the cold war.

The full on invasion of the Ukraine by Russia, a clear breach of international law and a couple of existing treaties, once again, changed everything.

Ah, ye olde militarism, can't say I missed ya

My country, Germany, usually obsessed with being as frugal as possible, suddenly found 100 Billion EUR to throw at our mismanaged and especially mis-consulted military. And our parliament, instead of bemoaning the necessities of war, gives itself standing ovations, as if every other member also sits on the board of directors of one of our countless weapons manufacturers (Actually, now that I think about that, that's probably closer to truth than I want to admit) or, worse, actually looks forward to finally show the world again that Germany is a strong country with a strong military.

Sorry, I had to puke and some of it got into my keyboard, it took a while to clean up.

The only silver lining seems to be that there seem to be some (finally) understanding that being completely dependent for energy sources (Coal, Oil, Gas) on a, shall we say slightly less democratic country like Russia is probably not a good idea and that renewables are actually a pretty clever idea to get rid of those dependencies.

Apart from that the new military budget, paired with the so called “debt brake” which disallows the state to increase the debt beyond certain limits makes for a rather bleak outlook in terms of investments into a more climate friendly future. Pretty sure all those new tanks and war planes we'll be getting will be hydrogen powered, right? Right?

Get to the fecken point, man!

After a lot of rambling, fuled by my very odd combination of a epidemic induced tiredness, excessive fear for our future (a nuclear winter might counteract global warming for some time, maybe?) and white hot rage, let's try to bring this to a point, because a point I wanted to make.

In the last couple of years, political commentators have often bemoaned the obvious lack of long term thinking in modern democratic politics. The (only recently ended) era of Chancellor Merkel was pretty much this very short term thinking and focus on reactive policing personified.

We have always said, that with the climate crisis, this short term thinking will fall on our feet at some point. Of course, this has already happened almost everywhere in the world, with Floods and Fires, Hurricanes, etc, but it is clear that a bit of global strategic, long term thinking could have prevented a lot of all of these terrible things.

To me, the Russian war on Ukraine and the limits of our space of possibilities to help Ukraine is also a result of that.

We could have made ourself less dependent on Russian energy sources a long time ago. Nord Stream 2, the gas pipeline now completed but probably doomed to never actually go into service (don't get me wrong, that's probably for the better, but what a waste of time and resources) is one of those examples where at every step someone should have said “No, this is not a great idea”.

Diamonds are an oligarchs best friend

Of course, the short term thinking was also paired with a healthy dose of greed (or should we just call it Capitalism?) as one could witness in the early talks about the sanctions against Russia where the dependencies on oligarch money became painfully clear – Milan wanted to be able to still sell overpriced bags, Antwerpen wanted to please be able to continue to sell Diamonds.

Do we need more lenses?

My friends and I often remarked during the pandemic how the coronavirus created a sort of lens through which faulting in our societies suddenly became visible (with the obviously terrible state of our health care work being the most drastic example).

It is both my hope and my fear that the next weeks shaped by this travesty of a war caused by a hurt ego of a very small man and his nationalist “thinkers” will create a lens that will inform our thinking and our actions for a very long time. Seeing the usually well buried but obviously not irradicated militarism awaken with such force in my home country does make me fear we might not only learn the correct lessons. It is our responsibility as citizens, as humans, to watch this closely and do everything we can to keep us from tumbling down the slippery slope that small man has so artfully created for us.

Glory to Ukraine!

All of that being said: A country led by a man who once played a piano with his penis on national television and who was the Ukrainian voice of Paddington Bear should be in a good position against any aggressor. And for once I am not even joking. Slava Ukraini!

After my last post about my first ride on an e-bike, things got out of hand quickly. First, a friend of mine, who recently started to work for dance.co got in touch and after a very nice breakfast with loads of nerding out on cycling and electronics, I got to test ride their current offering. It's a good bike that makes all the correct compromises for a city bike, I think. Unfortunately, while they definitely plan to expand beyond Berlin, a definite start date for Hamburg is not yet known and so I looked around and scanned the offerings of the biggest bike rental player, Swapfiets. They recently introduced the Power 1, which is, while quite a different beast than the dance bike, is at least the closest. With the introductory price of 49 EUR per month, testing this out was a no-brainer, and so I have one of these bikes in my posession right now.

It's a solid bike

The first, obvious thing is that this bike is heavy. At 25kg (with Battery) it is more than double the weight of my (comparably light) Stevens Courier SL and that makes heaving it in and out of my basement storage quite a different procedure.

The electric motor and drive is fine, but given that this is a single speed the experience of driving it is distinctly different from driving the 7 speed during our vacation. You accelerate to the 25 km limit quite quickly, but if you're sustaining at that tempo, it's quite exhausting, not so much for muscle power but for sheer speed of the movement. A different kind of workout, so to speak. That said, I think I tend to usually drive my bikes at rather low pedal speeds (tending towards the higher gears, so to speak) and so this may be a very specific problem of a low frequency pedaller.

Yeah, that front rack

The rest of the bike is the usual solid quality you come to expect from a dutch bicycle company, but I have to say, I really dislike the front wheel bike rack. I understand that many people really like that setup because you have your belongings always in sight, but the weight distribution, if I drive this with two loaded rack mount bags is far from ideal and there's really no way to mount something on the rear wheel.

Keeper?

All in all, I am not sure I'll keep this bike – Or rather, I am quite sure that I only will keep it until I can test out the dance bike.

There's also the question of how always driving an e-bike will impact my fitness, as my usual commute is definitely part of my cardio program – I decided to ignore this question for now and focus on the practicality of these bikes and then have a go at the question if an e-bike would make any sense for me in the city. Of that, I am not so sure right now.

I must admit that so far, I haven't been a strong proponent of electrically powered bicycles. I did see the benefits for people who, for what ever reasons were not able to ride bikes at “normal” speeds (What one considers “normal” is debatable, but I think 20 km/h, which is the speed city planners in cities like Copenhagen assume as the average speed, is a good threshold), but that was about it. Now, mind, apart from the occasional elderly riding their e-bike way outside their (or, rather, my) comfort zone, I didn't really think there was anything wrong with riding an e-bike – I just thought (and partially still think) that riding a good bicycle without additional help on an daily basis has benefits on its own and of course, e-bike tech will add additional weight and also cost to your bike that isn't strictly necessary.

That is until we loaned a pair of bikes for a day during our last vacation, on a rather windy day at the north sea coast.

The shop (Not a paid ad, we just really like their service) is famous for mostly loaning out these ridiculously looking cruiser bikes and while my s.o. got a rather normal looking dutch ride (albeit, as you might have guessed, with a beefy electric motor), I loaned one of their entry model cruisers.

Wheeeeeeee

And my mind was instantly blown. We spent that day driving around 45-50km in total in a little under 4 hours with some extended breaks (We are on holidays, after all). We've done similar trips before without motorization and I can tell you that those days usually leave us quite exhausted – Not so much with these magical electrically powered wonder horses. (Never mind I had just recently rolled my right ankle and so riding with electric support was the “healthier” option at that moment.

At times, driving these bikes almost felt like defying physics. Driving through open fields, with rather strong headwinds did require us to bump up the level of electric support eventually, but it almost feels surreal to push the pedals and you feel the wind, but the force required to push does not square with the wind resistance you're feeling and it all doesn't make any sense, probably especially for someone like me who rides their bike every single day under any conditions.

We probably had an average speed of around 22-23 km/h, so a bit below the max supported speed (you can ride these bikes as fast as you want, but if you're quicker than 25 km/h, you won't get any electric support at all) and most of the time I rode in “eco” mode and it still felt pretty much effortless. And it was really great to be able, for example to climb a dike, to just bump up the support from Eco to Tour to Sport to Turbo and just feel your own pedal power being multiplied by a bit of clever motor driving electronics.

So now that I have experienced that magic, how does that change my perception of e-bikes in general?

Good enough

First of all, it seems clear to me now that e-bike tech is already firmly in the “good enough” stage of product development and it will hopefully get a bit cheaper over time, the batteries maybe a bit smaller and lighter (or, if you choose, a bit more far reaching), but at its current state with ranges of well beyond 100km for one charge, it should be good enough for any sort of urban and suburban commuter use. I know I am just late to the game and this state has been probably reached quite a couple of years ago, but the exploding amount of e-bikes I encounter on the streets every day seems to suggest that some sort of threshold has been passed quite recently.

What we have here is a backup system

Second, I think I have to revise my thinking around when an e-bike can be useful. While I am quite okay with riding my non electrified bike most of the times, I think we all (who cycle every day) know these days where you step on the pedals and everything feels like a slog. It might be an upcoming cold, or just unfavourable wind conditions, or your route is surprisingly hilly, but it feels like you're driving through quicksand and you're not getting anywhere while quickly getting sweaty and uncomfortable. Being able to show these kinda days the finger and just bump the support level of the electric motor would definitely enhance my life quality.

And of course, they would make trips viable where I usually would probably take public transportation or even the car, for example the 15 odd km to my mums house, where I know that I can either treat it as a workout or just take the subway and take a book with me.

And augmentation to an augmentation

As biomechanical engineers long have stated, a human on a bicycle is by far the most effective animal in terms of both speed and endurance. I think it is this initial effectiveness of the human+bike system that makes it so incredibly easy and effective to lift it to another level with relatively small motors. The regulatory maximum in Germany for e-bikes classified as bikes (and not as motorbikes) is 250 Watts, or, if you prefer units particularly stuck in the petrol past or worse, 0.33 PS. And most of the time, at least in the city, you probably only need a fraction of that.

I could now definitely see my next bicycle to be an e-bike. Not 100% sure about this yet, I already drive a relatively expensive bike and I probably have to double the price of that to get a decent e-bike and also I know how good regular commutes without any support are for my health and fitness, but if it helps me to do even more trips by bike I would usually do with other means, it may just be worth it.

In any case: What an awesome experience. If you have the chance, on a vacation or otherwise, to test out an e-bike in a relaxed, realistic setting, do yourself a favour and do it. It may blow your mind.