Category Archives: Arduino

Years ago, I cloned the Arduino IDE “bit” macros for use in a GCC program (for testing generic Arduino code on a different system). I dug them out recently for a work project, and decided to share them here. Maybe they will be useful to someone else. (And apologies for WordPress clobbering the ampersand and turning it to HTML. When I edit and view it, it looks good, then WordPress “helps” — even though I am using a Syntax Highlighter plugin specifically for code examples.)

Things have been real busy lately at Sub-Etha Galactic Headquarters… Here are some updates:

CoCoWiFi

The CoCoWiFi has been tested on the bitbanger serial port and things seem to work just fine.

On the RS-232 Pak, a modification was needed to make the pak actually receive data (forcing the carrier detect signal). This has been done by an easy soldering mod to the DB9 connector. The downside is that it does not provide true CD, and there is no support for hardware flow control or DTR to drop calls. For just a bit more, there are RS232-to-TTL adapters that provide hardware flow control, which might help for doing high speed transfers. However, the lack of carrier detect and DTR means they won’t work with a BBS like they should

Thanks to David Chesek, new RS232-to-TTL adapters were located that include all the signals. These would be the best choice for running with an RS-232 Pak. I have two different types of adapters, but have only done some initial testing. I was unsuccessful getting the first adapter to work. I plan to test the second version this week.

I hope to have a hardware announcement to make before the CoCoFEST!

SirSound

I learned much while working on CoCoWiFi, so I returned to work on the previously “announced” SirSound project. I got everything wired up properly and was able to write a BASIC program to make it play tones. I also worked with John Strong and migrated the prototype over to an Arduino Nano (matching the original Arduino sound player board he sent me last year).

The next phases is to figure out the various modes that sound module will run in. I have proposed:

Direct. This mode just passes bytes to the sound chip, the same way you might do with a POKE command if it was a memory-mapped chip. BASIC is very slow at ANDing and ORing bits to make the messages, which is how my test program works, but this could be heavily optimized. This mode is mostly here to allow someone to port over code that was written for one of the other platforms that use an on-board SN76489 sound chip, though some of the bit-blasting players would probably not work as well over slow serial.

PLAY. This is the BASIC mode, that will simulate the PLAY command. You will be able to send a string of notes to SirSound and play them just as easy as in EXTENDED COLOR BASIC. There are a few things that have to be adapted, like support for the multiple channels of audio, and sub-strings. Last year, it was suggested to look at the MSX computer’s PLAY command for examples of how Microsoft did this very thing. I may follow that syntax. MSX also ads a PLAY() function that can tell is background audio is in progress, and we will be able to achieve the same results using the Printer Read/CD signal on the bitbanger port. I plan to also add some sequencing extensions so repeating music loops don’t have to be sent over and over again.

Optimized. This mode would be for assembly programs, and would pack data into 8-bit values rather than longer ASCII strings.

Interactive. I am planning on having a shell/command-line interface (CLI) available which could be accessed. It would be used for testing the device without needing to write a BASIC program.

Now working without the crystal. This is using a Teensy and one of the pins to generate a 4mhz signal. I will post a video in coming days, hopefully, as soon as I have some CoCo BASIC code talking to it.

The green and black wires running off of it wold go to a headphone jack that the cassette cable could plug in to so you could feed Sound back to the CoCo without needing to use an external speaker. AUDIO ON!

NEW “PRODUCT” ANNOUNCEMENT

Sir Sound is a solid-state multi-voice audio synthesizer that operates over a serial transport mechanism**. It provides arcade-quality*** sound with up to three independent tonal voices plus one white noise channel all in an external module that doesn’t require voiding your warranty to install. In fact, you won’t even need tools!

Pricing is to be announced but hopefully it will be around $50. Or maybe $30. Or cheaper. Or less if you build it yourself. Heck, we’ll probably just make kit versions available since we don’t really like to solder.

Sir Sound Configurations

Turnkey – This is a “plug and go” version where you just plug it in and go. No special drivers are needed, as they are already built in to both BASIC and OS-9.****

BYOE – The bring-your-own-everything edition is shipped as a set of simple instructions containing a parts list and how to run wires between the parts.

Custom – Also planned to be available are various custom configurations, like what color of case it comes in.

Pricing

We estimate the thing is gonna cost us, like, ten or so bucks to make using off-the-shelf parts ordered in small quantities from China. But, to make it a product, we really should have an integrated circuit board and a case made, which will run the costs up dramatically. Rest assured, we’ll pass those unsavings along to you!

Availability

The first prototype is in the process of being tested. Quit rushing us. We’ll let you know when it’s done.

Specs

SN76849 sound chip hooked to an Arduino Nano on a neat 3-D printed platform from StrongWare.

You kinda have to use some micro-controller since the sound chip turns on and starts making sound. Something has to issue the “shut up” instruction to it. If you just had hardware to translate a serial byte in to the command, and made the CoCo do all the work, the CoCo would have to load and run a program to shut the thing up every time you powered up. Fortunately, a custom-built Arduino that handles this can be done for like $5. There are cheaper PIC chips that could do it for less.

Then, you add a MAX232 type chip that goes from the TTL signal levels of the Arduino to RS232 signal levels, or using one of these $3 (or less) boards that’s already wired:

A small program on the Arduino will monitor the serial port for bytes and then relay them to the sound chip.

By doing some POKEs in BASIC to set the baud rate, you could make music by doing things like this:

REM PLAY MIDDLE C
PRINT #-2,CHR$(&H8E);CHR$(&H1D);CHR$(&H90);
FOR A=1 TO 1000:NEXT A
REM VOLUME OFF
PRINT #-2,CHR$(&H9F);

The notes always play, so you shut them off by setting volume off. There are different channel values for each of the four channels.

I envision having a “raw” mode where the device just translates the bytes from serial to the sound chip, and a “smart” mode where you could use an API and just send note values (like 1-88 of a piano keyboard, or MIDI note values).

…or whatever. You could sequence them together, like MIDI sequencers do, and have complex patterns that could play in the background while the program does other things.

There are lots of possibilities. We could even see about using the Carrier Detect line as a way to tell if the sound card was still playing something (rather than needing routines to read data back from the device, which would be doable but not from BASIC without assembly language code).

…and many more. I am just naming the machines and games I have heard of or seen/played.

Side Note: The Wikipedia entry also claims the Sega Genesis used one, but it had far fancier sound. A quick search shows the Genesis did not use this chip, so other systems may also be incorrect. Ah, Wikipedia…)

This chip is able to produce three tones and one white noise at a time, which sounds an awful lot like the audio capabilities of my first computer, the VIC-20.

The chip has none of the fancy synthesizer features found in other chips, such as the famous Commodore 64 SID chip. The only thing you can do is adjust the volume level of each channel of sound. Clever software uses this to produce bell sounds and other effects. (If Congo Bongo is really using this chip, it’s doing some fancy things to make those bongo sounds!)

Thanks to StrongWare‘s John Strong, I now have one of these chips to experiment with. It is wired up to an Arduino Nano clone. (NOTE: I had issues getting this clone recognized on my Mac, due to it using a different serial chip. I found the solution, and wrote about it earlier this week.)

SN76849 sound chip hooked to an Arduino Nano on a neat 3-D printed platform from StrongWare.

John pointed me to this short tutorial on how to use the chip:

http://danceswithferrets.org/geekblog/?p=93

Using sample code there, I was able to get the device making tones, and then expanded it to play a sequence of tones to make a tune.

The next day I added more code so it could do a multitrack sequence.

I thought it might be fun to share what I have learned the first two days of playing with the device, and share the code I have come up with.

I will do a full article on the chip and how it works (summarizing some overly complex explanations I have been reading), but until then, here is my sample project:

https://github.com/allenhuffman/MusicSequencerTest

It contains routines to poke bytes to the SN76489, plus a work-in-progress multitrack music sequence that currently plays the 2-voice intro music to Pac-Man :)

I’ve been fixing up the comments and squashing some bugs, so check back for the latest. I still have to add real/better support for the “noise” channel, but it works right now for playing simple tunes.

John Strong of StrongWare sent me an Arduino Nano to experiment with, and I was puzzled when it would not appear as a Port in the Arduino IDE. All I could select was “dev/cu.Bluetooth-Incoming-Port”.

I never had to install special drivers for Arduino on Mac before (but do on a PC) but I did some searching and decided to try the FTDI drivers (most recent release from 2015). No luck.

I then decided to try my UNO. I couldn’t find it, and had to open a brand new one up. It was also not recognized.

After some searching, I found out that many clone Arduino are using a different USB-to-Serial chip, and need special drivers. The “official” ones (from a Chinese website!) cause a kernel panic due to a bug in the current release.

I found this:

https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

These drivers work and I now can use this clone Arduino Nano:

Arduino Nano visible using replacement CH serial drivers.

I hope this helps someone else not waste an hour like I had to tonight to find this ;-)

2016/02/29 – Per a comment by James, I corrected my statement that sizeof() is a macro. It is not. It is a keyword. My bad.

In C, the sizeof() macro can be used to determine the size of a variable type or structure. For instance, if you need to know the size of an “int” on your system, you can use sizeof(int). If you have a variable like “int i;” or “long i;”, you can also use sizeof(i).

Note: sizeof() is not a library function. It is a macro C keyword that is handled by the C preprocessor during compile time. It will be replaced with the number representing the size the same way a #define replaces the define in the source code. At least, I think that’s what it does.

You should avoid making any assumptions about the size of data types beyond what the C standard tells you. For example, an “int” should be “at least 16-bit”. Thus, even a PC compiler could have chosen to make an “int” be 16-bits instead of 32.

A better way to use data types was added in the C99 specification, where you can include stdint.h and then request specific types of variables:

uint8_t unsignedByte;
uint16_t unsignedWord;
int32_t signed32bit;

But I digress.

The point of this article was to mention that you can also use sizeof() on strings IF they are known to the compiler at compile time. You can, of course, get the size of a pointer:

char *ptr;
printf("sizeof(ptr) is %dn", sizeof(ptr));

Depending on the size of a pointer on your system (16-bits on the Arduino, 32 on the PC), you will get back 2 or 4 (or 8 if it’s a 64-bit pointer, I suppose).

And the pointer is still the same size regardless of what it points to. You still get the same size even if you had something like this:

Those strings would be used elsewhere, and the length needed to be known by some write()-type function. Counting bytes in a quotes string and keeping that number updated sounds like work, so instead they could have used the sizeof() macro. Since it returns the size of the array (including the NIL zero byte at the end), they’d need to subtract one like this:

At compile time, the size of the character array is known, and the compiler substitutes that length where the “sizeof()” macro is. If the string is changed, that value also changes (at compile time).

Of course, since we are using NIL terminated strings, you could also just use the strlen() function. But, that is more for strings of unknown length, and it runs code that counts every character until the NIL zero, which is wasted CPU use and code space if you don’t actually need to do that.

My optimization tip for today is: If you are using hard coded constant strings, and you need to know the size of them, declare them as C arrays (not a pointer to the string) and use the sizeof() macro as a constant. Use strlen() only for times when the compiler cannot know the size of the character array (dynamic strings or things being passed in to a function from the outside).

Speaking of that … as long as the compiler can “see” where the array is declared, sizeof() will work. But if you had something like this:

…that will not work. By the time you pass in just a “pointer to” the array, all the compiler sees (inside that showSize function) is a pointer, and thus can only tell you the size of the pointer, and not what it points to.

As you see, this tip is of limited use, but I think it is still neat and a potential way to save some CPU cycles and program space bytes from time to time. Since I have worked on a number of Arduino Sketches that have gotten too big to fit (also on some TI MSP430 projects), small tricks like this can make a very big difference in getting something to fit or not fit.

Previously, I discussed a way to make string copies safer by using strncpy(). I mentioned there would be a bit of extra overhead and I’d like to discuss that. This made me wonder: how much overhead? I decided to try and find out.

First, I created a very simple test program that copied a string using strcpy(), or strncpy() (with the extra null added).

Since I am lazy, I didn't want to make two separate test programs. Instead, I used a #define to conditionally compile which version of the string copy code I would use.

When I built this using GCC for Windows (using the excellent Code::Blocks editor/IDE), I found that each version produced a .exe that was 17920 bytes. I expect the code size difference might start showing up after using a bunch of these calls, so this test program was not good on a Windows compiler.

Instead, I turned to the Arduino IDE (currently version 1.6.7). It still uses GCC, but since it targets a smaller 16-bit AVR processor, it creates much smaller code and lets me see size differences easier. I modified the code to run inside the setup() function of an Arduino sketch:

Then I selected Sketch Verify/Compile (Ctrl-R, or the checkmark button). Here are the results:

SMALL (strcpy) - 540 bytes

LARGE (strncpy) - 562 bytes

It seems moving from strcpy() to strncpy() would add only 22 extra bytes to my sketch. (Without the "buffer[BUFSIZE-1] = ' ';" line, it was 560 bytes.)

Now, this does not mean that every use of strncpy() is going to add 20 bytes to your program. When the compiler links in that library code, only one copy of the strncpy() function will exist, so this is more of a "one time" penalty. To better demonstrate this, I created a program that would always link in both strcpy() and strncpy() so I could then test the overhead of the actual call:

Now, with both calls used (and trying to make sure the optimizer didn't remove them), the sketch compiles to 604 bytes for SMALL, or 610 bytes for the larger strncpy() version. (Again, without the "buffer[BUFSIZE-1] = ' ';" line it would be 608 bytes.)

Conclusions:

The strncpy() library function is larger than strcpy(). On this Arduino, it appeared to add 20 bytes to the program size. This is a one-time cost just to include that library function.

Making a call to strncpy() is larger than a call to strcpy() because it has to deal with an extra parameter. On this Arduino, each use would be 4 bytes larger.

Adding the null obviously adds extra code. On this Arduino, that seems to be 2 bytes. (The optimizer is probably doing something. Surely it takes more than two bytes to store a 0 in a buffer at an offset.)

Since the overhead of each use is only a few bytes, there's not much of an impact to switch to doing string copies this safer way. (Assuming you can spare the extra 20 bytes to include the library function.)

Now we have a general idea about code space overhead, but what about CPU overhead? strncpy() should be slower since it is doing more work during the copy (checking for the max number of characters to copy, and possibly padding with null bytes).

To test this, I once again used the Arduino and it's timing function, millis(). I created a sample program that would do 100,000 string copies and then print how long it took.

When I ran this using SMALL strcpy(), it reports taking 396 milliseconds. When I run it using strncpy() with the null added, it reports 678 milliseconds. strcpy() appears to take about 60% of the time strncpy() does, at least for this test. (Maybe. Math is hard.)

Now, this is a short string that requires strncpy() to pad out the rest of the buffer. If I change it to use a 9 character string (leaving one byte for the null terminator):

...no padding will be done. Without padding, the SMALL version takes 572 and the strncpy()/null version takes... 478!?!

Huh? How can this be? How did the "small" version suddenly get SLOWER? Well, before, strcpy() only had to copy the five characters of "Hello" plus a null then it was done, while strncpy() had to copy "Hello" then pad out five nulls to fill the buffer. Once both had to do the same amount of work (copying nine bytes and a null), it appears that strncpy() is actually faster! (Your mileage may vary. Different compilers targeting different processors may generate code in vastly different ways.)

Perhaps there is just some optimization going on when the destination buffer size is know. (Note to self: Look in to the GCC strncpy source code and see what it does versus strcpy.)

Conclusion:

strncpy() isn't necessarily going to be slower (at least on this Arduino)!

strncpy() might be significantly slower if you copy a very short string ("Hi") in to a very long buffer (char buffer[80];).

Buyer Programmer beware!

I am sure glad we (didn't) clear that up. In the next part, I'll get back to talking about appending strings using strcat() and how to make that safer.

As of this writing it has only been about six months since the discovery. At the time, little was known about it beyond some documents in Chinese and some early attempts to write code to use it. Today, however, you can find this part on Amazon for $7.99 with Prime shipping, or much cheaper on e-Bay with slow shipping from China:

The chip can been hooked up to a UART (transmit and receive), or via SPI. This means, with a cheap TTL-to-RS232 adapter and a power supply, you could WiFi enable anything with an RS232 port with a bit of communications software.

The next time I have a few spare bucks, I plan to order one and see how easy it is to work with. It could be a fun way to WiFi-enable a CoCo or Arduino :)

And for those curious, here is a tutorial on using it I found:

http://www.instructables.com/id/Using-the-ESP8266-module/

Please leave a comment if you have worked with this chipset. It seems it might not take much to make a C library for Arduino that mirrored the official Arduino WiFi shield API, but used this inexpensive part.

Last year, I designed an adapter that would let me use original CoCo (or Tandy 1000) analog joysticks on a modern computer via USB. I also designed an opposite adapter, which would let a modern USB controller be used on an old CoCo or Tandy 1000.

I ordered all the parts for a prototype, and did some quick tests to prove that it worked… And then promptly moved on to other things.

Eventually I found some time and I dug out all of these parts and began wiring things up again. My hope was to have a few things available to sell at the Chicago CoCoFEST this past April 25 and 26, 2015. (Money is very tight here, so any thing I can do to generate some extra income is a good thing.) I was unable to go, so did no more work on the project.

Rather than collect dust, I thought I’d share my work so far in this article I originally started working on last February.

The hardware components I have will allow several things:

For the CoCo

Use modern USB joysticks/gamepads on the CoCo

Use modem Bluetooth wireless joysticks/gamepads on the CoCo

Use modern USB keyboards on the CoCo

Use modern Bluetooth wireless keyboards on the CoCo

For Mac/Linux/Windows

Use an original CoCo/Tandy 1000 joystick as a USB input device

Use an original CoCo/Tandy 1000 joystick as a wireless Bluetooth input device

Use an original CoCo keyboard as a USB keyboard

Use an original CoCo keyboard as a Bluetooth wireless keyboard

As you can see, there are two main goals (use modern stuff on a CoCo, or use old CoCo stuff on a modern computer), with a focus on USB or wireless Bluetooth. All of these are possible, with the cost of doing Bluetooth about the same (or maybe a few dollars less) than USB.

My current prototype reads a PC USB joystick and turns that in to a CoCo-readable analog joystick. I also wired up CoCo joysticks to use on my Mac (very direct and easy).

The keyboard stuff also interests me. I plan to order the Bluetooth part I need so I can embed it inside my CoCo, hooked to the keyboard connector, and use an external battery powered Bluetooth keyboard on my CoCo.

The other combinations are not high on my project list since I do not even own a wireless Bluetooth gamepad or controller (unless my OUYA console controller can be used). However, when I get to that point, I may be able to find someone I can borrow one from for testing.

My eyesight took a hit last year, and now I can no longer focus on things more than a few feet away so I probably won’t do much until I can afford a new set of glasses ;-) Mid-40s is trying to make me think I’m no longer in my mid-20s!