Archive for the ‘Microcontrollers’ Category

A quarter century of Java

July 4, 2020

We are all natives now, and everybody else not immediately one of us is an exotic. What looked once to be a matter of finding out whether savages could distinguish fact from fancy now looks to be a matter of finding out how others, across the sea or down the corridor, organise their significative world. (Clifford Geertz)

The Java Programming Language turned 25 years old on May 23 2020.

I’ve been writing Java code for 24 years, since 1996.

When Java arrived on the scene, my languages of choice were C, C++ and Perl, but mostly the first and last.

For me, there were at first various BASIC dialects, with smatterings of assembly code. Then at university and just at the moment I thought I knew something about programming, I learned Pascal, C and Fortran.

Later, languages such as LISP, Prolog, ML, CLIPS, SQL, even COBOL (about which I really never could find anything to like) showed me different ways in which a computer could be programmed.

Programming paradigms and language translation (compilers, interpreters) have interested me since around 1989. I wrote the ACE BASIC compiler in C from 1991 to 1996.

I’ve since designed and implemented other programming languages, including LittleLisp for the Newton PDA, and others that were only ever experiments, most personal projects, one commercial. In recent times I’ve been developing a domain specific functional language called VeLa that I’ll write about some time.

From the start, Java made it possible to write cross-platform programs, with or without GUIs, with relative ease.

Its byte-code compilation model resonated with me after having written my first compiler for a subset of Pascal in 1989 that generated USCD p-codes.

In 2004, six years after Java was released, Java 5 brought generics, regular expressions and assertions. I had craved these, especially the first two, for years, since writing C++ and Perl code in the early to mid-90s.

Java’s history is something of a long strange trip: from set-top boxes to web applets, the desktop, enterprise frameworks, smart cards and other embedded devices, to Just In Time compilation and dynamic profiling, WebStart and security model criticisms, and from Sun Microsystems to Oracle.

C# learned from Java’s mistakes. Some of its proponents have not always seemed to me to be honest about acknowledging its heritage though.

Programming Languages are tools for thought, for human communication, and not merely a means by which to bend a machine to our will. As I’ve mentioned elsewhere, they can also determine what it is possible for us to think.

My working days are now dominated by R, Python, C++ and sometimes Fortran; and bash of course. R and Python are powerful and have a rich ecosystem of tools and libraries, but I’m no fan of dynamic typing which makes it easy to get started, yet leaves too much unsaid, too many possibilities for error. This problem only becomes worse as programs grow.

Rust, Julia, Go, Clojure, Swift are all contenders to the throne now too. Which of these will stand the test of time? Which will one day be considered to have legacy code bases, just like Java, C, C++, Fortran, COBOL? All of them, I would say.

Then there are those languages like Haskell that blaze trails but tend not to be dominant. Java and most of the current crop owe such languages a debt of gratitude as functional programming’s higher order functions, type inference, and immutability have come out of academia to take over the world.

Distinguishing fact from fancy, fashion from solid ground, making predictions about the future of the programming language landscape is no easy task.

The older I get, the more selective I become about what new languages and frameworks to learn and the more interested I am in as much static typing, type inference, and run-time efficiency as I can get my hands on.

Yet, after a quarter century, I still like to code in Java whenever I can. It has its own beauty. I don’t pay much attention to its detractors. Of course, that’s where it’s important to think about context. If I’m writing code for a tiny embedded system or want to squeeze the most out of a machine, I’m more likely to code in C or C++ than anything else. But if I want to build a big habitable castle in the sky, I’ll still choose Java when I can.

Alto creator Charles P. Thacker dies

June 23, 2017

The influential American engineer Charles P. Thacker died on June 19, aged 74.

Thacker designed the Alto personal computer at Xerox PARC in the 1970s which influenced development of the Mac after Steve Jobs saw it during a visit to PARC.

He also contributed to the development of Ethernet, Tablet PCs, and laser printers.

The computer scientist Butler Lampson, one of Thacker’s colleagues at Xerox PARC and later at Microsoft has spoken about his ability to see what was important and his breadth of coverage:

He could do everything from circuit design all the way through hardware architecture and programming and user-interface design.

The Association for Computing Machinery and IEEE Computer Society recently honoured Charles P. Thacker with the Eckert-Mauchly Award.

An Arduino Olympic Torch model

February 5, 2014

The 2012 London Olympic Games coincided with my son’s last year of primary school. Each year the school has an “expo” in which students explore and create displays on some theme. In that year the school decided the theme would be the Olympics.

One idea we (my son, wife and I) came up with was a model of an olympic torch with a “flickering flame” effect. This was just one of a number of items that had to be prepared by my son for the “expo”, and some parental assistance was expected, so we helped with that.

My wife created the body of the torch from a cone-shaped industrial cotton reel and  cardboard coffee cup, all spray-painted gold.

I considered using a PIC micro-controller and a couple of discrete tri-colour high-intensity LEDs, but given the time and size constraints I decided to use a Freetronics LeoStick Arduino with two high-intensity LED units on a ProtoStick (from Jaycar in Adelaide) powered by a 9V battery. The LeoStick sits inside the coffee cup with cellophane over the top to provide a diffuser (added by my wife), as shown below.

ArduinoOlympicTorchTopView-cropped

A momentary push-button switch is used to start the “flickering flame” for a short time as shown in this YouTube video.

The serially clocked tri-colour high intensity LED units randomly and rapidly cycle through various colours to produce the effect.

This Freetronics page describes the LED components and their usage in more detail.

The following image shows the individual disassembled components:

ArduinoOlympicTorchComponents-cropped

Note the large (by comparison to the LeoStick) home-brew 5V regulated power supply to which a 9V battery is connected. The power supply and battery sit inside the conical handle attached to a toggle switch (power on/off) in the base, a water bottle lid in this case.

The following image shows the components connected:

ArduinoOlympicTorchCompleteCircuit-cropped

The high-intensity LED units are attached to the ProtoStick via headers soldered to the latter.

The following schematic shows the simple Arduino-based circuit:

arduino-olympic-torch-schematic

The resistor in the schematic is a surface mount component soldered to the ProtoStick.

The code for the project is shown below. As can be seen from the excluded code at the end of the loop() function, I toyed with adding a wake-from-sleep interrupt to conserve power while the circuit was active, but didn’t get that to function within the time available. There was no loss of functionality of course, just a greater drain on the battery because of the unfortunate busy-looping.

/*
  * 2012 EMPS Expo Olympic Torch RGB LEDs, for Nicholas.
  *
  * Arduino (LeoStick)
  *
  * References:
  * - http://www.freetronics.com/pages/leostick-getting-started-guide#.UBOpjJkthmo
  * - http://www.freetronics.com/pages/rgbled-rgb-led-quickstart-guide#.UAq-qZktg38
  * - http://www.arduino.cc/en/Tutorial/Debounce
  *
  * dbenn@computer.org, August 2012
  */

 #include <avr/sleep.h>

 // RGB LED strip pins (clock and serial data).
 const int CKI = 10;
 const int SDI = 12;

 // Button pin
 const int BUTTON = 2;

 // Button state variables.
 int buttonState = LOW;
 int lastButtonState = LOW; 

 // The following variables are longs because the time, measured in miliseconds,
 // will quickly become a bigger number than can be stored in an int.
 long lastDebounceTime = 0;  // the last time the output pin was toggled
 const long DEBOUNCE_DELAY = 50;  // the debounce time; increase if output is unstable

 // Function prototypes.
 void wakeupHandler();
 void blankLEDStrip();
 void randomiseLEDStrip(long millisecs);
 void setLEDStrip(int color1, int color2);
 void pushLED(int color);
 boolean isButtonToggled();
 boolean isButtonPressed();
 long getRndColor();

 void setup() {
   pinMode(BUTTON, INPUT);
   pinMode(SDI, OUTPUT);
   pinMode(CKI, OUTPUT);
   randomSeed(analogRead(1));
   blankLEDStrip();
 }

 void loop() {
   // When the button is toggled, generate
   // random colors with random pauses between
   // each for 15 seconds, then blank the LED strip.
   if (isButtonToggled()) {
     randomiseLEDStrip(15000);
     blankLEDStrip();
   }
 #if 0
   // A sleep mode with wake-from-interrupt would decrease power consumption.
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);
   sleep_enable();
   interrupts();
   attachInterrupt(0, wakeupHandler, RISING);
   sleep_mode();
 #endif
 }
 #if 0
 void wakeupHandler() {
   // When the button is toggled, generate
   // random colors with random pauses between
   // each for 15 seconds, then blank the LED strip.
 //  while (!isButtonToggled());
   randomiseLEDStrip(15000);
   blankLEDStrip();
 }
 #endif
 // Blank the RGB LED strip.
 void blankLEDStrip() {
     setLEDStrip(0x00000000, 0x00000000);
 }

 // Generate random colors for random periods for specified number of seconds.
 void randomiseLEDStrip(long millisecs) {
   long t1 = millis();

   while (millis() <= t1+millisecs) {
     setLEDStrip(getRndColor(), getRndColor());
     delay(random(100));    
   }
 }

 // Set the colors on the RGB LED strip.
 void setLEDStrip(int color1, int color2)
 {
   pushLED(color1);
   pushLED(color2);

   // Pull clock low to put LED strip into reset/post mode
   // and wait for 500 microseconds for completion.
   digitalWrite(CKI, LOW);
   delayMicroseconds(500);
 }

 // Push a 24-bit RGB colour data (RRGGBB; red is MSB) out to the LED strip.
 void pushLED(int color) {
   for (int color_bit = 23 ; color_bit >= 0 ; color_bit--) {

     // Low clock signals bit change start.
     digitalWrite(CKI, LOW);

     // Force mask to be 32-bit instead of 16-but by default.
     long mask = 1L << color_bit;

     // Write data bit and latch.
     digitalWrite(SDI, color & mask ? HIGH : LOW);
     digitalWrite(CKI, HIGH);
   }
 }

 // Returns whether the button was toggled (pressed then released).
 boolean isButtonToggled() {
   boolean toggled = false;

   if (isButtonPressed()) {
     while (isButtonPressed());
     toggled = true;
   }

   return toggled;
 }

 // Returns whether the button was pressed since the last time the function was called.
 boolean isButtonPressed() {
   // Read the state of the switch into a local variable.
   int currentButtonState = digitalRead(BUTTON);

   // Check to see if we just pressed the button 
   // (i.e. the input went from LOW to HIGH), and we've waited 
   // long enough since the last press to ignore any noise.  

   // If the switch changed, due to noise or pressing...
   if (currentButtonState != lastButtonState) {
     // ...reset the debouncing timer.
     lastDebounceTime = millis();
   } 

   if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
     // Whatever the current button state is, it's been there for longer
     // than the debounce delay, so take it to be the actual current state.
     buttonState = currentButtonState;
   }

   // Save the current button state. Next time through the loop,
   // it'll be the lastButtonState.
   lastButtonState = currentButtonState;

   return buttonState == HIGH;
 }

 // Return a random color.
 // Proportions of each color component can be tweaked in the selection comparisons.
 long getRndColor() {
   long primary = random(100);
   long rgb = 0xFFFFFF;

   if (primary < 50) {
       rgb = 0xFF0000 | random(0x100) << 8 | random(0x100); 
   } else if (primary < 75) {
       rgb = 0x00FF00 | random(0x100) << 16 | random(0x100); 
   } else {
       rgb = 0x0000FF | random(0x100) << 16 | random(0x100) << 8; 
   }

   return rgb;
 }

Explaining how computers work with the TEC-1

May 30, 2010

I was recently asked to give a talk to my son’s primary school class about how computers work.

The Powerpoint slides from the talk consist mostly of pictures and towards the end, a small Z80 machine code program (to add a number to itself) for the TEC-1 single board computer.

TEC-1 image from Issue 10 of Talking Electronics Magazine

TEC-1 from Issue 10 of Talking Electronics Magazine cover

My wife and I created a short video showing the program being entered and executed multiple times via the TEC-1’s hex keypad.

As I told the kids during that talk, if you want to understand how a computer really works, you need to get close to the machine-level and talk about processors, memory, buses and so on. So we did, and despite leaving out a lot of details, I think the idea of going from X = X+X to a sequence of simple instructions and a numeric representation palatable to a Z80 made some sense to many of the kids, and at least provided a source of fascination to most. Apart from that, I think it was fun.

We also spent a lot of time talking about the extent to which computers now pervade our lives and how much we take that and the people whose ideas and work made it all possible for granted, including Babbage and Lovelace, Leibniz, Boole, Turing, and so many hardware and software pioneers.

Like many hobbyists in the 70s, 80s and beyond, the idea of building a simple computer from components in a kit was alluring. I’ve been doing paid software development for almost 30 years but was a hobbyist for more than a decade or more before that. I was introduced to the Joy of Computing in Year 10 due to the purchase of a PDP-11/04 by my school (Norwood High in Adelaide) in the late 70s. Along with a love of astronomy that continues to this day, I maintained an interest in programming throughout the 80s, during which time I was a nurse. I eventually decided to convert one of my hobbies into a profession, but still maintain the attitude of a hobbyist, developing open source software such as my current project: VStar.

My hope is that I’ve instilled in at least some of those kids a hunger to know more about computers and programming.

Replacing an iPod Nano’s battery

July 24, 2008

I bought a first generation iPod Nano more than 2 years ago. I use it every work day (see also http://strangequark.me/2006/08/27/astronomy-science-podcasts/), but the battery has been on the way out over the last few months. In the end it was holding charge for less than an hour, irrespective of charge time, often dying before my walking trip was over.

Getting it replaced through official channels would’ve cost in excess of AUD $100, about a 3rd of the device’s original cost. So instead, I spent AUD $20 on an iPod replacement battery kit from JayCar (I’ve seen them advertised elsewhere on the web too).

It came with the 3.7V Li-ion Polymer battery (400mAh instead of the original 340mAh), two plastic tools to pry the case open, and a brief but effective instruction sheet.

The most painful part was getting the case open. The plastic tools from the kit only get you so far and I pretty much wrecked mine. My wife Karen and I took turns carefully prying open different sections of the case with a small flat blade jeweller’s screwdriver (not suggested by the instruction sheet, but effective nonetheless), in addition to using the plastic tools.

Once the back of the case was off, the battery was easily removed, and I used a fine-tipped soldering iron to remove the three wires from the PCB, and fine solder to connect the new battery’s wires in place before putting the case back together.

I replaced the battery on the weekend and didn’t have to charge it again until 3 days later. Hopefully this will make my Nano last another 2 or 3 years, by which time it will probably be time for an iPod upgrade. It won’t owe me anything by then, that’s for sure.

Now, all I have to do is stop breaking earphones.

PIC C Library on Sourceforge

May 8, 2007

My PIC C library is now on Sourceforge. I’ve developed and used this library for my own projects in conjunction with the Hi-Tech PICC Lite compiler on and off for a few years now. It’s been sitting on my laptop for personal use, and I thought it was time to make it available for others to use.

Making picclib available is my first experience of Sourceforge, and a fairly pleasant one. The documentation is quite reasonable, although it helps to have some background with Unix, ssh, CVS/Subversion etc. I chose Subversion as I’ve been using it for my own projects for awhile now.

There’s plenty of Sourceforge features yet to explore. I’ll certainly use it for future projects.

Embedded Java: Down to the metal

October 18, 2006

In September 2004 I gave a talk to the Adelaide Java User Group (http://ajug.org.au/display/AJUG/AjugAdlMeeting20040920) entitled Embedded Java: Down to the Metal at which I talked about:

The TINI is Java 1.1.6 compatible with respect to the language and libraries, while the Javelin Stamp implements a smaller subset of Java with some deviations (e.g. ints are really shorts, no interfaces, no GC).

At that JUG meeting I demonstrated the Javelin Stamp displaying the temperature from a DS1620 IC on an array of 7-segment LEDs and dumping to System.out, which on the Stamp is a serial port.I mostly use the Javelin Stamp to prototype an application with unfamiliar hardware due to its easy serial-port based progamming and source-level debugging, and because I can write OO code for similar yet slightly different devices (e.g. for 7-segment LED displays that are direct pin to pin, via BCD-to-7-segment IC, or via serial-to-parallel-to-7-segment IC), varying driver code implementation while keeping the interface fixed. It also comes with a nice assortment of Java library code for exploiting the Stamp’s hardware features.

I wasn’t quite ready to demonstrate the DS TINI during the JUG meeting, but have experimented further since. The TINI, like the Javelin Stamp has serial I/O, but in addition, physical interfaces for Ethernet, CAN bus, I2C, DS 1-wire, and iButton. It comes with a similarly rich set of Java libraries (along with the many of the standard Java 1.1.6 libraries including collections and network I/O) for working with its capabilities.

Here’s a link to a simple PLT Scheme (http://www.plt-scheme.org/) servlet (currently unavailable, Jan 2008) that connects to a Java server running on a DS TINI in my home with a DS18S20 temperature IC connected to its 1-wire adapter:

  

http://www.kepler.podzone.net:8080/servlets/david/get_tini_temp.ss 

The TINI is suitable for more ambitious yet relatively resource-low projects. If you want to see even more resource-constrained Java, check out JavaCard for smartcards. I worked on a team that developed a JavaCard VM for a smartcard development and test tool in the late ’90s.Here’s an embedded.com article about some alternatives to C for embedded system development: Java and Ada.

So folks, Java is not just for the desktop or web/Enterprise, but also for the embedded space.

About “Strange Quark’s”…

August 26, 2006

Thanks for visiting Strange Quark’s. In this first post I’ll tell you what I intend to write about and why I chose that name. In the late 80s I ran a “service” called Quark’s Cosmos on Australia’s Viatel, later called Discovery 40, pretty much the same as the UK Prestel (40 column teletext-style) system. The content of Quark’s Cosmos was focused upon astronomical and space mission news.

It was pre-Internet, so news items were distilled from traditional media along with regular snail mail from space agencies such as NASA, ESA, and occasionally NASDA (Japan) and the agencies of other countries such as Russian and India.

A highlight was that I was able to use the forum to provide up-to-date information about Neptune as seen through Voyager 2’s eyes in 1989 because of previous communications with the Tidbinbilla Deep Space Tracking Network near Canberra.

Quark’s Cosmos also had chat boards for these topics plus Sci-Fi and Philosophy along with running the odd astronomical quiz complete with prizes (books usually). Running Quark’s Cosmos was a labour of love and actually cost my wife and I money. Nevertheless, it was fun, rewarding, and appreciated by a lot of people.

With the advent of the Internet, Viatel and Quark’s Cosmos became less compelling. Competing with the richness of the Net became a zero sum game.

Much has changed in the last 20 years, but from a content and presentation perspective, systems like Viatel 40/Discovery and CompuServe were the ancestors of most of what we see on the Internet today. Long before Internet banking was available, Viatel had it for at least one large Australian bank. IRC, ICQ, blogs, all had some counterpart on these systems. The main difference is that the Internet is unbounded, unlike these older systems (and bulletin boards) hence the need for search engines.

I’ve been considering a blog for ages, and wanted to retain the “Quark” theme, but since I and the world in general are stranger than almost 20 years ago, Strange Quark’s place/blog seemed appropriate.

The main topics of interest to me these days are:

  1. Programming paradigms and languages
  2. Low-resource microcontrollers such as PIC, TI MSP430, AVR, 8051
  3. Amateur astronomy (generally sharing the night sky with others, planetary nebulae, the life & work of Johannes Kepler)
  4. Science Fiction books and movies
  5. Philosophy (in particular the Philosophy of Mind)

So, these are the topics I’ll mostly talk about. Anything else will be under clearly different categories. I’m doing this not because blogging is trendy but because I need a writing outlet, and believe I have some worthwhile things to share with others.

Finally, here’s a bit more general background about me:

  • I’m married (I mentioned Karen above) with a 6 year old son Nicholas and a 2 year old girl Heather.
  • I’m a professional developer having worked for Motorola, Freescale, the University of Tasmania, and ISPs (Vision Internet and Internode). Prior to that I was a nurse for the better part of a decade.
  • Several years ago I developed and released the ACE Basic compiler (Amiga) and LittleLisp interpreter (Apple Newton).

My long-standing and slightly antiquated website is at:

http://www.users.on.net/~dbenn

My email address is dbenn@computer.org

Stay tuned for more posts on topics such as:

  • Astronomy and Science podcasts
  • Web-based astronomy software under development
  • Java-based embedded systems
  • TI MSP430F20xx and PIC microcontrollers and rapid development
  • Reflections on personal loss (the odd one out, but something I need to write about).

That’s enough for a first post.