PBASIC Programming With Style: Column #30, August 1997 by Jon Williams
PBASIC Programming With Style: Column #30, August 1997 by Jon Williams
There are no gigabyte hard drives or megabyte memories with the Stamp, so resource planning and conservation is mandatory. Lets examine several aspects of PBASIC code writing that are important to your projects success: planning; Stamp variables and their conservation; the effective use of PBASIC symbols; and program format and structure. If all goes well, youll be writing better-behaved, higher-performance Stamp programs in less time than youre spending now. Are you ready? Okay then, lets get started! Plan Your Work, Work Your Plan Youve heard it a million times: plan, plan, plan. Nothing gets a programmer into more trouble than bad or inadequate planning. This is particularly true with the Stamp as resources are so limited. Most of the programs Ive fixed were broken due to bad planning and poor formatting which, in turn, lead to errors. Once youve read and digested the following information, youll be better prepared to plan your Stamp programs. In the meantime, here are some tricks I use during program development: Trick #1. Talk yourself through the program. Dont just think it through, talk it through. Talk to yourself out loud as if you were explaining the operation of the program to a fellow programmer. Often, just hearing our own voice is what makes the difference. Better yet, talk it out as if the person youre talking to isnt a programmer. This will force you to explain details. Many times we take things for granted when were talking to ourselves or others of similar ability. Please understand that I currently live alone, so this is not a problem. If you dont live alone, you may want to explain to your housemate(s) what youre doing and that theres no need to bring in the guys with the white jackets! Trick #2: Design the details of your program on a white (dry erase) board before you sit down at your computer. And use a lot of colors. I love the freedom of a white board and find that if Im stumped, the visual aspect of this exercise gives me new insight into the problem. The cool thing about a white board is that I can write code snippets or draw functional diagrams. Trick #3: Get out a pad of small sticky-notes. Write module names or concise code fragments on individual notes and then stick them up on the wall. Now stand back and take a look. Then move them around. Add notes, take some away; just do what feels right to you. This exercise works particularly well with groups. How do you know when youre done? When the sticky-notes stop moving!
Its a good idea to record the final outcome before starting your editor. Another tip: this trick works even better when combined with trick #2. You can draw lines between and around notes to indicate program flow or logical groupings. If its not quite right, just erase the lines or move some notes. Try this trick, it really does work. Neatness Counts I can hear the groans now (Yeah, yeah, yeah... ), especially from my good friend Steve. Most of us just love to sit down at our PCs and start flogging out code like theres no tomorrow and, quite often, this gets us into trouble. Come on, admit it. How many times have you sat down to write what was supposed to be a simple program only to spend many frustrating hours trying to make it work? If this hasnt happened to you, youre either incredibly well disciplined or you havent been coding very long. Keep in mind that it takes no more time to write a neatly formatted program than it does to make a big mess. So why bother with all this neatness nonsense? you ask. Two reasons: debugging and distribution. And very often these reasons are combined. The debugging part is obvious, or should be. Take a look at this code fragment:
loop: for b0 = 0 to 10 for w0 = 1 to 5 gosub myout b1 = b0 * w0 - 1 next goto loop
How much easier would this code be to trou-bleshoot if it looked something like this?
Main: FOR loop1 = 1 TO 10 FOR loop2 = 1 TO 5 GOSUB myOut lastOut = loop1 * loop2 - 1 NEXT loop2 NEXT loop1 GOTO Main
Do you see the problems in the second fragment that isnt as obvious in the first? The first fragment is missing a NEXT to complete the FOR statement. A bigger problem is that the second FOR/NEXT loop overwrites B0 and B1 and will cause unexpected results (more on this later).
Yes, I agree that this can happen with the use of symbols; however, when planning your program and deliberately defining symbols, youll find this occurrence less likely. I find it easier to write a neat program by starting with a template. Below is a template that works equally well for Stamp 1 and Stamp 2 programs. The difference is in the code syntax that you would use in the actual program. For the purposes of this article, well use Stamp 1 details and syntax. Notice how the template structure helps me keep the code organized and contains contact information about the author. This is a good idea if you choose to launch your programs into cyber-space.
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ---- [ Title ]--------------------------File...... NEW.BAS Purpose... PBASIC Programming Template Author.... Jon Williams E-Mail.... [email protected] WWW....... http://members.aol.com/jonwms Started... Updated... ---- [ Program Description ] --------------- [ Revision History ] ------------------ [ Constants ] ------------------------- [ Variables ] ------------------------- [ EEPROM Data ] ----------------------- [ Initialization ] -------------------- [ Main Code ] ------------------------- [ Subroutines ] --------------------
The second reason for using neat programming is distribution. What I mean by this is that well often share our programs with others. Many of us have programs floating around the Internet. Or we may share coding responsibilities with one or more programmers. A well-coded, neatly for-matted program is easier for your partners and others to understand and work on. And consider that you might come back to one of your own programs days, weeks, or even months later. A nicely coded program makes it easy to pick up where you left off. Its very frustrating to try to decode a poorly written program particularly one that youve written yourself!
For all its power, the Stamp 1 has a very limited set of resources: only 255 bytes of (tokenized) program space and just 14 bytes of user RAM. And two of these bytes are lost if GOSUBs are used. Perhaps some of you that are new to Stamps are thinking, Holy cow, what can I do with that? Actually, you can accomplish quite a lot, because the Stamp is very flexible in its use of RAM space. To get the most out of it, however, you really need to understand its organization and the ability to overlay variables. PBASIC 1 allows three variable types: bits, bytes, and words. You can think of the user RAM space as 14 bytes (B0 through B13) or seven words (W0 through W6), or some combination of the two (note that I am not including Dirs and Pins in my definition of user variables). Additionally, W0 (word 0) can be addressed as 16 individual bits (Bit0 through Bit15). For this reason, I generally reserve W0 (B0 and B1) when I start writing a program. I also reserve W6 (B12 and B13) for GOSUBs. A map of the Stamp 1s user-variable space looks like this:
Do you see whats going on here? The same physical space occupied by W0 is also occupied by B0 and B1 which, in turn, is also occupied by Bits 0 through 15. A change in Bit0, for example, will cause a change
in B0 and also in W0. Understanding and taking advantage of this structure can be very useful in the conservation of code space. Let me demonstrate: Instead of using two lines of code:
B0 = 0 B1 = 0
By using the latter technique, you can save up to three bytes of code space. This may not sound like much now, but it will make a big difference later when youre trying to squeeze that critical project into a Stamp 1. Heres a useful partial listing for converting four Stamp 1 pins to eight via a 4094 shift register. It takes advantage of bit addressing of B0. And since most shift registers can be stacked, this routine can be called multiple times for even more outputs.
SYMBOL Strobe = 0 SYMBOL Data = Pin1 SYMBOL Clock = 2 SYMBOL outByte = B0 SYMBOL outbit = Bit7 SYMBOL shift = B2 ' other code here... Out_8: FOR shift = 1 TO 8 Data = outBit PULSOUT Clock, 1 OutByte = outByte * 2 NEXT shift PULSOUT Strobe, 1 RETURN
' make bit available ' clock the bit ' shift bits left ' data -> outputs
SYMBOLic Programming
One of the most overlooked features of PBASIC is the use of symbols. Stated simply, a SYMBOL is just a new name for a Stamp variable or constant. If youve never used symbols, you may be wondering what all the fuss is about. The effective use of symbols can make your programs more readable and, in many cases, self-documenting.
Using symbols can dramatically mini-mize the amount of commenting needed to effectively document a program. Take a look at this PBASIC 1 example:
SYMBOL LGear = Pin0 SYMBOL Alarm = Pin1 SYMBOL SYMBOL SYMBOL SYMBOL Up = 0 Down = 1 On = 1 Off = 0 ' landing gear input
Dirs = %00000010 Alarm = Off CheckLG: IF LGear = Up THEN SndAlrm PAUSE 50 GOTO CheckLG SndAlrm: Alarm = On
Notice how the code is self-documenting and very easy to understand. This is particularly important when sharing programs or coming back to programs that youve put down for awhile. Without symbols or comments, the code might look like this:
Dirs = %00000010 Pin1 = 0 CheckLG: IF Pin0 = 0 THEN SndAlrm PAUSE 50 GOTO CheckLG SndAlrm: Pin1 = 1
I agree that, even without comments, this is not difficult to analyze for process, but not neces-sarily for purpose. And this is only a small frag-ment of a program. An entire program without symbols and with bad (if any) comments can be very difficult to work out. During a recent code review, I had to E-Mail the author three times to confirm my beliefs about what the program was supposed to be doing. With some practice, youll find that symbols remove a lot of confusion from program debugging. This is particularly true when you want to reuse a variable. You might, for example, need a loop counter in one part of your program and a memory address pointer in another. Your definitions would look something like this:
This is perfectly okay in PBASIC and it will make your program easier to read. The use of the standard variable name, B3, in the program may have led to confusion, and certainly would not have helped its readability. Using this technique will also help you conserve variable space. Just make sure that your program does not need to save the value of B3 (from our example) or you may get some unexpected behavior.
Naming Conventions and Formatting Guidelines
Now that weve seen how symbols can make our PBASIC code more readable, lets add a bit of formality and really make things neat. After starting with a template, I use the following formatting conventions in my PBASIC programs: Variables use mixed-case and begin with a low-ercase letter. Examples: lcdChar, hrs, iCount Constants (including subroutine address labels) use mixed-case and begin with an uppercase letter. Examples: LGear, SndAlrm, DlyTm PBASIC keywords use all uppercase. Examples: FOR, NEXT, GOSUB, RETURN White space (spaces, tabs, etc.) is used liberally to improve the readability of the program. White space has no impact of the size of the compiled (tokenized) program, so feel free to use it. I suggest starting the working code in the first column following a tab and indenting code within FOR/NEXT loops with two spaces.
In conclusion, writing code for your BASIC Stamp is a carefully crafted mix of art and sci-ence. The science part of this process has hard-and-fast rules, and our compilers quickly point out any violation of those rules. The art, however, is purely subjective; there are no rules. Find or develop a coding style that serves you and your programming process. The guidelines Ive presented here have served me well and I hope that you find them useful. And do try the planning tricks that I outlined at the beginning Im sure youll be happily surprised. If you have questions or comments, please feel free to send me an E-Mail.