Hex4 Mac OS
BS2sx, BS2e and BS2p applicationnotes
0xED, HexEd.it, and Hex Fiend are probably your best bets out of the 7 options considered. 'Responsive' is the primary reason people pick 0xED over the competition. This page is powered by a knowledgeable community that helps you make an informed decision. System 6.x - Mac OS 9.2.2 for v1.0.7 / System 9.x - Mac OS X for v1.8.5. It should run fine under: Basilisk II. To date, Macintosh Repository served 1413510 old Mac files, totaling more than 278279.9GB! Downloads last 24h = 928: 174310.4MB Last 5000 friend visitors from all. Is a full-featured Hex Editor for Mac OS X allowing you to edit files of unlimited size and interpret the bytes with dozens of text encodings. IHex is a lightweight and reliable OS X utility that features a smart hex editor, powerful file information viewer and checksum utility, all. Hexnode Partner Summit 2021 registrations are now live.
contents (updated 1/5/2002)
- Examples of crossbank calls
Introduction
TheBS2SX, the BS2e and the newBS2P offer more program memory and moreRAM than the original BS2. The BS2SX and BS2P also offer higherspeed. The BS2P offer a wealth of new commands. including formattedLCD output, support for I2C and Dallas one-sire protocols, and directcross-bank addressing of the entire 16kbyte data space.
The photo shows the gold BS2P in both the 40 pin package with atotal of 32 general purpose i/o pins and the compatable 24 pinpackage which has 16 general purpose i/os..
- The BS2SX, BS2e and the BS2P have 16kbytes of eeprom. Compare that with the 2k bytes of eeprom in the original BS2. The additional memory is capable of holding:
- 8 independent program blocks, think of it as 8 BASIC Stamp II's in one.
- 8 times as much program memory as a BASIC Stamp II, for a larger single program
- general main line program code
- program modules that are branches out from a main program in bank 0
- libraries of routines or subroutines that are 'called' from other banks
- math routines
- device drivers
- data that is generated or retrieved by the main program
- text prompts
- calibration tables
- data log file
- Using the program memory for a single large program takes some special tricks and advance planning. This document describes my own approach to this.
The 2048 bytes of program memory in the original BS2 presents a hard limit. When and if you run up against it, you have a challenge, to say the least, to trim the fat and to rethink your problem to the bare bone essentials. With the BS2SX and BS2e it is possible to build a lot of program machinery and leave it in place for use with different applications, instead of having to re-optimize the whole chip for each new application. The downside is the temptation to get sloppy, to add fat features and bugs that complicate life instead of simplifying it. The bank structure of the chip presents a significant challenge to the design of large, integrated programs.
- The BS2sx, BS2e, and the BS2P have scratchpad RAM for storing:
- rapidly changing variables
- parameters and flags
- pointers
- accumulations, maxima and minima
- tables of data.
- data buffer for transferring information from one program bank to another.
The BS2sx and BS2e have 63 bytes of scratchpad, while the BS2p offers 127.
This is in addition to the 26 bytes of main RAM. The scratchpad RAM can only be accessed via the GET and PUT commands. Only the 26 bytes of the main RAM can be used directly in assignment statements and formulas. The 26 bytes of the main RAM can be accessed as bits, nibs, bytes, and words and can be used directly as named variables in expressions and as the arguments of commands. In contrast, the scratchpad RAM can only be accessed one byte at a time, and the only way to retrieve a scratchpad byte it is by using the GET or PUT command). examples...
Both the main RAM and the scratchpad RAM are conserved when crossing from one bank to another with the RUN command.
- The BS2e (on the red carrier) executes instructions at exactly the same speed as the original BS2. The BS2e uses a Scenix SX28 chip clocked at 20 megahertz like the original BS2. A program that runs on the BS2 can also be run (only changing the file extension to .bse) on the BS2e without having to change any of the timing parameters, such as baud rates and pulse times. That makes it easy to migrate a system to the new chip when the BS2 no longer has the memory capacity for the system software. The BS2e with its SX28 chip requires more average power supply current than the BS2 (21 milliamps vs 7 milliamps), but not nearly as much as the speedy BS2sx (60 milliamps).
- The BS2SX (on the blue carrier) executes instructions 2.5 times as fast as the BS2 and the BS2e. The upside of this is that program execution is faster, and pulse and frequency inputs and outputs have a higher resolution in time. The downside is that the time scale is different than the original BS2. While the BS2sx can sample higher frequencies and shorter pulses with finer time steps, this is gained at the expense of not being able to monitor lower frequencies and longer pulses. Also, some devices, such as the SDI12 hydrology instruments cannot respond to the faster shiftout command speed. There are workarounds in most cases. Another downside of the high speed of the BS2SX, in my book, is that it draws considerably more power supply current (60 milliamps). It's Scenix SX28 microprocessor chip is clocked at 50 megahertz, and the current drain can make the voltage regulator get quite hot. (see below) That is not good for my micro-power data loggers.
- The BS2P (gold carrier) is based on the larger and more capable SX48 chip, running in turbo mode for higher speed and lower power consumption. The BS2P runs at 20 megahertz for timing similar to the BS2SX. The timing is not exactly the same however, because of small differences in the turbo mode. Be sure to consult the Parallax documentation for the exact timing values. These chips have a wealth of new commands, including support for :
- additional I/O pins (32 i/o in two banks of 16 on the 40 pin carrier)
- Dallas onewire protocol
- Phillips I2C protocol
- formatted output to LCD screens
- 127 bytes of eeprom instead of 63
- a polling type interrupt that checks the status of specified i/o pins beteen each and every instruction, and takes action or stores its result in a set of status registers that can be accessed in the scratchpad RAM area.
- a new STORE command that allows access for READ and WRITE to any bank in eeprom from of the program banks. That is my favorite addition.
- a new SPSTR modifier for the SERIN command that allows a program to capture long strings of data (for example, a sentence from a GPS) directly to the scratchpad RAM.
This chip is new, and I expect to have some more timing data on it at a later date. There is rumor that Parallax may introduce a version of the BS2p running on an 8 megahertz clock, for lower power consumption and greater compatibility with the BS2 and BS2e.
Refer to the following parallax documents, free downloads from theParallax web site, forinformation about the BASIC Stamp IIsx and the BASIC Stamp IIe.
I have no problems with it on my normal desktop and Compaq laptop PC running Windoze 95. But I cannot use it on my MacG3 under virtual PC, reason unresolved. It runs, and it will program BS2s, but not any of the multibank Stamps. I also found that I could not program Stamps with it on one cheap Toshiba laptop.
Tip: The installer is a large (3.5 megabyte) program that can be problematic if you do not have a good internet connection. The Stampw.exe program does not really need any of the additional help files or TSRs for its operation. The version 1.3 Stampw.exe is a 1.2 megabyte program file that you can simply install by dragging it where you want. It can be zipped down to 0.5 megabyte.There is also a DOS version of the software, a separate program for each flavor of Stamp. Stamp.exe, stamp2sx.exe, stamp2e.exe and stamp2p.exe. Please see below for a side by side procedure for using the DOS or the Windows software to load a program into the BS2sx.
Frequently asked questions
Example BS2SX test program, showing variable allocation |
---|
People who have never used the BS2SX before are often confused bythe process of loading programs into the different banks, and by theprocess of defining variables and passing control from one programbank to another. The BS2SX documentation comes with a short demoprogram, but it is a little too short to illustrate all theimportant features. Here is an alternative demo program that showsmore about passing variables in the RAM and in the scratchpad ram,and also how to define the convenient headers that tie together aBS2SX 'project' within the STAMP2W.EXE software.
Program for bank 0. Name it, 'TESTSX.BSX'. Notethe $STAMP directive that sets up a multi-bank project. The directiveis understood only by the STAMP2W.EXE software, and is ignored by theDOS version, STAMP2sx.EXE software. Use $STAMP BS2e for those BS2eprojects, with file extensions '.bse'.
Program for bank 1. Name it, 'TESTSX1.BSX'. Thispart of the project displays the values initialized in bank0 or thevalues recalculated in bank2. This does not require the $STAMPdirective. It is just put here for reference.
Program for bank 2. Name it, 'TESTSX.BSX'. Thisrecalculates values, and then jumps back to bank 1 to displaythem.
Using the DOS and Windows software with the BS2SX and BS2e |
---|
The way to load and run the program depends on which version ofthe software you are using.
- DOS, STAMP2SX.EXE or STAMP2e.EXE or STAMP2p.EXE
- Enter the first program above, press ALT-0 to target bank0, then press ALT-R to send the program to bank0 of the BS2SX and to run it. But it won't get very far, past the message 'testing bank 0', because you haven't yet entered the second and third programs. Do that now. Save the first program under the name 'testsx0.bsx'. Now you can type in the program for bank1, or modify the first one. When finished, Save this program as 'test1.bsx'. Press ALT-1 to target it to bank1, and press ALT-R to send it and run it. You should see the 'testing bank 0', followed by a printout of the initial values. Then, you guessed it, type in the program for bank2, and save it as 'test3.bsx'. Press ALT-2 to target it to bank2, and press ALT-R to send it and run it. Now you should see the whole action. It should go into a repeating pattern as the program alternates between bank 1 and bank 2. Pressing the reset button always runs the program in bank 0 first. It doesn't matter what you name the programs. There is no real association between them, except in your own planning. Any time when you load in a programs, one at a time, you must press the correct ALT-n command to target the program at hand to the proper bank, n, before you press ALT-R to actually send and run it. You can use an extension other than .bsx, but if you do, the dialog that comes up when you press ALT-L to load a new program will not display the files that do not have the .bsx extension.
- WINDOWS, STAMP2W.EXE version 1.1
- In the menu for preferences/editor operation, tell it you will be editing a BS2SX program in the dropdown menu. Also tell it to use either the 'all' or the 'modified' option for program download in another dropdown menu. Enter the first program in one window, then the second and third programs, each in a new window. Save and name the programs with the specific names that appear in the $STAMP directive above, using the .BSX or .BSE extension. These names above are test0.bsx, test1.bsx, and test3.bsx. Now you can close all of the programs. Now open the program for bank0, 'test0.bsx'. If you have entered the $STAMP directive correctly with all of the associated file names, then all three windows should pop up automatically. You have a 'project' consisting of three windows for the three banks. When you press CTRL-R or choose RUN from the menu, all three of the programs will be loaded into the BS2SX, and will run from the start of program 0. When you choose to quit or to close one of the programs, the editor will ask if you want to close all of the windows, because they are now part of a unified project. Note that if you want to create a program for bank 2, you first have to create programs for banks 0 and 1. If you want to leave a bank with nothing in it, you at least have to enter one dummy statement, like DATA 0, or the editor will not allow you to tokenize the programs.
- WINDOWS, STAMP2W.EXE version 1.3
- This is the same as version 1.1, but it insists that you put in the $STAMP directive to identify the type of stamp you are working with, and it does a good job of checking on what kind of stamp is actually attached to the serial port. This version also has the capability to create a self-standing loader routine, that can be used to encapsulate a Stamp program as an executable that can program a stamp or a stache at a remote site, without need to see the program code or to mess with the main program settings. Great for OEM users of the stamp.
The information about programming the BASIC Stamp 2SX, 2e or 2pused to be spread between the thin hardware manual, which containsinformation about the DOS software, and the thin manual for theWindows version 1.096 of the programming software. The latest versionof the manual is 2.0, which covers all of the Stamps, including thenew BS2P. The
It is important to name the program you load with the properextension for the stamp being targeted. You have three choices:
- program.bs2
- program.bsx
- program.bse
- program.bsp
Every program associated with a BS2sx or BS2e or BS2p projectshould have the appropriate extension attached. Once you give aprogram a name, with one of those extensions, then it will alwaystarget the correct flavor of stamp when you go to run the program. Inthe windows software that is regardless of the setting for defaultstamp type under the editor operation tab.
The default stamp type under the editor operation tabapplies only to new programs that you have just created and not yetnamed and saved to disk, or to programs that do not have one of theabove extensions, .txt for example. Once a program has one of theabove extensions, the extension overrides the default setting. Thus,you can have programs targeted to different flavors of stamps open inthe editor window at the same time, and STAMPW.EXE will attempt toconnect to a stamp based on the file name extension at RUN time. Ifthe type of stamp connected does not match the file extension (or thedefault setting if applicable), then the editor will return an errormessage that the 'Stamp of type xx has not been found'.
The directive {$STAMP BS2..,....,} has an even higher priority.That is, if a project has a directive that says the project is for aBS2e, and the program is named with the BS2 extension, it is the$STAMP directive that will take precedence, and the file extensionwill be ignored. Of course, it is a good idea to keep the file namesand the stamp directives consistent with one another. It is a goodpractice to include the $STAMP directive, now that there are so manyflavors of stamps available. The version 1.3 STAMPW.EXE IDE enforcesthe consitency of the $Stamp directive.
Defining 'global' and 'local' variables in RAM and Scratchpad |
---|
People often ask how to define variables that are to be sharedbetween banks in the BASIC Stamp 2SX or 2e when the programs getlarge and complicated. There are a couple of ways to do this. Iprefer to take advantage of the automatic variable allocation thatthe STAMPW compiler provides. Declare enough variables as words firstto accommodate all of the shared variables, and then create aliasnames for parts of those words to define shared bytes, nibs and bits.That puts all of the shared 'global' variables in the first few wordsof memory. Then 'local' variables can be defined for each bank asneeded. They take whatever ram is left above the 'global'variables.
It is important to understand that this works because the Stampalways allocates space for all the words you define in a program, inorder, before it allocates space for bytes, then nibs, then bits. Youcan see this in the memory map of RAM that comes up when you hitCTRL-M. For example, if you have define a word, then a byte, thenanother word, the two words will still come first in memory, beforethe byte. If in another bank you need to define another word, it willslip in under the byte. However, if you define a word, and thendefine the byte as an alias name for part of that word, you can counton it staying in the same place in memory. That is, if you define thesame essential words in the same order in each and every bank.
No matter how you cut it, when you get deep into programming theBS2SX, you have to think very carefully about how the variable spaceis allocated. It requires a very different way of thinking from thevanilla BS2.
For example, here is the start of the variable headers for oneparticular program. Note that there are three words defined, sxw,appw, and datpnt. Then by using aliases, the first two of these wordsare parsed into numerous named bytes, nibs and bits. Each of theseparts serves some definite purpose (or in some cases multiplepurposes) in the programs running in the different banks. Forexample, the config byte contains 8 one-bit status flags that arepassed without change from bank to bank.
Note in thinking about the above, where the STAMPW locates thevariables. If you were to define these bits directly, e.g.
instead of as aliases inside a word variable, the STAMPW compilerwould move them up to the end of the variable space. It would putthem after all of the words, bytes, and nibs. Adding any additionalwords, bytes or nibs would move the position of those bits in memory.In contrast, by defining the bits as alias names inside a word, wecan be assured that they will stay put. The STAMPW compiler alwaysputs the word variables in RAM first, in the order that they aredefined.
Hex4 Mac Os Update
Another alternative for working with global variables is to usethe fixed variable names that are defined by STAMPW to refer to thelocations in physical memory. (manual v1.9 page 214). For example,w12 is a predefined name that refers to the last word in the physicalmemory, and b25 similarly refers to the last byte. You can use thosepredefined names to put the 'global' values at the end of memory.Then use the normal method to define the temporary variables thatwill be local to each bank. When you need to define nibs and bits,you still have to use aliases, for example,
Keep in mind that the automatic variable allocation will not payany attention to your use of the fixed variables. If you go ahead anddefine 13 words in a program, that last word will quite happily existright on top of w13 with no warning that there is an overlap.
Scratchpad RAM |
---|
The scratchpad ram is shared between all of the BS2e and BS2SXprograms. Here is an example of variable definitions from oneprogram. Note that the addresses are absolute byte addresses, from 0to 62. The STAMP2W compiler does not do any kind of automaticallocation in the scratchpad area.
As with the ram variables, if you want to use the same definitionsin several banks of a BS2SX or BS2e project, you have to type in orcopy the same list of variable definitions at the top of each programin the project. And if you make any changes in the list, you have tomake that same change in all the banks. (It sure would be handy tohave an INCLUDE directive in PBASIC!)
The scratchpad buffer is used extensively to transfer data betweenbanks. For example, a program in one bank can READ bytes from eeprom,and PUT those bytes into a buffer in scratchpad RAM, and then RUN aprogram in another bank, which can use those bytes in some way.
The scatchpad can also be used as a stack, for advanced bankswitching applications. More below.
Crossbank 'calls' |
---|
The BS2SX has 8 separate program banks. The RUN ncommand allows a running program to jump from bank to bank. Theexample above shows how a program running inbank zero can run or chain to a program in bank 1. The exampleassumes that there is only one program in each bank. If there is morethan one, life is more complicated. What if you want a program tojump from a point in the middle of one bank to a point in the middleof another bank, do something, and then return back to the first bankto continue where it left off. The RUN command by itself does nottake care of the details of getting there and back and it does notallow for the possibility of more than one destination in eachbank.
Here is an approach that works for what I do. Something like thisis pretty much essential if you want to look at the 16kbytes ofprogram memory in the BS2sx or BS2e as space for one big program, asopposed to just 8 independent 2kbyte spaces that do not need tointercommunicate.
- a) routine in one bank needs to call a routine in another bank. It puts the return index on the stack, and loads the pointer to the target routine into a special variable, and issues a RUN command for the bank where the target program exists. This bank number and index are known in advance as part of the programming ritual.
- b,c) the RUN command begins execution in the target bank. A branch instruction looks up the index to take program execution to an actual address for the target routine.
- d,e) the target routine executes, then pulls the return index and bank number off the stack, and RUNs the return bank.
- f,g) the RUN command begins execution back at the first bank, where a branch instruction looks up the return index to branch to the address to continue program execution.
- h) the program resumes execution where it left off.
I use the word 'call' loosely. The RUN command trashes the BS2SXsubroutine stack, so I have implemented a supplementary return'stack' using a byte #62 in the scratchpad memory area. This is onlya one level stack. Okay, it would be possible to implement a deeperstack, but, hey! KISS. Also, I have limited the cross-bank 'call' to16 possible labels in each bank. So far I haven't needed more, butthis number is very easy to expand using an additional variable. Aspecial byte in RAM holds in its low nibble the number (0-->7) ofa target bank, and the same variable also holds in its high nibble anindex for a target routine. When the program finds itself booting upin a new bank, a BRANCH instruction takes execution to a routinepointed to by that variable. On return from a 'call', the contents ofscratchpad byte #62 is moved into that same special RAM variablebefore the RUN instruction is executed.
In the BASIC Stamp the contents of both the main RAM and thescratchpad RAM are preserved through the RUN instruction. So programsrunning in different banks can share those variables. There areprecautions you must take when defining variables in the differentbanks, so that the important ones will the same in all the banks.Discussed above.
When you reset the stamp or power it up, all RAM is zeroed. Whenthe program finds itself booting up in bank zero, from a power up,then the designated branch variable will equal zero. In the schemethat I use, that takes the program into its initializationroutine.
You cannot use a crossbank calls from within a subroutine. Allcrossbank calls have to be made from the main program level. The RUNcommand trashes the subroutine stack. The RUN command also trashesfor-next logic. You can not use these crossbank calls from within afor-next loop. You can always work around that limitation by makingyour own for-next logic in program code.
Here is a bare bones example of how the above is implemented.First the program for bank 0:
Now the program switch1.bsx for bank 1:
Hex4 Mac Os Download
The call always involves putting some value on the 'stack', whichhere is just one byte, 'sxret', a variable in RAM (or, could usescratchpad RAM instead, see below). Also the preparation for the callputs the desired target address into the variable 'sxgo'. The highnibble of sxgo, which is named, 'sxrun', holds the bank number, whilethe low nibble, named 'sxgo2', holds the index of the routine to runonce we arrive at the other bank. Now the Stamp executes RUN sxrun.The Stamp switches over and starts executing code in the new bank.The contents of the variables in RAM and scratchpad RAM areunaffected. The first command in the new bank is a branch, which usesthe low nibble of sxgo to branch to the specified target address inthat bank. The the low nibble of target is an index, not an actualaddress. The branch commands maps the index to an actual address. Theroutine at the target address executes. At its completion, it movesthe value from 'sxret' into the bank-switching variable sxgo, then ithits the command, RUN SXRUN. That causes the Stamp to start executingcode in the original bank. And the branch instruction there takes theprogram back to the predetermined target address.
The programs can to put whatever address on the stack. It does nothave to be a return to continuing code. It can branch to some thirdlocation, or it can cause a reset to the program top, or it can chainto a program in a different bank.
I usually put the return address in the scratchpad RAM. In thatscheme 'stack' is an address in the scratch RAM, and the operation isa PUT in the main program and then later a GET in the secondprogram.
Remember that crossbank calls cannot be done from withinsubroutines nor from within for-next loops. Well, they can be done,but the stack or nesting will not be preserved. If a repeating loopis necessary with a cross-bank call, the index and loop must bemanaged as an ordinary variable.
The overhead for the bank switching takes execution time. The RUNcommand on the BS2sx requires 350 microseconds, and a whopping 875microseconds on the BS2 or BS2e. That combined with the BRANCHcommand and the other setup instructions makes the whole sequencetake a couple of milliseconds. Does that matter? Maybe, maybe not. Iftiming is tight, minimize the number of transitions from bank tobank. Accumulate information in a buffer and then transfer it all atonce with one cross-bank call, instead of making a series ofcross-bank calls for each individual item. That applies to datalogging for example. To get the fastest execution time, it is betterto duplicate commonly accessed routine in several banks and thusavoid the cross-bank calls. For example, if code in several banks hasto read a real time clock or external memory, it may be better toduplicate the necessary routines in all the banks that need them.Break programs into units that can stand pretty much on theirown.
Crossbank 'calls' using a scratchpad stack |
---|
It is possible to extend the logic to use a true stack pointer. Iset aside the first byte in RAM as a stack pointer, and the secondbyte as the cross-bank variable.
Also, in the scatchpad RAM, I set aside an area to be used as astack, and initialize the stack pointer to point to that address:
When calling a new bank, the return address (as above) is put atthe address in spRAM specified by the stack pointer, and the stackpointer variable is then decremented to reference the next free stacklocation. On return from the call, the return address is popped fromthe stack and the pointer incremented. This is potentially moreversatile, as it can be used for data as well as for returnaddresses.
- Nested crossbank calls are possible.
- Variables or parameters can be passed systematically from one bank to another and back again via the stack.The stack can hold up to 60+ bytes, unless some of the scratch ram is required for other purposes.
- The stack ceiling can be dropped at run time, to allow for dynamic allocations.
- Some kinds of sub-programs need a lot of variable space in main RAM, and use it in a manner inconsistent with the main program. Examples are reception of long GPS sentences into RAM (pre BS2p), or a sensor that requires complex mathematical data processing to crunch its data and return a result to the main routine. Instead of dancing around coordinated variables between the banks, some or all of the contents of main RAM can be saved systematically on the stack, then the new program can use the main RAM in its own way, and then before returning, the original variables can be restored. This makes the operation of crossbank calls quite transparent. The only shared variable in the main RAM is then that first word, WSX, which contains the stack pointer byte and the crossbank address byte.
- The use of the stack mechanism can make such program units more secure. You may want to plug in a sensor 'driver' or some such thing without having to rethink the whole scheme of variable assignments in main RAM or without showing the code to the recipient.
On the down side, all of this bank-switching and stack mechanismdoes require a lot of extra execution time in the Stamp and a modestamount of additional code. There are extra steps required to managethe stack pointer. The process of storing and restoring many bytes ofdata can eat up 10s of milliseconds. But that may not matter incomparison to the great transparency of operation it affords, andthose milliseconds are nothing in some applications. Moreover, thestack mechanism demands extra programming and debugging care. Thestack mechanism is not handled automatically (as it is in manymicros) by the Stamp, and the IDE does not help with error messages.Rather, managing the stack is uniquely the responsibility of theperson doing the programming. It is easy to make mistakes with thestack pointer and have confusing overruns. In practice, each programrequires ad-hoc adjustments to the technique with tradeoffs betweenspeed and maintain-ability.
There was an extended discussion on the stamps discussion listabout this between myself and Peter Verkaik and others in May, 2001.Peter's take on this issue is posted on the FAQ at http://www.wd5gnr.com/stampfaq.htm.
The following is a demo based on the ideas presented in theprevious section. This demo switches to bank 1 to input a string fromthe serial port, or user keyboard, which is burned into data eepromin bank 1 before returning to bank 0. The program in bank 1 saves theentire contents of main ram on the stack before it does the serialinput. Imagine the need to receive a string of data quickly, as forexample, a GPS sentence. The entire main ram is needed to receive theserial string of length up to 24 bytes. The bank 1 routine restoresthe 24 original variables before it returns to bank 0. A secondroutine in bank 1 is xbank-called from bank 0, to display the storedmessage.
In the above 'getmsg' routines, when saving and restoring thevariables, I referred to the absolute variables b2(). That alwaysrefers to the third and successive bytes in the main ram. I couldjust have well used char() there. But this way emphasizes that savingand restoring operations on the stack really have nothing to do withthe naming or use of the variables.
Example of cross-bank calls, double precision math library |
---|
The following demo sets up several math routines in bank 1, sothat a program running in bank 0 can call them. The main program inbank 0 simply asks the user for two double precision numbers asinput, and prints out the results of addition, subtraction,multiplication and division. Please refer to a separate article forexplanation of the double precision mathroutines. The division is limited to divisors less than $7fff,and not zero, so the routine returns an error message in thescratchpad RAM if there is a problem there.
In the following program there are references of the form,'xdpmul', and also references to the same namewithout the 'x' , 'dpmul'. For example, thevalue of xdpmul is $21, which means that it is thesecond crossbank routine in bank 1. dpmul is the actualaddress of that routine in bank 1. The index is used to connect tothe actual address in the crossbank call.
Enter the following program, and name it'xbc1.bsx'. {'xbc1.bse' if you are using abs2e}. The crossbank logic is shown in red. There is a second programlisting below. 'xbc0.bsx', which has to go into bank0.
Note that this routine uses an spRAM location for its stackvariable, and the convention for the return addresses differs alittle from the previous discussion. Same general idea. There aremany ways to implement this and a lot depends on the specifics of theapplication, not to mention the whims of the programmer.
Enter the following program for bank 1, and name it'xbc0.bsx'. Or use 'xbc0.bse' if youare using a bs2e. This is the main bank 0 program that will call themath subroutiines.
Example of cross-bank calls, Stamp eeprom for data logging. |
---|
Hex4 Mac Os Catalina
The BS2e is a natural canditate for a small data logger, becauseof its extra banks of memory. The data logging program can reside inone bank, while the remaining memory serves to hold the acquireddata. The catch with the BS2e and BS2sx is that there is no way toput data directly into any bank other than the one that is currentlyrunning a program. The only link between banks is the RUN command,and and data to be transferred between banks must take the ride as avariable in either the main RAM or in the scratchpad RAM. Therefore,each bank that is going to hold data must also contain a smallroutine capable of writing the data and reading it back, and themechanism of crossbank calls.
Note: TheBS2p does not need the crossbank callsthat were necessary with the BS2e and BS2sx. It has a newlyintroduced STORE command that gives direct access to eeprom for datastorage in any bank, even from a program running in a different bank.Programming a data logger for the BS2p ismuch simpler and does not require crossbank calls.
But here is a demo program that shows how to do it with the BS2eor BS2sx. Te data to be entered will come from a DS1620temperature sensor. Banks 1 to 7 will hold data, and also thesmall but necessary interbank data transfer program. The time is setby the modestly accurate sleep timer. A fully developedimplementation of the data logger would have more than one channel ofdata to be logged, more accurate clock, etc etc.
A simple BS2 data logger using the DS1620 is to be found in unit 6of Earth Measurements from theStamps in Class series. The DS1620 here is the same as the onethere.
One big issue for a Stamp data logger is 'where to store theaddress pointer'? This is the address of the location in memory wherethe next data value will be stored.
- One obvious approach is to use a RAM location. The disadvantage of this is that the values in RAM are lost if the Stamp is reset or loses its power. If the Stamp has an external chip with battery backed RAM, such as a real time clock chip, that could be used to hold the address value.
- Another option is to use an eeprom location. The problem there is the possibility of wearing out the eeprom from overuse of one location. Each location in eeprom is good for maybe 1 million write cycles. At one WRITE per second, it only takes 12 days to arrive at 1 million. Overuse is not so much of a problem for the data itself, because presumably the data will be spread out over the whole memory so that no one location is overexercised. However, that is not true of the address pointer itself. It has to change every time a new entry is made into the data log.
- One way around this is to 'erase' the data in the log file completely by making all bytes some particular 'erased' value that can be distinguised from real data. For example, that could be an $FF, where the data is bytes restricted to 0 to $FE. Then, when the program starts up it can scan the memory to find the first instance of $FF and that is the first free byte. The scan can be made quite fast, with binary tree search. However, it takes quite a bit of time to erase the whole stamp memory (at about 5 milliseconds per bytes * 14000 bytes = 70 seconds).
- There are other ways to 'mark' the data records to distiguish one run from the next, that do not involve erasing the entire memory. For example, one bit or a few bits can be reserved in each record and used as a sequence number to distiguish different runs of data. This method too calls for a method to scan the memory at startup in order to restore the pointers.
- Another option is to keep the address pointer in one area of memory, but move it around from time to time. For example, it can be moved at the beginning of each new run. One memory location stores a pointer to the actual address pointer, which in turn points to the next free memory location. The wear can be spread out over a couple of hundred eeprom locations. It does take some programming overhead to implement this, but it has some other advantages.
- Yet another approach is to use an external memory chip that can be easily replaced!
All said, the following program cops out and simply uses RAM forthe address pointer. You start an experiment, and the logging loopruns until it collects the allotted number of points, then it stopscollecting data. When you reset the stamp, it asks via the debuginterface if you want to read the data. Yes? It spits out the datafrom the beginning of the log up to the allotted number. If theexperiment does not run for the full time, enough to fill the wholememory, then data displayed at the end will belong to a previous run.There are many ways to work around that. The point here is just toillustrate the mechanism of cross-bank calls for data logging andretrieval.
The data is stored in banks 1 to 7. The address pointer goes from0 to 13300 (7 banks at 1900 bytes per bank, with 148 bytes reservedfor the crossbank program). The bank to jump to is determined by acomputation, by dividing the address by the number of bytes allottedper bank. The address within each bank is then the remainder from thedivision. For example, if the address is currently 9753, then thebank number to read or write to is 5 (=9753/1900), and the address toaccess within that bank is 253 (=9753//1900).
For a change, the 'stack' in this short program is just a variablein the main ram, instead of in the spRAM. Same idea. It is theaddress to return to after a call. This program does not need a fancystack mechanism. The logger sleeps 10 minutes between readings.
The following code is for bank 0:
And the following code is for banks 1 to 7. Copy this code forall banks from 1 to 7, just name the files dlogger1.bse, dlogger2.bse... dlogger7.bse.
Here is the core of the same program, forthe BS2p. The big difference is that the little programs in banks 1to 7 are no longer necessary. The STORE command accesses the data inall those banks directly from the program running in bank 0.The READ and WRITE commands take an argument inthe range of 0 to 2047 just as with the earlier Stamps. But the STOREcommand changes the bank referred to. Since no memory in the otherbanks is needed for program, all 2048 bytes can be used for data, atotal of 14336 bytes (7*2048).
How the OWL2e uses Crossbank 'calls' to script data acquisition |
---|
My OWL data loggers make lots of use of crossbank calls. Separatebanks are dedicated to initialization and user input, to scanning theinput channels, to the memory and clock routines, and to the driversfor different types of sensors and processes.
Several of the core routines are repeated in each bank. Forexample, it is more convenient to repeat the routine that reads theclock and some of the eeprom routines in a couple of banks, ratherthan having to do a crossbank call to access them in anotherbank.
Here is an example of a use of the bank switching, as implementedin the OWL2e data logger. A main program loop reads data from a tablein eeprom. The table consists of multiple records, linked by avariable length offset.
Each record holds all the information necessary for one action tobe taken by the program. These actions are performed in sequence asthe table is scanned by the main program. The records in the currentincarnation can be from 3 to 13 bytes long, depending on how muchinformation is necessary to perform the action.
An action might be something like reading a temperature from acertain channel. The information needed will be the reference to a'driver' that runs in order to acquire the temperature, the channelnumber to which the sensor is attached, and perhaps calibrationfactors, format specifiers, units of measurement and so on. There aredifferent drivers for different types of sensors andactions--humidity, rainfall, windspeed, thermostat etc.
The main program loop that scans the table is relatively short andresides in bank 1, the same bank as the scan table itself.
The low nib of the first byte of each record specifies the lengthof the record, which is the same as the offset to the start of thenext record. (It would be better to have longer records, but thelength is limited by need to transfer information by way of the RAMor scratchpad RAM buffer. The new BS2P has a STORE command that makesit easy to access the scan table from a program running in anyprogram bank, so the scrachpad RAM or regular RAM will not benecessary to transfer this data.)
The high bit of the first byte flags the 'often' option. Someactions have to be performed every time around the loop (~1/second).This includes things like averaging and scanning rain gages. Theoften bit allows the program to run more efficiently and at a lowerpower consumption by skipping drivers that do not need the frequentattention.
The remaining three bits of the high nibble specify how many bytesof data this driver will put into the data buffer. This can be fromzero to 7. This is a data buffer that is maintained in the scratchpadRAM. This not only includes data that will be put into the log file,but also intermediate data such as counts and averages.
The program reads in the first byte of the scan table, and thendetermines if it needs to read more at this pass. If not, it simplyjumps to the next record and moves the data buffer pointer up by thespecified amount. If the program determines that it is time toexecute the full routine, it has more work to do. It reads in thesecond byte of the record. This is an index for a crossbank call,exactly as outlined in the previous article. It contains the banknumber and a branch address of a routine that will acquire andprocess the data from a certain sensor, or take some other desiredaction. That byte is read into the variable sxgo.
The rest of the parameters (1 to 11 of them) in the record areread into a buffer in RAM. The return address is PUT onto the'stack', and then a RUN command is executed to transfer control tothe driver routine in another bank. The driver routine does itsthing, expecting to find the parameters it needs in the RAM buffer.When the driver is finished, it GETs the return pointer from the'stack' and returns to the original bank where the main program loopcontinues with the next entry in the scantable.
The point of this scenario is:
- the operation of the program can be changed without doing any PBASIC programming. A change from one set of sensors to another is done entirely by changes to the table. The entries in the scan table can be made by a special program module that takes user input and enters it in the table.
- the drivers can be written to fit into this scheme, without rethinking the design of the entire program.
The other common parameters in a script record are:
- format byte(s): how data for this action will be formated. For example, the data might be displayed with two digits after the decimal point. The format where the data is to be displayed (log file, serial port, LCD screen).
- channel number: where data for this action will come from.
- units: units of measurement to appear on column header.
- calibration constants: offset and slope constants.
Operating and sleep current |
---|
The first question I had about the BS2SX and BS2e concerned theirpower consumption. My OWL2c data loggers are designed for operationin remote sites for extended periods of time, almost always from asmall solar panel, or from a small 1.2a-h gel-cell battery only. Thelogger can sleep much of the time, but needs to wake up at intervalsof ten seconds or so to take readings and to perform other tasks. Theoverall current drain and battery life is determined by the percenttime spent in the low current sleep mode and vs the high currentoperating mode.
The situation is complicated by the fact that, in the sleep mode,the Stamp wakes up once every 2 seconds (approx) to check its status.So for example if the SLEEP 10 command is encountered, the Stamp willwake up very briefly at 2, 4, 6, 8 and 10 seconds to check its statusand at the 10 second point it will stay awake and continue with thecommand after the SLEEP command. So during the sleep mode, there aretwo components to the current. One is a microamp level sleep current,punctuated by much higher operating current for the status check. Thetime average of those is the 'averaged sleep current'.
Here are my results from my first batch of 11 BS2sx' from thefirst (blue-board) production run. These were powered from a 6 voltgel cell with a terminal voltage of 6.4 volts. There was a shottkydiode in series with the battery connected to pin 1 of the BS2SX, theVin terminal. All of the user pins were configured as LO outputs,with no external connections. The currents were measured with a 4.5digit ammeter in series with the power supply lead. The timing wasmeasured using an analog scope triggered on the power supply currentspike. The program is listed below.
Hex4 Mac Os X
A word is in order about the last three items, leading to theaverage sleep current. The BS2SX in executing the SLEEP or ENDcommands wakes for 16 milliseconds, once every 2.15 seconds, to checkits status. During this mode the BS2SX draws 65 milliamps for 0.74%of the time (0.016/2.15), and it draws 46 microamps for 99.26%(2.144/2.15) of the time. The average current drain in thesemodes is thus
0.0074*65+0.9926*0.046 = 0.527 milliamps.
This value may change as temperature of the chip changes. The abovedata was taken at a temperature near 25°C.
The ideas in the previous paragraph are true of the non-turbo BS2as well, with its PIC processor running at a cool 20 mhz. But the BS2operating current is 7 milliamps, and the sleep current is 30microamps, giving an averaged sleep current of around 80 microamps.Actually the averaged current is near 50 microamps, because for somereason the PIC does not draw the full 7 milliamps when it wakes upfrom sleep to check status--it only draws about 2 milliamps then.
The above results were found by running the following program:
See here for a table comparing thepower supply drain of the different stamps.
Hot LT1121 regulator |
---|
Summary of the features of the LT1121CS8-5 regulator.
- Marked '11215' on the chip. or is it 121A5.
- Maximum input voltage: +/- 30 volts.
- Maximum output current before limiting: 150 milliamps minimum.
- Short circuit limited and temperature protected.
- Input can be at zero volts and output at +5 volts, with only 16 microamps reverse current.
- Minimum quiescent current ~ 30 to 50 microamps at Iout = 0.
- Ground pin current ~ 6.7% of output current.
- Power dissipation = Iout * (Vin - Vout) + Iout / 15 * Vin
- Maximum junction temperature: 125°C
- Thermal resistance junction to ambient with minimal heatsink: 125°C/watt.
- Critical power dissipation (125°C Tj) at 25°C ambient: 0.8 watt.
- Critical power dissipation at 50°C ambient: 0.625 watt.
The power rating is what I wanted to get to. What is the totalcurrent that can be supplied by the onboard regulator before it goesinto a limiting mode? The current supplied by the regulator is thesum of the 65ma base operating current for the Scenix processor, plusthe current sourced by the output pins, plus any additional currentdrawn by outside circuitry.
The first production run of the BS2SX used the LT1121CS8-5 voltageregulator, and I understand that future runs will use the improvedLT1121ACS8-5, which has a better thermal coefficient.
The following table considers three possible power supply voltagesapplied to pin 1 of the LT1121A or the LT1121. The body of the tableshows nominal output current at which the critical power is exceeded,for ambient temperatures of 25 deg C and 50 deg C. It assumes athermal coefficient of 131 degrees C per watt for the LT1121CS8-5,and thermal coefficient of 74 degrees C per watt for theLT1121ACS8-5.
The BS2SX draws 65 ma. It would not be prudent to draw more than75% of the limiting current. The table is a guideline for maximumallowable current. The above figures are liberal. The regulator onthe BS2sx is provided with hardly any heat sink at all, so theassumed thermal coefficient may be a bit too high. If you need highercurrents and high supply voltages, it would be good to use apreregulator or other means to keep the supply input voltage tobetween 6 and 9 volts.
The BS2e only draws 22ma while operating, so the power demand theregulator is much, much less a consideration unless it has to driveexternal loads or operate from a high input supply voltage.