Hello STM8, nice to meet you!

With Atmel being bought by Microchip, the age-old flamewar of AVR vs PIC might just be over. Wait, that didn’t come out right. I don’t think that the AVR will die a quick death. Especially the ATmega328 is too prominent in the Arduino community. But I’m not so sure about the other chips’ future. Will Microchip tolerate in-house rivals? I would sorely miss the Tiny13 and Tiny85 if they were to be discontinued. They’re perfect for smaller tasks. And I don’t like the PIC. There, I said it. I like being able to program my AVRs under Linux. I like being able to use cheap, robust tools, not the unstable disaster called PICkit 3.

Hum. Maybe it’s time to look at other architectures. MSP430 comes to mind, but I’d rather stay with 5V components for now. Looking at the STM8 series, there are nice and cheap solutions that could replace the AVR for me. Let’s have a closer look.

The STM8S003F3P6 comes to mind. A kilobyte of RAM, 8 kB of Flash, 128 bytes of EEPROM, 16 GPIOs (14 if you want to connect an external oscillator), 5V tolerant, I2C, SPI and UART for about 0.51 Euros, very interesting. That’s cheaper than the Tiny13, with way better specs. And it’s an accumulator machine, just like my beloved 6502! The sad part about the STM8 is that there are no DIP variants, so goodbye breadboard friendliness. Ah well, there are adapter boards out there, and stlink clones are cheap, let’s go shopping!

… a few days pass …

They’re here! And ohmygodthatssmall! TSSOP20 chips are tiny little buggers, with a total length of 6.6 mm, a challenge to solder by hand. Tip: Use a bigger solder tip and drag a glob of solder across the (fluxed) pins. I used a 2mm chisel with 1mm solder at 320°C and didn’t have any problems. The result: A breadboard-friendly STM8!

TSSOP20

Now for the “Hello, World!” program: Let’s just flash a LED. The STM needs a 1µF capacitor on a special pin, then we add a LED/resistor combo on PA3 to ground. No need for a transistor, the STM8 is strong enough for a LED. Connect the stlink to VDD/GND, Reset and SWIM (the ST single wire debug pin), and we’re ready to go!

Looking at the datasheet, we find three memory-mapped registers to use if we just want to turn a pin into a push-pull output: ODR, DDR and CR1. Set a bit in DDR (data direction register?) just like on AVR chips, then set the same bit in CR1 (otherwise we’d get an open drain output). Setting the appropriate bit in ODR will pull the pin up. The ports start at address 0x5000, with 5 bytes for each port. Let’s whip up some code:

#include <stdint.h>

#define PA_ODR  (*(volatile uint8_t *)0x5000)
#define PA_DDR  (*(volatile uint8_t *)0x5002)
#define PA_CR1  (*(volatile uint8_t *)0x5003)

main() {
  uint16_t i;
  PA_DDR = 0x08; // PA3
  PA_CR1 = 0x08;

  while (1) {
    PA_ODR ^= 0x08;
    for (i=0; i<60000; i++) {
    }
  }
}

The Small Device C Compiler (sdcc) supports a nice selection of architectures starting from the venerable 8051, and including STM8. Let’s compile our little test program:

sdcc -mstm8 one.c

SDCC is nice enough to create an Intel Hex file (.ihx) that we can burn to the chip with the stm8flash utility:

stm8flash -c stlinkv2 -p stm8s003f3 -w one.ihx

Seconds later, the LED starts blinking. Success! I’m not changing the clock settings here, which means that the chip uses its internal 16 MHz clock source with a divider of 8, resulting in a system clock frequency of 2 MHz. Good enough for a first test.

Whee

Now for that UART. Gonna play around with my new toy a little more…

Advertisements

Happy new year!

It was an interesting year. Not that I wrote a lot about it. No moments of sudden enlightenment for me, so there was nothing I deemed worthy of a blog post. But behind the curtain, a lot has happened. Both at work and at home. Basically I moved a lot closer towards hardware and firmware development.

It all started with a small App for Android phones that allows users to control an industrial device via Bluetooth. After “my student” became an official colleague, we refined our understanding of the Bluetooth chip used, and while he tried to get it working with BT LE too, I made the App… do more than before. How interesting. But. We had thought, hey, BT 4.0 sounds like a better version of BT 2.0, so it should be no problem to get this working with… other phones… that don’t use Android and don’t support BT 2.0… so let’s try this. Well, BT 2.0 and 4.0 are more than completely different, so no cigar here. Damn. BT LE is a major PITA. So we scrapped that plan.

Until management wanted to try something different: What about a Wifi hotspot instead of Bluetooth? We could have a small web server running on our target device, and any smart phone with a browser could connect and control the device! (Which is exactly the idea we scrapped two years before, because Bluetooth is oh-so-much-cooler and whatnot.) So we were asked to cobble together a proof of concept. And this is where it gets interesting.

Having a few Arduinos lying around, we looked for Wifi chips that can create an AP with WPA2 encryption. We quickly settled on the “maker” scene’s (then) new darling, the ESP8266, and ordered a few of them. Connecting them to the Arduino was a snap, writing a small web server a side note. We had the thing up and running in no time.

Then we became aware that the ESP has a larger uC than the Arduino itself, and it can be programmed directly, so why add more stuff than necessary? Our little hacking lab had already grown in size and complexity, and now we were writing firmware for the ESP. To cut the long story a little shorter, there were “voices” inside the company regarding the ESP8266, about it not being “professional”, and the uncertainty of its long-term availability. Whatever, at that price point we might just as well buy a few hundreds of thousands of them and let them rot in storage in case we need them, right? Wrong. We need another solution, from a more “professional” source.

Hint: If someone says “That’s not professional”, and not much else, it means “I don’t like this, but I’ve run out of actual arguments”. But whatever.

So we set out to find a new chip again, our little zoo of prototypes and POCs having grown to an impressive size already, with a few LAN connected devices on the side. We’ve all but stopped using stock Arduinos and clones and moved to designing our own PCBs. At home, I built temperature and humidity sensors and whatnot based on the ESP, and wired the house with them — so many possibilities! Having discovered banggood and drooling over the digital scope we use at work, my private little tinkerer lab grew as well. Hell, for just 20 Euros you can buy a starter kit with an Arduino clone, breadboard, jumper wires, LEDs, and the usual “chicken feed” (resistors, capacitors etc.)! Introduce your wife and kids to the world of micro controllers for the price of a steak at a halfway passable restaurant — what a time to be alive!

At work, we experimented with a few chips and finally settled on one of them. In 2016 we will make this little dude simulate the Bluetooth chip we were using up to now, so we can just plug it into our devices without any changes to the firmware. By now our reputation in the company is that of “the guys that make stuff work, fast”. Nice. Even if our POCs and prototypes are nowhere ready to be sold, we can show management what is possible. Get fantasy flowing. Make new ideas happen.

A good year.

Let’s see what 2016 has in store for us.

Progress

So I jumped into the deep end and tried the update to Windows 10. Not before backing up my entire /dev/sda drive, of course. A short trip to the BIOS to hide my Linux HD, insert the DVD burned before, and here we go!

So it’s a quick thing, at least it feels faster than installing Windows 98 or so. Answer some questions, and… what’s that? Ah, so I’m installing a German Windows 10 over an English Windows 7, so… I can’t keep my apps and settings? What the?!? Since when does the GUI language determine the future of my stuff? Ah whatever, I don’t use apps on the PC, and my settings are going to be all over the place anyway. Do what you must. Now wait, reboot, wait, reboot…

After playing a few games with the kids, I came back to a Windows 10 prompt! Whoa, talk abot painless. Log in… wait… wait a little more… ah, question time again. Let’s tell the system to disable all the spying stuff and hope that it adheres to my wishes. No, I’d like to choose my default photo viewer myself. But… why can’t I choose right here? Whatever. Desktop! Dark, smokey, looks clean, nice. My few desktop icons suddenly take up lots of space. The SSD LED is flashing like crazy. Looking around… no swiping, no stuff suddenly appearing at the screen sides like on Windows 8, no full screen app menu. I like! There’s a “messages” bar with a little button to make the lower row of buttons disappear, how cute. Completely pointless, but cute. Whatever. The SSD has stopped flashing.

Ah, the start menu. Lots of crap apps, unpin, unpin, unpin… done. Now to create the start menu I want, let’s add Netbeans, IntelliJ, Visual Studio, LibreOffice… just… where are they? Not in the start menu at least. No biggie, Explorer still comes up with Win-E. Go to C, program files… What. The. Eff. Nothing there. All my programs are gone. So the “apps” I couldn’t keep actually were… my programs? I have to install everything again, just because the GUI language is different? F*ck that! Could have just done a clean install instead of an upgrade, but then the key wouldn’t have been updated to Win10. Clean install now? Nope, at this point I’m going to look around first, and if I like what I see, I’ll do a clean install. Otherwise, it’s back to Win7.

Fooling around a little, I try some of the apps, but it seems like the only things that work without logging into a Microsoft account are the calculator and the weather app. Meh.

Start the new browser, hate the new title bars, it’s hard to tell the active window from an inactive one. Let’s change that first. Right click, appearance… change design… how do I change the active-window-title-bar-color? I could do that since Windows 95 without any problem, what’s this now? Google for the rescue. Ah, no network, card driver doesn’t work anymore. Um… Wifi stick, install driver, enter network. Download NIC driver, install, reboot, doesn’t work. Settle with Wifi for now. Google around for help with window color settings, find stuff dealing with Registry settings and design files. Helloooooooo, it’s 2015, and the newest Windows can’t do something we could do 20 years ago? Why? Couldn’t be that it took too much space on the DVD image, eh? Too complicated for people to use? Linux distros used to be ridiculed because it was oh so hard to edit some config files without a GUI, and now that there’s a GUI for everything, Windows goes back in time to manual Registry and file editing? No comment. At least not a printable one.

The last straw: Sound card stopped working too, driver is installed but “there is a problem”. Knowing what to expect, I try the automatic troubleshooter, not that it ever worked before, and sure, it doesn’t fail my expectations this time, either. Meh, it’s not like “Windows” and “just works” were ever said in the same sentence without a chuckle. Download new driver manually, install, reboot. No sound, there’s a problem.

Flip a few tables, throw a few chairs around, reboot, un-hide Linux drive, boot into Linux, hdimage to the rescue. 20 minutes later, I have my trusty Windows 7 back, and a few new experiences to share.

My verdict after a few hours of cursing: Win10 may be better than Win8 or Win8.1, but it’s not as good as Win7.

Just like Win7 was better than Vista, but worse than WinXP. Continue with ME and 2000.

It’s like Windows is going two steps backwards, then a single step forward, and somehow that feels like progress. Too much stuff that suddenly doesn’t work anymore. Standard run-of-the-mill network card, standard sound card, both stop working, Windows 10 drivers don’t work, there’s a problem. Visual settings are inaccessible without manual fooling around, lots of standard apps that don’t work without a MS account, the cloud folder sync thing getting on my nerves, stopped using that crap long ago after it ate some of my files, and so on.

Looks like Windows 7 is going to be the new Windows XP. The one companies keep using, because it works well enough, and doesn’t cause too much trouble with nothing really new to show for it. Win10 has a better kernel then Win7? Didn’t notice. What I did notice was lots of privacy stuff I had to disable to keep my figurative bathroom door closed, too much hassle with doing simple stuff that should be simple, and device drivers not working, because “there is a problem”.

So at home, it’s back to Win7 for me. At work, we don’t have any plans of switching, but I’ll try to move a little more in the direction of platform independent code in the future. Just to be sure.

Could Windows 10 be the best thing that ever happened to Linux?

Defending Pascal

Yup, it’s one of those posts again. Somehow I just can’t stop advocating programming languages that are, let’s say, underrepresented in today’s professional environment. This time, it’s Pascal (cue melodramatic shuddering in the audience). No, not the Pascal you’ve learnt at school, but modern dialects such as the ones implemented in FreePascal.

It’s an interesting language. Simple yet powerful. A basic comparison with C makes it look like just the same thing, just with different syntax and names. All the usual suspects are there: Basic data types, if/then/else, loops (for, while, repeat/until), pointers, arrays, structures (records). Just that you use a different assignment operator and “begin”/”end” instead of curlies. Then you compile to native code, use a debugger, a profiler and whatnot to tune your program. Same old, eh?

But there are bigger differences, of course (why else would I bother writing about it?). Strings, for example. You get a full Unicode string datatype, with reference counting so you don’t have to take care of releasing memory yourself. Somewhat like C++ strings, but with readable error messages if you screw up. And Pascal’s unit concept is so much better than C/C++ header files. One logical block of code, one file. No screwing around with pragmas and header protection. Files are much more readable.

The screaming I hear in the background must be the C guys calling Pascal an abomination. Sure, you have to do more typing. Sure, variables have to be declared at the beginning of a procedure instead of inline at the site of first use. The horror. Heads up: Making your procedures small enough for that not to matter is good code style anyway. Oh, and typing “begin” and “end” is sooooo much more work than pressing two keys. But guess what: Once you write a slightly longer piece of code, this just stops being relevant. It’s more the hassle of using a syntax you’re not accustomed to than a real problem. Source code is read way more often than written anyway. Man up and learn more than one programming language.

OK, so we have nice Unicode strings and a better code unit concept. What else do we get? Damn fast compilation. Classes with all the standard OO style goodies. Sure, it’s not really object oriented, but neither are C++, Java and C#. Real OOP in the original sense is something only provided by Smalltalk and Common Lisp anyway. And Erlang, with some artistic freedom. But FreePascal at least provides classes with virtual methods, interfaces, generics, RAII (!) and the freedom to decide when to use OOP and when to just stick to classic structured programming. No more Java/C# style “everything has to be inside a class hurr durr”. I like.

And the kicker: Lazarus. A free Delphi like environment, a giant standard library, great tools and portability between the three big ones (Windows, Linux, Mac OS). What’s not to like?

Yeah, what do we miss? A real standard, for one. As with Perl (and many other languages), the main implementation is the standard. Portability is not that great, either; you can’t just run your code on a microcontroller with FreePascal the way you can with the dozens of C compilers. But to be fair, when I look at the microcontroller C compilers of today, with all their deviations from the standard, the portability issues, all the bugs still present in 2014, no matter that the compiler still only supports a (large) subset of C89… argh. There is not a single compiler I’m really, truly happy with. Still, C is omnipresent, FreePascal is not.

But don’t think C and C++ are the only languages that translate to assembly in a more or less straightforward way. Hell, with the FreeBasic compiler, even Basic has evolved into something to be taken seriously now.

Shudder.

The year of Windows 2000 on the desktop?

Every now and then, I am forced to fire up an old virtual machine I keep lying around. It’s a Windows 2000 installation, with some of the tools of days gone by, and lots of software that doesn’t run anymore on modern systems. It offers better compatibility than Wine or Dosbox, so I use it whenever I have to break out into Windows land on my Linux boxen. I like having to boot up that VM.

And boy am I ever so glad that I bought that full Windows license back then, instead of just using the pre-installed one. From my point of view, Windows 2000 was — and, with all the service packs installed, still is — the perfect desktop operating system. That little VM takes up as much as 10 GB on my drive, including multiple development environments, office software, games and whatnot. Still less than a default Windows 7 installation without any applications. Windows 2000 runs happily on as little as 512 MB of virtual RAM, without any swapping. Applications start up fast, no lag, no waiting for some pretty animations to finish. Double-click on an icon, and the program is just there, waiting for input.

Granted, my software selection doesn’t exactly classify as usual. The programs I run are mostly old or non-standard. So what? Software doesn’t rust. Delphi 7 is just as usable as it was back then. Picture Publisher 8, an image manipulation program from the late 90s, still has some features I can’t find in modern software, barring the real big (as in expensive) ones. Ruby layer, anyone? Or have a look at SoftMaker Office, an inexpensive, nifty little piece of code that opens my Word and Excel documents way better than, say, LibreOffice, and it’s small and fast. And it looks like Office 2000 with nicer icons, doesn’t contain Clippy, and has a more logical (to me) menu structure, and very good support for the newer file formats. Win-win-win. And, like the others, it works well, stable, and fast. And all this software doesn’t need online activation to work. Don’t have an internet connection? No problem, everything still works. It’s not free? So what, I don’t mind paying for good software.

Now compare that to current standard software: The Office 2010 installation I’m forced to use at work, for example. I still can’t get over the feeling that lots of features were removed from the newer MS Office versions. Need an example? Making a chart used to be so simple. Now? I still haven’t figured out how to use the first column of a selection as the X axis values. Lots of manual adjusting, sure, it works. But it used to be as simple as clicking on a checkbox in a wizard, and you were done. SoftMaker and LibreOffice can do this, no problem at all.

And what has happened to help systems in general? You know, there used to be a time where you pressed F1 and in a split second there was a new window containing lots of text that explained how to use the feature you’re stuck with. There used to be printed manuals going into detail, sometimes even explaining the reason behind some design decisions. There were examples or even step-by-step tutorials. Nowadays, if the F1 key works at all, you see a “please wait…” message indicating that some HTML files are being downloaded from some server. If you’re as lucky as me, the files have been moved somewhere else by now, and you have to do a manual search at the newer location to find some cobbled-together, preliminary stuff of little actual help.

Maybe it’s me. Maybe I’m on the verge of becoming a grumpy old guy sitting on his front porch telling kids to get off his lawn. But I can’t shake this feeling that, for all the technological advancements, lots of things used to be better 15 years ago. I’m not against newer technologies, as long as they make things better. And that’s where a lot goes wrong today.

Is an online help system really better than offline help? Oh yeah, you always get the newest information, cool. But. If I install a C++ compiler I expect the documentation to match the libraries installed. If my libraries don’t change, their documentation shouldn’t need to change that fast, either. Give me an update system to keep things current, sure. But don’t make me depend on an always-on uplink. This is one of the many things that Linux distros get right. The desktop not crashing and breaking things all the time is one of the many things they don’t.

So far the system of my dreams would be Windows 2000, but still supported with security updates so I can hook it up to the net, with a fast, responsive, stable web browser, a usable, fast, stable office suite, development environment, and everything with a complete offline help system that’s actually helpful. Something like what we had about 10-15 years ago, just on a modern PC.

One can dream. Or use a VM.

How we reduced our codebase by n kloc by switching programming languages

You’ve seen them before. Those stories of companies that switched from their early design language to some other, did a complete re-write of their money maker, and ended up with a much smaller code base. And as with scientific studies, especially in the field of nutrition, you can find an example for every combination that shows the new approach is “better”. So Rust delivers shorter code than Python, Go leads to a significant reduction in code size compared to Ruby and so on. Oh, and the new code is always faster, more stable and easier to maintain.

My problem with that? Stay with one language and just re-write your code. The results will be (mostly) the same.

The code replaced in those stories usually “grew in an organic fashion”, that is, it was cobbled together haphazardly. It works? Ship it! No time for refactorings. No time for getting rid of that ugly-yet-working-timer or the Thread.Sleep() loop. If you take such a piece of code and just clean it up, it will shrink and become more robust just by you taking the time to plan a little more ahead. You have a better understanding of the requirements. You have all those nagging thoughts still edged into your brain: If only I could do this part in that way. Would be oh so much better, but I can’t, because of that fubar over there that would have to be fixed first. And so on. By writing your code anew, you can address all those little points with the bosses’ blessings instead of slipping in a tiny refactoring under the radar now and then.

The verdict? I reduced a codebase of 250 kloc down to 69 kloc by staying in C#. From 79 kloc in Java down to 23 kloc, still Java. The language used does play a part in this, and the C# base, for example, might have come down to 10 kloc of Lisp or Python. But always keep in mind that there is a difference between essential and accidental complexity.

Choosing the right language for the job

Quick: Which programming language would you use for a big project?

There is no single answer to that question without a few more specifics. The “right” language to use depends heavily on the type of problem at hand. What about a thought experiment?

Here is a list of all programming languages that I know at least a little:

Ada, Awk, Assembler, BASIC, C, C++, C#, COMAL, Common Lisp, D, Delphi, Erlang, Factor, Forth, Go, Haskell, Java, Javascript, Lua, OCaml, Turbo Pascal, Perl, PHP, Python, Scheme, Shell, Tcl, Visual Basic Classic, Visual Basic .NET

Let’s skip the oldies that don’t run on modern hardware or operating systems anymore. Say goodbye to BASIC, COMAL, Turbo Pascal and Visual Basic Classic.

Now let’s fantasize about a program I want to write. It should be portable across the most important platforms of today, it shouldn’t require a big setup step. Just a single file to download and execute, that’d be fine. And it should be as cheap as possible, as I don’t want to spend lots of money on a personal side project just yet. Those requirements aren’t that weird for a non-web app. Let’s go over them in detail:

I want my programs to deploy as a self-contained executable: Lots of scripting languages and VM based systems can’t do this, so we can strike out Awk, C#, Erlang, Java, Javascript, Lua, Perl, PHP, Python, Shell and Visual Basic .NET. Ouch. As a heavy C# user at work, that’s a language I’ll miss dearly. But single file executables still need the Framework installed for the time being, so it’s a no-go.

I want my sources to be platform independent, so we strike out Assembler. For developing larger applications I want either a sound type system with templates or generics, XOR duck typing: Goodbye, C, Forth and Go.

For my home-brewn projects I want free development tools: Delphi has to go, too. D and Lazarus sadly still don’t make the stability cut. Ada and C++ drop out because I happen to like Garbage Collection as much as I dislike typing my fingers off just to sum up a list of numbers. And the single-file packagers for Java are a little steep for my taste.

So what we end up with is a small but interesting list:

  • Common Lisp
  • Factor
  • Haskell
  • OCaml
  • Scheme
  • Tcl

Look Ma, no C like syntax! Instead we have two Lisps, two full-blown functional languages, albeit differing in purity, a concatenative language and my beloved quirky little Tcl. Which would be my weapon of choice, unless we need max performance. Strange that a language many programmers have never heard of would be my top choice…

Tcl is great for quick GUI projects that don’t have to be as fast as possible. With a Tclkit you can pack your application code, libraries and configuration files, even media files, into a single executable. It’s great for quick-and-dirty programming, but when it comes to performance, it sucks.

Now if we change our requirements a little, the list would look entirely different. If we don’t mind a big installer, and our target platform is Windows, but we need SPEED!, suddenly C# is the tool to use, maybe with a C DLL thrown in. Or use Java with a nice installer. Or could we…? Yup, just use that C DLL that encapsulates the performance-critical stuff in a Tcl program, and you’re good.

As long as your program doesn’t get too big, that is. Now we face a different problem: While C# is a mostly statically typed language, Tcl is not. Static type systems are great if you work together with other programmers in a big team, as you can use tools like ReSharper and FxCop to look for pitfalls. No chance here in a Tcl source. Same thing with Lisps or Factor: Formidable tools for a single hacker, but a disaster if you have a team of programmers with differing skill sets working on a big piece of code. Suddenly interfaces between chunks of your application and a whole lot of tests become paramount.

On the other hand, interfaces and tests should be what drives your development efforts anyway. Divide your application into separate modules, define sound interfaces, and every team member picks a module to hack on. Why should the programming language used matter here? You should use the same big test suite in a C# project that you would have in a Tcl source. What is it that makes us think that dynamic typing is bad for big teams? The practice of factoring a problem into smaller parts was described oh so well in Thinking Forth, a masterpiece of programming literature that few people read as it seems to be about Forth only. Hint: It’s not. Only on the surface. Factoring is all the same, in every language you’ll ever use. But here it is, described in terms of Forth, a language that considers the difference between a single byte and a “cell” (read: Machine word) a type system. Seems like static typing isn’t that important for big teams after all.

On the other hand again, I LOVE ReSharper. Seriously. Nothing beats that feeling of being on top of it when you open a file of code and see the most common issues in it highlighted within a second. No chance here in a dynamic language like Tcl.

I’ll need to think topic about this a little more.