uBasic on 8051

BASIC is a very popular programming language taught in schools. There have been various derivatives of the BASIC programming language. The most popular ones are GW-BASIC, QBASIC and Visual Basic. In fact there are versions of BASIC for the 8051 as well, called the MCS BASIC-52.

The MCS BASIC-52, is written in assembly language, and hence is hard to extend. Mordern 8051s have large memories and hence it is possible to implement a BASIC interpreter in C. This article shows how to port a tiny BASIC interpreter to the ZKit-51.

uBasic

The BASIC we are going to port is uBasic from http://www.sics.se/~adam/ubasic/ It is a very tiny BASIC interpreter, written in C, with minimal features. It was designed to be a scripting language in large applications. This is a perfect fit for our experiment.

The interpreter has only three C files - tokenizer.c, ubasic.c and use-ubasic.c. The first two files implement the language, and the use-ubasic.c invokes the interpreter by passing it the BASIC program as C string.

Modifications

The following are required for uBasic to run on the ZKit-51.

  • Enable external memory, since the internal memory is not sufficient for the interpreter.

  • Implement putchar so that printf() prints to the serial port.

  • Implement a board_init() function that will initialize the serial port.

  • Implement exit() which is used by the interpreter, but is not available in SDCC.

We put this up in a separte file called zkit-51.c.

#include <serial.h>

void exit(int status)
{
        while(1);
}

/* Enable extenal RAM. */
int _sdcc_external_startup()
{
        __sfr __at (0x8E) AUXR;
        AUXR = 0x0;
        return 0;
}

/* Print goes to the serial port. */
void putchar(char c)
{
        serial_putc(c);
}

/* Initialize the serial port */
void board_init()
{
        static char fifo;
        serial_init(&fifo, 1);
}

We then modify use-basic.c, to invoke our board_init().

diff -Naur a/use-ubasic.c b/use-ubasic.c
--- a/use-ubasic.c      2007-02-01 02:55:51.000000000 +0530
+++ b/use-ubasic.c      2010-12-04 17:40:04.000000000 +0530
@@ -44,6 +44,7 @@
 int
 main(void)
 {
+  board_init();
   ubasic_init(program);

   do {

We are done. We compile all the files using the large model and link them up to get the .ihx file, which we then flash into our board. The BASIC program should get executed and the output gets displayed on the serial port.