The Sound Of Music

FreeBASIC is a great language for informal messing around. In two lines of code, you can be drawing graphics in full-color 1080p. Now that FBC supports compiling for x64, you can allocate ridiculous size arrays using as much memory as you have available.

It’s the ideal modern back-of-the-envelope prototype language for those of us who grew up on BASICA, Tandy BASIC, and QBasic/QuickBasic. But as with most reboots of beloved childhood franchises, a few things seem to be missing.

Playing music, for one, was very easy back in the days of BASIC. Most languages included a “play” keyword that could be called to play various notes. Type something like “play cdefg” and you could make the speaker produce a simple scale.

FreeBasic, unfortunately, doesn’t have the “play” keyword (though, oddly, WinFBE still flags it as a keyword.) FreeBasic is cross-platform, being available for Windows, DOS, and Linux — and so hardware-specific things like speaker support weren’t included.

Fortunately, however, there’s a workaround that ends up being a significant upgrade. Windows provides various APIs that can be used by programs to request functionality from the OS. One of these is the ability to emulate General MIDI instruments, and to accept commands for these from programs. With a little setup, FreeBasic can have access to all of Windows’ General MIDI capabilities.

So now, instead of commanding simple beep melodies, we can produce almost-performance-quality music. The API is even relatively easy to set up once you know the right commands — and this is where Google helps immensely. After a brief search, I found an example by FreeBasic.net user “Mihail_B” that shows how to get Windows to play a couple of percussion samples via MIDI.

A quick look at the MIDI specification helped decode what was happening. For each note played, a MIDI “note on” command is sent. One of the relevant lines of code is:

midiOutShortMsg1(midihandle,&h403f90)

This calls the “midiOutShortMsg1” wrapper to the midiOutShortMsg() function provided by Windows. (See the code example above for the supporting API calls — there’s some setup needed.) The information as to what to play is contained in the three hex bytes at the end: 40, 3f, and 90.

Breaking these down, the “90” is the status byte, the “3f” is the note number, and “40” is the velocity. The first four bits of the status byte (the “9”) tell us that this is a Note On command, and the second four bits (the “0”) tell us that this command is being sent to MIDI channel zero.

The “3f” is the note number — decimal 63, where the notes are numbered from 0 to 127 with 60 being middle c. So note 63 (3f in hex) is three half-steps above Middle C, or D#4.

Finally, the “40” is the note-on velocity. This translates to 64 in decimal, which is halfway up the velocity scale (and the default velocity sent by keyboards and other instruments which don’t record velocity information.) A good electronic piano would send varying velocity information with the note commands; a harpsichord, which doesn’t have key-velocity dynamics, would probably just send 64 with each note.

With this understanding, a wrapper function can be written to play notes more easily. The FreeBasic code linked below (a spinoff using key pieces of the code linked above) implements the “playNote()” and “stopNote()” functions. Both take (note, velocity, channel) as arguments.

So, once MIDI is initialized and the instrument patch is selected (the default is grand piano), playing middle C is as simple as:

playNote(60, 64, 0)

It’s good MIDI practice to turn the notes off, as well. With patches like the grand piano, it may not matter much, since most instruments will automatically silence the oldest notes as needed if given more to play. But with other patches (pipe organ, violin, etc) which can play continuously, it becomes very important. Sending a Note Off command or a Note On with velocity zero will silence the selected note.

Here is a quick chord demo, easily modified to play whatever notes you like once you know the MIDI note numbers. Share and enjoy!

Posted in BASIC, Coding, HOW-TO, Music | Tagged , , , , , , , , | Leave a comment

A Change In The Weather

The original Weather Prognosticator worked well for several years, but the downside to relying on an external API is that it can get changed out from under you. Or removed entirely.

Last Fall, Weather Underground turned off the API that the Prognosticator had been using. I’d be tempted to ask for my money back, except that it was a free API. Oh, well.

Fortunately, other solutions exist, and OpenWeather’s API is still more or less what is needed. Their hourly data requires a subscription, but three-hour temperature forecasts are still free (within reason.) This means that, instead of displaying hourly temperature forecasts, data is available in three-hour increments — but is available several days out. So instead of displaying hourly data for the next ten hours, the display now shows three-hour temperatures for the next thirty.

The updated code is available here; you will need a free OpenWeatherMap API to be able to use the API.

Enjoy — and stay safe out there!

Posted in Internet, Networking, Projects | Tagged , , , , | Leave a comment

TinyFPGA / ICEStudio

Microcontrollers are deservedly a favorite component for many electronics hobbyists. They’re straightforward to use, cheap, powerful, and capable of doing any number of simple tasks well. The popularity of the Arduino ecosystem — not just the boards, but the IDE and the whole Arduino way of doing things — makes microcontroller-based prototyping easy, fast, and fun.

Although popular dev boards like Digilent‘s BASYS series do exist, FPGAs have been largely left out of this revolution. Programming even a low-end Spartan3E FPGA requires downloading, licensing, configuring, and installing ISE Webpack — a huge set of utilities from Xilinx. The download is several gigabytes, and it all unpacks to something like 10GB once installed.

Webpack, like the name would imply, is a suite of programs that work together to produce the final configuration bitstream for the FPGA. The IDE works with a synthesis tool as well as PlanAhead, where you plan out the inputs and outputs in terms of pins on the FPGA itself (not the board.) Once all that is done, you generally need an uploader program like Digilent‘s Adept. This is straightforward and reliable to use, but it’s an additional step.

Wouldn’t it be nice if something more like the Arduino IDE existed, with an option to quickly compile-and-upload to test code? Even better, what if you could use such an IDE with an inexpensive, breadboardable FPGA-on-a-stick?

The TinyFPGA BX board, wired up with some test peripherals.

The TinyFPGA BX board, plus the amazing ICEStudio IDE, makes this a reality. We finally have an open-source FPGA toolchain that makes getting up and prototyping with FPGAs almost as easy as programming an Arduino board.

FPGAs are, of course, fundamentally different from microcontrollers. Instead of having a fixed set of instructions to be executed, FPGAs are best thought of as a “sea of logic gates” which can be made into whatever sort of digital hardware you need for your task. You don’t tell them what to do — you tell them what to be.

If you’re used to thinking procedurally and writing programs in procedural languages such as C (and Python, and Java, and BASIC, and Fortran, and so on), this can take some getting used to. (One popular solution is to actually instantiate a microcontroller in the FPGA logic, and then program that in C, which sounds like cheating but works.)

The advantages to FPGAs, though, are that they’re inherently as parallel as you want them to be. FPGAs don’t have to just do one thing at a time; they can have hundreds or thousands of processes executing independently on different parts of the chip. They’re also fast. The TinyFPGA BX runs at 16MHz, which is pretty slow for an FPGA — but because the logic is so configurable, it can get a lot done in that one clock cycle. Simple Boolean logic and binary arithmetic can be done in real time, even if you need dozens or hundreds of calculations done in parallel.

ICEStudio tries to make this way of developing as intuitive as possible. FPGA-based design is often done with a mix of code and schematic capture, with data in the form of either single bits or buses representing binary numbers being carried from one module to another by lines.

For devices like FPGAs, which can be thought of as dataflow devices more than as procedural devices, it works. This approach is flexible enough to allow you to code what you like and connect the rest. Click on a module, edit the code, then press ctrl-u to compile and upload. Easy.

ICEStudio, showing a solution for a LED wave-of-light demo.
(Click for larger)
https://www.facebook.com/m.eric.carr/videos/10223344596951825/?t=1
The TinyFPGA running the solution above.

A breadboardable, open-source FPGA toolchain — and one that can go from updated code to reprogrammed board in ten seconds or so (for simple solutions like the example above)?

Global pandemics not withstanding, I love living in the future.

Posted in Digital, Electronics, FPGAs, Reviews, Tools, Toys, Verilog | Tagged , , , , , | Leave a comment

Brute Force and Ignorance

Computers generally don’t solve problems the same way humans do.

Take Sudoku, for instance. A human Sudoku player will usually look for patterns in the existing numbers, looking for possible spots to place a 1, 2, 3, etc. Or maybe they will notice that a particular square has everything but a 7 and 8, with one in line with another 8, and will deduce what goes where based on that. We look for what makes sense, and try to piece together a rational solution based on logic and observation.

Such relatively sophisticated, creative, intuitive heuristics don’t always represent the easiest way to solve a problem using a computer. Sometimes a simple exhaustive search (one that my former Calculus teacher called the “Brute Force and Ignorance” approach) is best. After all, modern computers have a lot of brute force to bring to bear!

How could one most simply describe how to solve a Sudoku puzzle, given that the solver could follow instructions exactly — and was really, really fast at carrying them out? One method would be to try every single possible combination until something works, backtracking when you come across a dead end. Try to place a “1” in the first blank square, and check to see if there are any conflicts. If not, good — write it down and solve the remaining puzzle. If no such solution exists, or the “1” doesn’t fit, erase it and try a “2” there — and so on. This is the algorithm presented in an excellent recent Computerphile video about how to solve Sudoku in Python.

For some problems, like Chess, this kind of approach is untenable, since it won’t finish before the expected heat death of the Universe. Chess, while nowhere near as complex as Go, still has something like 10^120 possible games.

For Sudoku, however, this works surprisingly well. Most numbers that are tried are dead ends — but if so, they are usually found out quickly. If the algorithm successfully placed a “1,” for instance, it will still blindly try to place a “1” right next to it, since that’s the next step. This will fail, but it will fail quickly, allowing the algorithm to advance and try a “2” and then “3” until it finds something that sticks. No human would check all of these clearly-wrong branches — but they also take much longer to check the plausible ones.

How long would such a dumb, brute-force algorithm take to solve a Sudoku? I wasn’t sure — maybe years? So I tried programming it in C. (Here is the source file.) The example puzzle from the video was solved in about 120 milliseconds on my (ten-year-old but still modern-ish) PC, after having searched 37,652 possible number placements. Not bad!

Next, I looked for a real challenge, and came across what is said to be the world’s hardest Sudoku puzzle…

The “World’s hardest Sudoku,” by Arlo Irkala of AISudoku.com.

This is a nasty one! Nothing obvious jumps out at you, although in a few cases, you can narrow down the choices a bit and start to make progress. I entered in the data and re-ran the program.

This puzzle put up a good fight — there was actually a noticeable pause before the solution displayed — but roughly 1.65 seconds (and maybe something like five billion clock cycles) later, the unique solution popped up:

Nasty, but still solvable!

Lots of progress has been made on many fascinating, important problems by coming up with new algorithms. QuickSort, hashes, distributed computing, heuristics, and similar advancements have made efficient search engines possible. Clever branch-and-bound approaches have enabled Chess (and probably Go) engines to outplay any human.

But sometimes, all you really need is a big hammer.

Posted in Algorithms, C, Coding, Math | Tagged , , , , , | Leave a comment