Author Archives: Allen Huffman

About Allen Huffman

Co-founder of Sub-Etha Software.

const-ant confusion in C.

Updates:

  • 2017-11-30 – Fixing description of MyStructure example. Thanks, Lost Wiz!
  • 2024-10-30 – Fixed some formatting.

Embedded Life

I currently make my living doing embedded C programming. I am not quite sure how to define what “embedded” programming is other than to say: you probably don’t have everything you expect.

You often program on systems without file systems, without gigabytes of RAM and without an operating system to do most of your work for you. For example, at my previous job one of my main platforms (a TI MSP430 processor) had only 10K of RAM and the program was limited to 40K of flash storage. At my current job, I work on several variations of ARM processors, with one configured to give me only 7K of RAM and 36K of program space.

These systems are much closer to an Arduino UNO, which has 32K of flash and 2K of RAM, than a desktop Windows or Linux machine.

Not all embedded systems are this tiny, of course. There are many embedded systems that run Linux, but once you have a full operating system and a file system, the definition of “embedded” seems to be used to just mean “smaller than Windows”.

But I digress…

Over the past six years, I’ve worked on code that was created and maintained by many different programmers before I worked on it. I have learned some cool tricks and also seen some very un-cool tricks (i.e., just wrong). I expect I will be leaving my own cool/un-cool bits of code for future programmers to find.

With that said, there is one item that keeps turning up repeatedly that many of us C programmers don’t seem to really understand because we keep misusing it. And by “we” I include myself.

“const”

There is a keyword in C called “const” which, according to Wikipedia, “indicates that the data is read only.” For example, suppose you wrote a function that accepts a string (actually, pointer to a bunch of characters) like this:

void PrintErrorMessage( char *message )
{
   fputs( "ERROR: ", stderr );
   fputs( message, stderr );
}

In this example, whatever string passed in will be displayed with “ERROR: ” prepended to it.

int main( int argc, char **argv )
{
   PrintErrorMessage("File Not Found");

   return EXIT_SUCCESS;
}

That would display a message to standard error output:

ERROR: File Not Found

But, there is nothing preventing the function from trying* to modify the string that was passed in.

* Key word is “trying”… If that string were embedded in the binary and it was running out of ROM or Flash, attempts to modify it would be rejected by the “hardware can’t do that” exception ;-)

void PrintErrorMessage( char *message )
{
   fputs( "ERROR: ", stderr );

   // Convert message to uppercase
   for (int i=0; i<strlen(message); i++)
   {
      message[i] = toupper(message[i]);
   }
   fputs( message, stderr );
}

The intent here would be to display the error message in uppercase, such as “ERROR: FILE NOT FOUND”. This would work if the string being passed in was modifiable, such as:

char message[80];

strcpy(message, "File Not Found");
PrintErrorMessage( message );

…but after returning from that call, the string would have been modified by the function and would now be “FILE NOT FOUND” in memory. This is fine, if that is theĀ intent of the function, but if you do not intend the string to be modified, you can take steps to prevent the function from being able to do it.

Only read this…

“const” will tell the compiler to not allow code to be built that modifies the variable. You see it used all the time by standard C library functions that take strings, such as puts(), strcpy(), etc.

int puts ( const char * str );

For puts() and similar functions, the use of const disallows modifying that string within the function. In the earlier example, we could make the passed-in string “read only” like this:

void PrintErrorMessage( const char *message )
{
   int i;
   fputs( "ERROR: ", stderr );

   // Convert message to uppercase
   for (int i=0; i<strlen(message); i++)
   {
      message[i] = toupper(message[i]);
   }

   fputs( message, stderr );
}

With that change made, the compiler now should issue warnings (or errors) on attempts to modify the “message” string inside the function:

error: assignment of read-only location '*(message + (sizetype)((unsigned int)i * 1u))'|

The moment the function tries to modify “message[i]” causes a problem, because “const” has told the compiler whatever is passed in should not be modified.

Because of the usefulness of this extra compile-time error checking, const is a good thing to use.

And many of us do.

Incorrectly.

There is a bit of confusion in how const works. In the above example, we pass in the pointer to some memory that contains a string. We do not want the memory that is being passed in to be modified, so we use “const char *message”. According to the “C Gibberish” website, that means:

declare message as pointer to const char

We might also want to prevent the pointer itself from being modified by using “const char const * message” … and that would be incorrect. That is not the proper syntax for “const”:

declare message as pointer to const const char

The confusion comes from const allowing two ways of doing the same thing. Did you know that:

const char

…is the same as:

char const

In C, the true syntax seems to be using “const” after the thing you are declaring, like “char is a constant” or “* is a constant”. But, at the start of that line, const can be used at the beginning to mean the same thing, and since we see that all the time, many of us seem to think that const describes what comes after it. Which it doesn’t.

To properly declare that the pointer and the data it points to should be read-only, it should be:

char const * const message;

C Gibberish agrees:

declare message as const pointer to const char

We need to learn this double “before or after is the same thing” use, or only use the “after” use and be consistent.

// declare message as const pointer to const char
const char * const message;

is the same as

// declare message as const pointer to const char
char const * const message;

My most recent encounter with this was in code at work that did something like this:

void Initialize(const MyStructure *config);

They must have intended this to mean “I’m passing in a constant MyStructure pointer which cannot be modified” but, in reality, what they were getting was:

declare config as pointer to const struct MyStructure

They were telling the compiler that the structure being pointed to was read-only and should not be modified. But the function’s purpose was to modify elements of that structure:

config->type = 10;
config->foo = 'a';

Because of this misuse of const, many compiler warnings were generated.

||=== Build: Debug in Const (compiler: GNU GCC Compiler) ===|
main.c||In function 'Initialize':|
main.c|16|error: assignment of member 'type' in read-only object|
main.c|17|error: assignment of member 'foo' in read-only object|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

The fix was to correct the prototype and function to do what was actually intended:

// declare config as const pointer to struct MyStructure
void Initialize(MyStructure * const config);

This now disallows the “config” pointer from being changed, but not the structure it points to. Thus, this would not work:

config++; // Increment config pointer.

…but the intended structure modifications would:

config->type = 10;
config->foo = 'a';

I’m sad to say I’ve been using “const” incorrectly as long as I can remember using “const.”

For a future article, I may dive in to some deep const-ant confusion I recently found myself in, and see if someone out there can tell me if I am finally doing it correctly or not.

Until then…

Happy Halloween in November!

A few side projects keep me busy during the year. One is doing things for local festivals (show guides, websites, newspaper ads, TV commercials, etc.) and the other is maintaining my haunted house website: www.dmhauntedhouses.com

During October, I visit with all the local haunted attractions to get information from that website. I do video interviews, create custom audio/video effects for them, and other projects. Over the years I have done quite a bit in this area, from building BASIC-Stamp based prop controllers to doing complex DMX lighting/audio show control programs.

For 2018, I am going to start documenting my projects, and making plans available for those who want to recreate them. I also plan on making items available pre-built for those who just want to use and not build.

More to come…

Happy birthday, computer revolution.

Today marks the 40th anniversary of the Radio Shack TRS-80 Model I computer. TRS stood for Tandy/Radio Shack, and the 80 came from the Z-80 processor it uses. The Model I came from Tandy’s belief there would be more than one model ;-)

When the TRS-80 came out in 1977, there were already many kit computers, and a few you could order that were assembled. But, none were widely available at thousands of retail locations across America. The TRS-80 became the first widely available home computer.

And they were made in Texas :-)

Radio Shack was soon outselling Apple, and was truly the number one name in little computers (as the slogan said). Keep in mind, back in the 80s there were more Radio Shacks than McDonalds. It was huge.

Many other firsts would come from Ft. Worth, such as the first IBM PC clone that was under $1000 (the Tandy 1000). It was a historic era in home computer.

But soon the market was flooded with other cheap home computer offerings from companies like Atari, Commodore, and Texas Instruments.

Happy birthday, TRS-80. :)

All quiet on the Western front…

Things have been very quiet here. I started a new job a few months ago and have been having a blast doing embedded C firmware programming for power-over-ethernet LED light control systems. I am currently working on the CoAP protocol, as mentioned previously.

I have a few articles for this site waiting for me to get back to them:

  • Tiny BBS – A new take on my 1983 *ALLRAM* BBS for the Radio Shack Color Computer. A few years ago, I had ported my old MIcrosoft BASIC BBS program to Arduino C. I decided to do a new version of the system using things I have learned over the past 34 years. I had worked up a proof-of-concept version earlier this year which had a substantially larger message base in the same memory. I hope to find time to return to this. I think it would be fun to take a CoCo and a $3 WiFi-to-serial adapter and put a micro BBS online ;-)
  • const-ant confusion in C – I have another article in the works that will delve in to the const keyword in C, based on how I’ve been mis-using it most of my programming career. I learned quite a bit about it at a recent job, since we had it defined in our coding style guide. But, many of us there were still using it incorrectly.

But meanwhile, I’ll be chugging away at my day job, working on my Iowa Adventureland amusement park website, and doing various side projects to earn extra income so I can save up for something really cool for my child’s birthday.

To be continued…

More CoAP musings…

Last week I implemented a simple version of CoAP protocol at work, going by the main specification:

https://tools.ietf.org/html/rfc7252

CoAP seems to be similar to how a web browser works with a web server: GET some content, POST something back.

A CoAP server could report back the status of various sensors, and they would be given names similar to a web page. Instead of featching a web page using HTTP protocol like:

http://www.subethasoftware.com/bikelights

…you would use the COAP protocol to reference some resource:

coap://127.0.0.1/motionsensor

You can GET, PUT, POST or DELETE, which I am told mimics things web developers are familiar with. Instead of passing around huge HTML text packets using TCP, CoAP sends a very tiny and compact bit of binary data using the smaller and faster UDP protocol.

CoAP is only a few years old, so many items that I needed to implement were not part of the main specification. I had to consult a second RFC document to learn about the “Observe” option:

https://tools.ietf.org/html/rfc7641

Observe is a mechanism that allows being notified when a resource changes. For instance, if you were monitoring a motion sensor, you might GET the /motionsensor resource, and specify the Observe option. CoAP should respond with the status of the motion sensor, and any time the status changes, send a message with the update.

Fun.

I was able to quickly put together a simple version that could receive and respond to CoAP messages — at least the ones that we’d be needing. However, there are still many features of CoAP I have yet to tackle.

One such features is outgoing confirmable messages. The challenge with those is that all the important information has to be retained somewhere so it can be re-transmitted if the receiver doesn’t receive :)

When I first began researching CoAP, I found several CoAP implementations for memory constrained devices like Arduino. Now that I know more about the protocol, I thought I’d revisit them and see how they approached things like Confirmable messages and Observe.

It turns out, many of the features I have been kludging together are just not supported at all by the simple CoAP implementations.

Here is one called microcoap:

https://github.com/1248/microcoap

With a few small changes, I was able to compile it up for a Windows PC using the GCC compiler. It easily allows creating a new endpoint function that is called when the CoAP message is received, with all important information parsed out and presented as elements in a C structure. All one needs to do is deal with the payload (passed along as a pointer to it, and the length) and generate a response packet.

It does not handle Observe or Confirmable messages, but it does have enough framework to quickly parse incoming CoAP messages, run some code, and send back a response. Like many I have looked at, this version also seems to be geared just for listening and responding. If you have a need for CoAP on that level, it’s a good place to start.

Once I get my work project done, I expect to attempt a similar project, just for fun, that will run on an Arduino with 2K of RAM.  (microcoap has 8K of buffers set aside on startup!)

More to come, maybe.

CoAP – Constrained Application Protocol

Has anyone out there done any work with CoAP?

https://tools.ietf.org/html/rfc7252

And the Observe (subscription) extension proposal:

https://tools.ietf.org/html/rfc7641

I am implementing it for my day job for an embedded system. I am doing it from scratch using just the RFC for reference.

I am thinking of doing another implementation (not using any work code, of course) for the Arduino. I’ve found a few attempts to implement it, often with many missing features or missing many needed features.

Anyone out there a CoAP expert?

Back from CoCoFEST! 2017

I have made it back from the 2017 26th annual “Last” Chicago CoCoFEST! It was a pretty spectacular year with many new hardware items being demonstrated, as well as new software projects. I will try to share some details and photos when I get caught up.

1985 unlicensed Dr. Who game for the CoCo

Updates:

  • 2024-01-01 – Added YouTube video of the Doctor Who logo/music demo.

In 1985, a new game was advertised byĀ Prickly-Pear Software for the Radio Shack TRS-80 Color Computer:

DR. WHO

Here is the ad found on page 68 of the the December 1985 issue, typos and all:

Dr. Who ad in the December 1985 Rainbow magazine.

As a kid who had watched Doctor Who on the local PBS station in Houston, Texas, I just had to have this game. I had just moved from Houston to the tiny town of Broaddus (population 225) and no longer could receive a PBS station, so this would be as much Doctor Who as I would get while living there.

I do not think I even had a disk drive of my own yet, since I recall ordering this on cassette.

In those days, us kids would go down to the post office and buy a money order and mail it to the company, then wait for them to mail back the software. This really helped build up anticipation.

Finally, the game arrived:

Dr. Who by Larry Lansberry, as sold by Prickly-Pear Software.

It came with a manual, which I have yet to locate. When I find it, I will scan it and upload it to the Color Computer Archive. Fortunately, it at least has some instructions:

Dr. Who instructions, page 1.
Dr. Who instructions, page 2.

And, the promise of many levels of difficulty:

Dr. Who difficulty levels.

I was a bit disappointed to find that the game was written in BASIC. It also included one machine language program called “CTRYROAD.BIN.” This was a multi-voice music file that played John Denver’s Country Roads hit from the 1970s. And it played it while displaying the instructions, so you had to sit there for several minutes until the song was complete.

After this, the game would present some side scrolling text explaining what keys did what. Thank goodness for the manual! The text went by pretty quick.

After several minutes of generating data for the game, you were presented with the main game screen:

Dr. Who main game screen.

And, you also had the map view:

Dr. Who map view.

There were also animated scenes that showed the TARDIS descending to the planet’s surface, but without the manual, I cannot remember how to even get to the planets.

But … the effect was less than impressive. It was a very disappointing purchase from a cosmetic and user-interface standpoint.

HOWEVER, the actual game was quite good. It reminded me of the Star Trek-style games where you moved around a galactic grid in search of starbases and Klingons.

I must have written Prickly-Pear Software because somehow I got in touch with the author, Larry Lansberry, and we exchanged some letters. I recently found some of these letters, so I need to re-read them and see what we discussed. I know he explained the music choice and why the animation style was done like it was.

I always thought this game would be fantastic with a facelift. Perhaps now that it has been unearthed, someone may consider doing an update/remake of it.

You can try it yourself in a CoCo 1/2 emulator. The disk image is available here:

http://www.colorcomputerarchive.com/coco/Disks/Games/Dr.%20Who%20(Prickly-Pear%20Software).zip

And, just for fun, an old Doctor Who music demo I wrote has also been posted:

http://www.colorcomputerarchive.com/coco/Disks/Demos/Dr.%20Who%20Demo%20(Allen%20Huffman).zip
Doctor Who music demo.
Video of the Doctor Who demo

Side Note: I don’t think Zigwald X. Malushi was a real person, and if he was, he had nothing to do with this demo. I used to see that name pop up on random pieces of software, often of the “questionable” nature. Since I was posting a copyrighted tune, I did not want to post it under my name so I used that one. I should find some of the other “Zigwald” programs and make a collection of them. I wonder how many used that name.

Enjoy!

Getting started with Roger Taylor’s “CoCo on a Chip” FPGA CoCo 3

NOTE: This is a work-in-progress. Check back for updates. I will note any revisions at the top of this article.

Updates:

  • 2017-03-19 – Fixed a typo (thanks, Roger), and minor clean up.

Cyclone CoCo – Roger Taylor’s FPGA CoCo on a Chip

In July 2015, Roger Taylor began the process of recreating a CoCo 3 system in an FPGA (field programmable gate array). Using a low-cost (less than $80) Terasic DE0-Nano development board and a custom I/O add-on board, he quickly got a virtual CoCo running. He has been continually improving the system and adding more features. His “CoCo on a Chip” Facebook group has documented this every step of the way.

Last year, I had acquired one of these DE0-Nano development boards and the RGB22VGA add-on board from Ed Snider. I was planning on using it to hook my old CoCo 3 up to a borrowed VGA monitor. But, at last year’s 25th annual CoCoFEST! near Chicago, Mark Marlette of Cloud-9 was selling his all-in-one version of this RGB to VGA adapter. I picked on of those up, and never used the DE0-Nano.

Roger recently sent me one of his add-on boards so I can finally put together my own FPGA CoCo. Let’s see how it goes…

Hardware Required

  1. Terasic DE0-Nano Development and Education Board. These list for $79 on the manufacturer’s website ($61 for academic purchasers). It comes with a retractable USB Mini cable, which will be used to program the FPGA.
  2. Roger Taylor’s Terasic DE0-Nano Upgrade Daughter Board. He sometimes has these available completely assembled for around $99 (via his e-Bay store). You can also just buy the bare boards and build one yourself.
  3. SD memory card. Currently, the project does not support SDHC cards, so you have to find an older, smaller capacity SD (SDSC) card like a 2GB. I picked up a Transcend 2GB card on Amazon for about $7.
  4. PS/2 Keyboard (and optional mouse). I have never owned anything that used PS/2, so I didn’t have an old keyboard to use. I found a cheap Logitech Classic Keyboard K100 on Amazon for $11.99.
  5. VGA Monitor. I have one I borrowed to use with my CoCo, but I think VGA ports can still be found on some modern monitors.
  6. USB Power Supply for the DE0-Nano. You can use the included USB Mini cable and use a USB power port, or use a similar USB charging cable with a Mini connector.
A cheap PS/2 keyboard, 2GB SD card, DE0-Nano and Roger’s add-on card.

About Roger’s Terasic DE0-Nano Upgrade Daughter Board

Roger’s add-on board has RAM, two PS/2 style ports, a 1/8″ audio output jack, and VGA port. There are header connectors for plugging in a module that handles the SD card, and ones for WiFi and Bluetooth. My unit has The SD card and WiFi installed. I will be ordering a Bluetooth module for wireless serial ports (they are very cheap).

The card has writing along the bottom indicating which direction it should be plugged up tot he DE0-Nano: “Faces DE0-Nano USB connector –>>”:

Writing on the board points the way to proper installation…

You can also tell orientation by the cutout in the board, which lines up with some small 2-pin connector on the DE0-Nano below:

Cutout in the board allows access to a connector below.

Software Needed

  • Roger recommends installing the Quartus II programming app. (Smaller than having to install the full Quartus II IDE).
  • You will also need to install the USB Blaster device driver, which will be found in the install directory of the programming app.
  • You also want the latest Cyclone CoCo firmware from his Facebook group. He calls it Cyclone CoCo, for reasons that will become obvious once you start using it :)

Installing

It seems the first step will be to install the Terasic software, and then hook the DE0-Nano up and load Roger’s firmware. The software is only available for Windows and Linux. Since I am a Mac user, I will either have to run it via virtualization (I use Parallels Desktop and Windows 10) or find a PC to use. I have several Raspberry Pis running Linux, so maybe that is an option as well.

After that, you will have to install a driver, and lastly you will be able to load Roger’s firmware on to the device and turn it in to an FPGA CoCo. Here are the steps I took:

Step 1: Install the free programming app.

Download it here:

https://www.altera.com/downloads/software/prog-software/121.html

I am using the Windows version, so my screen shots will be from that version.

Installing the Stand-Alone Quantus II Programmer from Altera.

This will make available a program called “Quartus II 12.1 Programmer” in the Altera 12.1 Build 177 folder.

NOTE: Your version number may be different if you are using later or earlier versions than I have. If you are setting up one of these, I’m sure you can figure that out.

Step 2: Install the USB driver.

When you plug in the DE0-Nano to the computer, Windows should prompt you for a driver. My Windows 10 did not, so I had to manually install it. If yours does, you can skip the next step and go straight to how to browse to the driver.

First, I had to open the Device Manager and find the USB-Blaster in the Other devices section:

Device Manager showing the USB section, missing the driver.

Double clicking on USB-Blaster brings up information about the device:

USB-Blaster needs a driver.

Select “Update Driver…” and then choose “Browse my computer for driver software“. You have to manually tell it where the driver will be found (inside the programmer install directory):

Select the second option so you can browse to where the driver is located.

On my system, I used the default install location and the driver was located here:

C:\altera\12.1\qprogrammer\drivers\usb-blaster\
Browse to the drivers directory inside of the programmer software directory.

Your directory names may be different, depending on what version of the software you install. Browser there, and then click Next:

The system should find the driver and install it.

Step 3: Program the DE0-Nano

Plug in the DE0-Nano to a USB port using the included cable, then launch the Quartus II 12.1 Programmer application.

Quartus II 32-bit Programmer showing No Hardware.

If your Hardware Setup box says “No Hardware”, click the Hardware Setup button and select “USB-Blaster“:

Select the USB-Blaster device.

After you close that windows, you can use File->Open to browse to and load the FPGA firmware image you downloaded from Roger’s Facebook page:

Load Roger’s firmware image.

When it is loaded, you will need to check off “Program/Configure” and (probably optional) “Verify” to enable the Start button:

Firmware loaded and ready to program.

Once those two buttons are checked, you can then click Start to begin programming. After a few moments, you should see “100% (Successful)” in the top right green box:

Programming in progress. It only takes a few moments.

Congratulations! You now have an FPGA CoCo!

Hello, FPGA CoCo!

After these steps, I plugged the device up to a VGA monitor and plugged in my PS/2 keyboard to the left port, and powered it up. It should instantly come to life with a familiar green screen, but if you have not prepared the special SD card for it yet, it will hang, trying to boot from that card.

You can hold down ESCape when you power up to bypass that, and find yourself at a nice virtual CoCo:

Hello, FPGA CoCo!

In the next part, I will figure out how to configure the SD card so I can actually load some software on it, and save any programs I create.

Until then … wow. This was easy! I can’t wait to see what all it can do. Thanks, Roger!