IoT rant

I love making things with microcontrollers and such-like, so I would rebuff any accusation that I’m a luddite or old man shaking his fist at the sky when it comes to tech.

Despite – or maybe because – of this I eschew all things “IoT” and “cloud” in products. It baffles me how anyone can really trust these things when we have seen, time after time, how badly supported they are.

Matt Pulzer sums it up eloquently in his March 2020 editorial in Practical Electronics:

One of the big tech news stories the week Iā€™m writing this Editorial is the howls of outrage that greeted the announcement by smart speaker manufacturer Sonos that they were no longer supporting some of their older products ā€“ and in some cases not-so-old ā€“ with software updates. Customers who had spent small fortunes on whole-house installations were furious that their investment was compromised and that at best they would need to run two incompatible systems to pipe music though their home. This came just eight months after Google announced it was to cease supporting its Works programme, which allowed third-party vendors to integrate products such as smart light bulbs with its Nest ecosystem of home automation.

Pulzer drew five conclusions:

  • Company size is no guarantee of anything
  • companies can be arrogant and stupid.
  • software is likely to expire
  • “all-in-one” systems are especially vulnerable to these problems
  • simplicity is a prerequisite to reliability (paraphrasing here)

I don’t own a kindle, for example, and I doubt I ever will. For starters, I’m not shelling out on a piece of electronics when, you know, I could just read a book. And secondly, I just don’t trust Amazon enough. I buy plenty of stuff from Amazon, but I just don’t trust their servers, or their business ethics, enough to buy a kindle.

Within the last decade we seem to have entered a brave new world of “Big Tech” (I usually hate to reduce things to slogans, but in this case, I think you can see my point). We’ve happily gone along with Facebook, Twitter and Google and their unconscionable snooping.

Well, I could go on, but that’ll do you for now.

Posted in Uncategorized | Leave a comment

In praise of the #RaspberryPi Pico

I’ve seen a lot of criticism for the new Pico, usually around price versus features/power. An often-preferred solution is the Espressif ESP-32 or one of its variants. It weighs in at approximately the same price as a Pico, but comes with WiFi and bluetooth.

The ESP-32 is certainly impressive, and it’s easy to see why it is popular with makers. I, myself, even figured that these guys would sweep all the competition before them.

Wi-Fi is not the be-all and end-all of everything, though. The ESP-32 development boards are a little too chunky to be convenient. You have to straddle two breadboards to plug them in. I’ve also become somewhat disillusioned with WiFi. WiFi adds additional complexity to a project, and is often unreliable.

My conclusion: are you sure, really sure, that your project needs WiFi?

And I’ll tell you this: I’ve had enough hassle setting up my own network infrastructure – something over which I have complete control – to ever trust some third-party device.

Espressif does offer a nice SDK, with examples, and it’s clear that they’re willing to put effort into providing a pleasant environment for developers.

STM8S chips are worthy of consideration. They never really caught on in the maker market, which I think is a bit of a shame. What I like about them is their simplicity, price and a small form factor that nevertheless offers plenty of pins.

To program them I use my own custom code that I built from the ground up. I use the free sdcc compiler. It’s not without its quirks, but it’s good enough for my purposes.

STM32 chips are also pretty good. A lot more effort is required compared to an STM8S. I use my own custom code for the STM32 too, and it’s a lot more work!

Which brings me to … I hate their own development ecosystem. It’s not exclusive to STM32, not by a long shot. There is plenty of scorn to be poured of vendor-supplied developer systems.

The general problem is that they tend to be over-bloated. They’ll often be based on Eclipse, a big fat hog of an development environment . They often suffer from what I call the “Microsoft Disease”: big bloated, complicated systems that spew files all over the place where it’s a complete mystery knowing what they do or why they’re doing it.

Anecdote time: I was working for the then-Logica back in the late 90’s. Most of my development work was done on Sun Solaris systems. I loved those systems. I went on a project for a few months that was based on MS Visual C++. As my project manager observed: “What do all these files ‘do’?” He was a big fan of Lisp, BTW.

I have somewhat relented on my scorn for all things Microsoft when I saw their latest version of Visual Studio for Linux. It was much lighter weight than I was expecting. I tried it, and it seemed like a reasonable offering to me. I can see why people would be interested in it. VS and Eclipse seem like strong competitors in the IDE space, with VS edging ahead in terms of popularity.

VS is something I’m prepared to investigate again. I’m still a fan of the combo of vim and a makefile, though. Incidentally, I was talking to an old chum of mine who made it really big as an IT officer in the investment industry. He said that vim is the generally-preferred solution. Back in the 90’s when I was doing my PhD one of the research guys there was a huge fan of vi, which I often mocked him for. My preferred “IDE” at the time was notepad. Hmm, OK.

I’m not a fan of ST’s HAL (Hardware Abstraction Layer), either. I ended up thinking that this kind of stuff adds complexity, rather than removing it. I’m not a huge fan of their CubeMX thing, either. Ostensibly it simplifies configuring a chip. In practise, I find it presents a bewildering array of bells, whistles, dials and buttons, a veritable cockpit of instruments set before you. The problem is that it lacks focus for whittling down what I’m trying to achieve.

I’m not much of a fan of mbed, either. This is a kind of SDK/OS developed by ARM. I’ve tried to like it, but ultimately failed to do so. It’s a nice idea, but falls short in accessibility. It’s what I call an “Alphabet Soup”: all the letters are there somewhere, they’ve just been put into a big pot and stirred. There’s no coherency, it’s all a big mish-mash. ARM seems to offer a selection of kits to choose from. Mbed, which I presume to be the one ring to rule them all, seems to have it’s own variants, too, with plenty of examples that is deprecated. As a newcomer to their platform, it is exceedingly off-putting. It smacks of being an immature platform to me, although I’m sure that ARM has put a lot of effort into it and would vigorously deny that assessment.

So, where I’m coming from, I have a bias to rolling my own stuff. There’s advantages and disadvantages to that, of course. The big disadvantage is that it’s heavy-going. I often look at forums and YouTube for guidance, as there is usually some fundamental twist that needs to be used in order to get something to work. There are quite a few advantages, however. The results is vastly simpler, vastly more compact, and vastly easier to understand. It’s usually way quicker to compile, too, because I’m compiling for that project, for that chip.

I don’t think there’s anything wrong with the chips, mind. I never met a MCU (microcontroller) that I didn’t like.

Arduino Unos, what about them? Well, actually, I think it’s easy to see why they are popular. Sure the IDE is somewhat slow and imperfect, but it works. There’s arduino-cli for people like me who think that stuff made out of Java isn’t such a great idea.

The thing about Arduino is that they’ve thought long and hard about what they’re trying to achieve. I can upload code to the MCU easily, the chips are nice and simple, and they’ve tried hard to make a good SDK. There’s a mature ecosystem of third-party software and hardware support surrounding them, too.

The Atmel documentation also looks pretty good, too. You know, people bad-mouth Arduinos as being too simplistic, but there’s nothing to stop an avid explorer peering under the hood and doing things at the register level.

Although the Arduinos are not without their limitations, and they’re certainly not cheap for what they are, I would still recommend them as excellent devices for people wanting to get into microcontrollers.

OK, but what does all this have to do with the Pico, I hear you ask? Well, it’s not just word-padding to meet minimum content-length, you understand. It’s a backdrop from which to assess the Pico as an offering. Chips have to be assessed as a complete package with a number of intangibles – their “pleasantness” – rather than just a count of the number of pins or the speed of the CPU.

The first thing I liked about the Pico is that it uses a standard compiler toolchain. Being an ARM processor certainly helps here. ARM is a first-class citizen of the GNU toolchain. Extremely well-supported. I can install the compiler from my Linux distribution. No need to download some vendors offering, or their bizarre IDE.

Building a project requires cmake, which I don’t particularly like, but is tolerable. Like I said before, I’m a bit old school: give me vim, Makefile and a library. I’m not a fan of building the world from scratch. I need to cut some slack here, though. Pico’s SDK allows you to custom-compile features like exception-handling, so a generic library might not be feasible. It’s all pretty quick to compile though, which mitigates some of the disappointment.

Next I’d say is that the Pi Foundation, like Arduino, seem to have a clear vision as to what it is they’re trying to accomplish.

The documentation for their SDK is excellent. The SDK is top-notch, too. Unlike other processors like STM32s, I’m not tempted to write my own code from scratch. Just use the SDK. It is fairly easy to set up, too.

Their engineers seem to patrol the forums, too, and I’ve had valuable tips from them.

Their dedication to producing the highest quality documentation is admirable, too. I have submitted a couple of suggestions as to how it could be improved, and they’ve duly obliged.

As with all things engineering, you get what you design for. The Pi team has designed for hardware that is relatively easy to understand. They’ve put heavy emphasis on documenting it, too. Because, let’s face it, at the end of the day, it doesn’t matter how sophisticated the hardware is, if it’s use is unfathomable to mere mortals, then it might as well not exist.

So, the Pico is very “maker” friendly. It is bound to attract a huge following. I knew when I read the Pi’s announcement that it was a chip worth investigating. So, yeah, despite the naysayers, it is rapidly growing on me a chip that is very pleasant to work with.

Downsides? I was slightly surprised at the way they chose to program the chip. Arduinos work better in this respect. I’d like to see serial communication work more seamlessly, too. Thinner chips would be nice, too. And definitely, definitely, pin labelling on the top of the chip rather than the underside. I’ll leave it as an exercise for the designers as to how they can make the chips thinner and label the pins on the topside. šŸ˜‰

I am also curious as to what direction the foundation is going with respect to their new chip. Like the Cyclons, perhaps. They have a plan, but they’re just not telling us. Their chips are being incorporated into other vendors: Adafruit, Arduino, Pimoroni, and undoubtedly others of whom I am unaware.

Could this be an entree into a much bigger idea? Like leading ARM into some kind of consistent infrastructure, kind-of like what made Intel so useful as a system. Or maybe some kind of Pi/Pico hybrid? Like, all the goodness of a system on a chip with all the simplicity of a microcontroller. Hmmm. I wonder where all this is taking us. Maybe nowhere. Maybe Eben Upton has some big masterplan, maybe he doesn’t, and maybe this will take us to places that no-one has even imagined yet.

Hmmm.

So, anyway, that’s me, a big fan of the Pico, a chip that tries to be maker-friendly.

Posted in Uncategorized | Leave a comment

A simple VCO (voltage controlled oscillator) for audio

It is possible to generate square waves suitable for audio output using a battery, Schmitt Inverter, capacitor, small speaker, and resistor. A highly recommended option is to use an OPAMP to boost the signal.

Here’s a video demonstration:

I’m actually quite pleased with the result. Throughout the rest of the discussion I will assume the use of an OPAMP. A schematic in its pure form looks like this:

The Schmitt inverter is the triangle on the left. The one on the right is an OPAMP, which has been configured as a buffer.

A good choice for R1 is a 100K potentiometer, and for C1 a 0.01uF capacitor. I was able to generate signals in the range 140Hz to 17kHz (approx).

Schmitt inverters are typically sold as “Schmitt Hex Inverters”, meaning that there are six of them on a single chip, rather than just one. A 74HC14 is a suitable choice.

An equivalent circuit to the above, but this time showing chip pinout connections, is as follow:

The relevant internals of the chips are also shown.

You can construct an LFO (Low Frequency Oscillator) using an R1 of 20K ohms (variable, of course) and C1 of 100uF. I was able to generate frequencies in the the range 0.7Hz – 280Hz with these values.

Why would you want to generate these signals at such comparatively low frequencies? Well, you could use it for blinky lights. The frequencies are low enough to be visible. But what I really had in mind was to use it as a control signal to a “stepper” module. The LFO can be used to control the “beats” of a synthesiser, i.e. how fast our synth will play.

More of that in a future post.

Posted in Uncategorized | Leave a comment

#RaspberryPi bare metal: progress on Terrible Allocation Table

So, I’ve got the SD card working on a Pi 0 bare metal. Cool.

FAT32 is a bit trickier. I found someone’s project, but I couldn’t get it to work. So I was pondering whether to try to fix it, or just go make my own filesystem.

Oh hell, I decided, I’d just roll my own. SD cards are a bit of a dark art with microcontrollers generally. I’ve had them going on-and-off with things like STM32 and ESP32s. It’s difficult to know what’s wrong. Is it the library, or is it the hardware?

I’m sticking with the Pi0 for now, anyway, as I don’t have to bother hooking up a card. The Pi Foundation are working on a SD library for the Pico, so that will be nice to see working. In the meantime, I’ll just follow the path of least resistance.

So, roll-my-own filesystem it is. I watched a couple of vids on how the FAT32 system worked, but got confused. I want something to Just Work for now, so that I can store samples on an SD card and play them on this daft idea of a synthesiser I have.

The simplest idea that I could come up with is TAT, my Terrible Allocation Table. What you do is set aside a partition, then invoke the formatter. This splits the partition into 20 equal file slots, each of equal size. You can then save files to the slots.

So far, I can store, ls, and retrieve a file (the last one not bare-metal itself). So it’s looking pretty cool. And, because I wrote it myself, I have a much greater comprehension of what’s going on.

Other than being limited to 20 files, there is no directory structure. Just straight files. I’m not interested in any fancy stuff.

If you’re interested in the basic concept, then check out the following two directories:

  • * dir1 – which works on Linux and connects to an SD card via loopback, and
  • * dir2 – which works on Pi 0 bare metal

The first directory is for development work. It is tested there first, and migrated across via some common files.

It has many jutting-out flesh-tearing shards at the moment, but it works at a barebones level. It’s probably too cryptic for other people to figure out, but if there’s interest, I am open to explaining things in greater detail, and to start knocking off some of the roughest edges.

Posted in Uncategorized | Leave a comment

#RaspberryPi 0: PWM hard-coded bare metal audio working

I’ve been experimenting with PWM on the RaspberryPi again. I managed to get a hard-coded sample working, which you can view here.

This is pretty cool, because my rough-around-the-edges bare-metal “unikernel”, Crunky, is showing its usefulness to me. Porting the BCM2835 library has been a great help.

I’m inching closer to getting a real-time synth going.

I’ve got the SD card “working”, too, so it is at least conceivable that I’ll be able to save and load my work. Currently SD works only as a block reading and writing device. FAT filesystem support does not exist. I’m thinking it’s too complicated for me to implement, too. I’m thinking of, maybe, implementing my own filesystem. Something simple.

Also, maybe, just maybe, I’ll be able to crib some code from the Cambridge University site and get a USB keyboard working. That would be so cool!

USB is a nightmare on the Pi, and it’s really difficult to know how to approach it. I’ve not had much success with it. Maybe tinyusb might be something in the way of a solution.

In fact, USB is kinda what lets the Pi down. It’s complicated, and not something I relish tackling.

I’m in two minds at the moment as to the best hardware with which to approach real-time systems. Should it be the Pi0 or the Pico? I’m edging in favour of the Pi0.

Posted in Uncategorized | Leave a comment

#RaspberryPi Pico I2C OLED display updated

Thanks to a pull request from Joe Jackson, an example bitmap display is given for my Pico OLED 128×64 I2C display (see here).

My code isn’t perfect, but at least it works. You can do bitmaps and text, which is I think is really useful. It won’t quite work with a 128×32 OLED display. I have one of those, so undoubtedly I’ll incorporate a suitable enhancement one day.

Update 2021-04-16: The code now works with a 128×32 display.

Posted in Uncategorized | 3 Comments

#RaspberryPi Pico: A piano “synthesiser”

After having made an atrocious synthesiser, I thought it would be good to up my game and create a slightly less atrocious synthesiser. This time, instead of using the serial port, I thought I’d actually make a synthesiser. It is based on the Rolf Harris Stylophone from the early 70’s. I think my stylus piano actually sounds better, and at the very least it isn’t mired in as much controversy as anything associated with Rolf Harris.

One of the questions I pondered over was: how should I make a piano? I have a whole bunch of screws left over from when I’ve tinkered around with desktop computers. An actual keyboard would be too complicated to make, and would actually cost money. My engineering skills aren’t up to much. My craftsmanship is even worse.

I decided that the best approach would be to create a stylophone-type contraction. The keys are separated by resistors, and the stylus transmits a voltage to an ADC. That way, I have only 3 wires coming out the back of the stylus, rather than one wire per key. It means you can only play one note at a time, and there is the inconvenience of a stylus. But my desire to avoid a bunch of wiring made this a good trade-off. It’s only a toy, after all.

Here’s the schematic:

You touch the stylus, marked JS, against any one of the screw contacts J1-J11. There is actually a design fault. There should be a 220 ohm resistor between J11 and the 100K ohm resistor. It means that you can’t actually play the F5 key. I decided not to sweat the issue, as it was only a an experiment.

The actual “piano” itself looks like this:

Topside

When I say “stylus”, I of course mean “crocodile clip”. The wire running from the clip to the board is excessive for what we really need, but I just used a long piece of wire that I had available.

I used a piece of MDF as the base, and drilled holes in it through which I put the screws. I also gave names to the keys and their positions on the music stave, as I am hopeless at reading music. There are no black keys on my piano. You could add some, if you liked, but it would have made the board more complicated.

The underside of the board is sparse:

Underside

A big mistake I made was that I discovered that you can’t really solder to screws. So I had to tie some conducting wire around the screws, and solder the resistors to that. A better solution would be to use washers and trap the resistors between the washers and the board. Nuts could then keep the whole thing tight. I had neither screws that were long enough, washers or nuts, though. My original plan was to put the resistors on the underside of the board, but I quashed that idea when I discovered that you can’t solder resistors to screws.

Here’s what the complete assembly looks like, including the Pico and speaker:

Complete circuit

The 100k resistor is to create contact between the ADC input and ground. Otherwise you just have a floating ADC input, which gives spurious readings. 100k is large in relation to the other resistors, so that there is a much smaller resistance when the stylus connects with any of the key screws.

Video demonstration:

Here’s the code:

#include <stdio.h>
#include <vector>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/adc.h"
#include "hardware/pwm.h"
#include "hardware/clocks.h"

using namespace std;

using  u16 = uint16_t;
using  u32 = uint32_t;
using  u64 = uint64_t;

#define SPK 15

typedef struct {const char* name; u16 adc; u16 freq;} note_t;

const vector<note_t> notes = {
	{"C4",	11,	262},
	{"D4",	430,	294},
	{"E4",	834,	330},
	{"F4",	1252,	349},
	{"G4",	1650,	392},
	{"A4",	2060,	440},
	{"B4",	2480,	494},
	{"C5",	2880,	523},
	{"D5",	3303,	587},
	{"E5",	3701,	659},
	{"F5",	3900,	698} // F5 won't work properly
};

vector<u16> cutoffs; // for the midpoints in the notes table

//#define NO_NOTE_IDX  0xBAD;
uint slice_num; // of speaker SPK

void set_freq(u32 freq)
{
	u32 top, level;
	if(freq==0) {
		top = 0;
		level = 0;
	} else { 
		top = 1'000'000UL/freq-1;
		level = (top+1)/2-1; // 50% duty cycle
	}

	pwm_set_wrap(slice_num, top);
	pwm_set_chan_level(slice_num, pwm_gpio_to_channel(SPK), level);
}

bool repeating_timer_callback(struct repeating_timer *t) {
	static int reading_number = 0;
	//printf("Reading %d ", reading_number++);
	static int idx = -1;
	int adc = adc_read();
	//printf("adc:%d\n", adc);

	// find cutoff
	int idx1 = -1;
	for(int i=0; i< cutoffs.size(); i++) {
		if(cutoffs[i]>adc) {idx1 = i; break;}
	}
	//printf("Cutoff index: %d\n", idx1);
	if(idx == idx1) return true;
	idx=idx1;	
	u16 freq = 0;
	if(idx>=0) freq = notes[idx].freq;

	set_freq(freq);


	return true;
}


int main() 
{
	stdio_init_all();
	puts("synth-1 started");
	adc_init();
	adc_gpio_init(26); // ADC0

	gpio_set_function(SPK, GPIO_FUNC_PWM);
	slice_num = pwm_gpio_to_slice_num(SPK);
	pwm_set_clkdiv(slice_num, clock_get_hz(clk_sys)/1'000'000UL);
	pwm_set_enabled(slice_num, true);

	//init cutoffs
	puts("Init cutoffs...");
	cutoffs.reserve(notes.size());
	for(int i = 0; i< notes.size()-1; i++) {
		cutoffs.push_back((notes[i].adc + notes[i+1].adc)/2);
		printf("Cutoff %d:adc %d\n", i, cutoffs[i]);
	}
	cutoffs.push_back(3900); // not really right
	puts("...OK");

	set_freq(0);

	struct repeating_timer timer;

	u32 ms = 50;
	//ms = 1000; // for debugging purposes
	add_repeating_timer_ms(-ms, repeating_timer_callback, NULL, &timer);


	for(;;);


	return 0;
}

You will probably need to tweak the ADC values (second field in note_t struct) in the notes vector. To obtain these values, you can put my adc project onto the Pico, and note down the ADC values as you work through each key on your keyboard.

From the notes, the Pico computes a vector of cutoffs, being the midpoint between ADC values. The function

repeating_timer_callback() 

is triggered every 50ms. It takes an ADC reading, and uses the cutoffs to determined an index into the notes array. From that it obtains a frequency for the note it should play.

Future directions? Well, I recently discovered that my local library does 3D printing. So the next logical step would be to try to see if I could actually 3D print keys, correct the current design flaws, and create a much more professional-looking product.

I am, however, half-inclined to abandon the keyboard idea. My keyboard skills are, shall we say, rather crude, so I might be better off going to a “tracker” type approach, where I enter keys into a program. This is bringing me back to using a Raspberry Pi 0.

Decisions decisions.

Anyway, you might like the above for a fun and doable project in any case.

Have fun.

Update 2021-02-19 Ice cream lid upgrade

I was fed up with the stylus idea and decided to upgrade it to a full keyboard (um, such as it is):

What I did was take an ice cream lid, cut it to size, and cut narrow slots into it so that it has a number of tabs, one for each screw, of the right spacing. The plastic lid gives flexibility to the keys. I used pritt stick to glue a sheet of aluminium foil to the underside of the lid.

Using a craft knife and some scissors, I split the aluminium along the slots to separate out the keys again. I cut a few strips of MDF to place under the lid, so that the keys separated from the screws below.

I drilled a couple of guide holes into the lid and base. I looped some thin wire around one of the holes, and used some sellotape to hold the wire in place. The other end of the wire was left protruding out of the side.

I then screwed the lid to the base. I removed the stylus. This left two wires sticking out: one from the stylus, and the other that was sandwiched to the underside of the aluminum foil. I joined the two ends together.

That way, when you press down a key, it creates a short in a similar way to the stylus. When you release the key, contact is broken.

It works pretty good, actually, even better than the stylus. I’d say.

Posted in Uncategorized | Leave a comment

Inside C++ is a Turing Incomplete language waiting to get out

OK, I lied. I’m just clickbaiting. It ain’t waiting for that. But I have something to say about the concept …

There’s an esolong (esoteric programming language) out there named something like “Froogle”. That’s not it’s name, but it’s something like that. If anyone can identify it’s actual name, then please comment. It has an interesting feature that you can do loops and conditionals in it (IIRC), but it is nevertheless Turing Incomplete. It has a companion language, named something like “Smoogle”, that adds on extra feature: jumps. This one extra feature makes it Turing Complete.

Someone observed that C++’s templates are Turing Complete. I joked that in order to find the answer to any problem one didn’t need to go through the labour of actually running a program; merely compiling it would suffice.

But here’s the interesting thing … C++ is accumulating a lot of features like constexpr which are accessible at compile time.

So you can do a lot of compiler checks. Aha, isn’t that interesting? It’s like Rust being able to do a lot of consistency checks, but with C++ not as powerful as Rust.

So idea here is to somehow have a split-level language: a part that is Turing incomplete, and a part that is complete. This peculiar lower-tier as-yet-to-be-determined language could speed up computation in the higher tier, and act as a correctness guarantee.

We can see contracts and stuff entering C++. The debate rages on as to whether late binding is a good idea or not. People like Alan Kay, and Lispers, are firmly in the camp of extreme late binding. C++ is firmly in the camp of Bondage And Discipline. What you get out of the latter is at least some guarantees of correctness. In fact, it’s pretty clear the direction that C++ wants to go in: it wants to be an engineering language, like Rust.

Can this idea be pushed further, and what form would it take, and how would it be implemented? So, my idea is that you could somehow specify what relationships can exist between objects, and the compiler could statically verify that these constraints hold.

My idea formed when I was looking at the clock settings for the Raspberry Pi Pico (great microcontroller with some good documentation). The Pico SDK is written in C, and it made me wonder what could happen if written in C++.

Here’s the specific problem I was thinking of: it’s a general problem in MCUs (microcontrollers) that you want to set the frequency of something, say a PWM frequency. What you must often do is to factor about that number into a prescaler and a count, such that prescaler*count = frequency.

Now, the problem is, you might not do it right, and say, compute a wrong count for the size of the register. That means that you mess up your frequency calculation, and the MCU won’t behave in the way you want it to.

Now, C++ has “limits”, which tell you the bounds on a number. Maybe, with some constexprs and some static setup, you could get C++ to statically assert the frequencies always make sense.

That’s just an example. The trick would be to come up with some language that could solve that kind of problem generically.

There’s an Indian professor at an American university that studies the expressiveness of programming languages. He’s fairly well-known, but alas, I don’t remember his name (once again, if you can supply his name, then please do). He is interested in making strict mathematical statements about what it means for a language to be more expressive than another.

I’m almost inverting his ideas: I want to know what a less expressive language can buy me,

Anyway, that’s just a daft idea I had late last night. Don’t be hating.

Posted in Uncategorized | Leave a comment

#RaspberryPi0 bare metal C++ (mostly working)

I’ve been able to get my Crunky “unikernel” to compile C++. It has stdlib working (string, vectors, etc), class initialisation, and so forth. The big sticking point is exceptions. You can throw exceptions, but it will cause a crash.

Linking libraries together is a bit of a dark art. You need to select a library and link everything in the right order. I’ve mostly used the newlib nano library. But I also link against a gnu stdlib, which seems to provide exceptions, but I’m wondering if I’ve linked against some kind of Linuxism.

So far I’ve assumed that I need something like newlib nano for bare-metal programming. Maybe the full newlib is what I’m after. Documentation seems a little sparse on how to enable it, though.

It’s not a pressing matter. So here is some example code:

#include <uart0.h>
#include <stdio.h>

#include <string>
#include <vector>

class Foo {
	public:
		Foo();
		~Foo();
		void hi();
	private:
		int meaning = 42;
};


Foo::Foo()
{
	puts("Foo created");
}

Foo::~Foo()
{
	puts("Foo being destroyed");
}

void Foo::hi()
{
	printf("foo says hi, and notes that the meaning of life is %d\n", meaning);
}


void test_foo()
{
	Foo foo;
	foo.hi();
}


void test_throw()
{
#if 0	 // causes crash.
	puts("test_throw:begin");
	try {
		throw 20;
		std::vector<int> vec;
		vec.at(2);
		puts("this is never printed");
	} catch(int e) {
		printf("Caught int exception\n");
	} catch (std::exception& e) {
		printf("Caught exception.\n");
	}
	puts("test_throw:exiting");
#endif
}


extern "C" void kernel_main(void)
{
	uart0_init_as_stdio();

	Foo foo();

	puts("C++ test 2");
	test_foo();
	test_throw();

	std::string str("my string");
	printf("std::string is %s\n", str.c_str());

	puts("I will now echo what you type");
	while (1) {
		char c = getchar();
		putchar(c);
		//if(c=='\r') uart_send('\n'); // prolly needs linefeed
	}
}

I’m quite chuffed with this, as it means that I can use C++ on bare metal (with a heavy caveat about exceptions).

You can find the code here.

Enjoy!

Posted in Uncategorized | Leave a comment

IG Holdings

A few days ago IG stated that it is having service difficulties due to an unprecedented high volume of trades and new accounts. Something to do with Gamestop and another company, I figure.

I have an IG account, and trade infrequently. So I haven’t noticed any problems.

Anyway, the point it, expect good results from IG when it next reports. I hold.

Posted in Uncategorized | Leave a comment