commit 507f2aedbc90be01d1c58b88a3b836add77036d7
Author: jdreichmann
Date: Sun Jun 23 14:56:45 2019 +0200
Initial commit after migrating repo and assuring the product launches
diff --git a/.classpath b/.classpath
new file mode 100644
index 0000000..eee8c20
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ae3c172
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/bin/
diff --git a/.project b/.project
new file mode 100644
index 0000000..7dbb771
--- /dev/null
+++ b/.project
@@ -0,0 +1,28 @@
+
+
+ pbi-ide
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+ org.eclipse.pde.ManifestBuilder
+
+
+
+
+ org.eclipse.pde.SchemaBuilder
+
+
+
+
+
+ org.eclipse.pde.PluginNature
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..0c68a61
--- /dev/null
+++ b/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/.settings/org.eclipse.pde.core.prefs b/.settings/org.eclipse.pde.core.prefs
new file mode 100644
index 0000000..4b08937
--- /dev/null
+++ b/.settings/org.eclipse.pde.core.prefs
@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+pluginProject.extensions=false
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..3a10b8a
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,23 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Elias Groll, Johanna Reichmann
+
+For further contributers, see CONTRIBUTORS.md
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..bb0a9fb
--- /dev/null
+++ b/META-INF/MANIFEST.MF
@@ -0,0 +1,17 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: πBASIC IDE
+Bundle-SymbolicName: edu.fichte.pbi.ide;singleton:=true
+Bundle-Version: 1.0.0
+Bundle-Vendor: FICHTE-GYMNASIUM
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ com.github.eliasgroll.pbi.interpreter;bundle-version="1.0.0";resolution:=optional,
+ org.eclipse.e4.ui.model.workbench;bundle-version="1.0.1",
+ org.eclipse.ui.intro;resolution:=optional,
+ org.eclipse.ui.editors;resolution:=optional,
+ org.eclipse.osgi;resolution:=optional,
+ org.eclipse.jface.text;resolution:=optional
+Bundle-ActivationPolicy: lazy
+Bundle-Activator: edu.fichte.pbi.ide.Activator
diff --git a/PBI-IDE.launch b/PBI-IDE.launch
new file mode 100644
index 0000000..148c66a
--- /dev/null
+++ b/PBI-IDE.launch
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/build.properties b/build.properties
new file mode 100644
index 0000000..e6fd9b9
--- /dev/null
+++ b/build.properties
@@ -0,0 +1,20 @@
+source.. = src/
+output.. = bin/
+bin.includes = plugin.xml,\
+ META-INF/,\
+ .,\
+ icons/,\
+ splash.bmp,\
+ help/,\
+ plugin_customization.ini,\
+ contexts.xml,\
+ bin/,\
+ config/
+src.includes = plugin_customization.ini,\
+ icons/,\
+ help/,\
+ contexts.xml,\
+ bin/,\
+ splash.bmp,\
+ config/
+jre.compilation.profile = JavaSE-1.7
diff --git a/config/ca.cfg b/config/ca.cfg
new file mode 100644
index 0000000..1f01e9e
--- /dev/null
+++ b/config/ca.cfg
@@ -0,0 +1,64 @@
+## This is the configuration of the interpreter's content assistance.
+## You can comment something by starting a line with ## .
+## You can freely add/remove/modify by adding/removing/modifying a line.
+## A line is build like this: keyword->replacement
+## You can start the content-assistance by CTRL+SPACE.
+## It is only executed if you're at the beginning of a line and if there is no other match with a keyword.
+## You can use /CR to define a new line in a replacement.
+
+ SOUND -> SOUND port, (freq, time)
+ SD -> SOUND port, (freq, time)
+ HIGH -> HIGH port
+ LOW -> LOW pin
+ OUTPUT -> OUTPUT port
+ OP -> OUTPUT port
+ PAUSE -> PAUSE time
+ PS -> PAUSE time
+ GOTO -> GOTO label
+ JMP -> GOTO label
+ IF -> IF expr THEN label
+ END -> END
+ GOSUB -> GOSUB sub
+ SUB -> GOSUB sub
+ RETURN -> RETURN
+ FOR -> FOR counter = start TO end/CR'some content/CR NEXT
+ LOOP -> FOR counter = start TO end/CR'some content/CR NEXT
+ WHILE -> loop:/CRIF expr THEN end/CR'some content/CRGOTO loop/CRend:
+ DOWHILE -> loop:/CR'some content/CRIF expr THEN loop
+ NEXT -> NEXT
+ DEBUG -> DEBUG args
+ DB -> DEBUG args
+ DG -> DEBUG args
+ SAY -> DEBUG args
+ BREAKPOINT -> BREAKPOINT
+ BP -> BREAKPOINT
+ SYMBOL -> SYMBOL ref = var
+ LOOKUP -> LOOKUP index, (val0, val1)
+ LU -> LOOKUP index, (val0, val1)
+ LD -> LOOKDOWN target, (val0, val1)
+ LOOKDOWN -> LOOKDOWN target, (val0, val1)
+ POT -> POT pin, scale, var
+ PULSIN -> PULSIN pin, state, var
+ PINS -> PINS=%00000000 'ports 76543210
+ POUT -> PULSOUT pin, duration
+ PULSOUT -> PULSOUT pin, duration
+ LET -> LET var = val
+ = -> LET var = val
+ INPUT -> INPUT port
+ IP -> INPUT port
+ ASSERT -> ASSERT exp
+ CHECK -> ASSERT exp
+ ACTIVATEINFO -> ACTIVATEINFO
+ AI -> ACTIVATEINFO
+ DI -> DEACTIVATEINFO
+ DEACTIVATEINFO -> DEACTIVATEINFO
+ BRANCH -> BRANCH offset, (label0, label1)
+ NAP -> NAP time
+ SLEEP -> SLEEP time
+ EEPROM -> EEPROM location, (val0, val1)
+ RANDOM -> RANDOM seed
+ READ -> READ location,var
+ WRITE -> WRITE location, value
+ TOGGLE -> TOGGLE port
+ REVERSE -> REVERSE port
+ DIRS -> DIRS=%00000000 'ports 76543210
diff --git a/config/color.cfg b/config/color.cfg
new file mode 100644
index 0000000..fd779fe
--- /dev/null
+++ b/config/color.cfg
@@ -0,0 +1,6 @@
+## This is the color configuration to change the look and feel of the IDE.
+## You can comment by starting a line with ## .
+## Do not add/delete a line.
+
+## set the scheme of the console on startup (values: black, blue, white)
+console scheme= blue
diff --git a/config/set.cfg b/config/set.cfg
new file mode 100644
index 0000000..f9d285e
--- /dev/null
+++ b/config/set.cfg
@@ -0,0 +1,17 @@
+## This is the run configuration of the interpreter.
+## You can comment by starting a line with ## .
+## Do not delete a line.
+## A line is build like this: setting= value
+## You can enable/disable a setting by: true/false.
+
+## Slow down the execution speed to the speed of Basic Stamp 1.
+emulate 4Mhz= true
+
+## Activate additional information about the commands at the beginning of the execution.
+activate info= false
+
+## Deactivate display of warnings.
+ignore warnings= false
+
+## Activate display of the parsing-result
+print intern composition= false
\ No newline at end of file
diff --git a/contexts.xml b/contexts.xml
new file mode 100644
index 0000000..703f7dd
--- /dev/null
+++ b/contexts.xml
@@ -0,0 +1,13 @@
+
+
+
+ This is the context help for the sample view with a tree viewer. It was generated by a PDE template.
+
+
+
+
+
+
+
+
+
diff --git a/help/BasicStampHelp/BASIC Stamp Help.exe b/help/BasicStampHelp/BASIC Stamp Help.exe
new file mode 100644
index 0000000..259eec7
Binary files /dev/null and b/help/BasicStampHelp/BASIC Stamp Help.exe differ
diff --git a/help/BasicStampHelp/Content/FAQTopics/FIFObuffers.htm b/help/BasicStampHelp/Content/FAQTopics/FIFObuffers.htm
new file mode 100644
index 0000000..b4cc54e
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/FIFObuffers.htm
@@ -0,0 +1,91 @@
+
+
+
+ FIFO Buffer Settings
+
+
+
+
+
+
If you are using a standard serial port connection (not a USB port with a USB to serial adapter) and the Run/Identify Test shows no Device Type, but a "Yes" in the Echo column, or a "Yes" in both the Loopback and Echo columns, like this:
+
+
+
+
+
...you may need to adjust the port's FIFO buffer setting.
+
+
+
Make note of the COM port number in the row where it displays a "Yes" for Echo. (In this example it is COM5).
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/InsertBS2popup.htm b/help/BasicStampHelp/Content/FAQTopics/InsertBS2popup.htm
new file mode 100644
index 0000000..4f2252a
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/InsertBS2popup.htm
@@ -0,0 +1,26 @@
+
+
+
+ Insert the BASIC Stamp module
+
+
+
+
+
+
Insert the BASIC Stamp module
+
+
Use the silkscreen pictures that show the three prominent chips on the BASIC Stamp to determine how to orient it before inserting it into its socket. There is also a small semi-circular notch at in the top-center of the BASIC Stamp module that indicates which way is “up.” Match this reference notch to the notch in the socket.
+
After correctly orienting the 24-pin BASIC Stamp module, gently insert it into its socket as shown at (1) in the picture below.
+
Make sure that each pin is seated in its corresponding socket hole, then apply firm downward pressure with your thumb. The module should sink about ¼ of an inch (~0.6 mm) into the socket, and only the flared portion of each BASIC Stamp leg should be visible above the socket.
+
Visually inspect the legs to make sure each pin is in its socket and that no pins are folded underneath the module.
+
+
+
+
+
+
Caution! Do not remove the BASIC Stamp module from its socket, unless it needs to be replaced with another module! Every time the BASIC Stamp is removed and re-inserted into the socket, you risk damaging it. You do not need to remove it for storage.
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/InvalidPort.htm b/help/BasicStampHelp/Content/FAQTopics/InvalidPort.htm
new file mode 100644
index 0000000..7746132
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/InvalidPort.htm
@@ -0,0 +1,72 @@
+
+
+
+ Invalid Port
+
+
+
+
+
+
Invalid Port
+
+
+
+
+
The port may have been disabled. Right click the port in your Ports list and click Enable.
If you are using a BASIC Stamp development board with a USB connector, or a serial board with a Parallax USB to Serial Adapter, you may need to adjust your computer's latency timer settings if any of these are true:
+
+
The Run/Identify Test shows no Device Type, but a "Yes" in both the Loopback and Echo columns, or a "Yes" only in the Echo column.
+
You have passed the Run/Identify test but when you try to download a program with Run/Run, you get a "No BASIC Stamps Found" message.
+
You are able to download short programs, but not long ones.
+
You are able to program intermittently, but sometimes it fails.
+
+
How to adjust the Latency Timer settings
+
+
Using the Identification window from the Run/Identify Test procedure, make note of the COM port number in the row where it displays a "Yes" for Echo.
If you are on this page, you probably tried to download a program to your BASIC Stamp but got the "No BASIC Stamps found" message:
+
+
+
+
+
+
First, try these quick fixes:
+
+
Loose connections: Double-check the connections between your computer and your programming cable, the Parallax USB to Serial Adapter if you are using one, and the development board.
+
No power: double-check the power supply that you have connected to your board. (See Power Supplies for options). If your board has a power switch, make sure it is switched on and the power indicator is lit. If you are using a 9V battery, try a fresh one. If you are using a battery pack, make sure the batteries are all inserted into the pack correctly; try fresh batteries. If you are using a wall-mount supply, make sure the wall outlet is not turned off at a wall switch. If you have a voltmeter, use it to measure the voltage supplied by the battery pack or wall-mount to rule out defective power supply hardware.
+
USB drivers: If you are using a Parallax USB connection, you may need to update your USB drivers. See the USB Drivers page for help.
+
+
USB ports freeze after disconnecting from USB 3.0 port: USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
Beware of non-Parallax USB to Serial Adapters: Not every brand of USB to Serial Adapter supports the timing precision needed for BASIC Stamp programming. Some known-incompatible brands are Belkin and Gigaware. Keyspan #USA19-HS is known to be compatible. You can order an inexpensive Parallax USB to Serial Adapter (#28030) from www.parallax.com.
+
If you are using other terminal software to communicate with your BASIC Stamp, such as StampPlot, Parallax Serial Terminal, or Hyperterminal, it may be holding the port open. Disconnect the port in the terminal software.
+
If you are using a USB connection, try adjusting your computer's Latency Timer Settings.
+
If none of these things helped, Contact Parallax Tech Support for assistance.
Loose connections: Double-check the connections between your computer and your programming cable, the Parallax USB to Serial Adapter if you are using one, and the development board.
+
No power: double-check the power supply that you have connected to your board. (See Power Supplies for options). If your board has a power switch, make sure it is switched on and the power indicator is lit. If you are using a 9V battery, try a fresh one. If you are using a battery pack, make sure the batteries are all inserted into the pack correctly; try fresh batteries. If you are using a wall-mount supply, make sure the wall outlet is not turned off at a wall switch. If you have a voltmeter, use it to measure the voltage supplied by the battery pack or wall-mount to rule out defective power supply hardware.
+
USB drivers: If you are using a Parallax USB connection, you may need to update your USB drivers. See the USB Drivers page for help.
+
+
USB ports freeze after disconnecting from USB 3.0 port: USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
Beware of non-Parallax USB to Serial Adapters: Not every brand of USB to Serial Adapter supports the timing precision needed for BASIC Stamp programming. Some known-incompatible brands are Belkin and Gigaware. Keyspan #USA19-HS is known to be compatible. You can order an inexpensive Parallax USB to Serial Adapter (#28030) from www.parallax.com.
+
+
+
+
+
+
+
If the Run/Identify test shows no entry in the "Device Type" column, you can try these various fixes based on your Loopback and Echo results.
+
+
There is a "No" in Loopback, and "No" in Echo.
+
+
+
+
+
+
If you are using a Parallax USB connection, the USB port may be using the wrong drivers. Go to the USB Drivers page for help.
+
If you are using a serial connection, your serial cable may be at fault. You must use a standard straight-through serial cable, not a null modem or cross-over cable. If you have a multimeter, perform a continuity test of each pin to confirm you are using an undamaged standard straight-through serial cable.
If you are using a serial connection, try adjusting the COM port's FIFO Buffer Settings.
+
It is possible that your BASIC Stamp module has been damaged. Please Contact Parallax Tech Support.
+
+
+
There is a "Yes" in Loopback and a "No" in Echo:
+
+
+
+
+
+
If you have forgotten to install the BASIC Stamp into its socket on the Board of Education, or you may have plugged it in upside-down, review the directions on how to Insert the BASIC Stamp module.
If you are using a serial connection, your serial cable may be at fault. You must use a standard straight-through serial cable, not a null modem or cross-over cable. If you have a multimeter, perform a continuity test of each pin to confirm you are using an undamaged standard straight-through serial cable.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/NoPortsFound.htm b/help/BasicStampHelp/Content/FAQTopics/NoPortsFound.htm
new file mode 100644
index 0000000..a88ef79
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/NoPortsFound.htm
@@ -0,0 +1,90 @@
+
+
+
+ No Usable Serial Ports Found
+
+
+
+
+
+
No Usable Serial Ports Found
+
If you see the error message shown below, the ports may have been excluded from the BASIC Stamp Editor's search, or the ports may have been disabled in your computer's Device Manager. You can check for both situations following the instructions below.
+
+
+
+
The ports may have been excluded from the BASIC Stamp Editor's search
Look for "Communications Port" or "USB Serial Port" in italics, with a "Yes" in the Present column. Ports that are present but have been excluded from the BASIC Stamp Editor's Serial Port Search List will appear in italics in the list. (Note that Bluetooth communications ports are excluded by default.)
+
Right-click that port and select "Re-Include Port" and then click Accept.
+
+
+
+
+
The port may have been disabled in your computer's Device Manager
+
+
Right click the port in your computer's Ports list (it will be labeled "Communications Port" with a serial connection, or "USB Serial Port" with a USB connection)
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/PortInUse.htm b/help/BasicStampHelp/Content/FAQTopics/PortInUse.htm
new file mode 100644
index 0000000..312b242
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/PortInUse.htm
@@ -0,0 +1,90 @@
+
+
+
+ Can't open port; in use
+
+
+
+
+
+
Can't open port; in use
+
If you see this message, there is likely to be some other software that has used that port previously, and is now interfering.
+
+
+
+
Serial Terminal Software
+
+
If you are using other terminal software to communicate with your BASIC Stamp, such as StampPlot, Parallax Serial Terminal, or Hyperterminal, it may be holding the port open. Disconnect the port in the terminal software.
+
+
Devices with Automatic Synchronization Software
+
If you have used a device such as a PDA with this computer, the device's software (such as Weatherbug or HotSync software) may be holding the port open.
+
+
Check your computer's system tray to see if the device's software is enabled, and disable it temporarily.
+
If disabling the software in the above step did not release the COM port, you may need to uninstall and reinstall the COM port (sounds scary but it isn't really).
+
+
+
+
Unplug your programming cable from your computer.
+
Open your Ports list and right-click on the port you want to uninstall.
Parallax BASIC Stamp Development Boards may have either a barrel jack connector, 9 V battery clip connector, or both (as does the Board of Education.) This page gives options for both types of power connectors.
+
For Boards with a Barrel Jack Connector
+
The two most common power supply options used with this connector are wall-mount DC power supply, and battery holders.
+
Wall-mount DC Power Supplies
+
+
Plug: it must have a 2.1 mm center-positive barrel plug. Look for this symbol, indicating the positive connection is in the center of the plug:
+
+
+
+
+
+
Output current: wall-mount power supplies must have a DC (direct current) output. Look for a statement that indicates VDC output or uses this symbol: . For example:
+
+
+
+
OUTPUT: 7.5 VDC 1000 mA
+
+
OUTPUT: 7.5 V
+ 1.4 A
+
+
+
+
+
Output voltage: The power supply's output voltage must be compatible with the voltage rating on your board. For example, the Board of Education requires 6 to 9 VDC.
+
Input voltage and current: Wall-mount power supplies must be compatible with the frequency and amplitude of the AC power at the wall outlet you are using. This may vary depending on the country you live in. In the US and Canada, the input should be compatible with 120 VAC, 60 Hz.
+
+
Parallax carries power supplies compatible with BASIC Stamp development boards. For example, the 7.5 V, 1 amp supply (#750-00009) is compatible with the Board of Education.
+
+
+
+
Battery Holders
+
Like wall-mount supplies, battery holders must have a 2.1 mm center-positive plug. However, many battery holders don't have a symbol indicating whether or not the plug is center-positive. Use a voltmeter to test any battery holder of unknown origins. A 4 AA cell battery holder with a 2.1 mm center-positive plug is available from Parallax (#700-00038); this is the one included in the Boe-Bot Robot Kit.
+
+
+
+
+
For Boards with Battery Clip Connector
+
9-Volt Batteries
+
9 V Alkaline or rechargeable batteries with a snap-connector are fine. For best results, rechargeable batteries should be rated for 100 mAh (milliamp hours) or higher.
+
Not all chargers work with all types of batteries. Make sure your charger is recommended for the type of battery you are using. Follow all battery and charger instructions and caution statements.
+
9 V Battery Extension
+
The figure below shows a DC supply and a 9 V battery extension that can be used with battery clip connectors, such as the one on the BASIC Stamp HomeWork Board. Read the CAUTION statement below the picture.
+
+
+
+
Beware of Universal Adapters and Reversed Supply Terminals!
+
The picture below shows a common mistake that should be avoided with universal adapters. Many of these allow you to reverse the terminals on the 9 V battery extension. Although it cannot hurt the BASIC Stamp, Board of Education, or HomeWork Board, it can destroy a Parallax Standard Servo connected to Vin in a matter of seconds. The only system that can protect the servo from this mistake is a Board of Education that has a jumper between the servo ports, with that jumper set to Vdd.
+
+
+
+
Beware of "Battery Replacers"
+
Many battery replacers are designed to supply appliances with low current draw. With current ratings in the neighborhood of 10 mA, their output capacities are insufficient for many of the activities in the Stamps in Class texts. For example, two LEDs connected to 220-ohm resistors draw a total of 14.5 mA, and that definitely won't work with a "battery replacer."
+
Note: It's pretty easy to tell when a circuit is drawing more current than the supply can deliver because the Power LED on the Board of Education flickers and/or goes dim. On the HomeWork Board, the "Running" LED may flicker if the power drops low enough to cause the BASIC Stamp to reset and restart the program.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/PwrSupplyPopup.htm b/help/BasicStampHelp/Content/FAQTopics/PwrSupplyPopup.htm
new file mode 100644
index 0000000..211b1a7
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/PwrSupplyPopup.htm
@@ -0,0 +1,67 @@
+
+
+
+ Power Supplies
+
+
+
+
+
Power Supplies
+
Parallax BASIC Stamp Development Boards may have either a barrel jack connector, 9 V battery clip connector, or both (as does the Board of Education.) This page gives options for both types of power connectors.
+
For Boards with a Barrel Jack Connector
+
The two most common power supply options used with this connector are wall-mount DC power supply, and battery holders.
+
Wall-mount DC Power Supplies
+
+
Plug: it must have a 2.1 mm center-positive barrel plug. Look for this symbol, indicating the positive connection is in the center of the plug:
+
+
+
+
+
+
Output current: wall-mount power supplies must have a DC (direct current) output. Look for a statement that indicates VDC output or uses this symbol: . For example:
+
+
+
+
OUTPUT: 7.5 VDC 1000 mA
+
+
OUTPUT: 7.5 V
+ 1.4 A
+
+
+
+
+
Output voltage: The power supply's output voltage must be compatible with the voltage rating on your board. For example, the Board of Education requires 6 to 9 VDC.
+
Input voltage and current: Wall-mount power supplies must be compatible with the frequency and amplitude of the AC power at the wall outlet you are using. This may vary depending on the country you live in. In the US and Canada, the input should be compatible with 120 VAC, 60 Hz.
+
+
Parallax carries power supplies compatible with BASIC Stamp development boards. For example, the 7.5 V, 1 amp supply (#750-00009) is compatible with the Board of Education.
+
+
+
+
Battery Holders
+
Like wall-mount supplies, battery holders must have a 2.1 mm center-positive plug. However, many battery holders don't have a symbol indicating whether or not the plug is center-positive. Use a voltmeter to test any battery holder of unknown origins. A 4 AA cell battery holder with a 2.1 mm center-positive plug is available from Parallax (#700-00038); this is the one included in the Boe-Bot Robot Kit.
+
+
+
+
+
For Boards with Battery Clip Connector
+
9-Volt Batteries
+
9 V Alkaline or rechargeable batteries with a snap-connector are fine. For best results, rechargeable batteries should be rated for 100 mAh (milliamp hours) or higher.
+
Not all chargers work with all types of batteries. Make sure your charger is recommended for the type of battery you are using. Follow all battery and charger instructions and caution statements.
+
9 V Battery Extension
+
The figure below shows a DC supply and a 9 V battery extension that can be used with battery clip connectors, such as the one on the BASIC Stamp HomeWork Board. Read the CAUTION statement below the picture.
+
+
+
+
Beware of Universal Adapters and Reversed Supply Terminals!
+
The picture below shows a common mistake that should be avoided with universal adapters. Many of these allow you to reverse the terminals on the 9 V battery extension. Although it cannot hurt the BASIC Stamp, Board of Education, or HomeWork Board, it can destroy a Parallax Standard Servo connected to Vin in a matter of seconds. The only system that can protect the servo from this mistake is a Board of Education that has a jumper between the servo ports, with that jumper set to Vdd.
+
+
+
+
Beware of "Battery Replacers"
+
Many battery replacers are designed to supply appliances with low current draw. With current ratings in the neighborhood of 10 mA, their output capacities are insufficient for many of the activities in the Stamps in Class texts. For example, two LEDs connected to 220-ohm resistors draw a total of 14.5 mA, and that definitely won't work with a "battery replacer."
+
Note: It's pretty easy to tell when a circuit is drawing more current than the supply can deliver because the Power LED on the Board of Education flickers and/or goes dim. On the HomeWork Board, the "Running" LED may flicker if the power drops low enough to cause the BASIC Stamp to reset and restart the program.
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/RunIdTest.htm b/help/BasicStampHelp/Content/FAQTopics/RunIdTest.htm
new file mode 100644
index 0000000..db35eba
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/RunIdTest.htm
@@ -0,0 +1,123 @@
+
+
+
+ Run/Identify Test
+
+
+
+
+
+
This page will help you troubleshoot problems found after trying the Run/Identify test to verify the programming connection between your computer and BASIC Stamp. You should have already tried the common quick fixes and the Run/Identify test.
Loose connections: Double-check the connections between your computer and your programming cable, the Parallax USB to Serial Adapter if you are using one, and the development board.
+
No power: double-check the power supply that you have connected to your board. (See Power Supplies for options). If your board has a power switch, make sure it is switched on and the power indicator is lit. If you are using a 9V battery, try a fresh one. If you are using a battery pack, make sure the batteries are all inserted into the pack correctly; try fresh batteries. If you are using a wall-mount supply, make sure the wall outlet is not turned off at a wall switch. If you have a voltmeter, use it to measure the voltage supplied by the battery pack or wall-mount to rule out defective power supply hardware.
+
USB drivers: If you are using a Parallax USB connection, you may need to update your USB drivers. See the USB Drivers page for help.
+
+
USB ports freeze after disconnecting from USB 3.0 port: USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
Beware of non-Parallax USB to Serial Adapters: Not every brand of USB to Serial Adapter supports the timing precision needed for BASIC Stamp programming. Some known-incompatible brands are Belkin and Gigaware. Keyspan #USA19-HS is known to be compatible. You can order an inexpensive Parallax USB to Serial Adapter (#28030) from www.parallax.com.
+
To make sure your BASIC Stamp module can communicate with your computer, click the Run menu, then select Identify.
+
+
+
+
+
+
Or, you can use the ID icon on the toolbar:
+
+
+
+
+
An identification window will appear similar to the one shown here. This example shows that a BASIC Stamp 2 has been detected on COM5.
+
+
+
+
+
Check the Identification window to make sure your BASIC Stamp module has been detected on one of the COM ports. If it has been detected, then you are ready to program your BASIC Stamp.
+
+
+
+
+
It Passed the Run/Identify Test but Still Won't Program Reliably
+
+
If your USB-connected BASIC Stamp is detected and you see Yes in both columns, but can program only intermittently or get a "No BASIC Stamps Found" or a hardware/communication failure message, try adjusting the Latency Timer Settings.
+
+
+
It Failed the Run/Identify Test
+
If the Run/Identify test DID NOT find your BASIC Stamp on any COM port, the message that appeared can help diagnose connection problems.
+
+
Click on a message (below) to go to its troubleshooting page.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/SerialPortSearch.htm b/help/BasicStampHelp/Content/FAQTopics/SerialPortSearch.htm
new file mode 100644
index 0000000..44ba255
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/SerialPortSearch.htm
@@ -0,0 +1,132 @@
+
+
+
+ Serial Port Search List
+
+
+
+
+
+
This dialog indicates what serial ports will be scanned, and the order they will be accessed, whenever a BASIC Stamp identification or download process is started. Use this feature to fine-tune the BASIC Stamp search to include or exclude certain serial ports.
+
+
+
+
+
To access this dialog, click the "Edit Ports..." button that appears on the Identification Window or the Preferences > Editor Operation tab:
+
+
Identification Window: This appears when you press Ctrl+I or select the Run > Identify menu.
+
Preferences > Editor Operation tab: This appears when you press F5, or select the Edit > Preferences... menu, and select the Editor Operation tab.
+
+
Port List
+
The port list automatically updates whenever ports appear and disappear; such as USB-to-Serial ports. This is an interactive control; use your mouse to view and modify the list as indicated below.
+
+
Port ID column: Indicates the Port ID.
+
Port Description column: Indicates the friendly name for the port, similar to that shown in the Windows Device Manager tool.
+
Present column: 'Yes' if the port is currently present on the system, 'No' if not; this indicates a user rule is including a port in the search list that isn't currently present on the system.
+
+
Viewing and Modifying the List and Association Rules
+
The list of ports is shown in the order in which they will be scanned during BASIC Stamp identification and/or download processes. The ports to be scanned, and the order in which they are scanned, can be set through this interface, described below.
To change the order in which ports are scanned, left-click and drag port rows up and down. In this example, we selected the COM11 row, left-clicked it and dragged it up to be above the first Bluetooth Communications Port row (COM3). This results in a new scan order of COM11, COM3, COM6, and lastly COM12.
Ports may be included or excluded from the search list based on one or more user-defined rules.
+
To see what rule is applying to a particular port, point the mouse at the port's row and read the hint that appears. The example shown here indicates that port COM12 is being "Included by default" which means there is no rule explicitly including or excluding the port.
+
+
+
+
+
To exclude or include a port by the port's ID, right-click the port's row and select the "Exclude/Include Port (COMxx)" item. In this example, we chose to exclude COM12.
+
+
+
+
+
After excluding it, the ports list will update as shown below. Notice that it appears ghosted and in italics to indicate it will not be scanned; it will be ignored during an identification and download process. Also, hovering the mouse over it will display a hint saying, "Excluded by Port ID rule."
+
+
+
+
+
Tip: You can remove this Port ID rule by right-clicking on the port's row and selecting the "Re-include/exclude port (COMxx)" item.
To exclude or include a port by its description, right-click the port's row and select the "Filter Port(s) by Description…" item.
+
+
+
+
+
This will open a new dialog that allows you to set the desired description rule. In this example, we set it to "Exclude" any ports matching "Bluetooth Communications Port" in their description.
+
+
+
+
Click OK to update the ports list. Notice that COM3 and COM6 (the ports whose descriptions read "Bluetooth Communications Port") appear ghosted and in italics to indicate it they will not be scanned; they will be ignored during an identification and download process. Also, hovering the mouse over those ports will display a hint saying, "Excluded by Port Description rule."
+
+
+
+
+
Tip: You can edit or remove this Port Description rule for a single port by by right-clicking on the port's row and selecting the "Include Port (COMxx)" option. You can change or remove it from all ports with the "Edit Port Description Rule..." or "Remove port description rule…" options.
+
+
+
+
+
Tip: On the Filter Port(s) by Description dialog, the Port Description field can be as general or as specific as necessary by using asterisk (*) characters as wild cards. For example, to exclude all ports beginning with the word "USB," enter "USB *" in the field. To exclude all ports with the word USB appearing anywhere within them, enter "*USB*" in the field. The bottom of the dialog shows the number of "Matches Found;" the number of existing ports that the rule applies to.
+
Tip: To exclude all ports except specific ports, right-click on any port row and select "Exclude all ports by default," then right click on any desired ports and select either "Include Port (COMxx)" or "Filter Port(s) by Description…" and enter the desired match string of ports to include.
+
+
+
Buttons
+
+
Restore Defaults: Press this button to remove all user-defined serial port rules and return the BASIC Stamp Editor Serial Port Search List to its default scanning sequence. Note that Bluetooth ports are excluded by default.
+
Accept: Press this button to apply all modifications made to the serial port search list and corresponding rules.
+
Cancel: Press this button to cancel all recent modifications made to the serial port search list and corresponding rules.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/FAQTopics/TFAQ.htm b/help/BasicStampHelp/Content/FAQTopics/TFAQ.htm
new file mode 100644
index 0000000..e2a129e
--- /dev/null
+++ b/help/BasicStampHelp/Content/FAQTopics/TFAQ.htm
@@ -0,0 +1,73 @@
+
+
+
+ Connection Troubleshooting
+
+
+
+
+
+
You are here: Connection Troubleshooting
+
+
Connection Troubleshooting
+
This is the "triage" area for troubleshooting the programming connection between your computer and your BASIC Stamp development board.
+
+
Let's rule out the most common causes of communications failure first:
+
+
Loose connections: Double-check the connections between your computer and your programming cable, the Parallax USB to Serial Adapter if you are using one, and the development board.
+
No power: double-check the power supply that you have connected to your board. (See Power Supplies for options). If your board has a power switch, make sure it is switched on and the power indicator is lit. If you are using a 9V battery, try a fresh one. If you are using a battery pack, make sure the batteries are all inserted into the pack correctly; try fresh batteries. If you are using a wall-mount supply, make sure the wall outlet is not turned off at a wall switch. If you have a voltmeter, use it to measure the voltage supplied by the battery pack or wall-mount to rule out defective power supply hardware.
+
USB drivers: If you are using a Parallax USB connection, you may need to update your USB drivers. See the USB Drivers page for help.
+
+
USB ports freeze after disconnecting from USB 3.0 port: USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
Beware of non-Parallax USB to Serial Adapters: Not every brand of USB to Serial Adapter supports the timing precision needed for BASIC Stamp programming. Some known-incompatible brands are Belkin and Gigaware. Keyspan #USA19-HS is known to be compatible. You can order an inexpensive Parallax USB to Serial Adapter (#28030) from www.parallax.com.
+
+
+
+
Okay, if that didn't solve the problem, let's keep going:
+
+
If you are able to program your USB-connected board sometimes, but it fails sometimes or requires several tries (and you are SURE the power supply is not the problem), you may need to change your computer's Latency Timer Settings.
+
If you are using a Parallax BASIC Stamp development board (such as a Board of Education, HomeWork Board, or Professional Development Board), and your PC cannot communicate with your BASIC Stamp, go to the Run/Identify Test page.
+
If you are using a USB-based board or USB to Serial Adapter, and repeated BASIC Stamp resets are interfering with your program, see the USB Resets BASIC Stamp page.
+
If you are using a development board and/or BASIC Stamp OEM that you assembled yourself, there are a number of tests that can be performed best with the help of the Parallax Tech Support crew, and a voltmeter. Please Contact Parallax Tech Support.
If you are using a Parallax board with a USB connector, or a Parallax USB to Serial Adapter:
+
+ ...or...
+
...you will need USB drivers from Parallax Inc.
+
+
Beware of non-Parallax USB to Serial Adapters: Not every brand of USB to Serial Adapter supports the timing precision needed for BASIC Stamp programming. Some known-incompatible brands are Belkin and Gigaware. Keyspan #USA19-HS is known to be compatible. You can order an inexpensive Parallax USB to Serial Adapter (#28030) from www.parallax.com.
+
+
Unplug the USB cable to your BASIC Stamp development board at the computer.
Windows 2K: Start Menu > Settings > Control Panel > System > click Hardware Tab > Device Manager... > expand Ports (COM & LPT)
+
+
Windows XP: Start Menu > right-click My Computer > Properties > click Hardware Tab > Device Manager > expand Ports (COM & LPT)
+
+
Windows Vista or Windows 7: Start Menu (Windows icon) > right-click Computer > Properties > Device Manager (left pane) > expand Ports (COM & LPT)
+
+
+
+
+
+
+
If there is no yellow exclamation mark (like the image below), the drivers have been installed correctly and you can now go try the Run/Identify Test again.
+
+
+
+
+
+
There will be a yellow exclamation mark (!) by the device if the drivers either were not installed successfully or not at all. Contact Parallax Tech Support for assistance.
A BASIC Stamp connected to a PC via a USB can be reset by the USB connection. This can occur with USB-based boards, and with serial boards using the USB to Serial Adapter. Resets can happen when:
+
+
Connecting the board to the USB port.
+
Disconnecting the board from the USB port, at either end of the USB cable.
+
Connecting or disconnecting another USB device on a port adjacent to your BASIC Stamp board's USB port.
+
+
The resets are caused by the PC's operating system checking to see if a new plug-and-play device (such as a mouse) was just connected. Disconnecting your board may cause a single reset. Reconnecting typically causes several resets in a row during the first few seconds.
+
Tip: If you are using the USB to Serial Adapter, resets are easy to avoid. After connecting your board to your PC the first time, always disconnect and reconnect at the serial (9-pin) end of the USB to Serial Adapter. Leaving the Adapter connected to your PC keeps the virtual communications port open, preventing an unwanted reset.
+
What BASIC Stamp Resets Do
+
Each time a BASIC Stamp is reset:
+
+
The program execution restarts from the beginning of code.
+
All variables are set to their initial value (zero by default).
+
+
Make sure to keep this in mind while working on your BASIC Stamp projects. Some programs have variable values that you do not want to lose when you disconnect or reconnect your board to the PC. This is common with datalogging activities.
+
Datalogging Activities
+
Some Stamps in Class activities use BASIC Stamp programs that log sensor data. Typically, the programmed board is disconnected from the PC, and taken someplace to record data with sensors. Afterward, the board is reconnected to the PC so the sensor data can be displayed on the Debug Terminal or saved to the PC for later use.
+
If a program only records sensor data in RAM as variable values, a USB-based board will lose that data when reconnecting to the PC because the BASIC Stamp will reset. So, USB-based boards must stay connected to the computer with programs that hold data RAM as variable values.
+
For USB-based boards and datalogging programs with applications where the board is disconnected and reconnected to the PC, the program should:
+
+
Save values to EEPROM
+
Use a one-second delay at the beginning of the program.
+
+
Save Values to EEPROM using READ, WRITE, and DATA
+
A simple solution for retaining values between resets is to save them in portions of the EEPROM program memory that are not used to store the actual program. Since the program is stored starting at the highest memory address, the low memory addresses are usually available for storing these values.
+
Use the WRITE command to store values to addresses in BASIC Stamp EEPROM memory. Then, use READ commands to retrieve those values from EEPROM, even after connecting it to the PC. You can build READ commands into your main program, or even run a separate program to retrieve those values.
+
Pre-initialized values can also be stored in EEPROM with the DATA directive.
+
See the PBASIC Language Reference's READ, WRITE, and DATA commands for more information.
+
Prevent Unexpected Bugs by Starting Your Programs with a One-Second Delay
+
If your application requires reconnecting your USB board to the PC while the BASIC Stamp program is running, always add a one-second delay to the beginning of your program. Examples of one-second delays for BS2 modules include: PAUSE 1000 and FREQOUT Pin, 1000, Frequency.
+
Adding a one-second delay at the start of your program could prevent these two unwanted behaviors:
+
+
If the BASIC Stamp transmits serial messages immediately after these resets, the operating system could mistake it for a serial mouse or other plug-and play-device.
+
If your program advances a value stored in EEPROM with each reset, the value will increase by one or more (ten is not uncommon) each time you connect your USB BASIC Stamp board to a PC.
+
+
Again, the one-second delay at the very beginning of the program prevents these issues. Other ways to prevent them include leaving the power off until one second after you have connected your USB board, or pressing and holding the reset button for that time.
+
Programs that Use the Reset Button
+
Some programs use your board's Reset button to advance a value stored in EEPROM with each reset, or use the reset to trigger a "record" or "playback" mode.
+
For reset button applications with USB boards, it's best to design the application assuming the reset will happen when you disconnect and reconnect the board to the PC. Then, make sure to press and hold the reset button each time you disconnect or reconnect your board. This will ensure that a single, expected reset occurs, and not multiple resets as can happen with reconnection.
+
This example program uses a DATA directive to pre-initialize the value stored by EEPROM address 0 to 255 when the program is loaded. The READ command fetches this value from EEPROM and adds 1 to it. For a byte variable, 255 + 1 = 0 since 255 is the largest it can store, so it rolls over to zero. Taking the remainder of this eeVal/2 results in either 0 or 1. The WRITE command stores this modified value back to EEPROM address 0. Then, the ON…GOTO… command uses eeVal, which stores 0 or 1. With each reset of the BASIC Stamp, the value advances from 0 to 1, to 0 again, and so on…
+' {$STAMP BS2} ' Select BS2 as target module
+' {$PBASIC 2.5} ' Select PBASIC 2.5 as language
+
+eeVal VAR Byte ' EEPROM value variable
+DATA 255 ' Pre-initialize EEPROM address 0 to 255
+
+PAUSE 1000 ' Always wait 1 s before advancing EEPROM
+
+READ 0, eeVal ' Fetch value from EEPROM address 0
+eeval = eeVal + 1 ' Add 1 to eeVal
+eeval = eeval // 2 ' Take remainder of eeVal / 2
+WRITE 0, eeVal ' Write new result back to EEPROM
+
+ON eeVal GOTO Playback, Record ' Use eeVal result to select routine
+
+Playback: ' Playback label
+ DEBUG "Playing back..." ' Debug message indicating playback started
+ ' Report logged data code here ' Your playback code goes here
+ END ' End, don't record after playback
+
+Record: ' Record label
+ DEBUG "Recording..." ' Message indicates recording started
+ ' Datalogging code here ' Your datalogging code goes here
+ END
+
Check for the PC Connection with SERIN
+
Another useful strategy is to write a program routine that checks to see if the board is connected to the PC. Then the program can make decisions based on this information. For example, "if not connected, then log data” and “if connected, then display data.”
+
The code example below demonstrates one way to do this. It displays a message to press any key, then a SERIN command that waits for a message from P16 (the programming port) for 2000 ms. If a character is typed into the Debug Terminal’s Transmit windowpane during that time, the program continues through the Playback routine. If not, it jumps to the Record routine.
+' {$STAMP BS2} ' Select BS2 as target module
+' {$PBASIC 2.5} ' Select PBASIC 2.5 as language
+
+char VAR Byte ' Variable for getting character
+
+PAUSE 1000 ' Always wait 1 s before serial transmit
+DEBUG "Press any key...", CR ' User prompt
+
+' Wait 2 s for character from Debug Terminal’s Transmit windowpane. Jump to
+' Record label if no character received during that time. Continue to Playback
+' label if character received.
+SERIN 16, 84, 2000, Record, [char]
+
+Playback: ' Playback label
+ DEBUG "Playing back..." ' Debug message indicating playback started
+ ' Report logged data code here ' Your playback code goes here
+ END ' End, don’t record after playback
+
+Record: ' Record label
+ DEBUG "Recording..." ' Message indicates recording started
+ ' Datalogging code here ' Your datalogging code goes here
+ END
+
See the PBASIC Language Reference's SERIN command for more information.
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/HardwareTopics/BS_Chart.htm b/help/BasicStampHelp/Content/HardwareTopics/BS_Chart.htm
new file mode 100644
index 0000000..a737595
--- /dev/null
+++ b/help/BasicStampHelp/Content/HardwareTopics/BS_Chart.htm
@@ -0,0 +1,464 @@
+
+
+
+ Products
+
+
+
+
+
+
You are here: Products
+
+
BASIC Stamp Comparison Chart
+
BASIC Stamp microcontroller modules are like tiny single-board computers. Many projects that require an embedded system with some level of intelligence can use a BASIC Stamp module as the controller. Each BASIC Stamp module contains a PBASIC Interpreter chip, internal memory (RAM and EEPROM), a 5-volt regulator, a number of general-purpose I/O pins (TTL-level, 0-5 volts), and a set of built-in commands for math and I/O pin operations.
We recommend using a Parallax development board and cable for programming BASIC Stamp modules. When these items are not available, you may create your own board by duplicating the following diagrams with your own circuits and cables.
+
Be very careful to follow these diagrams closely; it is quite common for programming problems with the BASIC Stamp to be a result of a poorly made custom cable or programming connections on your applications board. For example, with the programming connections for all the BS2 models, it is possible to reverse a couple of wires and still get positive results using some of the "connection" tests and yet you still will not be able to communicate with the BASIC Stamp. It is vital that you check your connections with a meter and verify the pin numbering to avoid problems like this.
+
Programming and Run-time Communication Connections for all BS2 models
+
Though it is not shown, power must be connected to the BASIC Stamp to program it. Note that the programming connections for the 40-pin BS2p40 are the same as for the 24-pin BS2 models.
+
+
+
+
+
BS1 Programming Connections with BS1 Serial Adapter
+
Though it is not shown, power must be connected to the BS1 to program it.
+
+
+
+
+
BASIC Stamp 1 Serial Adapter
+
Starting with Version 2.1, the BASIC Stamp Editor/Compiler supports programming
+BASIC Stamp 1 modules through a standard serial connection using the adapter shown above and below. The adapter translates the voltage
+and mechanical differences of the BS1 to be compatible with the serial port. For convenience, Parallax
+manufactures the BASIC Stamp 1 Serial Adapter (#27111) that plugs into the end of a serial cable and connects
+to the programming header of the BS1.
+
+
+
+
+
For those that would like to make their own adapter, the schematic is shown
+below.
Unregulated power in: accepts 5.5 - 15 VDC (6-40 VDC on BS1‑IC rev. b), which is then internally regulated to 5 volts. May be left unconnected if 5 volts is applied to the VDD (+5V) pin.
+
+
+
+
+
2
+
+
+
VSS
+
+
+
System ground: connects to BS1 Serial Adapter ground for programming.
+
+
+
+
+
3
+
+
+
PCO
+
+
+
PC Out: 4800 baud serial output (TTL level) to PC.
+
+
+
+
+
4
+
+
+
PCI
+
+
+
PC In: 4800 baud serial input (TTL level) from PC.
+
+
+
+
+
5
+
+
+
VDD
+
+
+
5-volt DC input/output: (Also called +5V) if an unregulated voltage is applied to the VIN pin, then this pin will output 5 volts. If no voltage is applied to the VIN pin, then a regulated voltage between 4.5V and 5.5V should be applied to this pin.
+
+
+
+
+
6
+
+
+
RES
+
+
+
Reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the BASIC Stamp to reset. Can be driven low to force a reset. This pin is internally pulled high and may be left disconnected if not needed. Do not drive high.
+
+
+
+
+
7-14
+
+
+
P0-P7
+
+
+
General-purpose I/O pins: each can sink 25 mA and source 20 mA. However, the total of all pins should not exceed 50 mA (sink) and 40 mA (source).
+
+
+
+
BASIC Stamp 2
+
+
+
+
+
+
+
+
+
+
Pin
+
+
Name
+
+
Description
+
+
+
+
1
+
+
SOUT
+
+
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25 pin 3) for programming.
+
+
+
+
2
+
+
SIN
+
+
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin 2) for programming.
+
+
+
+
3
+
+
ATN
+
+
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25 pin 20) for programming.
+
+
+
+
4
+
+
VSS
+
+
System ground: (same as pin 23) connects to PC serial port GND pin (DB9 pin 5 / DB25 pin 7) for programming.
+
+
+
+
5-20
+
+
P0-P15
+
+
General-purpose I/O pins: each can sink 25 mA and source 20 mA. However, the total of all pins should not exceed 50 mA (sink) and 40 mA (source) if using the internal 5-volt regulator. The total per 8-pin groups (P0 – P7 or P8 – 15) should not exceed 50 mA (sink) and 40 mA (source) if using an external 5-volt regulator.
+
+
+
+
21
+
+
VDD
+
+
5-volt DC input/output: if an unregulated voltage is applied to the VIN pin, then this pin will output 5 volts. If no voltage is applied to the VIN pin, then a regulated voltage between 4.5V and 5.5V should be applied to this pin.
+
+
+
+
22
+
+
RES
+
+
Reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the BASIC Stamp to reset. Can be driven low to force a reset. This pin is internally pulled high and may be left disconnected if not needed. Do not drive high.
+
+
+
+
23
+
+
VSS
+
+
System ground: (same as pin 4) connects to power supply’s ground (GND) terminal.
+
+
+
+
24
+
+
VIN
+
+
Unregulated power in: accepts 5.5 - 15 VDC (6-40 VDC on BS2-IC Rev. e, f, and g), which is then internally regulated to 5 volts. Must be left unconnected if 5 volts is applied to the VDD (+5V) pin.
+
+
+
+
BASIC Stamp 2e, 2sx, 2p, 2pe, 2px
+
+
+
+
+
+
+
+
+
+
Pin
+
+
Name
+
+
Description
+
+
+
+
+
1
+
+
+
SOUT
+
+
+
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25 pin 3) for programming.
+
+
+
+
+
2
+
+
+
SIN
+
+
+
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin 2) for programming.
+
+
+
+
+
3
+
+
+
ATN
+
+
+
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25 pin 20) for programming.
+
+
+
+
+
4
+
+
+
VSS
+
+
+
System ground: (same as pin 23), connects to PC serial port GND pin (DB9 pin 5 / DB25 pin 7) for programming.
+
+
+
+
+
5-20
+
+
+
P0-P15
+
+
+
General-purpose I/O pins: each can source and sink 30 mA. However, the total of all pins should not exceed 75 mA (source or sink) if using the internal 5-volt regulator. The total per 8-pin groups P0 – P7 or P8 – 15 should not exceed 60 mA (source or sink) if using an external 5-volt regulator.
+
+
+
+
+
21
+
+
+
VDD
+
+
+
5-volt DC input/output: if an unregulated voltage is applied to the VIN pin, then this pin will output 5 volts. If no voltage is applied to the VIN pin, then a regulated voltage between 4.5V and 5.5V should be applied to this pin.
+
+
+
+
+
22
+
+
+
RES
+
+
+
Reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the BASIC Stamp to reset. Can be driven low to force a reset. This pin is internally pulled high and may be left disconnected if not needed. Do not drive high.
+
+
+
+
+
23
+
+
+
VSS
+
+
+
System ground: (same as pin 4) connects to power supply’s ground (GND) terminal.
+
+
+
+
+
24
+
+
+
VIN
+
+
+
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended), which is then internally regulated to 5 volts. Must be left unconnected if 5 volts is applied to the VDD (+5V) pin.
+
+
+
+
BASIC Stamp 2p40
+
+
+
+
+
+
+
+
+
+
Pin
+
+
Name
+
+
Description
+
+
+
+
+
1
+
+
+
SOUT
+
+
+
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25 pin 3) for programming.
+
+
+
+
+
2
+
+
+
SIN
+
+
+
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin 2) for programming.
+
+
+
+
+
3
+
+
+
ATN
+
+
+
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25 pin 20) for programming.
+
+
+
+
+
4
+
+
+
VSS
+
+
+
System ground: (same as pin 39) connects to PC serial port GND pin (DB9 pin 5 / DB25 pin 7) for programming.
+
+
+
+
+
5-20
+
+
+
P0-P15
+
+
+
General-purpose I/O pins: each can source and sink 30 mA. However, the total of all pins (including X0-X15) should not exceed 75 mA (source or sink) if using the internal 5-volt regulator. The total per 8-pin groups (P0 – P7, P8 – 15, X0 – X7 or X8 – X15) should not exceed 100 mA (source or sink) if using an external 5-volt regulator.
+
+
+
+
+
21-36
+
+
+
X0-X15
+
+
+
Auxiliary Bank of General-purpose I/O pins: each can source and sink 30 mA. However, the total of all pins (including P0 – P15) should not exceed 75 mA (source or sink) if using the internal 5-volt regulator. The total per 8-pin groups (P0 – P7, P8 – 15, X0 – X7 or X8 – X15) should not exceed 60 mA (source or sink) if using an external 5-volt regulator.
+
+
+
+
+
37
+
+
+
VDD
+
+
+
5-volt DC input/output: if an unregulated voltage is applied to the VIN pin, then this pin will output 5 volts. If no voltage is applied to the VIN pin, then a regulated voltage between 4.5V and 5.5V should be applied to this pin.
+
+
+
+
+
38
+
+
+
RES
+
+
+
Reset input/output: goes low when power supply is less than approximately 4.2 volts, causing the BASIC Stamp to reset. Can be driven low to force a reset. This pin is internally pulled high and may be left disconnected if not needed. Do not drive high.
+
+
+
+
+
39
+
+
+
VSS
+
+
+
System ground: (same as pin 4) connects to power supply’s ground (GND) terminal.
+
+
+
+
+
40
+
+
+
VIN
+
+
+
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended), which is then internally regulated to 5 volts. Must be left unconnected if 5 volts is applied to the VDD (+5V) pin.
No site license or end user license is required to use this software. By downloading or otherwise obtaining a copy of this software, you agree that it is to be used exclusively with Parallax BASIC Stamp products. Any other uses are not permitted and may represent a violation of Parallax copyrights, legally punishable according to Federal copyright or intellectual property laws. Any duplication of this documentation for commercial uses is expressly prohibited Parallax Inc. Duplication for educational use is permitted subject to the following Conditions of Duplication: Parallax Inc. grants the user a conditional right to download, duplicate, and distribute the Help content without Parallax's permission, under the following conditions: the material, or any portion thereof, may not be duplicated for commercial use; it may be duplicated only for educational purposes when used solely in conjunction with Parallax BASIC Stamp products, and the user may recover from the student only the cost of duplication.
BASIC Stamp, Board of Education, and Boe-Bot are federally registered trademarks of Parallax Inc.
+
PBASIC, Parallax and the Parallax logo are trademarks of Parallax Inc.
+
Windows is a registered trademark of Microsoft Corporation.
+
I2C is a registered trademark of Philips Corporation.
+
1-Wire is a registered trademark of Maxim/Dallas Semiconductor.
+
Other brand and product names are trademarks or registered trademarks of
+their respective holders.
+
Disclaimer of Liability
+
Parallax Inc. is not responsible for special, incidental, or consequential
+damages resulting from any breach of warranty, or under any legal theory,
+including lost profits, downtime, goodwill, damage to or replacement of equipment
+or property, and any costs of recovering, reprogramming, or reproducing any data
+stored in or used with Parallax products. Parallax Inc. is also not responsible for any personal damage, including that to life and health, resulting from use of any Parallax products. You take full responsibility for your BASIC Stamp application, no matter how life-threatening it may be.
Each release of BASIC Stamp Help and the BASIC Stamp Editor software can include new or enhanced items that may not be readily apparent. This topic is a summary of these notable changes.
+
Note that these changes are also reflected in the online version of the Help files. The Online Help is divided into three sections:
Version 2.5 (Released with BASIC Stamp Editor Software v2.5)
+
This is a much-improved help system that coincides with the release of What's A Microcontroller? v3.0.
+
+
Now includes a Getting Started with Stamps in Class section to assist new users following Stamps in Class tutorials such as What's a Microcontroller? and Robotics with the Boe-Bot.
Contains many enhancements to aid navigation, save favorite topics for later, search for information, and find additional BASIC Stamp resources.
+
Published in Web Help format (.htm).
+
+
Versions 1.0 - 1.4
+
The first releases of BASIC Stamp Help in compiled HTML help format (.chm).
+
+
+
BASIC Stamp Editor Software
+
Version 2.5.3
+
General
+
+
Updated installer to include BASIC Stamp Help v2.5.4 and updated a few related source code examples.
+
Updated BASIC Stamp Editor to include the adjusted source code examples in module libraries.
+
+
Version 2.5.2
+
Bug Fix
+
+
Fixed bug that was preventing the Generate Object Code feature from properly extracting the Stamp Loader.
+
+
+
Version 2.5.1
+
Bug Fix
+
+
Fixed bug causing Edit Tips button to fail on the Tip of the Day window.
+
Fixed bug causing copy/paste operations to fail from BASIC Stamp Help.
+
+
General
+
+
Updated error 305 - "Hardware communication failure! Check serial cable and power supply" to use the term "programming cable" instead of "serial cable" since it applies to both serial cables and USB cables.
+
Fixed misspelled word "occurrence" in error and status messages.
+
Updated Run menu to include function key shortcuts instead of Ctrl+ shortcuts. NOTE: Ctrl+ shortcuts still remain in effect.
+
Added serial search rule to automatically exclude the PropScope from serial port search operations.
+
+
Misc
+
+
Updated the included Parallax USB Driver Installer to v2.08.02.
+
+
+
Version 2.5
+
General
+
+
Enhanced Help menu to include links to new BASIC Stamp Help, BASIC Stamp Manual v2.2, and What's A Microcontroller? v3.0 text.
+
Updated a number of example BASIC Stamp programs.
+
+
Misc
+
+
Replaced USB Drivers with Parallax USB Driver Installer v2.04.16 (R2).
The BS2p, BS2pe, and BS2px is available as a 24-pin module that is pin-compatible
+with the BS2, BS2e, and BS2sx. Also available is a 40-pin module called the BS2p40
+with an additional 16 I/O pins (for a total of 32). The BS2p40's extra, or
+auxiliary, I/O pins can be accessed in the same manner as the main I/O pins
+(by using the IDs 0 to 15) but only after issuing an AUXIO or IOTERM 1 command. The AUXIO command causes the BASIC
+Stamp to affect the auxiliary I/O pins instead of the main I/O pins in all further
+code until the MAINIO or IOTERM 0 command is reached, or the BASIC Stamp
+is reset or power-cycled. AUXIO is also used when setting the DIRS register
+for auxiliary IO pins on the BS2p40.
+
The following example illustrates this:
+Main:
+ HIGH 0
+ AUXIO
+ LOW 0
+
+
The first line of the above example will set I/O pin 0 of the main I/O pins
+(physical pin 5) high. Afterward, the AUXIO command tells the BASIC
+Stamp that all commands following it should affect the auxiliary I/O pins.
+The following LOW command will set I/O pin 0 of the auxiliary I/O pins
+(physical pin 21) low.
+
Note that the main I/O and auxiliary I/O pins are independent of each other;
+the states of the main I/O pins remain unchanged while the program affects the
+auxiliary I/O pins, and vice versa.
+
Reducing Power Consumption
+
When the BASIC Stamp is reset all RAM variables, including DIRS and OUTS are
+cleared to zero. This goes for main and auxiliary pins. On the BS2p24,
+BS2pe, and BS2px the auxiliary pins from the interpreter chip are not connected to
+physical IO pins on the BASIC Stamp. While not connected to anything, these
+pins do have pull-ups activated, effectively connecting them to Vdd. After
+reset, reading the auxiliary pins from a BS2p24, BS2pe, or BS2px will return all 1s.
+For lowest possible current consumption where required, you may set the BS2p24,
+BS2pe, and BS2px auxiliary pins as output low.
+Setup:
+ AUXIO ' select AUXIO pins
+ OUTS = $0000 ' force outputs low
+ DIRS = $FFFF ' make (unconnected) pins outputs
+ MAINIO ' back to MAINIO group
+
The BRANCH instruction is useful when you want to write something like this:
Test_Value:
+ IF value = 0 THEN Case_0 ' if value is 0, jump to Case_0
+ IF value = 1 THEN Case_1 ' if value is 1, jump to Case_1
+ IF value = 2 THEN Case_2 ' if value is 2, jump to Case_2
+
+
You can use BRANCH to organize this into a single statement:
+
+
+
BRANCH value, (Case_0, Case_1, Case_2)
+
+
+
BRANCH value, (Case_0, Case_1, Case_2)
+
This works exactly the same as the previous IF…THEN example. If the value isn’t in range (in this case if value is greater than 2), BRANCH does nothing and the program continues with the next instruction after BRANCH.
Monitor and process a pushbutton input, perform auto-repeat, and branch to address
+if button is in target state. Button circuits may be active-low or active-high.
+
+
+
+
Pin is a variable/constant/expression* (0 - 15) that specifies
+ the I/O pin to use. This pin will be set to input mode.
+
DownState is a variable/constant/expression* (0 or 1) that
+ specifies which logical state occurs when the button is pressed.
+
Delay is a variable/constant/expression* (0 - 255) that specifies
+ how long the button must be pressed before auto-repeat starts. The delay is
+ measured in cycles of the BUTTON routine. Delay has two special
+ settings: 0 and 255. If Delay is 0, BUTTON performs no debounce
+ or auto-repeat. If Delay is 255, Button performs debounce, but no
+ auto-repeat.
+
Rate is a variable/constant/expression* (0 - 255) that specifies
+ the number of cycles between auto-repeats. The rate is expressed in cycles
+ of the BUTTON routine.
+
Workspace is a byte variable used by BUTTON for workspace.
+ It must be cleared to 0 before being used by BUTTON for the first time
+ and should not be adjusted outside of the BUTTON instruction. NOTE:
+ All RAM is cleared to 0 by default upon power-up or reset of the BASIC
+ Stamp.
+
TargetState is a variable/constant/expression* (0 or 1) that
+ specifies which state the button should be in for a branch to occur (0=not
+ pressed, 1=pressed).
+
Address is a label that specifies where to branch if the button
+ is in the target state.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
+
Explanation
+
When you press a button or flip a switch, the contacts make or break a connection.
+A brief (1 to 20-ms) burst of noise occurs as the contacts scrape and bounce against
+each other. By scanning an input within a loop to ensure that the contact remains
+in a specified state for a minimum duration, spurious multiple inputs caused by
+contact noise can be eliminated. The BUTTON instruction helps prevent this
+noise from being interpreted as more than one switch action; this is the function
+of the Delay parameter. (For a demonstration of switch bounce, see the demo
+program for the COUNT instruction.) Delay, combined
+with the Rate parameter, allows the programmer to control the rate at which
+multiple inputs are accepted by the BASIC Stamp.
+
BUTTON also lets PBASIC react to a button press the way your computer
+keyboard does to a key press. When you press a key, a character immediately appears
+on the screen. If you hold the key down, there's a delay, then a rapid-fire stream
+of characters appears on the screen. BUTTON's auto-repeat function can be
+set up to work much the same way.
+
BUTTON is designed for use inside a program loop. Each time through the
+loop, BUTTON checks the state of the specified pin. When it first matches
+DownState, BUTTON begins the Delay countdown for auto-repeat.
+Then, in accordance with TargetState, it either branches to address
+(TargetState = 1) or doesn't (TargetState = 0).
+
If the switch stays in DownState, BUTTON counts the number of
+program loops that execute. When this count equals Delay, BUTTONonce again triggers the action specified by TargetState and Address. Hereafter,
+if the switch remains in DownState, BUTTON waits Rate number
+of cycles between actions. The Workspace variable is used by BUTTON
+to keep track of how many cycles have occurred since the pin switched to
+TargetState or since the last auto-repeat.
+
BUTTON does not stop program execution. In order for its delay and auto
+repeat functions to work properly, BUTTON must be executed from within a
+program loop.
Enable or disable comparator, compare voltages on P1 and P2 and retrieve
+comparison result to store in Result.
+
+
+
+
Mode is a variable/constant/expression (0 – 2) that enables
+ or disables the comparator (input pins P1 and P2) and determines if the
+ optional comparator output pin (pin P0) is enabled or not. See the table
+ below for an explanation of the Mode values.
+
Result is a variable (usually a bit) in which the
+ comparison result is stored.
+
+
Quick Facts
+
+
+
+
BS2px
+
+
+
Mode Values
+
0: Disables comparator.
+
+
+
1: Enables comparator with P0 as Result output.
+
+
+
2: Enables comparator without P0 as Result output.
+
+
+
Result Values
+
0: Voltage P1 > P2; P0 optionally outputs 0.
+
+
+
1: Voltage P1 < P2; P0 optionally outputs 1.
+
+
+
Explanation
+
The COMPARE command enables or disables the built-in comparator
+hardware on the BS2px's I/O pins P0, P1, and P2. I/O pins P1 and P2 are
+the comparator inputs and P0 is optionally the comparator result output
+pin.
+
By default, the comparator feature is disabled. Using the COMPARE command with a Mode argument of 1 or 2 enables the comparator feature
+(using input pins P1 and P2) and returns the result of the comparison in
+Result. If Mode is 1, the result of the comparison is also
+output on I/O pin P0. The following is an example of the COMPARE command:
+result VAR Bit
+
+Main:
+ COMPARE 1, result
+
+
This example enables the comparator (setting P0 to output the result,
+with P1 and P2 as the comparator inputs) and writes the result of the
+comparison into result. Both Result and the output pin P0
+will be 0 if the input voltage on P1 was greater than that of P2.
+result and the output pin P0 will be 1 if the input voltage on P1
+was less than that of P2.
+
Note that the comparator hardware operates independently of the
+execution speed of the BS2px and will continue to run and update P0 if
+Mode = 1, even during sleep mode (execution of END, NAP,
+POLLWAIT 8, or SLEEP commands). To avoid spurious current
+draw during sleep mode, disable the comparator first.
Mode is a variable/constant/expression (0 – 3), or one
+ of four predefined symbols, that specifies the I/O pin property to configure:
+ Schmitt Trigger, Logic Threshold, Pull-up Resistor or Output Direction. See
+ table below for an explanation of Mode values.
+
PinMask is a variable/constant/expression (1 – 65535)
+ that indicates how Mode is applied to I/O pins. Each bit of
+ PinMask corresponds to an individual I/O pin. A high bit (1) enables
+ the Mode and a low bit (0) disables the Mode on the
+ corresponding I/O pin.
The CONFIGPIN command enables or disables special I/O pin properties
+on all 16 I/O pins at once. There are four properties, or modes, available:
+Schmitt Trigger, Logic Threshold, Pull-up Resistor, and Output Direction.
+Each I/O pin on the BS2px contains special hardware dedicated to each of
+these properties.
+
By default, all BASIC Stamp I/O pins are set to inputs. Enabling the
+Output Direction mode sets an I/O pin’s direction to output. Disabling
+the Output Direction mode sets an I/O pin’s direction to input. This has
+the same effect as using the OUTPUT or INPUT commands, or the
+DIRx = # assignment statement to configure I/O pin directions. The
+following is an example of the CONFIGPIN command using the Output
+Direction mode:
+ CONFIGPIN DIRECTION, %0000000100010011
+
+
Every high bit (1) in the PinMask argument enables the output direction
+for the corresponding I/O pin while every low bit (0) disables the output
+direction. In the above example, I/O pins 8, 4, 1, and 0 are set to the
+output direction and all other I/O pins are set to the input direction. This
+is similar to the following statement:
+ DIRS = %0000000100010011
+
+
Pull-up resistors are commonly used in circuitry where a component, such
+as a button, provides an open/drain signal; the signal is either floating
+(open) or is driven to ground (drain). Since the BASIC Stamp input pins
+must always be connected to either 5 volts or ground (0 volts) in order to
+read a reliable logic state with them, a pull-up resistor is required on
+circuitry, such as the button circuit mentioned above, so that the signal is
+never left floating (electrically disconnected).
+
The following example enables internal pull-up resistors on I/O pins 15,
+12, 6, and 3, and disables internal pull-up resistors on all other I/O pins:
+ CONFIGPIN PULLUP, %1001000001001000
+
+
Note that the internal pull-up resistors are intentionally weak, about 20
+kΩ. Additionally, the internal pull-up resistors can be activated for all
+pins, regardless of pin direction, but really matter only when the
+associated pin is set to input mode.
+
An input pin’s logic threshold determines the voltage levels that are
+interpreted as logic high (1) and logic low (0). Most microcontrollers, and
+other integrated circuits use one of two types of logic threshold: TTL Level
+or CMOS Level. The BASIC Stamp I/O pins are, by default, configured for TTL
+level logic thresholds. The figure below is an illustration of the difference
+between TTL and CMOS logic levels.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
TTL Logic Level
+
+
+
CMOS Logic Level
+
+
+
+
+
The logic threshold for TTL is 1.4 volts; a voltage below 1.4 is considered
+to be a logic 0 while a voltage above 1.4 is considered to be a logic 1. The
+logic threshold for CMOS is 50% of Vdd; a voltage below ½ Vdd is
+considered a logic 0 while a voltage above ½ Vdd is considered a logic 1.
+
For the CONFIGPIN command's THRESHOLD mode, a high bit (1) in the
+PinMask argument sets the corresponding I/O pin to CMOS threshold
+level, and a low bit sets it to a TTL threshold level. The following example
+sets CMOS threshold level on I/O pins 3, 2, 1, and 0, and TTL threshold
+level on all other I/O pins.
+ CONFIGPIN THRESHOLD, %0000000000001111
+
+
The threshold level can be set for all pins, regardless of pin direction, but
+really matters only when the associated pin is set to input mode.
+
Normally, if a signal on an input pin is somewhat noisy (the voltage level
+randomly rises and falls beyond the logic threshold boundary) then
+reading that pin’s input value will result in spurious highs and lows (1s
+and 0s). Schmitt Triggers are circuits that make inputs more steady and
+reliable by adding a region of hysteresis around the logic threshold that
+the signal must completely traverse before the logic level is interpreted as
+being changed. By default BASIC Stamp I/O pins are set to normal input
+mode, but the BS2px can be configured for Schmitt Trigger mode as well.
+The figure below illustrates Schmitt Trigger characteristics.
+
+
+
+
+
+
+
+
+
In Schmitt Trigger mode, the threshold for a logic 0 is approximately 15%
+of Vdd and the threshold for a logic 1 is approximately 85% of Vdd. The
+input pin defaults to an unknown state until the initial voltage crosses a
+logic 0 or logic 1 boundary. Thereafter, the voltage must cross above 85%
+of Vdd to be interpreted as a logic 1 and must cross below 15% of Vdd to
+be interpreted as a logic 0. If the voltage transitions somewhere between
+the two thresholds, the interpreted logic state remains the same as the
+previous state.
+
For the CONFIGPIN command’s SCHMITT mode, a high bit (1) in the
+PinMask argument enables the Schmitt Trigger on the corresponding I/O
+pin and a low bit (0) disables the Schmitt Trigger. The following example
+sets Schmitt Triggers on I/O pins 7, 6, 5, and 4, and sets all other I/O pins
+to normal mode.
+ CONFIGPIN SCHMITT, %0000000011110000
+
+
Schmitt Trigger mode can be activated for all pins, regardless of pin
+direction, but really matters only when the associated pin is set to input
+mode.
Count the number of cycles (0-1-0 or 1-0-1) on the specified pin during the Duration time frame and store that number in Variable.
+
+
+
+
Pin is a variable/constant/expression (0 – 15) that specifies
+ the I/O pin to use. This pin will be set to input mode.
+
Duration is a variable/constant/expression (1 – 65535) specifying
+ the time during which to count. The unit of time for Duration is described
+ below.
+
Variable is a variable (usually a Word) in which the count will
+ be stored.
The COUNT instruction makes the Pin an input, then for the specified
+duration, counts cycles on that pin and stores the total in a variable. A
+cycle is a change in state from 1 to 0 to 1, or from 0 to 1 to 0.
+
According to table above, COUNT on the BS2 can respond to transitions
+(pulse widths) as small as 4.16 microseconds (µs). A cycle consists of two transitions
+(e.g., 0 to 1, then 1 to 0), so COUNT (on the BS2) can respond to square
+waves with periods as short as 8.32 µs; up to 120 kilohertz (kHz) in frequency.
+For non-square waves (those whose high time and low time are unequal), the shorter
+of the high and low times must be at least 4.16 µs in width (on the BS2). Refer
+to the table for data on other BASIC Stamp modules.
+
If you use COUNT on slowly changing analog waveforms like sine waves,
+you may find that the value returned is higher than expected. This is because the
+waveform may pass through the BASIC Stamp’s 1.4-volt logic threshold slowly enough
+that noise causes false counts. You can fix this by passing the signal through
+a Schmitt Trigger, like one of the inverters of a 74HCT14. Or, you may use the
+BS2px’s built-in Schmitt-Trigger pin property; see
+CONFIGPIN for details.
When you download a program into the BASIC Stamp, it is stored in the EEPROM starting
+at the highest address (2047) and working towards the lowest address. Most programs
+don't use the entire EEPROM, so the lower portion is available for other uses.
+The DATA directive allows you to define a set of data to store in the available
+EEPROM locations. It is called a "directive" rather than a "command" because it
+performs an activity at compile-time rather than at run-time (i.e.: the DATAdirective is not downloaded to the BASIC Stamp, but the data it contains is downloaded).
+
The simplest form of the DATA directive is something like the following:
+ DATA 100, 200, 52, 45
+
+
This example, when downloaded, will cause the values 100, 200, 52 and 45 to be
+written to EEPROM locations 0, 1, 2 and 3, respectively. You can then use the
+READ and WRITE commands in your code to access these locations and
+the data you've stored there.
+
DATA uses a counter, called a pointer, to keep track of available EEPROM
+addresses. The value of the pointer is initially 0. When a program is downloaded,
+the DATA directive stores the first byte value at the current pointer address,
+then increments (adds 1 to) the pointer. If the program contains more than one
+DATA directive, subsequent DATAs start with the pointer value left
+by the previous DATA. For example, if the program contains:
+ DATA 72, 69, 76, 76, 79
+ DATA 104, 101, 108, 108, 111
+
+
The first DATA directive will start at location 0 and increment the pointer
+for each data value it stores (1, 2, 3, 4, and 5). The second DATA directive
+will start with the pointer value of 5 and work upward from there. As a result,
+the first 10 bytes of EEPROM will look like the following:
+
+
+
+
EEPROM Location (address)
+
+
+
0
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
+
+
Contents
+
72
+
69
+
76
+
76
+
79
+
104
+
101
+
108
+
108
+
111
+
+
+
+
What if you don't want to store values starting at location 0? Fortunately,
+the DATA directive has an option to specify the next location to use. You
+can specify the next location number (to set the pointer to) by inserting a
+DataItem in the form @x ;where x is the location number. The following code
+writes the same data in the table above to locations 100 through 109:
In this example, the first DataItem is @100. This tells the DATA directive
+to store the following DataItem(s) starting at location 100. All the
+DataItems to the right of the @100 are stored in their respective locations
+(100, 101, 102... 109).
+
In addition, the DATA directive allows you to specify new starting locations
+at any time within the DataItem list. If, for example, you wanted to store
+56 at location 100 and 47 at location 150 (while leaving every other location intact),
+you could type the following:
+ DATA @100, 56, @150, 47
+
+
If you have multiple DATA directives in your program, it may be difficult
+to remember exactly what locations contain the desired data. For this reason, the
+DATA directive can optionally be prefixed with a unique symbol name. This
+symbol becomes a constant that is set equal to the location number of the first
+byte of data within the directive. For example,
+MyNumbers DATA @100, 72, 73
+
+
This would store the values 72 and 73 starting with location 100 and will create
+a constant, called MyNumbers, which is set equal to 100. Your program can then
+use the MyNumbers constant as a reference to the start of the data within a READor WRITE command. Each DATA directive can have a unique symbol preceding
+it, allowing you to reference the data defined at different locations.
+
There may be a time when you wish to reserve a section of EEPROM for use by your
+BASIC code, but not necessarily store data there to begin with. To do this, simply
+specify a DataItem within parentheses, as in:
+ DATA @100, (20)
+
+
The above DATA directive will reserve 20 bytes of EEPROM, starting with
+location 100. It doesn't store any values there, rather it simply leaves the data
+as it is and increments DATA's location pointer by 20. A good reason to
+do this is when you have a program already downloaded into the BASIC Stamp that
+has created or manipulated some data in EEPROM. To protect that section of EEPROM
+from being overwritten by your next program (perhaps a new version of the same
+program) you can reserve the space as shown above. The EEPROM's contents from
+locations 100 to 119 will remain intact. NOTE: This only "reserves" the space for
+the program you are currently downloading; the BASIC Stamp does not know to
+"reserve" the space for future programs. In other words, make sure use this
+feature of the DATA directive in every program you download if you don't
+want to risk overwriting valuable EEPROM data.
+
It is important to realize that EEPROM is not overwritten during programming
+unless it is needed for program storage, or is filled by a DATA directive
+specifying data to be written. During downloading, EEPROM is always written in
+16-byte sections if, and only if, any location within that section needs writing.
+
DATA can also store the same number in a block of consecutive locations.
+This is similar to reserving a block of EEPROM, above, but with a value added before
+the first parenthesis. For example,
+ DATA @100, 0 (20)
+
+
This statement writes the value 0 in all the EEPROM locations from 100 to 119.
+
A common use for DATA is to store strings; sequences of bytes representing
+text. PBASIC converts quoted text like "A" into the corresponding ASCII character
+code (65 in this case). To make data entry easier, you can place quotes around a
+whole chunk of text used in a DATA directive, and PBASIC will understand
+it to mean a series of bytes (see the last line of code below). The following
+three DATA directives are equivalent:
+ DATA 72, 69, 76, 76, 79
+ DATA "H", "E", "L", "L", "O"
+ DATA "HELLO"
+
+
All three lines of code, above, will result in the numbers 72, 69, 76, 76, and
+79 being stored into EEPROM upon downloading. These numbers are simply the ASCII
+character codes for "H", "E", "L", "L", and "O", respectively. See the
+Example program link at the top for a demonstration of storing and
+reading multiple text strings.
+
The EEPROM is organized as a sequential set of byte-sized memory locations.
+By default, the DATA directive stores bytes into EEPROM. If you try to
+store a word-size value (ex: DATA 1125) only the lower byte of the value
+will be stored. This does not mean that you can't store word-sized values, however.
+A word consists of two bytes, called a low-byte and a high-byte. If you wanted
+to store the value 1125 using the DATA directive, simply insert the prefix
+"Word" before the number, as in:
+ DATA Word 1125
+
+
The directive above will automatically break the word-size value into two bytes
+and store them into two sequential EEPROM locations (the low-byte first, followed
+by the high-byte, or "Little Endian"). In this case, the low-byte is 101
+and the high byte is 4 and they will be stored in locations 0 and 1, respectively.
+If you have multiple word-size values, you must prefix each value with "Word",
+as in:
+ DATA Word 1125, Word 2000
+
+
To retrieve a word-size value, you'll need to use the Word modifier with
+READ (only available in PBASIC 2.5 syntax). For example,
+' {$PBASIC 2.5}
+
+result VAR Word
+
+Storage:
+ DATA Word 1125
+
+Main:
+ READ 0, Word result
+ DEBUG DEC result
+ END
+
+
This code would write the low-byte and high-byte of the number 1125 into locations
+0 and 1 during download. When the program runs, the READ function (with
+the Word modifier) will retrieve the value out of EEPROM and then display the value
+on the screen. See the READ and WRITE commands for more information.
+
Finally, a DataItem may be defined using a simple expression with the binary
+operators as shown below:
+MinLvl CON 10
+
+myLvl VAR Byte
+
+Level1 DATA MinLvl + 10
+Level2 DATA MinLvl * 5 + 21
+
+Main:
+ READ Level2, myLvl ' read EE location Level2
+ DEBUG DEC myLvl ' show value of myLvl (71)
+ END
+
Display information on the PC screen within the BASIC Stamp editor program. This
+command can be used to display text or numbers in various formats on the PC screen
+in order to follow program flow (called debugging) or as part of the functionality
+of the BASIC Stamp application.
+
+
+
OutputData is a variable/constant/expression* (0 - 65535) that
+ specifies the information to output. Valid data can be ASCII characters (text
+ strings and control characters), decimal numbers (0 - 65535), hexadecimal numbers
+ ($0000 - $FFFF) or binary numbers (up to %1111111111111111). Data can be
+ modified with special formatters as explained below.
+
+
* Note: Expressions are not allowed as arguments on the BS1. The only
+ constant allowed for the BS1 DEBUG command is a text string.
+
Quick Facts
+
+
+
+
BS1
+
BS2, BS2e, BS2sx, BS2p, and BS2pe
+
BS2px
+
+
+
Serial Protocol
+
Asychronous 4800 baud, N, 8, 1 Inverted polarity,
+ Raw Data Custom packetized format
+
Asychronous 9600 baud, N, 8, 1 Inverted polarity,
+ Raw Data
+
Asychronous 19.2 kBaud, N, 8, 1 Inverted polarity,
+ Raw Data
DEBUG provides a convenient way for your BASIC Stamp to send messages to
+the PC screen while running. The name "debug" suggests its most popular use;
+debugging programs by showing you the value of a variable or expression, or by
+indicating what portion of a program is currently executing. DEBUG is also
+a great way to rehearse programming techniques. Throughout this manual, we use
+DEBUG to give you immediate feedback on the effects of instructions. The
+following example demonstrates using the DEBUG command to send the text
+string message "Hello World!".
+ DEBUG "Hello, World!" ' test Message
+
+
After you download this one-line program, the BASIC Stamp Editor will open a
+Debug terminal on your PC screen and wait for a response from the BASIC Stamp.
+A moment later, the phrase "Hello World!" will appear. Note that if you close the
+Debug terminal, your program keeps executing, but you can't see the DEBUG
+data anymore.
+
Multiple pieces of data can be sent with one DEBUG command by separating
+the data with commas (,). The following example produces exactly the same results
+as the example above.
+ DEBUG "Hello, ", "World!" ' test Message
+
+
DEBUG can also print and format numbers (values) from both constants
+and variables. Please note that formatting the DEBUG output with the BS1
+differs significantly from formatting the DEBUG output with the BS2 family.
+Please read the appropriate sections that follow carefully.
+
Tip: Don't let your BASIC Stamp be mistaken for a mouse!
+
+ Connecting USB-based boards to your PC may cause the BASIC Stamp to reset. If your BASIC Stamp program immediately starts sending serial data to the computer via a DEBUG or SEROUT command, your computer's operating system may mistake it for a mouse or other serial plug-and-play device. To avoid this, place a 1-second pause at the beginning of the program.
+
+ BASIC Stamp 1 Formatting
+
On the BS1, the DEBUG command, by default, displays numbers in the format
+"symbol = value" (followed by a carriage return), using the decimal number system.
+For example:
+SYMBOL x = B2
+
+Init:
+ x = 75
+
+Main:
+ DEBUG x
+ END
+
+
...displays "x = 75" on the screen. To display the value, in decimal, without
+the "x =" text, use the decimal formatter (#) before the variable name. For
+example, the following code displays "75" on the screen:
+SYMBOL x = B2
+
+Init:
+ x = 75
+
+Main:
+ DEBUG #x
+ END
+
+
To display numbers in hexadecimal or binary form, use the $ or % formatter,
+respectively. The code below displays the same number in its hexadecimal and binary
+forms.
+SYMBOL x = B2
+
+Init:
+ x = 75
+
+Main:
+ DEBUG $x, %x
+ END
+
+
After running the above code, "X = $4B" and "X = %01001011" should appear on the
+screen. To display hexadecimal ($) or binary (%) values without the "symbol = "
+preface, use the # modifier as shown below:
+SYMBOL x = B2
+
+ x = 75
+ DEBUG #x, "as HEX is ", #$x ' displays "75 as HEX is $4B"
+
+
To display a number as its ASCII character equivalent, use the ASCII formatter
+(@). Typing DEBUG @x (in place of the DEBUG statement in the code
+above) would display "x = 'K'" on the screen.
+
Two pre-defined symbols, CR and CLS, can be used to send a carriage-return or
+clear-screen command to the Debug Terminal. The CR symbol will cause the Debug
+Terminal to start a new line and the CLS symbol will cause the Debug Terminal to
+clear itself and place the cursor at the top-left corner of the screen. The
+following code demonstrates this.
+ DEBUG "You can not see this.", CLS, "Here is line 1", CR, "Here is line 2"
+
+
When the above is run, the final result is "Here is line 1" on the first line
+of the screen and "Here is line 2" on the second line. You may or may not have
+seen "You can not see this." appear first. This is because it was immediately
+followed by a clear-screen symbol, CLS, which caused the display to clear the
+screen before displaying the rest of the information.
+
Tip: The rest of this discussion does not apply to the BASIC Stamp
+1.
+
+
+ BASIC Stamp 2 Series Formatting
+
On the all BASIC Stamp models except the BS1, the DEBUG command, by default,
+displays everything as ASCII characters. What if you want to display a number?
+You might think the following example would do this:
+x VAR Byte
+
+Init:
+ x = 65
+
+Main:
+ DEBUG x ' show value of x
+ END
+
+
Since we set x equal to 65 (in line 2), you might expect the DEBUG line
+to display "65" on the screen. Instead of "65", however, you'll see the letter
+"A" if you run this example. The problem is that we never told the BASIC Stamp
+how to output x, and it defaults to ASCII (the ASCII character at position 65 is
+"A"). Instead, we need to tell it to display the "decimal form" of the number in
+X. We can do this by using the decimal formatter (DEC) before the variable. The
+example below will display "65" on the screen.
+x VAR Byte
+
+Init:
+ x = 65
+
+Main:
+ DEBUG DEC x ' show decimal value of x
+ END
+
+
In addition to decimal (DEC), DEBUG can display numbers in hexadecimal
+(HEX) and binary (BIN). See the table below for a complete list of formatters.
+
Expressions are allowed within the DEBUG command arguments as well. In
+the above code, DEBUG DEC x+25 would yield "90" and DEBUG DEC
+x*10/2-3 would yield "322".
+
+
+
+
Formatter
+
Description
+
+
+
?
+
Displays "symbol = x' + carriage return; where x is a number. Default
+ format is decimal, but may be combined with conversion formatters (ex:
+ BIN ? x to display "x = binary_number").
+
+
+
ASC ?
+
Displays "symbol = 'x'" + carriage return; where x is an ASCII character.
+
+
+
DEC{1..5}
+
Decimal, optionally fixed to 1 - 5 digits
+
+
+
SDEC{1..5}
+
Signed decimal, optionally fixed to 1 - 5 digits
+
+
+
HEX{1..4}
+
Hexadecimal, optionally fixed to 1 - 4 digits
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally fixed to 1 - 4 digits
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally fixed to 1 - 4 digits
Indicated binary, optionally fixed to 1 - 16 digits
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally fixed to 1 - 16 digits
+
+
+
STR ByteArray
+
ASCII string from bytearray until byte = 0.
+
+
+
STR ByteArray {\L}
+
ASCII string consisting of n bytes from bytearray.
+
+
+
REP Byte\L
+
Display ASCII character n times.
+
+
+
As seen above, special versions of the DEC, HEX and BIN formatters allow for
+the display of indicated, signed and fixed-width numbers. The term "indicated"
+simply means that a special symbol is displayed, before the number, indicating
+what number system it belongs to. For example:
+x VAR Byte
+
+Init:
+ x = 65
+
+Main:
+ DEBUG HEX x ' show hexadecimal value of x
+ END
+
+
...displays "41" (65, in decimal, is 41, in hexadecimal). You might see a problem
+here... unless you knew the number was supposed to be hexadecimal, you might think
+it was 41, in decimal... a totally different number. To help avoid this, use the
+IHEX formatter (the "I" stands for indicated). Changing the DEBUG line to
+read: DEBUG IHEX x would print "$41" on the screen. A similar formatter
+for binary also exists, IBIN, which prints a "%" before the number.
+
Signed numbers are preceded with a space ( ) or a minus sign (-) to indicate a
+positive or negative number, respectively. Normally, any number displayed by the
+BASIC Stamp is shown in its unsigned (positive) form without any indicator. The
+signed formatters allow
+you to display the number as a signed (rather than unsigned) value.
+
Tip: Only
+Word-sized variables can be used for signed number display.
+
+
The code below
+demonstrates the difference in all three numbering schemes.
+x VAR Word
+
+Init:
+ x = -65
+
+Main:
+ DEBUG "Signed: ", SDEC x, " ", ISHEX x, " ", ISBIN x, CR
+ DEBUG "Unsigned: ", DEC x, " ", IHEX x, " ", IBIN x
+ END
+
The signed form of the number -65 is shown in decimal, hexadecimal and then in
+binary on the top line. The unsigned form, in all three number systems, is shown
+on the bottom line. If the unsigned form looks strange to you, it's because negative
+numbers are stored in twos-compliment format within the BASIC Stamp.
+
Suppose that your program contained several DEBUG instructions showing
+the contents of different variables. You would want some way to tell them apart.
+One possible way is to do the following:
+x VAR Byte
+y VAR Byte
+
+Init:
+ x = 100
+ y = 250
+
+Main:
+ DEBUG "X = ", DEC x, CR ' show decimal value of x
+ DEBUG "Y = ", DEC y, CR ' show decimal value of y
+ END
+
+
...but typing the name of the variables in quotes (for the display) can get a
+little tedious. A special formatter, the question mark (?), can save you a lot
+of time. The code below does exactly the same thing (with less typing):
+x VAR Byte
+y VAR Byte
+
+Init:
+ x = 100
+ y = 250
+
+Main:
+ DEBUG DEC ? x ' show decimal value of x
+ DEBUG DEC ? y ' show decimal value of y
+ END
+
+
The display would look something like this:
x = 100 y = 250
+
+
The ? formatter always displays data in the form "symbol = value" (followed by
+a carriage return). In addition, it defaults to displaying in decimal, so we really
+only needed to type: DEBUG ? x for the above code. You can, of course,
+use any of the three number systems. For example: DEBUG HEX ? x or
+DEBUG BIN ? y.
+
It's important to note that the "symbol" it displays is taken directly from what
+appears to the right of the ?. If you were to use an expression, for example:
+DEBUG ? x*10/2+3 in the above code, the display would show: "x*10/2+3
+= 503".
+
A special formatter, ASC, is also available for use only with the ? formatter
+to display ASCII characters, as in: DEBUG ASC ? x.
+
What if you need to display a table of data; multiple rows and columns? The
+Signed/Unsigned code (above) approaches this but, if you notice, the columns don't
+line up. The number formatters (DEC, HEX and BIN) have some useful variations to
+make the display fixed-width. Up to 5 digits can be displayed for decimal numbers.
+To fix the value to a specific number of decimal digits, you can use DEC1, DEC2,
+DEC3, DEC4 or DEC5. For example:
+x VAR Byte
+
+Init:
+ x = 165
+
+Main:
+ DEBUG DEC5 x ' show decimal value of x
+ END ' in 5 digits
+
+
...displays "00165". Notice that leading zeros? The display is "fixed" to 5 digits,
+no more and no less. Any unused digits will be filled with zeros.
+
Using DEC4 in the same code would display "0165". DEC3 would display "165".
+What would happen if we used DEC2? Regardless of the number, the BASIC Stamp will
+ensure that it is always the exact number of digits you specified. In this case,
+it would truncate the "1" and only display "65".
+
Using the fixed-width version of the formatters in the Signed/Unsigned code
+above, may result in the following code:
+x VAR Word
+
+Init:
+ x = -65
+
+Main:
+ DEBUG "Signed: ", SDEC5 x, " ", ISHEX4 x, " ", ISBIN16 x, CR
+ DEBUG "Unsigned: ", DEC5 x, " ", IHEX4 x, " ", IBIN16 x
+ END
+
Note that the columns don't line up exactly (due to the extra "sign" characters
+in the first row), but it certainly looks better than the alternative.
+
Displaying Strings (Byte Arrays)
+
If you have a string of characters to display (a byte array), you can use the
+STR formatter to do so. The STR formatter has two forms (as shown in the table above)
+for variable-width and fixed-width data. The example below is the variable-width
+form.
This code displays "ABCD" on the screen. In this form, the STR formatter displays
+each character contained in the byte array until it finds a character that is equal
+to 0 (value 0, not "0"). This is convenient for use with the SERIN command's STR
+formatter, which appends 0's to the end of variable-width character string inputs.
+NOTE: If your byte array doesn't end with 0, the BASIC Stamp will read and output
+all RAM register contents until it finds a 0 or until it cycles through all RAM
+locations.
+
To specify a fixed-width format for the STR formatter, use the form STR alpha\n;
+where alpha is the byte array and n is the number of characters to print. Changing
+the DEBUG line in the example above to: DEBUG STR alpha\2 would display
+"AB" on the screen.
+
If you need to display the same ASCII character multiple times, the REP (repeat)
+formatter can help. REP takes the form: REP x\n ;where x is the character and
+n is the number of times to repeat it. For example:
+ DEBUG REP "-"\10
+
+
...would display 10 hyphens on the screen, "----------".
+
Since individual DEBUG instructions can grow to be fairly complicated,
+and since a program can contain many DEBUGs, you'll probably want to control
+the character positioning of the Debug Terminal screen. DEBUG supports a
+number of different control characters, some with pre-defined symbols. The Debug
+Terminal in the Windows® version of the editor supports all the
+control characters shown below, while the DOS version only supports a few of them.
+
Some of the control characters have pre-defined symbols associated with them.
+In your DEBUG commands, you can use those symbols, for example: DEBUG"Hello", CR displays "Hello" followed by a carriage return. You can always use
+the ASCII value for any of the control characters, however. For example: DEBUG"Hello", 13 is exactly the same as the code above.
+
The Move To control character is perhaps the most unique of the set. If the
+Debug Terminal receives this character, it expects to see an x and y position value
+to follow (in the next two characters received). The following line moves the
+cursor to column number 4 in row number 5 and displays "Hello":
+ DEBUG CRSRXY, 4, 5, "Hello"
+
+
The upper-left cursor position is 0, 0 (that is column 0, line 0). The right-most
+cursor positions depend on the size of the Debug Terminal window (which is user
+adjustable). If a character position that is out of range is received, the Debug
+Terminal wraps back around to the opposite side of the screen.
+
The Clear EOL (end of line) control character clears the characters that appear
+to the right of, and on, the cursor's current position. The cursor is not moved
+by this action.
+
The Clear Down control character clears the characters that appear below, and
+on, the cursor's current line. The cursor is not moved by this action.
+
+
+
Name
+
Symbol
+
ASCII Value
+
Description
+
+
+
Clear Screen
+
CLS 1
+
0
+
Clear the screen and place cursor at home position.
+
+
+
Home
+
HOME
+
1
+
Place cursor at home in upper-left corner of the screen.
+
+
+
Move To (x, y)
+
CRSRXY 2
+
2
+
Move cursor to specified location (column, line). Must be
+ followed by two values (x and then y)
+
+
+
Cursor Left
+
CRSRLF 2
+
3
+
Move cursor one character to left.
+
+
+
Cursor Right
+
CRSRRT 2
+
4
+
Move cursor one character to right.
+
+
+
Cursor Up
+
CRSRUP 2
+
5
+
Move cursor one character up.
+
+
+
Cursor Down
+
CRSRDN 2
+
6
+
Move cursor one character down.
+
+
+
Bell
+
BELL
+
7
+
Beep the PC speaker.
+
+
+
Backspace
+
BKSP
+
8
+
Back up cursor to left one space.
+
+
+
Tab
+
TAB
+
9
+
Tab to the next column.
+
+
+
Line Feed
+
LF
+
10
+
Move cursor down one line.
+
+
+
Clear to End of Line
+
CLREOL 2
+
11
+
Clear line contents to the right of cursor.
+
+
+
Clear Down
+
CLRDN 2
+
12
+
Clear screen contents below cursor.
+
+
+
Carriage Return
+
CR 1
+
13
+
Move cursor to the first column of the next line (shift any
+ data on the right down to that line as well)
+
+
+
Move To Column X
+
CRSRX 2
+
14
+
Move cursor to specified column. Must be followed by byte
+ value (x) for the column (0 is the left-most column)
+
+
+
Move To Line Y
+
CRSRY 2
+
15
+
Move cursor to specified line. Must be followed by byte
+ value (y) for the line (0 is the top-most line)
+
+
+
1 Supported by BS1 DEBUG command (others not supported). 2 This control character only works with the Windows®
+version of the editor software.
+
+
In the BS2 family, DEBUG is actually a special case of the SEROUTinstruction. It is set for inverted (RS-232-compatible) serial output through the
+programming connector (the SOUT pin) at 9600 baud (BS2, BS2e, BS2sx, BS2p, and
+BS2pe) or 19.2 kBaud (BS2px), no parity, 8 data bits, and 1 stop bit.
+For example,
+ DEBUG "Hello"
+
+
...is exactly like:
+ SEROUT 16, $4054, ["Hello"]
+
+
in terms of function (on a BS2). The DEBUG line actually takes less
+program space, and is obviously easier to type.
+
You may view DEBUG's output using a terminal program set to the above
+parameters, but you may have to modify either your carrier board or the serial
+cable to temporarily disconnect pin 3 of the BASIC Stamp (pin 4 of the DB-9
+connector). See the SEROUT command for more detail.
+
Another method to decrease program space is to reduce the number of DEBUG
+instructions by spreading DEBUG data across multiple lines. To do this,
+each line that wraps around must end with a comma as in the example below:
+
+
+ DEBUG "This is line 1", CR,
+ "This is line 2"
+
+
The example above works identically to, but uses less program space than, this version:
+ DEBUG "This is line 1", CR
+ DEBUG "This is line 2"
+
+
Tip: Note that spreading a DEBUG statement across multiple lines requires the
+declaration of PBASIC 2.5 syntax.
Retrieve information from the user via the Debug Terminal window within the BASIC Stamp editor program.
+
+
+
+
InputData is list of variables and formatters that tells
+ DEBUGIN what to do with incoming data. DEBUGIN can store data in
+ a variable or array, interpret numeric text (decimal, binary, or hex) and store
+ the corresponding value in a variable, wait for a fixed or variable sequence of
+ bytes, or ignore a specified number of bytes. These actions can be combined
+ in any order in the InputData list.
+
+
Quick Facts
+
+
+
+
BS2, BS2e, BS2sx, BS2p, and BS2pe
+
BS2px
+
+
+
Serial Protocol
+
Asychronous 9600 baud, N, 8, 1 Inverted polarity,
+ Raw Data
+
Asychronous 19.2 kBaud, N, 8, 1 Inverted polarity,
+ Raw Data
DEBUGIN provides a convenient way for your BASIC Stamp accept input from
+the use via the Debug Terminal. DEBUGIN can wait for, filter and
+convert incoming data in powerful ways, using the same techniques and modifiers
+as SERIN.
+
+
+
This simple example waits for a number from the user, then prints a message
+the specified number of times:
+lines VAR Nib
+idx VAR Nib
+
+Main:
+ DEBUG CLS, "How many lines to print (1 - 5)? --> "
+ DEBUGIN DEC1 lines
+
+ IF ((lines >= 1) AND (lines <= 5)) THEN
+ DEBUG CR, CR
+ FOR idx = 1 TO lines ' print message specified times
+ DEBUG DEC1 idx, ". "
+ DEBUG "BASIC Stamp!", CR
+ NEXT
+ END ' end of program
+ ELSE
+ DEBUG CR, "Invalid entry!" ' warning message
+ PAUSE 2000 ' wait 2 seconds
+ GOTO Main ' get another entry
+ ENDIF
+
+
After you download this program, the BASIC Stamp Editor will open a Debug
+Terminal on your PC screen and wait for an entry from the user. Since the DEC1
+modifier is used with DEBUGIN, the program will ignore all keys except
+"0" - "9". If the value entered is between 1 and 5, the message will be printed,
+otherwise the program will display an "Invalid entry" message, then loop back
+and wait for another entry.
+
DEBUGIN is actually a special case of the SERIN instruction. It
+is set for inverted (RS-232-compatible) serial output through the programming
+connector (the SIN pin) at 9600 baud (BS2, BS2e, BS2sx, BS2p, and BS2pe) or
+19.2 kBaud (BS2px), no parity, 8 data bits, and 1 stop bit.
+For example,
+ DEBUGIN DEC1 lines
+
+
...is exactly like:
+ SERIN 16, $4054, [DEC1 lines]
+
+
...in terms of function (on a BS2). The DEBUGIN line actually takes less
+program space, and is obviously easier to type.
+
The tables below list all the available conversion formatters and special
+formatters available to the DEBUGIN command. See the
+SERIN command for additional information and examples
+of their use.
+
+
+
Conversion Formatter
+
Type of Number
+
Numeric Characters Accepted
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally limited to 1 - 5 digits
+
0 through 9
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally limited to 1 - 5 digits
+
-, 0 through 9
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally limited to 1 - 4 digits
+
0 through 9, A through F
+
1,3
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally limited to 1 - 4 digits
+
-, 0 through 9, A through F
+
1,2,3
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally limited to 1 - 4 digits
+
$, 0 through 9, A through F
+
1,3,4
+
+
+
ISHEX{1..4}
+
Signed, indicated hexadecimal, optionally limited to 1 - 4 digits
+
-, $, 0 through 9, A through F
+
1,2,3,4
+
+
+
BIN{1..16}
+
Binary, optionally limited to 1 - 16 digits
+
0, 1
+
1
+
+
+
SBIN{1..16}
+
Signed binary, optionally limited to 1 - 16 digits
+
-, 0, 1
+
1,2
+
+
+
IBIN{1..16}
+
Indicated binary, optionally limited to 1 - 16 digits
+
%, 0, 1
+
1,4
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally limited to 1 - 16 digits
+
-, %, 0, 1
+
1,2,4
+
+
+
NUM
+
Generic numeric input; hex or binary number must be indicated
+
$, %, 0 through 9, A through F
+
1,3,4
+
+
+
SNUM
+
Similar to NUM with value treated as signed with range -32768 to +32767
+
-, $, %, 0 through 9, A through F
+
1,2,3,4
+
+
+
+
All numeric conversions will continue to accept new data until receiving
+ either the specified number of digits (ex: three digits for DEC3) or a
+ non-numeric character.
+
To be recognized as part of a number, the minus sign (-) must immediately
+ precede a numeric character. The minus sign character occurring in non-numeric
+ text is ignored and any character (including a space) between a minus and a
+ number causes the minus to be ignored.
+
The hexadecimal formatters are not case-sensitive; "a" through "f" means
+ the same as "A" through "F".
+
Indicated hexadecimal and binary formatters ignore all characters, even
+ valid numerics, until they receive the appropriate prefix ($ for hexadecimal,
+ % for binary). The indicated formatters can differentiate between text and
+ hexadecimal (ex: ABC would be interpreted by HEX as a number but IHEX would
+ ignore it unless expressed as $ABC). Likewise, the binary version can
+ distinguish the decimal number 10 from the binary number %10. A prefix
+ occurring in non-numeric text is ignored, and any character (including a
+ space) between a prefix and a number causes the prefix to be ignored. Indicated,
+ signed formatters require that the minus sign come before the prefix, as
+ in -$1B45.
+
+
+
+
+
Special Formatter
+
Action
+
+
+
STR ByteArray \L {\E}
+
Input a character string of length L into an array. If specified, an end
+ character E causes the string input to end before reaching length L.
+ Remaining bytes are filled with 0s (zeros).
+
+
+
WAITSTR ByteArray {\L}
+
Wait for a sequence of bytes matching a string stored in an array variable,
+ optionally limited to L characters. If the optional L argument is left off,
+ the end of the array-string must be marked by a byte containing a zero (0).
+
+
+
SKIP Length
+
Ignore Length bytes of characters.
+
+
+
+
+
+
+
+
+
+
+
+
+
Special Formatter
+
Action
+
+
+
SPSTR L
+
Buffer length L bytes (up to 126) of serial characters to Scratchpad RAM,
+ starting at location 0. Use GET to retrieve the
+ characters.
+
+
+idx VAR Nib
+char VAR Byte
+
+Setup:
+ DEBUG CLS, "Enter (4-character) passcode: "
+
+Main:
+ DEBUGIN SPSTR 4
+ DEBUG CLS, "Checking: "
+ FOR idx = 0 TO 3
+ GET idx, char
+ DEBUG char
+ NEXT
+ END
+
+
The example above will redirect four characters from the Debug Terminal
+input to Scratchpad locations 0 - 3.
DO...LOOP loops let your program execute a series of instructions
+indefinitely, or until a specified condition terminates the loop. The simplest
+form is shown here:
In this example the error message will be printed on the
+DEBUG screen every two seconds until the BASIC Stamp is
+reset. Simple DO...LOOP loops can be terminated with
+EXIT. For example:
+Error_Message:
+ DO
+ DEBUG "Error...", CR
+ PAUSE 1000
+ IF (AckPin = 0) THEN EXIT ' wait for user button press
+ LOOP
+ GOTO Initialize ' re-initialize system
+
+
In this case the loop will continue until the pin named AckPin is pulled low,
+then the loop will terminate and continue at the line GOTO Initialize.
+
More often than not, you will want to test some condition to determine whether
+the loop code should run or continue to run. A loop that tests the condition before
+running loop code is constructed like this:
+reps VAR Nib
+
+Print_Stars:
+ DO WHILE (reps < 3) ' test before loop statements
+ DEBUG "*"
+ reps = reps + 1
+ LOOP
+
+
In this program the loop code DEBUG "*" will not run unless the WHILE
+condition evaluates as True. Another way to write the loop is like this:
+reps VAR Nib
+
+Print_Stars:
+ DO
+ DEBUG "*"
+ reps = reps + 1
+ LOOP UNTIL (reps >= 3) ' test after loop statements
+
+
The difference is that with this loop, the loop statements will always run at
+least once before the condition is tested and will continue to as long as the
+UNTIL condition evaluates as False.
+
Note that WHILE (loop runs while True) and UNTIL (loop runs until
+True) tests can be interchanged, but are generally used as illustrated above.
+
Pin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin to use. This pin will be set to output mode during generation of
+ tones and set to input mode afterwards.
+
OnTime is an optional variable/constant/expression (0 - 65535)
+ specifying a duration of the tone. The unit of time and the default time for
+ OnTime is described below.
+
OffTime is an optional variable/constant/expression (0 - 65535)
+ specifying the length of silent pause after a tone (or between tones, if
+ multiple tones are specified). The unit of time and the default time for
+ OffTime is described below.
+
Tone is a variable/constant/expression (0 - 15) specifying the
+ DTMF tone to generate. Tones 0 through 11 correspond to the standard layout
+ of the telephone keypad, while 12 through 15 are the fourth-column tones used
+ by phone test equipment and in ham-radio applications.
DTMF tones are used to dial the phone or remotely control certain radio equipment.
+The BASIC Stamp can generate these tones digitally using the DTMFOUT
+instruction.
+
This figure shows how to connect an audio amplifier or speaker to hear these
+tones:
+
+
+
+
+
...and this figure shows how to connect the BASIC Stamp to the phone line:
+
+
+
+
+
The following DTMFOUT instruction will generate DTMF tones on I/O pin 0:
+
+
If the BASIC Stamp is connected to the phone line properly, the above command
+would be equivalent to dialing 1-916-624-8333 from a phone keypad. If you wanted
+to slow the pace of the dialing to accommodate a noisy phone line or radio link,
+you could use the optional OnTime and OffTime values:
+
+
In this example, on a BS2 theOnTime is set to 500 ms (1/2 second) and OffTime to 100 ms (1/10th second).
+
+
+
+
+
Tone Value
+
Corresponding Telephone Key
+
+
+
0 - 9
+
Digits 0 through 9
+
+
+
10
+
Star (*)
+
+
+
11
+
Pound (#)
+
+
+
12 - 15
+
Fourth column tones A through D
+
+
+
+
+
The BASIC Stamp microcontroller is a purely digital device. DTMF tones are analog
+waveforms, consisting of a mixture of two sine waves at different audio frequencies.
+So how does a digital device generate analog output? The BASIC Stamp creates and
+mixes the sine waves mathematically, then uses the resulting stream of numbers to
+control the duty cycle of a very fast pulse-width modulation (PWM) routine. So
+what's actually coming out of the I/O pin is a rapid stream of pulses. The purpose
+of the filtering arrangements shown in the figures above is to smooth out the
+high-frequency PWM, leaving only the lower frequency audio behind.
+
Keep this in mind if you want to interface a BASIC Stamp module's DTMF output to radios
+and other equipment that could be adversely affected by the presence of
+high-frequency
+noise on the input. Make sure to filter the DTMF output thoroughly. The circuits
+above are only a starting point; you may want to use an active low-pass filter
+with a roll-off point around 2 kHz.
Location is an optional variable/constant (0 - 255) that
+ specifies the starting location in the EEPROM at which data should be stored.
+ If no location is given, data is written starting at the next available
+ location.
+
DataItem is a constant (0 - 255) to be stored in EEPROM.
+
+
Quick Facts
+
+
+
+
+
+
BS1
+
+
+
Special Notes
+
Writes values to EEPROM during download. Can be used to decrease program size.
When you download a program into the BASIC Stamp 1, it is stored in the EEPROM
+starting at the highest address (255) and working towards the lowest address. Most
+programs don't use the entire EEPROM, so the lower portion is available for other
+uses. The EEPROM directive allows you to define a set of data to store in
+the available EEPROM locations. It is called a "directive" rather than a "command"
+because it performs an activity at compile-time rather than at run-time (i.e., the
+EEPROM directive is not downloaded to the BASIC Stamp 1, but the data it
+contains is downloaded).
+
The simplest form of the EEPROM directive is something like the following:
+EEPROM (100, 200, 52, 45)
+
+
This example, when downloaded, will cause the values 100, 200, 52 and 45 to be
+written to EEPROM locations 0, 1, 2 and 3, respectively. You can then use the
+READ and WRITE commands in your code to access these locations and
+the data you've stored there
+
The EEPROM directive uses a counter, called a pointer, to keep track of
+available EEPROM addresses. The value of the pointer is initially 0. When a program
+is downloaded, the EEPROM directive stores the first byte value at the current
+pointer address, then increments (adds 1 to) the pointer. If the program contains
+more than one EEPROM directive, subsequent EEPROM directives start
+with the pointer value left by the previous EEPROM directive. For example,
+if the program contains:
The first EEPROM directive will start at location 0 and increment the
+pointer for each data value it stores (1, 2, 3, 4 and 5). The second EEPROMdirective will start with the pointer value of 5 and work upward from there. As
+a result, the first 10 bytes of EEPROM will look like the following:
+
+
+
+
EEPROM Location (address)
+
+
+
0
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
+
+
Contents
+
72
+
69
+
76
+
76
+
79
+
104
+
101
+
108
+
108
+
111
+
+
+
What if you don't want to store values starting at location 0? Fortunately,
+the EEPROM directive has an option to specify the next location to use.
+You can specify the next location number (to set the pointer to) by using the
+optional Location argument before the list of DataItems. The following
+code writes the same data in the table above to locations 50 through 59:
In this example, the Location argument is given and tells the EEPROMdirective to store the following DataItem(s) starting at location 50. The
+DataItems in the list are stored in their respective locations (50, 51,
+52... 59).
+
It is important to realize that the entire BASIC Stamp 1 EEPROM is overwritten
+during programming. Any EEPROM location not containing a PBASIC program or
+DataItems from an EEPROM directive is written with a 0.
+
A common use for EEPROM is to store strings; sequences of bytes representing
+text. PBASIC converts quoted text like "A" into the corresponding ASCII character
+code (65 in this case). To make data entry easier, you can place quotes around a
+whole chunk of text used in a EEPROM directive, and PBASIC will understand
+it to mean a series of bytes (see the last line of code below). The following three
+EEPROM directives are equivalent:
All three lines of code, above, will result in the numbers 72, 69, 76, 76, and
+79 being stored into EEPROM upon downloading. These numbers are simply the ASCII
+character codes for "H", "E", "L", "L", and "O", respectively. See the
+Example program above for a demonstration of storing and
+reading multiple text strings.
+
The EEPROM is organized as a sequential set of byte-sized memory locations.
+The EEPROM directive only stores bytes into EEPROM. If you try to store
+a word-size value, for example: EEPROM (1125), only the lower byte of the
+value will be stored (in this case, 101). This does not mean that you can't store
+word-sized values, however. A word consists of two bytes, called a low-byte and
+a high-byte. If you wanted to store the value 1125 using the EEPROM directive
+you'll have to calculate the low-byte and the high-byte and insert them in the
+list in the proper order, as in:
+EEPROM (101, 4)
+
+
The directive above will store the two bytes into two sequential EEPROM
+locations (the low-byte first, followed by the high-byte). We calculated this in
+the following manner: 1) high-byte is INT(value / 256) and 2) low-byte is value -
+(high-byte * 256).
+
To retrieve a word-size value, you'll need to use two READ commands and
+a word-size variable. For example,
+SYMBOL result = W1 ' word-sized variable
+SYMBOL resLo = B2 ' B2 is low-byte of W1
+SYMBOL resHi = B3 ' B3 is high-byte of W1
+
+EEPROM (101, 4)
+
+Main:
+ READ 0, resLo
+ READ 1, resHi
+ DEBUG #result
+ END
+
+
This code would write the low-byte and high-byte of the number 1125 into
+locations 0 and 1 during download. When the program runs, the two READcommands will read the low-byte and high-byte out of EEPROM (reconstructing it in
+a word-size variable) and then display the value on the screen. See the READ
+ and WRITE commands for more
+information.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/LanguageTopics/Commands/END.htm b/help/BasicStampHelp/Content/LanguageTopics/Commands/END.htm
new file mode 100644
index 0000000..71db7f2
--- /dev/null
+++ b/help/BasicStampHelp/Content/LanguageTopics/Commands/END.htm
@@ -0,0 +1,127 @@
+
+
+
+ END
+
+
+
+
+
+
END
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Syntax: END
+
Function
+
End the program, placing the BASIC Stamp into low-power mode indefinitely. This
+is equivalent to having a program that does not loop continuously; once the BASIC
+Stamp reaches the end of the PBASIC program, it enters low-power mode indefinitely.
+The END command is optional, but recommended.
*Note: This is an approximate value, not including loads on the I/O pins
+
Explanation
+
END puts the BASIC Stamp into its inactive, low-power mode. In this
+mode the Stamp's current draw (excluding loads driven by the I/O pins) is
+reduced to the amount shown above. END keeps the BASIC Stamp
+inactive until the reset line is activated, the power is cycled off and back on
+or the PC downloads another program.
+
During execution of power conserving commands (END, NAP, POLLWAIT, and SLEEP), current will occasionally be interrupted
+on I/O pins for about 18 ms durations (60 µs on the BS2pe). The reason is that the
+watchdog-timer reset that awakens the BASIC Stamp during these commands also causes all of the pins to
+switch to input mode for approximately 18 ms (60 µs on the BS2pe). When the interpreter
+firmware regains control of the processor, it restores the I/O direction dictated
+by your program.
+
If you plan to use END, NAP, POLLWAIT, or SLEEP in your programs,
+make sure that your loads can tolerate these power outages. The simplest solution
+is often to connect resistors high or low (to +5V or ground) as appropriate to
+ensure a continuing supply of current during the reset.
The EXIT command allows a program to terminate a loop structure before
+the loop limit test is executed. While not required, EXIT is usually
+used as part of an IF...THEN construct to test a secondary condition for
+terminating a loop, or for testing a termination condition of an unconditional
+DO...LOOP structure.
+col VAR Byte
+row VAR Byte
+
+Main:
+ FOR col = 0 TO 3
+ FOR row = 0 TO 15
+ IF (row > 9) THEN EXIT
+ DEBUG CRSRXY, (col * 8), row, DEC row, CR
+ NEXT
+ NEXT
+ END
+
+
In this program, the FOR row = 0 TO 15 loop will not run past nine because
+the IF (row > 9) THEN EXIT contained within will force the loop to terminate
+when row is greater than nine. Note that the EXIT command only terminates
+the loop that contains it. In this program, the outer loop (col) will continue to
+run until complete.
Syntax : FORCounter = StartValueTOEndValue {STEP StepValue}... NEXT
+
Function
+
Create a repeating loop that executes the program lines between FOR and
+NEXT, incrementing or decrementing Counter according to StepValue until the value of the Counter variable passes the EndValue.
+
+
+
+
Counter is a variable (usually a byte or a word) used as a
+ counter.
+
StartValue is a variable/constant/expression* (0 - 65535) that
+ specifies the initial value of the variable (Counter).
+
EndValue is a variable/constant/expression* (0 - 65535) that
+ specifies the end value of the variable (Counter). When the value
+ of Counter is outside of the range StartValue to EndValue, the
+ FOR...NEXT loop stops executing and the program goes on to the instruction
+ after NEXT.
+
StepValue is an optional variable/constant/expression* (0 -
+ 65535) by which the Counter increases or decreases with each iteration
+ through the FOR...NEXT loop. On the BS1, use a minus sign (-)†
+ in front of the StepValue to indicate a negative step. On all other
+ BASIC Stamp models, if StartValue is larger than EndValue, PBASIC
+ understands StepValue to be negative, even though no minus sign is used.
+
+
* Note: expressions are not allowed as arguments on the BS1.
+
† Note: Use a minus sign to indicate negative StepValues on the BS1.
+
Quick Facts
+
+
+
+
BS1
+
BS2 Family
+
+
+
Max. nested commands
+
8
+
16
+
+
+
To decrement counter variable
+
Set StartValue > EndValue and enter
+ negative StepValue *
+
Set StartValue > EndValue
+
+
+
Counter comparison
+
Exit loop if Counter exceeds EndValue
+
Exit loop if Counter outside of range set by
+ StartValue to EndValue
*Note: Direction (ie: increment/decrement) cannot be changed at runtime.
+
Explanation
+
FOR...NEXT loops let your program execute a series of instructions for a
+specified number of repetitions (called iterations). By default, each time through
+the loop, the counter variable is incremented by 1. It will continue to loop until
+the result of the counter is outside of the range set by StartValue and
+EndValue. Also, FOR...NEXT loops always execute at least once. The
+simplest form is shown here:
+
+
+
+
+SYMBOL reps = B2 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 3 ' repeat with Reps = 1, 2, 3
+ DEBUG "*" ' print * on the screen
+ NEXT
+ END
+
+
+
+
+
+reps VAR Nib ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 3 ' repeat with Reps = 1, 2, 3
+ DEBUG "*" ' print * on the screen
+ NEXT
+ END
+
+
In the above code, the FOR command sets Reps = 1. Then the DEBUG
+line (within the FOR...NEXT loop) is executed; printing an asterisk (*) on
+the screen. When the BASIC Stamp sees the NEXT command, it goes back to
+the previous FOR command, adds 1 to Reps and compares the result to the
+range set by StartValue and EndValue. If reps is still within range,
+it executes the code in the loop again. Each time the FOR...NEXT loop
+executes, the value of reps is updated (incremented by 1) and the code within the
+loop (the DEBUG line) is executed; printing another asterisk on the screen.
+This code will run through the loop three times; setting reps to 1, 2 and 3, and
+printing three asterisks on the screen. After the third loop, again the BASIC
+Stamp goes back up to the FOR command, adds 1 to reps and compares the result
+(4 in this case) to the range. Since the range is 1 to 3 and the value is 4 (outside
+the range) the FOR...NEXT loop is done and the BASIC Stamp will jump down
+to the first line of code following the NEXT command.
+
You can view the changing values of reps by including the reps variable in a
+DEBUG command within the loop:
+
+
+
+
+SYMBOL reps = B2 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 3 ' repeat with Reps = 1, 2, 3
+ DEBUG #reps, CR ' print number on the screen
+ NEXT
+ END
+
+
+
+
+
+reps VAR Nib ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 3 ' repeat with Reps = 1, 2, 3
+ DEBUG DEC reps, CR ' print number on the screen
+ NEXT
+ END
+
+
Running this example should display "1" , "2", and "3" on the screen.
+
FOR...NEXT can also be made to decrement (rather than increment) the
+counter variable. The BS1 does this when you specify a negative StepValue(as well as a StartValue that is greater than the EndValue). All
+other BASIC Stamp models do this automatically when the StartValue is greater
+than the EndValue. Examples of both are shown below:
+
+
+
+
+SYMBOL reps = B2 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 3 TO 1 STEP -1 ' repeat with Reps = 3, 2, 1
+ DEBUG #reps, CR ' print number on the screen
+ NEXT
+ END
+
+
+
+
+
+reps VAR Nib ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 3 TO 1 ' repeat with Reps = 3, 2, 1
+ DEBUG DEC reps, CR ' print number on the screen
+ NEXT
+ END
+
+
Note that the code for the BS2 series did not use the optional STEP argument.
+This is because we wanted to decrement by positive 1 anyway (the default unit)
+and the BASIC Stamp realizes it needs to decrement because the StartValueis greater than the EndValue. A negative StepValue on the BS2 series
+would be treated as its positive, two's complement counterpart. For example, -1
+in two's complement is 65535. So the following code executes only once:
+reps VAR Nib ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 3 TO 1 STEP -1 ' decrement 3 by 65535
+ DEBUG DEC reps, CR ' print number on the screen
+ NEXT
+ END
+
+
The above code would run through the loop once with reps set to 3. The second
+time around, it would decrement reps by 65535 (-1 is 65535 in two's complement)
+effectively making the number -65532 (4 in two's complement) which is outside the
+range of the loop.
+
All the arguments in the FOR...NEXT command can be constants, variables
+or expressions (on the BS2 series). This leads to some interesting uses. For
+example, if you make the StartValue and EndValue a variable, and
+change their values within the loop, you'll change the behavior of the loop itself.
+Try the following:
+reps VAR Byte ' counter for the FOR/NEXT loop
+startVal VAR Byte
+endVal VAR Byte
+
+Setup:
+ startVal = 1 ' initialize startVal to 1
+ endVal = 3 ' initialize endVal to 3
+
+Main:
+ FOR reps = startVal TO endVal ' repeat for 1 to 3
+ DEBUG DEC reps, CR
+ IF (reps = 3) THEN ' if reps = 3 then swap startVal and endVal
+ startVal = 3 ' otherwise continue loop
+ endVal = 1
+ ENDIF
+ NEXT
+
+
Here the loop starts with a range of 1 to 3. First, the DEBUG line
+prints the value of reps. Then the IF...THEN line makes a decision; if
+reps is equal to 3, then swap the order of startVal and endVal,
+otherwise continue the loop execution. The next time through the loop (after
+startVal and endVal have been swapped), reps will be decremented
+instead of incremented because startVal is greater than endVal.
+The result is a display on the screen of the numbers 1, 2, 3, 2, 1.
+
The following example uses the value of reps as the StepValue. This
+creates a display of power's of 2 (1, 2, 4, 8, 16, 32, 64, etc):
+
+
+
+
+SYMBOL reps = B2 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 256 STEP reps ' each loop add current value of Reps
+ DEBUG reps ' show reps in Debug window.
+ NEXT
+ END
+
+
+
+
+
+reps VAR Byte ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 1 TO 256 STEP reps ' each loop add current value of Reps
+ DEBUG ? DEC reps ' show reps in debug window.
+ NEXT
+ END
+
+
There is a potential bug that you should be careful to avoid. The BASIC Stamp
+uses unsigned 16-bit integer math for any math operation it performs, regardless
+of the size of values or variables. The maximum value the BASIC Stamp can internally
+calculate is 65535 (the largest 16-bit number). If you add 1 to 65535, you get 0
+as the 16-bit register rolls over (like a car's odometer does when you exceed
+the maximum mileage it can display). Similarly, if you subtract 1 from 0, you'll
+get 65535 as the 16-bit register rolls under (a rollover in the opposite direction).
+
If you write a FOR...NEXT loop who's StepValue would cause the
+counter variable to go past 65535, this rollover may cause the loop to execute
+more times than you expect. Try the following example:
+
+
+
+
+SYMBOL reps = W1 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 0 TO 65535 STEP 3000 ' each loop add 3000
+ DEBUG reps ' show reps in debug window
+ NEXT
+ END
+
+
+
+
+
+SYMBOL reps = W1 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 0 TO 65535 STEP 3000 ' each loop add 3000
+ DEBUG reps ' show reps in debug window
+ NEXT
+ END
+
+
The value of reps increases by 3000 each trip through the loop. As it approaches
+the EndValue, an interesting thing happens; reps is: 57000, 60000, 63000,
+464, 3464... It passes the EndValue, rolls over and keeps going. That's
+because the result of the calculation 63000 + 3000 exceeds the maximum capacity
+of a 16-bit number and then rolls over to 464. When the result of 464 is tested
+against the range ("Is reps > 0 and is reps < 65500?") it passes the test and the
+loop continues.
+
A similar symptom can be seen in a program whose EndValue is mistakenly
+set higher than what the counter variable can hold. The example below uses a
+byte-sized variable, but the EndValue is set to a number greater than what
+will fit in a byte:
+
+
+
+
+SYMBOL reps = W1 ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 0 TO 300 ' each loop add 1
+ DEBUG reps ' show reps in debug window
+ NEXT
+ END
+
+
+
+
+
+reps VAR Byte ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 0 TO 300 ' each loop add 1
+ DEBUG DEC ? reps ' show reps in debug window
+ NEXT
+ END
+
+
Here, reps is a byte variable; which can only hold the number range 0 to 255.
+The EndValue is set to 300, however; greater than 255. This code will loop
+endlessly because when reps is 255 and the FOR...NEXT loop adds 1, reps
+becomes 0 (bytes will rollover after 255 just like words will rollover after 65535).
+The result, 0, is compared against the range (0 - 255) and it is found to be within
+the range, so the FOR...NEXT loop continues.
+
It's important to realize that on the BS2 series, the test is against the entire
+range, not just the EndValue. The code below is a slight modification of
+the previous example (the StartValue is 10 instead of 0) and will not loop
+endlessly.
+
+
+
+
+reps VAR Byte ' FOR...NEXT loop counter
+
+Main:
+ FOR reps = 10 TO 300 ' each loop add 1
+ DEBUG DEC ? reps ' show reps in debug window
+ NEXT
+ END
+
+
Reps still rolls over to 0, as before, however, this time it is outside the
+range of 10 to 255. The loop stops, leaving reps at 0. Note that this code is
+still in error since reps will never reach 300 until it is declared as a Word.
+
NOTE: On the BS1, the loop will continue until Counter has gone past
+EndValue. The rollover error will still occur if the BS1 cannot determine
+if Counter went past EndValue.
Generate one or two sine-wave tones for a specified duration.
+
+
+
+
Pin a variable/constant/expression (0 - 15) that specifies the
+ I/O pin to use. This pin will be set to output mode.
+
Duration a variable/constant/expression (0 - 65535) specifying
+ the amount of time to generate the tone(s). The unit of time for Duration is
+ described in the table below.
+
Freq1 is a variable/constant/expression (0 - 32767) specifying
+ frequency of the first tone. The unit of Freq1 is described in the table
+ below.
+
Freq2 is an optional argument exactly like Freq1. When specified,
+ two frequencies will be mixed together on the specified I/O pin.
FREQOUT generates one or two sine waves using a pulse-width modulation
+algorithm. The circuits in the figure below work by filtering out the
+high-frequency PWM used to generate the sine waves. FREQOUT works over a
+very wide range of frequencies so at the upper end of its range, those PWM
+filters will also filter out most of the desired frequency. You may find it
+necessary to reduce values of the parallel capacitors shown in the circuit, or
+to devise a custom active filter for your application.
+
+
+
+
+
+
Here's a simple FREQOUT command:
+ FREQOUT 2, 1000, 2500
+
+
On the BS2, this command generates a 2500 Hz tone for 1 second (1000 ms) on
+I/O pin 2. See the table above for timing data on other BASIC Stamp models.
+
To play two tones on the same I/O pin at once:
FREQOUT 2, 1000, 2500, 3000
+
This will generate a 2500 Hz and 3000 Hz tone (on the BS2) for 1 second. The frequencies will mix together for a chord- or bell-like sound. To generate a silent pause, specify frequency value(s) of 0.
Read value(s) from Scratchpad RAM, starting at Location and store in
+Variable(s)*.
+
+
+
+
Location is a variable/constant/expression (0 – 63 for Bs2e
+ and BS2sx, and 0 – 135 for BS2p, BS2pe, and BS2px) that specifies the Scratchpad
+ RAM location to read from.
+
Variable is a variable (usually a byte; unless using the optional Word modifier) to store the
+ value into.
+
+
*Note: The optional arguments require PBASIC 2.5.
+
Quick Facts
+
+
+
+
BS2e and BS2sx
+
BS2p, BS2pe, and BS2px
+
+
+
Scratchpad RAM size and organization
+
64 bytes (0 – 63). Organized as bytes only.
+
136 bytes (0 – 135). Organized as bytes only.
+
+
+
General purpose locations
+
0 - 62
+
0 – 126
+
+
+
Special use location
+
Current program slot number in read-only location 63.
+
Current program slot number in lowest nibble of read-only location 127. Current read/write slot number in highest nibble of location 127.
+
+
+
Additional locations
+
None
+
Locations 128 - 135 (read-only) hold state of polled input pins.
Multiple sequential variables may be read from the Scratchpad RAM.
+
The optional Word modifier may be specified to retrieve 16-bit values.
+
+
+
+
Explanation
+
By default, the GET command reads a byte-sized value from the specified
+Scratchpad RAM location and stores it into variable. All values in all locations
+can be retrieved from within any of the eight program slots.
+
Scratchpad RAM is useful for passing data to programs in other program
+slots and for additional workspace. It is different than regular RAM in
+that symbol names cannot be assigned directly to locations and each
+location is always configured as a byte only. The following code will read
+the value at location 25, store it in a variable called temp and display
+it:
+
The following example illustrates this:
+temp VAR Byte
+
+Main:
+ GET 25, temp
+ DEBUG DEC temp
+ END
+
+
When using the $PBASIC 2.5 directive, multiple sequential variables may be read
+from the Scratchpad RAM, starting at Location, and the Word modifier may
+be specified for 16-bit values.
+
+
+
+
+' {$PBASIC 2.5}
+
+value VAR Word
+value2 VAR Word
+addr VAR Word ' EEPROM address
+test VAR Byte ' test byte read back
+
+Main:
+ value = $11
+ value2 = $2003
+ PUT 0, value, Word value2 ' write value to SP location 0
+ ' and value2 to SP locations 1 & 2
+
+ value = $FF ' modify variables
+ value2 = $FFFF
+
+ GET 0, value, Word value2 ' retrieve from Scratchpad
+
+ DEBUG HEX2 ? value ' display
+ DEBUG HEX4 ? value2
+ END
+
+
The low nibble of location 63 (BS2e and BS2sx) and location 127 (BS2p,
+BS2pe, and BS2px) is a special, read-only location that always contains the
+number of the currently running program slot. On the BS2p, BS2pe, and BS2px,
+the high nibble of location 127 also contains the current program slot that
+will be used for the READ and WRITE commands. See the
+demo program for an example of use.
+
+
+
+
+
On the BS2p and BS2pe, the state of polled input pins can be retrieved from
+upper Scratchpad locations:
+
+
128 : MAINIO pins 0 - 7
+
129 : MAINIO pins 8 - 15
+
130 : AUXIO pins 0 - 7
+
131 : AUXIO pins 8 - 15
+
+
This information can be used to determine which input pin (or pins) has
+triggered a polled event.
Store the address of the next instruction after GOSUB, then go to the point
+in the program specified by Address; with the intention of returning to the
+stored address.
+
+
* Note: Using GOSUB on the BS1 requires variables B12 and B13 (W6) making them unavailable for general program use.
+
Explanation
+
GOSUB is a close relative of GOTO, in fact, its name means, "GO
+to a SUBroutine". When a PBASIC program reaches a GOSUB, the program
+executes the code beginning at the specified address label. Unlike GOTO,
+GOSUB also stores the address of the instruction immediately following
+itself. When the program encounters a RETURN command, it interprets it
+to mean, "go to the instruction that follows the most recent GOSUB." In
+other words, a GOSUB makes the BASIC Stamp do a similar operation as
+you do when you see a table or figure reference in this manual; 1) you
+remember where you are, 2) you go to the table or figure and read the
+information there, and 3) when you've reached the end of it, you "return"
+to the place you were reading originally.
+
GOSUB Can Save EEPROM (Program) Space
+
GOSUB is mainly used to execute the same piece of code from multiple
+locations. If you have, for example, a block of three lines of code that need
+to be run from 10 different locations in your entire program you could
+simple copy and paste those three lines to each of those 10 locations. This
+would amount to a total of 30 lines of repetitive code (and extra space
+wasted in the program memory). A better solution is to place those three
+lines in a separate routine, complete with it's own label and followed by a
+RETURN command, then just use a GOSUB command at each of the 10
+locations to access it. This technique can save a lot of program space.
+
Try the example below:
+
+
+Main:
+ GOSUB Hello
+ DEBUG "How are you?", CR
+ END
+
+Hello:
+ DEBUG "Hello my friend.", CR
+ RETURN
+
+
The above code will start out by executing a GOSUB to the section of code beginning with the label Hello. It will print "Hello my friend." on the screen then RETURN to the line after the GOSUB...which prints "How are you?" and ENDs.
+
Watch Out For Subroutines That Your Program Can "Fall Into"
+
There's another interesting lesson here; what would happen if we removed
+the END command from this example? Since the BASIC Stamp reads the
+code from left to right / top to bottom (like the English language) once it
+had returned to and run the "How are you?" line, it would naturally "fall
+into" the Hello routine again. Additionally, at the end of the Hello routine,
+it would see the RETURN again (although it didn't GOSUB to that
+routine this time) and because there wasn't a previous place to return to, the
+BASIC Stamp will start the entire program over again. This would cause
+an endless loop. The important thing to remember here is to always make
+sure your program doesn't allow itself to "fall into" a subroutine.
+
* Note: On the BS1, a RETURN without a GOSUB will return
+the program to the last GOSUB (or will end the program if no GOSUBwas executed).
+
GOSUB Limitations
+
Only a limited number of GOSUBs are allowed per program (as shown in above),
+and they may be nested only four levels deep. In other words, the subroutine that's
+the destination of a GOSUB can contain a GOSUB to another subroutine,
+and so on, to a maximum depth (total number of GOSUBs before the first
+RETURN) of four. Any deeper, and the program will "forget" its way back to
+the starting point (the instruction following the very first GOSUB).
+
When GOSUBs are nested, each RETURN takes the program back to the
+instruction after the most-recent GOSUB. As is mentioned above, if the
+BASIC Stamp encounters a RETURN without a previous GOSUB, the
+entire program starts over from the beginning. Take care to avoid these
+phenomena.
Unlimited, but good programming practices suggest minimizing the use of GOTO.
+
+
+
Explanation
+
The GOTO command makes the BASIC Stamp execute the code that starts at the
+specified Address location. The BASIC Stamp reads PBASIC code from
+left-to-right, top-to-bottom, just like in the English language. The GOTOcommand forces the BASIC Stamp to jump to another section of code.
+
A common use for GOTO is to create endless loops; programs that repeat
+a group of instructions over and over. For example:
+
+
The above code will print "Hi" on the screen, over and over again. The
+GOTO Hello line simply tells it to go back to the code that begins with
+the label Hello.
Receive data from a device using the I2C® protocol.
+
+
+
+
Pin is a variable/constant/expression (0 or 8) that specifies
+ which I/O pins to use. I2C devices require two I/O pins to communicate.
+ The Pin argument serves a double purpose; specifying the first pin (for
+ connection to the devices's SDA pin) and, indirectly, the other required pin (for
+ connection to the devices's SCL pin). See explanation below. Both I/O pins will
+ be toggled between output and input mode during the I2CIN command and both
+ will be set to input mode by the end of the I2CIN command.
+
SlaveID is a variable/constant/expression (0 - 255) indicating
+ the unique ID of the I2C device.
+
Address is a variable/constant/expression (0 - 255) indicating
+ the desired address within the I2C device to receive data from. The
+ Address argument may be used with the optional LowAddress argument
+ to indicate a word-sized address value. Note that some devices like the
+ PCF8574 do not require an internal address, so this parameter is optional (BS2p
+ firmware 1.3 or later is required to omit the Address parameter).
+
LowAddress is a variable/constant/expression (0 - 255)
+ indicating the low-byte of the word-sized address within the I2C
+ device to receive data from. This argument must be used along with the
+ Address argument.
+
InputData is a list of variables and modifiers that tells
+ I2CIN what to do with incoming data. I2CIN can store data in a
+ variable or array, interpret numeric text (decimal, binary, or hex) and store
+ the corresponding value in a variable, wait for a fixed or variable sequence
+ of bytes, or ignore a specified number of bytes. These actions can be combined
+ in any order in the InputData list.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Value of Pin
+
0
+
8
+
+
+
I/O Pin Arrangement
+
0: Serial Data (SDA) pin 1: Serial Clock (SCL) pin
+
8: Serial Data (SDA) pin 9: Serial Clock (SCL) pin
+
+
+
Transmission Rate
+
Approximately 81 kBits/sec (BS2p), 45 kBits/sec (BS2pe),
+ 83 kBits/sec (BS2px) -- not including overhead.
+
+
+
Special Notes
+
Both the SDA and SCL pins must have 4.7 kΩ
+ pull-up resisters. The I2CIN command does not allow for multiple masters. The BASIC Stamp cannot operate as an I2C slave device.
The I2C protocol is a form of synchronous serial communication
+developed by Philips Semiconductor. It only requires two I/O pins and both
+pins can be shared between multiple I2C devices. The I2CINcommand allows the BASIC Stamp to receive data from an I2C device.
This code will transmit a "read" command to an I2C device (connected
+to I/O pins 0 and 1) and then will receive one byte and store it in the variable
+result. Though it may seem strange, the I2CIN command first transmits
+some data and then receives data. It must first transmit information (ID, read/write
+and address) in order to tell the I2C device what information it would
+like to receive. The exact information transmitted ($A1, 0) depends on the
+I2C device that is being used.
+
The example above will read a byte of data from location 0 of a 24LC16B EEPROM
+from Microchip. The figure below shows the proper wiring for this example to work.
+The SlaveID argument ($A1) is both the ID of the chip and the command to
+read from the chip; the 1 means read. The Address argument (0) is the EEPROM
+location to read from. Note that the I2CIN command will make up to eight
+attempts to connect to the addressed device. If the device does not properly
+respond, the I2CIN command will timeout and the InputData will
+remain unchanged.
+
Note: The 4.7 kΩ resisters are required for the I2CINcommand to function properly.
+
+
+
+
+
The I2CIN command's InputData argument is similar to the
+SERIN command's InputData argument. This means data can be received
+as ASCII character values, decimal, hexadecimal and binary translations and string
+data as in the examples below. (Assume the 24LC16B EEPROM is used and it has the
+string, "Value: 3A:101" stored, starting at location 0).
The tables below list all the available conversion formatters and special
+formatters available to the I2CIN command. See the SERIN command for additional information and examples
+of their use.
+
+
+
Conversion Formatter
+
Type of Number
+
Numeric Characters Accepted
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally limited to 1 - 5 digits
+
0 through 9
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally limited to 1 - 5 digits
+
-, 0 through 9
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally limited to 1 - 4 digits
+
0 through 9, A through F
+
1,3
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally limited to 1 - 4 digits
+
-, 0 through 9, A through F
+
1,2,3
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally limited to 1 - 4 digits
+
$, 0 through 9, A through F
+
1,3,4
+
+
+
ISHEX{1..4}
+
Signed, indicated hexadecimal, optionally limited to 1 - 4 digits
+
-, $, 0 through 9, A through F
+
1,2,3,4
+
+
+
BIN{1..16}
+
Binary, optionally limited to 1 - 16 digits
+
0, 1
+
1
+
+
+
SBIN{1..16}
+
Signed binary, optionally limited to 1 - 16 digits
+
-, 0, 1
+
1,2
+
+
+
IBIN{1..16}
+
Indicated binary, optionally limited to 1 - 16 digits
+
%, 0, 1
+
1,4
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally limited to 1 - 16 digits
+
-, %, 0, 1
+
1,2,4
+
+
+
NUM
+
Generic numeric input; hex or binary number must be indicated
+
$, %, 0 through 9, A through F
+
1,3,4
+
+
+
SNUM
+
Similar to NUM with value treated as signed with range -32768 to +32767
+
-, $, %, 0 through 9, A through F
+
1,2,3,4
+
+
+
+
All numeric conversions will continue to accept new data until receiving
+ either the specified number of digits (ex: three digits for DEC3) or a non-numeric
+ character.
+
To be recognized as part of a number, the minus sign (-) must immediately
+ precede a numeric character. The minus sign character occurring in non-numeric
+ text is ignored and any character (including a space) between a minus and a number
+ causes the minus to be ignored.
+
The hexadecimal formatters are not case-sensitive; "a" through "f" means
+ the same as "A" through "F".
+
Indicated hexadecimal and binary formatters ignore all characters, even valid
+ numerics, until they receive the appropriate prefix ($ for hexadecimal, % for
+ binary). The indicated formatters can differentiate between text and hexadecimal
+ (ex: ABC would be interpreted by HEX as a number but IHEX would ignore it unless
+ expressed as $ABC). Likewise, the binary version can distinguish the decimal
+ number 10 from the binary number %10. A prefix occurring in non-numeric text
+ is ignored, and any character (including a space) between a prefix and a number
+ causes the prefix to be ignored. Indicated, signed formatters require that the
+ minus sign come before the prefix, as in -$1B45.
+
+
+
+
+
Special Formatter
+
Action
+
+
+
STR ByteArray \L {\E}
+
Input a character string of length L into an array. If specified, an end
+ character E causes the string input to end before reaching length L. Remaining
+ bytes are filled with 0s (zeros).
+
+
+
WAITSTR ByteArray {\L}
+
Wait for a sequence of bytes matching a string stored in an array variable,
+ optionally limited to L characters. If the optional L argument is left off,
+ the end of the array-string must be marked by a byte containing a zero (0).
+
+
+
SKIP Length
+
Ignore Length bytes of characters.
+
+
+
SPSTR Length
+
Buffer Length bytes (up to 126) of serial characters to Scratchpad RAM,
+ starting at location 0. Use GET to retrieve the characters.
+
+
+
+
The I2C protocol has a well-defined standard for the information
+passed at the start of each transmission. First of all, any information sent must
+be transmitted in units of one byte (8-bits). The first byte, we call the
+SlaveID, is an 8-bit pattern whose upper 7-bits contain the unique ID of
+the device you wish to communicate with. The lowest bit indicates whether this
+is a write operation (0) or a read operation (1). Here is the SlaveID format:
+
+
+
+
7
+
6
+
5
+
4
+
3
+
2
+
1
+
0
+
+
+
A6
+
A5
+
A4
+
A3
+
A2
+
A1
+
A0
+
R/W
+
+
+
+
+
The second byte, immediately following the SlaveID, is the Address.
+It indicates the 8-bit address (within the device) containing the data you would
+like to receive.
+
Some devices require more than eights bits of address. For this case, the optional
+LowAddress argument can be used for the low-byte of the required address.
+When using the LowAddress argument, the Address argument is effectively
+the high-byte of the address value. For example, if the entire address value is
+2050, use 8 for the Address argument and 2 for the LowAddress argument
+(8 * 256 + 2 = 2050).
+
Following the last address byte is the first byte of data. This data byte may
+be transmitted or received by the BASIC Stamp. In the case of the I2CINcommand, this data byte is transmitted by the device and received by the BASIC
+Stamp. Additionally, multiple data bytes can follow the address, depending on the
+I2C device. Note that every device has different limitations regarding
+how may contiguous bytes they can receive or transmit in one session. Be aware of
+these device limitations and program accordingly.
+
Every I2C transmission session begins with a Start Condition and
+ends with a Stop Condition. Additionally, immediately after every byte is
+transmitted, an extra clock cycle is used to send or receive an acknowledgment
+signal (ACK). All of these operations are automatically taken care of by the
+I2CIN command so that you need not be concerned with them. The general
+I2C transmission format is shown below.
+
+
+
+
+
Since the I2CIN command is intended for input only, it actually overrides
+the "R/W" bit (bit 0) in the SlaveID argument. This is done so that it can
+use the I2C protocol's "Combined Format" for receiving data. Put simply,
+this means a command such as:
+
+
I2CIN 0, $A1, 10, [result]
+
...actually transmits $A0, then 10, then $A1 and then it reads the data back from the device. The $A0 means "write", the 10 is the address to write to and, finally, the $A1 indicates a change of direction; to "read" the location, instead. Even though the I2CIN command really doesn't care what the value of the SlaveID's LSB is, it is suggested that you still set it appropriately for clarity.
+
+
Also note that the I2CIN command does not support multiple I2C
+masters and the BASIC Stamp cannot operate as an I2C slave device.
Send data to a device using the I2C® protocol.
+
+
+
+
Pin is a variable/constant/expression (0 or 8) that specifies
+ which I/O pins to use. I2C devices require two I/O pins to communicate.
+ The Pin argument serves a double purpose; specifying the first pin (for
+ connection to the device's SDA pin) and, indirectly, the other required pin (for
+ connection to the device's SCL pin). See explanation below. Both I/O pins will be
+ toggled between output and input mode during the I2COUT command and both
+ will be set to input mode by the end of the I2COUT command.
+
SlaveID is a variable/constant/expression (0 - 255) indicating
+ the unique ID of the I2C device.
+
Address is a variable/constant/expression (0 - 255) indicating
+ the desired address within the I2C device to send data to. The
+ Address argument may be used with the optional LowAddress argument
+ to indicate a word-sized address value. Note that some devices like the
+ PCF8574 do not require an internal address, so this parameter is optional (BS2p
+ firmware 1.3 or later is required to omit the Address parameter).
+
LowAddress is a variable/constant/expression (0 - 255) indicating
+ the low-byte of the word-sized address within the I2C device to send
+ data to. This argument must be used along with the Address argument.
+
OutputData is a list of variables, constants, expressions and
+ formatters that tells I2COUT how to format outgoing data. I2COUTcan transmit individual or repeating bytes, convert values into decimal,
+ hexadecimal or binary text representations, or transmit strings of bytes from
+ variable arrays. These actions can be combined in any order in the
+ OutputData list.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Value of Pin
+
0
+
8
+
+
+
I/O Pin Arrangement
+
0: Serial Data (SDA) pin 1: Serial Clock (SCL) pin
+
8: Serial Data (SDA) pin 9: Serial Clock (SCL) pin
+
+
+
Transmission Rate
+
Approximately 81 kBits/sec (BS2p), 45 kBits/sec (BS2pe),
+ 83 kBits/sec (BS2px) -- not including overhead.
+
+
+
Special Notes
+
Both the SDA and SCL pins must have 4.7 kΩ pull-up
+ resistors.
The I2C protocol is a form of synchronous serial communication developed
+by Philips Semiconductor. It only requires two I/O pins and both pins can be
+shared between multiple I2C devices. The I2COUT command allows
+the BASIC Stamp to send data to an I2C device.
+
The following is an example of the I2COUT command:
I2COUT 0, $A0, 5, [100]
+
This code will transmit a "write" command to an I2C device (connected
+to I/O pins 0 and 1), followed by an address of 5 and finally will transmit the
+number 100.
+
The example above will write a byte of data to location 5 of a 24LC16B EEPROM from
+Microchip. The figure below shows the proper wiring for this example to work. The
+SlaveID argument ($A0) is both the ID of the chip and the command to write to
+the chip; the 0 means write. The Address argument (5) is the EEPROM location
+to write to.
+
Note: The 4.7 kΩ resisters are required for the I2COUT
+command to function properly.
+
+
+
+
+
The I2COUT command's OutputData argument is similar to the
+DEBUG and SEROUT command's OutputData argument. This means
+data can be sent as literal text, ASCII character values, repetitive values,
+decimal, hexadecimal and binary translations and string data as in the examples
+below. (Assume the 24LC16B EEPROM is being used).
+value VAR Byte
+
+Setup:
+ value = 65
+
+Main:
+ I2COUT 0, $A0, 0, [value] ' send ASCII character "A"
+ I2COUT 0, $A0, 0, [REP value\5] ' send "A" five times, i.e., "AAAAA"
+ I2COUT 0, $A0, 0, [DEC value] ' send "6" and "5"
+ I2COUT 0, $A0, 0, [HEX value] ' send "4" and "1"
+ I2COUT 0, $A0, 0, [BIN value] ' send "1000001"
+ END
+
+
The tables below list all the available conversion formatters and special
+formatters available to the I2COUT command. See the DEBUG and SEROUT commands for
+additional information and examples of their use.
+
+
+
Conversion Formatter
+
Type of Number
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally fixed to 1 - 5 digits
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally fixed to 1 - 5 digits
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally fixed to 1 - 4 digits
+
1
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally fixed to 1 - 4 digits
+
1,2
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally fixed to 1 - 4 digits
Indicated binary, optionally fixed to 1 - 16 digits
+
1
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally fixed to 1 - 16 digits
+
1,2
+
+
+
+
Fixed-digit formatters like DEC4 will pad the number with leading 0s if
+ necessary; ex: DEC4 65 sends 0065. If a number is larger than the specified
+ number of digits, the leading digits will be dropped; ex: DEC4 56422 sends
+ 6422.
+
Signed modifiers work under two's complement rules.
+
+
+
+
+
Special Formatter
+
Action
+
+
+
?
+
Displays "symbol = x' + carriage return; where x is a number. Default
+ format is decimal, but may be combined with conversion formatters (ex: BIN
+ ? x to display "x = binary_number").
+
+
+
ASC ?
+
Displays "symbol = 'x'" + carriage return; where x is an ASCII character.
+
+
+
STR ByteArray {\L}
+
Send character string from an array. The optional \L argument can be used
+ to limit the output to L characters, otherwise, characters will be sent up to
+ the first byte equal to 0 or the end of RAM space is reached.
+
+
+
REP Byte\L
+
Send a string consisting of Byte repeated L times (ex: REP "X"\10
+ sends "XXXXXXXXXX").
+
+
+
+
The I2C protocol has a well-defined standard for the information
+passed at the start of each transmission. First of all, any information sent must
+be transmitted in units of one byte (8-bits). The first byte, we call the
+SlaveID, is an 8-bit pattern whose upper 7-bits contain the unique ID of
+the device you wish to communicate with. The lowest bit indicates whether this
+is a write operation (0) or a read operation (1). Here is the SlaveID format:
+
+
+
+
7
+
6
+
5
+
4
+
3
+
2
+
1
+
0
+
+
+
A6
+
A5
+
A4
+
A3
+
A2
+
A1
+
A0
+
R/W
+
+
+
+
+
The second byte, immediately following the SlaveID, is the Address.
+It indicates the 8-bit address (within the device) where the OutputData is
+to be written (the first location if more than one byte is written). Note that
+the Address argument is optional and may be left unspecified for devices
+that don't require an address parameter.
+
Some devices require more than eights bits of address. For this case, the optional
+LowAddress argument can be used for the low-byte of the required address.
+When using the LowAddress argument, the Address argument is
+effectively the high-byte of the address value. For example, if the entire
+address value is 2050, use 8 for the Address argument and 2 for the
+LowAddress argument (8 * 256 + 2 = 2050).
+
Following the last address byte is the first byte of data. This data byte may
+be transmitted or received by the BASIC Stamp. In the case of the I2COUT
+command, this data byte is transmitted by the BASIC Stamp and received by the
+device. Additionally, multiple data bytes can follow the address, depending on
+the I2C device. Note that every device has different limitations
+regarding how may contiguous bytes they can receive or transmit in one session.
+Be aware of these device limitations and program accordingly.
+
Every I2C transmission session begins with a Start Condition and
+ends with a Stop Condition. Additionally, immediately after every byte is
+transmitted, an extra clock cycle is used to send or receive an acknowledgment
+signal (ACK). All of these operations are automatically taken care of by the
+I2CIN command so that you need not be concerned with them. The general
+I2C transmission format is shown below.
+
+
+
+
+
+
Since the I2COUT command is intended for output only, it actually
+overrides the "R/W" bit (bit 0) in the SlaveID argument. This is done to
+avoid device conflicts should the value be mistyped. Put simply, this means
+commands such as:
+
+
I2COUT 0, $A0, 10, [0]
+
...and:
I2COUT 0, $A1, 10, [0]
+
...both transmit the same thing ($A0, then 10, then the data). Even though the
+I2COUT command really doesn't care what the value of the SlaveID's
+LSB is, it is suggested that you still set it appropriately for clarity.
+
Also note that the I2COUT command does not support multiple I2C
+masters and the BASIC Stamp cannot operate as an I2C slave device.
Evaluate Condition and, if it is true, go to the point in the program marked
+by Address.
+
+
+
+
Condition is a statement, such as "x = 7" that can be evaluated
+ as True or False. The Condition can be a very simple or very complex
+ relationship, as described below.
+
Address is a label that specifies where to go in the event that
+ Condition is true.
+
+
Note: See IF…THEN…ELSE for all BS2 models and PBASIC 2.5.
+
Quick Facts
+
+
+
+
BS1
+
BS2 Family
+
+
+
Comparison operators
+
=, <>, >, <, >=, <=
+
=, <>, >, <, >=, <=
+
+
+
Conditional Logic Operators
+
AND, OR
+
NOT, AND, OR, XOR
+
+
+
Format of Condition
+
Variable Comparison Value; where Value is a variable or constant
+
Value1 Comparison Value2; where Value1 and Value2 can be any of variable, constant or expression
IF...THEN is PBASIC's primary decision maker. It tests a condition and, if
+that condition is true, goes to a point in the program specified by an address label.
+The condition that IF...THEN tests is written as a mixture of comparison
+and logic operators. The available comparison operators are:
+
+
+
+
Comparison Operator Symbol
+
Definition
+
+
+
=
+
Equal
+
+
+
<>
+
Not Equal
+
+
+
>
+
Greater Than
+
+
+
<
+
Less Than
+
+
+
>=
+
Greater Than or Equal To
+
+
+
<=
+
Less Than or Equal To
+
+
+
+
+
Comparisons are always written in the form: Value1 Comparison Value2. The
+values to be compared can be any combination of variables (any size), constants,
+or expressions.
+
+ Note: On the BS1, expressions are not allowed as arguments, and
+Value1 (to the left of comparison) must be a variable.
+
The following example is an IF...THEN command with a simple condition:
+ IF 10 < 200 THEN Main
+
+
This code will compare the number 10 to the number 200. If 10 is less than 200,
+the condition is true. In this case, 10 is less than 200 (and always will be),
+so the program will jump (or GOTO) the label called Main. Of course, this
+is a silly example (10 is always less than 200 so this line will always cause a
+jump to Main). Most of the time, you'll use at least one variable in your condition:
+
+
+
+
+SYMBOL value = W1
+
+Main:
+ PULSIN 0, 1, value
+ DEBUG #value, CR
+ IF value < 4000 THEN Main
+ DEBUG "Value was greater than 4000!"
+ END
+
+
+
+
+
+value VAR Word
+
+Main:
+ PULSIN 0, 1, value
+ DEBUG DEC value, CR
+ IF (value < 4000) THEN Main
+ DEBUG "Value was greater than 4000!"
+ END
+
+
Here, the BASIC Stamp will look for and measure a pulse on I/O pin 0, then compare
+the result, value, against 4000. If value is less than (<) 4000, it will jump
+back to Main. Each time through the loop, it displays the measured value and once
+it is greater than or equal to 4000, it displays, "Value was greater than 4000!"
+
+
+
+
+
On the BS2, BS2e, BS2sx, BS2p, and BS2pe, the values can be expressions as well.
+This leads to very flexible and sophisticated comparisons. The IF...THEN
+statement below is functionally the same as the one in the program above:
+ IF (value < (45 * 100 - (25 * 20))) THEN Main
+
+
+
+
+
+
Here the BASIC Stamp evaluates the expression: 45 * 100 = 4500, 25 * 20 = 500,
+and 4500 - 500 = 4000. Then the BASIC Stamp performs the comparison: is value <
+4000? Another example that is functionally the same:
+ IF ((value / 100) < 40) THEN Main
+
+
+
+
+
+
It's important to realize that all comparisons are performed using unsigned,
+16-bit math. This can lead to strange results if you mix signed and unsigned numbers
+in IF...THEN conditions. Watch what happens here when we include a signed
+number (-99):
+ IF (-99 < 100) THEN Is_Less
+ DEBUG "Greater than or equal to 100"
+ END
+
+Is_Less:
+ DEBUG "Less than 100"
+ END
+
+
+
+
Although -99 is obviously less than 100, the program will say it is greater.
+The problem is that -99 is internally represented as the two's complement value
+65437, which (using unsigned math) is greater than 100. This phenomena will occur
+whether or not the negative value is a constant, variable or expression.
+
IF...THEN supports the conditional logic operators NOT, AND, OR, and XOR.
+See the table below for a list of the operators and their effects. NOTE: The NOT
+and XOR operators are not available on the BS1.
+
The NOT operator inverts the outcome of a condition, changing False to True,
+and True to False. The following IF...THENs are equivalent:
+ IF (x <> 100) THEN Not_Equal ' Jump to Not_Equal if x is not 100
+ IF NOT (x = 100) THEN Not_Equal ' Jump to Not_Equal if x is not 100
+
+
+
+
+
+SYMBOL value1 = B2
+SYMBOL value2 = B3
+
+Setup:
+ value1 = 5
+ value2 = 9
+
+Main:
+ IF value1 = 5 AND value2 = 10 THEN Is_True ' change AND to OR and see
+ DEBUG "Statement was false." ' what happens
+ END
+
+Is_True:
+ DEBUG "Statement was true."
+ END
+
+
+
+
+
+value1 VAR Byte
+value2 VAR Byte
+
+Setup:
+ value1 = 5
+ value2 = 9
+
+Main:
+ ' Change AND to OR and see what happens
+ IF (value1 = 5) AND (value2 = 10) THEN Is_True
+ DEBUG "Statement was false."
+ END
+
+Is_True:
+ DEBUG "Statement was true."
+ END
+
+
The condition "(value1 = 5) AND (value2 = 10)" is not true. Although value1 is
+5, value2 is not 10. The AND operator works just as it does in English; both
+conditions must be true for the statement to be true. The OR operator also works
+in a familiar way; if one or the other or both conditions are true, then the
+statement is true. The XOR operator (short for exclusive-OR) may not be familiar,
+but it does have an English counterpart: If one condition or the other (but not
+both) is true, then the statement is true.
+
The table below summarizes the effects of the conditional logic operators. As
+with math, you can alter the order in which comparisons and logical operations
+are performed by using parentheses. Operations are normally evaluated left-to-right.
+Putting parentheses around an operation forces PBASIC 2.0 to evaluate it before
+operations not in parentheses.
+
+ Note: On the BS1, parentheses are not allowed within
+arguments.
+
+
+
+
Condition A
+
NOT A
+
+
+
False
+
True
+
+
+
True
+
False
+
+
+
+
+
+
+
Condition A
+
Condition B
+
A AND B
+
+
+
False
+
False
+
False
+
+
+
False
+
True
+
False
+
+
+
True
+
False
+
False
+
+
+
True
+
True
+
True
+
+
+
+
+
+
+
Condition A
+
Condition B
+
A OR B
+
+
+
False
+
False
+
False
+
+
+
False
+
True
+
True
+
+
+
True
+
False
+
True
+
+
+
True
+
True
+
True
+
+
+
+
+
+
+
Condition A
+
Condition B
+
A XOR B
+
+
+
False
+
False
+
False
+
+
+
False
+
True
+
True
+
+
+
True
+
False
+
True
+
+
+
True
+
True
+
False
+
+
+
+
+
Unlike the IF...THEN commands in other BASIC language variants, PBASIC 1.0/2.0's
+IF...THEN can only go to a label as the result of a decision. It cannot
+conditionally perform some instruction, as in "IF x < 20 THEN y = y + 1" (This
+is possible using the $PBASIC 2.5 directive). To achieve this in PBASIC 1.0 and 2.0,
+you have to invert the logic using NOT and skip over the conditional instruction
+unless the condition is met:
+ IF NOT (x < 20) THEN No_Inc ' Don't increment y unless x < 20.
+ y = y + 1 ' Increment y if x < 20.
+
+No_Inc: ' Program continues.
+
+
You can also code a conditional GOSUB, as in "IF (x = 100) THEN GOSUB Centennial."
+In PBASIC 2.0:
+ IF NOT (x = 100) THEN No_Cent
+ GOSUB Centennial ' IF x = 100 THEN GOSUB Centennial.
+
+No_Cent: ' Program continues.
+
+
Internally, the BASIC Stamp defines "False" as 0 and "True" as any value other
+than 0. Consider the following instructions:
+flag VAR Bit
+
+Setup:
+ flag = 1
+
+Test:
+ IF flag THEN Is_True
+
+Is_False:
+ DEBUG "False", CR
+ END
+
+Is_True:
+ DEBUG "True"
+ END
+
+
Since flag is 1, IF...THEN would evaluate it as true and print the message
+"True" on the screen. Suppose you changed the IF...THEN command to read
+"IF NOT (flag) THEN IsTrue." That would also evaluate as True. Whoa! Isn't NOT 1
+the same thing as 0? No, at least not in the 16-bit world of the BASIC Stamp.
+
Internally, the BASIC Stamp sees a bit variable containing 1 as the 16-bit number
+%0000000000000001. So it sees the NOT of that as %1111111111111110. Since any
+non-zero number is regarded as True, NOT 1 is True. Strange but true.
+
The easiest way to avoid the kinds of problems this might cause is to always
+use a conditional operator with IF...THEN. Change the example above to read
+IF (flag = 1) THEN Is_True. The result of the comparison will follow IF...THENrules. Also, the logical operators will work as they should; IF NOT (flag = 1)
+THEN Is_True will correctly evaluate to False when flag contains 1.
+
This also means that you should only use the "named" conditional logic operators
+NOT, AND, OR, and XOR with IF...THEN. The conditional logic operators format
+their results correctly for IF...THEN instructions. The other logical
+operators, represented by symbols ~ & | and ^ do not; they are binary logic operators.
Evaluate Condition and, if it is true, execute the statement(s) following
+THEN, otherwise jump to and evaluate the ELSEIF condition. If no
+ELSEIF statement/block is provided, jump to and execute the statements that
+follow ELSE. If no ELSE block is provided, the program will continue
+at the line that follows ENDIF (or the next line when single-line syntax
+is used).
+
+
+
+
Condition is a statement, such as "x = 7" that can be evaluated
+ as True or False. The Condition can be a very simple or very complex
+ relationship, as described below.
+
Statement is any valid PBASIC statement. Multiple statements
+ may be placed on the same line (though not recommended) by separating each
+ statement with a colon ( : ).
+
+
Quick Facts
+
+
+
+
BS2 Family
+
+
+
Comparison operators
+
=, <>, >, <, >=, <=
+
+
+
Conditional Logic Operators
+
NOT, AND, OR, XOR
+
+
+
Format of condition
+
Value1 Comparison Value2; where Value1 and Value2 can
+ be any of variable, constant or expression
IF...THEN...ELSE is a primary PBASIC decision maker that allows one block of
+code or [optionally] another to run based on the value (True or False) of a condition.
+The condition that IF...THEN...ELSE tests is written as a mixture of
+comparison and logic operators. The available comparison operators are:
+
+
+
+
Comparison Operator Symbol
+
Definition
+
+
+
=
+
Equal
+
+
+
<>
+
Not Equal
+
+
+
>
+
Greater Than
+
+
+
<
+
Less Than
+
+
+
>=
+
Greater Than or Equal To
+
+
+
<=
+
Less Than or Equal To
+
+
+
+
+
Comparisons are always written in the form: Value1 Comparison Value2. The values
+to be compared can be any combination of variables (any size), constants, or
+expressions.
+value VAR Word
+
+Main:
+ DO
+ PULSIN 0, 1, value ' measure pulse input
+ DEBUG DEC value, CR
+ IF (value > 4000) THEN ' evaluate duration
+ DEBUG "Value was greater than 4000"
+ ELSEIF (value = 4000) THEN
+ DEBUG "Value was equal to 4000"
+ ELSE
+ DEBUG "Value was less than 4000"
+ ENDIF
+ DEBUG CR, CR
+ PAUSE 1000
+ LOOP
+
+
Here, the BASIC Stamp will look for and measure a pulse on I/O pin 0, then
+compare the result, value, against 4000. Based on this comparison, a message
+regarding the pulse width value will be printed.
+
In the following example, single-line syntax is used. Note that ENDIF
+is not required when using single-line formatting of IF...THEN...ELSE:
+
+
+ DEBUG "Your grade is: "
+ IF (score >= 90) THEN DEBUG "A", CR : ELSE DEBUG "B (or less)", CR
+
+
See IF…THEN for additional details on the use of
+comparison and conditional operators.
There are several ways to make a pin an input. When the BASIC Stamp is reset, all
+of the pins are inputs. Commands that rely on input pins, like PULSIN and
+SERIN, automatically change the specified pin to input. Writing 0s to
+particular bits of the variable DIRS makes the corresponding pins inputs. And
+then there’s the INPUT command.
+
When a pin is an input, your program can check its state by reading from
+the corresponding INS variable (PINS on the BS1). For example:
+
+
+
+
+Setup:
+ INPUT 4
+
+Hold:
+ IF PIN4 = 0 THEN Hold ' Stay here until P4 is 1
+
+
+
+
+
+Setup:
+ INPUT 4
+
+Hold:
+ IF (IN4 = 0) THEN Hold ' Stay here until P4 is 1
+
+
What happens if your program writes to the OUTS bit (PINS bit on the
+BS1) of a pin that is set up as an input? The value is stored in OUTS (PINS
+on the BS1), but has no effect on the outside world. If the pin is changed to
+output, the last value written to the corresponding OUTS bit (or PINS bit
+on the BS1) will appear on the pin. The Example program shows how this works.
The BS2p, BS2pe, and BS2px is available as a 24-pin module that is pin-compatible
+with the BS2, BS2e, and BS2sx. Also availabe is a 40-pin module called the BS2p40
+with an additional 16 I/O pins (for a total of 32). The BS2p40's I/O pins are
+organized into two groups, called main and auxiliary. The I/O pins in each group
+can be accessed in the same manner (by referencing I/O pins 0 - 15) but access is
+only possible within one group at a time. The IOTERM command causes the
+BASIC Stamp to affect either the main or auxiliary I/O pins in all further code
+until the MAINIO, AUXIO or another IOTERM command is reached,
+or the BASIC Stamp is reset or power-cycled. The value of Port determines
+which group of I/O pins will be referenced. Using 0 for Port will switch
+to the main I/O group and using 1 for Port will switch to the auxiliary group.
+
The following example illustrates this:
+ HIGH 0
+ IOTERM 1
+ LOW 0
+
+
The first line of the above example will set I/O pin 0 of the main I/O pins
+(physical pin 5) high. Afterward, the IOTERM command tells the BASIC
+Stamp that all commands following it should affect the auxiliary I/O pins
+(Port = 1). The following LOW command will set I/O pin 0 of the
+auxiliary I/O pins (physical pin 21) low.
+
Note that the main I/O and auxiliary I/O pins are independent of each
+other; the states of the main I/O pins remain unchanged while the
+program affects the auxiliary I/O pins, and vice versa.
Pin is a variable/constant/expression (0 - 1 or 8 - 9) that
+ specifies which I/O pins to use. The LCD requires, at most, seven I/O pins
+ to operate. The Pin argument serves a double purpose; specifying the
+ first pin and, indirectly the group of other required pins. See explanation
+ below. All I/O pins will be set to output mode.
+
Command is a variable/constant/expression (0 - 255) indicating
+ the LCD command to send.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Values for Pin
+
0, 1, 8, or 9
+
+
+
I/O pin arrangement when Pin
+ is 0 or 1
+
0 or 1 (depending on Pin) : LCD Enable (E) pin 2 : LCD Read/Write (R/W) pin 3 : LCD Register Select (RS) pin 4 - 7 : LCD Data Bus (DB4 - DB7, respectively) pins
+
+
+
I/O pin arrangement when Pin is
+ 8 or 9
+
8 or 9 (depending on Pin) : LCD Enable (E) pin 10 : LCD Read/Write (R/W) pin 11 : LCD Register Select (RS) pin 12 - 15 : LCD Data Bus (DB4 - DB7, respectively) pins
+
+
+
Special Notes
+
LCDCMD is designed to use the LCD's 4-bit mode only.
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
+BS2p, BS2pe, or BS2px to interface directly to standard LCD displays that feature
+a Hitachi 44780 controller (part #HD44780A). This includes many 1 x 16, 2 x 16,
+and 4 x 20 character LCD displays.
+
The Hitachi 44780 LCD controller supports a number of special instructions for
+initializing the display, moving the cursor, changing the default layout, etc.
+The LCDCMD command is used to send one of these instructions to the LCD.
+It is most commonly used to initialize the display upon a power-up or reset
+condition. Note that LCDCMD, LCDIN and LCDOUT use a 4-bit
+interface to the LCD which requires a specific initialization sequence before
+LCDIN and LCDOUT can be used. Specifics on the initialization
+sequence will follow.
+
The following is an example of the LCDCMD command:
+ LCDCMD 1, 24
+
+
The preceding code will send the Scroll Left command (represented by the number
+24) to the LCD whose enable pin is connected to I/O pin 1. This will cause the LCD
+display to scroll, or shift, the entire display one character to the left.
+
You may have noticed that the Pin argument in the example above was 1.
+The LCDCMD command actually uses more than just this I/O pin, however.
+The LCDCMD command requires seven I/O pins. This is because the standard
+LCD displays have a parallel interface, rather than a serial one. The Pin
+argument can be the numbers 0, 1, 8, or 9 and will result in the use of the I/O
+pins shown above. The figure below shows the required wiring for the above command
+to work.
+
+
+
+
+
Note that we could have used 0 for the Pin argument and moved the LCD's Enable
+pin (pin 6) to I/O pin 0. Similarly, using 9 for the Pin argument would have
+required us to wire the LCD's pins to I/O pins 9 through 15, rather than I/O pins
+1 through 7.
+
When the LCD is first powered-up, it will be in an unknown state and must be
+properly configured before sending commands like the one shown above. This process
+is known as initializing the LCD and is the first thing your program should do
+upon starting up. The following code is a good example of LCD initialization.
+(Refer to Hitachi documentation for details).
+Init_LCD:
+ PAUSE 1000 ' allow LCD to power-up
+ LCDCMD 1, 48 ' Send wake-up sequence (3x)
+ PAUSE 5
+ LCDCMD 1, 48
+ PAUSE 1
+ LCDCMD 1, 48
+ PAUSE 1
+ LCDCMD 1, 32 ' Set data bus to 4-bit mode
+ LCDCMD 1, 40 ' Set 2-line mode with 5x8 font
+ LCDCMD 1, 8 ' Turn display off
+ LCDCMD 1, 12 ' Turn display on without cursor
+ LCDCMD 1, 6 ' Auto-increment cursor
+ LCDCMD 1, 1 ' Clear the display
+
+
This initialization code is the most commonly used sequence for a 2 x 16 and
+4 x 20 LCD display (the 2-line mode instruction sets the 4 x 20 to 4-line mode).
+The PAUSE 1000 command is optional, but only if your program takes more
+than approximately 700 ms before it executes the Init_LCD code above. Without
+it, upon powering your circuit, the BASIC Stamp may talk to the LCD too early,
+the LCD will then miss some of the commands and the display will operate strangely,
+or not at all.
+
Do not change the "wake-up" and "4-bit mode" sequence commands. However, the
+commands below the line that says, "Set data bus to 4-bit mode" may be modified
+to set other desired modes.
+
The table below shows the most commonly used LCD commands. Here's an example:
+ LCDCMD 1, 128 + 64
+
+
The preceding command will move the cursor to the first character position
+on the second line (on a 2 x 16 display). 128 is the Move To Display Address
+command and 64 is the location number. See the "Character Positioning" section
+below, for more information.
+
Common LCD Commands
+
+
+
+
Command (Decimal)
+
Description
+
+
+
Do Nothing
+
0
+
Don't perform any special function.
+
+
+
Clear Display
+
1
+
Move cursor and display to home position.
+
+
+
Home Display
+
2
+
Move cursor and display to home position.
+
+
+
Inc Cursor
+
6
+
Set cursor direction to right, without a display shift.
+
+
+
Display Off
+
8
+
Turn off display (display data is retained).
+
+
+
Display On
+
12
+
Turn on display without cursor (display is restored).
+
+
+
Blinking Cursor
+
13
+
Turn on display with blinking cursor.
+
+
+
Underline Cursor
+
14
+
Turn on display with underline cursor.
+
+
+
Cursor Left
+
16
+
Move cursor left one character.
+
+
+
Cursor Right
+
20
+
Move cursor right one character.
+
+
+
Scroll Left
+
24
+
Scroll display left one character.
+
+
+
Scroll Right
+
28
+
Scroll display right one character.
+
+
+
Move To CGRAM Address
+
64 + address
+
Move pointer to Character Generator RAM location
+
+
+
Move To DDRAM Address
+
128 + address
+
Move cursor to Display Data RAM location
+
+
+
+
While most users will only need the commands shown above, the table below
+details all of the instructions supported by the LCD (for advanced users). Many
+instructions are multipurpose, depending on the state of special bits. Clever
+manipulation of the instruction bits will allow for powerful control of the LCD.
+
+
+
+
Command Code (bits)
+
Description
+
+
+
7
+
6
+
5
+
4
+
3
+
2
+
1
+
0
+
+
+
Clear Display
+
0
+
0
+
0
+
0
+
0
+
0
+
0
+
1
+
Clear entire display and move cursor home (address 0)
+
+
+
Home Display
+
0
+
0
+
0
+
0
+
0
+
0
+
1
+
0
+
Move cursor home and return display to home position.
+
+
+
Entry Mode
+
0
+
0
+
0
+
0
+
0
+
1
+
M
+
S
+
Sets cursor direction (M: 0=left, 1=right) and display scrolling
+ (S: 0=no scroll, 1=scroll)
Shifts display or cursor (C: 0=cursor, 1=display) left or
+ right (M: 0=left, 1=right).
+
+
+
Function Set
+
0
+
0
+
1
+
B
+
L
+
F
+
0
+
0
+
Sets bus size (B: 0=4-bits, 1=8-bits), number of lines
+ (L: 0=1?line, 1=2-lines) and font size (F: 0=5x8, 1=5x10)
+
+
+
Move To CGRAM Address
+
O
+
1
+
A
+
A
+
A
+
A
+
A
+
A
+
Move pointer to Character Generator RAM location specified
+ by address (A)
+
+
+
Move To DDRAM Address
+
1
+
A
+
A
+
A
+
A
+
A
+
A
+
A
+
Move cursor to Display Data RAM location specified by
+ address (A)
+
+
+
+
The last command shown above (Move To DDRAM Address) is used to move the cursor
+to a specific position on the LCD. The LCD's DDRAM (Display Data RAM) is a fixed
+size with unique position number for each character cell. The viewable portion
+of the DDRAM depends on the LCD's logical view position (which can be altered with
+the Scroll Display command). The default view position is called the Home position;
+it means that the display's upper left character corresponds to DDRAM location 0.
+The diagrams below indicates the position numbers for characters on the LCD screen.
+
Note that the diagram shows the most common DDRAM mapping, though some LCD's
+may have organized the DDRAM differently. A little experimentation with your LCD
+may reveal this.
+
2 x 16 Display
+
+
+
+
On-screen Positions*
+
Off-screen
+
+
+
Line 1
+
0
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
...
+
39
+
+
+
Line 2
+
64
+
65
+
66
+
67
+
68
+
69
+
79
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
...
+
103
+
+
+
* Assuming the display is in the home position
+
4 x 20 Display
+
+
+
Line 1
+
0
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
+
+
Line 2
+
64
+
65
+
66
+
67
+
68
+
69
+
79
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
+
+
Line 3
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
+
+
Line 4
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
+
+
+
On a standard 2 x 16 character display, the following command would move the
+cursor to the third column of the second line:
+ LCDCMD 1, 128 + 66
+
+
The number 128 tells the LCD we wish to move the cursor and 66 is the location
+number of the desired position. Similarly, sending just 128 (128 + 0) would move
+the cursor to the first character of the first line (the upper left character if
+the display is at the home position).
+
You may have noticed that the 2 x 16 display has many locations that are not
+visible; they are to the right of the edge of the screen. These locations (16 -
+39 and 80 to 103) become important for scrolling operations. For example, it is
+possible to move the cursor to location 16, print some text there and then issue
+a number of Scroll Left instructions (LCDCMD 1, 24) to slowly scroll the
+text onto the display from right to left. If you did so, the DDRAM positions that
+were on the left of the screen would now be past the left edge of the screen. For
+example:
+ LCDCMD 1, 24
+ LCDCMD 1, 24
+
+
...would cause the screen to scroll to the left by two characters. At this point,
+the upper-left character in the display would actually be DDRAM location 2 and the
+lower-left character would be DDRAM location 66. Locations 0, 1, 64 and 65 would
+be off the left edge of the LCD and would no longer be visible. Some interesting
+effects can be achieved by taking advantage of this feature.
+
The 4 x 20 LCD has a strange DDRAM map. The upper-right character is location
+19 and the next location, 20, appears as the first character of the third line.
+This strange mapping is due to constraints in the LCD controller and the
+manufacturers design, and unfortunately makes the scrolling features virtually
+useless on the 4 x 20 displays.
+
Even though the LCD requires many pins to talk to it, only the Enable pin needs
+to remain dedicated to the LCD and all the other pins can be multiplexed (shared)
+with certain other devices (if wired carefully). In addition, the I/O pin connected
+to the LCD's R/W pin is only necessary if the LCDIN command will be used
+in the application. If the LCDIN command will not be used, LCD pin 5 (R/W
+pin) can be connected to ground and I/O pin 2 (shown above) may be left disconnected.
+I/O pin 2 will still be set to output mode for each LCDCMD and LCDOUTcommand executed, however.
Pin is a variable/constant/expression (0 - 1 or 8 - 9) that
+ specifies which I/O pins to use. The LCD requires, at most, seven I/O pins to
+ operate. The Pin argument serves a double purpose; specifying the first
+ pin and, indirectly, the group of other required pins. See explanation below.
+ All I/O pins will be set to output mode initially and the upper I/O pins (4 -
+ 7 or 12 - 15) will be set to input mode by the end of the LCDIN command.
+
Command is a variable/constant/expression (0 - 255) indicating
+ the LCD command to send.
+
InputData is a list of variables and formatters that tells
+ LCDIN what to do with incoming data. LCDIN can store data in a
+ variable or array, interpret numeric text (decimal, binary, or hex) and store
+ the corresponding value in a variable, wait for a fixed or variable sequence
+ of bytes, or ignore a specified number of bytes. These actions can be combined
+ in any order in the InputData list.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Values for Pin
+
0, 1, 8, or 9
+
+
+
I/O pin arrangement when Pin is
+ 0 or 1
+
0 or 1 (depending on Pin) : LCD Enable (E) pin 2 : LCD Read/Write (R/W) pin 3 : LCD Register Select (RS) pin 4 - 7 : LCD Data Bus (DB4 - DB7, respectively) pins
+
+
+
I/O pin arrangement when Pin is
+ 8 or 9
+
8 or 9 (depending on Pin) : LCD Enable (E) pin 10 : LCD Read/Write (R/W) pin 11 : LCD Register Select (RS) pin 12 - 15 : LCD Data Bus (DB4 - DB7, respectively) pins
+
+
+
Special Notes
+
LCDIN is designed to use the LCD's 4-bit mode only.
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
+BS2p, BS2pe, or BS2pe to interface directly to standard LCD displays that feature
+a Hitachi 44780 controller (part #HD44780A). This includes many 1 x 16, 2 x 16,
+and 4 x 20 character LCD displays. Note that LCDCMD, LCDIN and
+LCDOUT use a 4-bit interface to the LCD which requires a specific
+initialization sequence before LCDIN and LCDOUT can be used
+(see LCDCMD for initialization details).
+
The LCDIN command is used to send one instruction and then receive at
+least one data byte from the LCD's Character Generator RAM (CGRAM) or Display Data
+RAM (DDRAM). The following is an example of the LCDIN command:
The preceding example will read the character value at location 0 of the DDRAM.
+See the "Character Positioning" section, below, for more information.
+
The LCDIN command actually uses more than just the I/O pin specified by
+the Pin argument. The LCDIN command requires seven I/O pins. This
+is because the standard LCD displays have a parallel interface, rather than a
+serial one. The Pin argument can be the numbers 0, 1, 8, or 9 and will
+result in the use of the I/O pins shown above. Please refer to the
+LCDCMD command description for information on properly
+wiring the LCD display.
+
When the LCD is first powered-up, it will be in an unknown state and must be
+properly configured before sending commands like the one shown above. This process
+is known as initializing the LCD and is the first thing your program should do
+upon starting up. Please refer to the LCDCMD command
+description for information on properly initializing the LCD display.
+
The LCDIN command's InputData argument is similar to the SERIN command's InputData argument. This means data can be received as ASCII
+character values, decimal, hexadecimal and binary translations and string data as
+in the examples below (assume the LCD display has "Value: 3A:101" starting at the
+first character of the first line on the screen).
+value VAR Byte(13)
+
+Main:
+ LCDIN 1, 128, [value] ' receive ASCII code for "V"
+ LCDIN 1, 128, [DEC value] ' receive the number 3
+ LCDIN 1, 128, [HEX value] ' receive the number $3A
+ LCDIN 1, 128, [BIN value] ' receive the number %101
+ LCDIN 1, 128, [STR value\13] ' receive the string "Value: 3A:101"
+
+
The tables below list all the available conversion formatters and special
+formatters available to the LCDIN command. See the
+SERIN command for additional information and examples
+of their use.
+
+
+
Conversion Formatter
+
Type of Number
+
Numeric Characters Accepted
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally limited to 1 - 5 digits
+
0 through 9
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally limited to 1 - 5 digits
+
-, 0 through 9
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally limited to 1 - 4 digits
+
0 through 9, A through F
+
1,3
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally limited to 1 - 4 digits
+
-, 0 through 9, A through F
+
1,2,3
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally limited to 1 - 4 digits
+
$, 0 through 9, A through F
+
1,3,4
+
+
+
ISHEX{1..4}
+
Signed, indicated hexadecimal, optionally limited to 1 - 4 digits
+
-, $, 0 through 9, A through F
+
1,2,3,4
+
+
+
BIN{1..16}
+
Binary, optionally limited to 1 - 16 digits
+
0, 1
+
1
+
+
+
SBIN{1..16}
+
Signed binary, optionally limited to 1 - 16 digits
+
-, 0, 1
+
1,2
+
+
+
IBIN{1..16}
+
Indicated binary, optionally limited to 1 - 16 digits
+
%, 0, 1
+
1,4
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally limited to 1 - 16 digits
+
-, %, 0, 1
+
1,2,4
+
+
+
NUM
+
Generic numeric input; hex or binary number must be indicated
+
$, %, 0 through 9, A through F
+
1,3,4
+
+
+
SNUM
+
Similar to NUM with value treated as signed with range -32768 to +32767
+
-, $, %, 0 through 9, A through F
+
1,2,3,4
+
+
+
+
All numeric conversions will continue to accept new data until receiving
+ either the specified number of digits (ex: three digits for DEC3) or a
+ non-numeric character.
+
To be recognized as part of a number, the minus sign (-) must immediately
+ precede a numeric character. The minus sign character occurring in non-numeric
+ text is ignored and any character (including a space) between a minus and a
+ number causes the minus to be ignored.
+
The hexadecimal formatters are not case-sensitive; "a" through "f" means
+ the same as "A" through "F".
+
Indicated hexadecimal and binary formatters ignore all characters, even
+ valid numerics, until they receive the appropriate prefix ($ for hexadecimal,
+ % for binary). The indicated formatters can differentiate between text and
+ hexadecimal (ex: ABC would be interpreted by HEX as a number but IHEX would
+ ignore it unless expressed as $ABC). Likewise, the binary version can
+ distinguish the decimal number 10 from the binary number %10. A prefix
+ occurring in non-numeric text is ignored, and any character (including a
+ space) between a prefix and a number causes the prefix to be ignored. Indicated,
+ signed formatters require that the minus sign come before the prefix, as
+ in -$1B45.
+
+
+
+
Special Formatter
+
Action
+
+
+
STR ByteArray \L {\E}
+
Input a character string of length L into an array. If specified, an end
+ character E causes the string input to end before reaching length L.
+ Remaining bytes are filled with 0s (zeros).
+
+
+
WAITSTR ByteArray {\L}
+
Wait for a sequence of bytes matching a string stored in an array
+ variable, optionally limited to L characters. If the optional L argument is
+ left off, the end of the array-string must be marked by a byte containing a
+ zero (0).
+
+
+
SKIP Length
+
Ignore Length bytes of characters.
+
+
+
SPSTR Length
+
Buffer Length bytes (up to 126) of serial characters to Scratchpad RAM,
+ starting at location 0. Use GET to retrieve the
+ characters.
+
+
+
+
Some possible uses of the LCDIN command are 1) in combination with the
+LCDOUT command to store and read data from the unused DDRAM or CGRAM
+locations (as extra variable space), 2) to verify that the data from a previous
+LCDOUT command was received and processed properly by the LCD, and 3) to
+read character data from CGRAM for the purposes of modifying it and storing it
+as a custom character.
Pin is a variable/constant/expression (0 - 1 or 8 - 9) that
+ specifies which I/O pins to use. The LCD requires, at most, seven I/O pins
+ to operate. The Pin argument serves a double purpose; specifying the
+ first pin and, indirectly, the group of other required pins. See explanation
+ below. All I/O pins will be set to output mode initially and the upper I/O
+ pins (4 - 7 or 12 - 15) will be set to output mode by the end of the LCDOUT command.
+
Command is a variable/constant/expression (0 - 255) indicating
+ an LCD command to send.
+
OutputData is a list of variables, constants, expressions and
+ formatters that tells LCDOUT how to format outgoing data. LCDOUT
+ can transmit individual or repeating bytes, convert values into decimal, hex
+ or binary text representations, or transmit strings of bytes from variable
+ arrays. These actions can be combined in any order in the OutputDatalist.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Values for Pin
+
0, 1, 8, or 9
+
+
+
I/O pin arrangement when Pin is
+ 0 or 1
+
0 or 1 (depending on Pin) : LCD Enable (E) pin 2 : LCD Read/Write (R/W) pin 3 : LCD Register Select (RS) pin 4 - 7 : LCD Data Bus (DB4 - DB7, respectively) pins
+
+
+
I/O pin arrangement when Pin is
+ 8 or 9
+
8 or 9 (depending on Pin) : LCD Enable (E) pin 10 : LCD Read/Write (R/W) pin 11 : LCD Register Select (RS) pin 12 - 15 : LCD Data Bus (DB4 - DB7, respectively) pins
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
+BS2p, BS2pe, or BS2pe to interface directly to standard LCD displays that feature
+a Hitachi 44780 controller (part #HD44780A). This includes many 1 x 16, 2 x 16,
+and 4 x 20 character LCD displays. Note that LCDCMD, LCDIN and
+LCDOUT use a 4-bit interface to the LCD which requires a specific
+initialization sequence before LCDIN and LCDOUT can be used
+(see LCDCMD for initialization details).
+
The LCDOUT command is used to send one instruction followed by at least
+one data byte to the LCD. The data that is output is written to the LCD's
+Character Generator RAM (CGRAM) or Display Data RAM (DDRAM). The following is an
+example of the LCDOUT command:
+ LCDOUT 1, 1, ["Hello World!"]
+
+
The preceding example will clear the LCD screen and then send "Hello World!" to
+the screen. The first argument (1) is the starting I/O pin number and the second
+argument (also 1) is the LCD's instruction for Clear Screen.
+
The LCDOUT command actually uses more than just the I/O pin specified
+by the Pin argument. The LCDOUT command requires seven I/O pins. This is
+because the standard LCD displays have a parallel interface, rather than a serial
+one. The Pin argument can be the numbers 0, 1, 8, or 9 and will result in
+the use of the I/O pins shown above. Please refer to the
+LCDCMD command description for information on properly
+wiring the LCD display.
+
When the LCD is first powered-up, it will be in an unknown state and must be
+properly configured before sending commands like the one shown above. This process
+is known as initializing the LCD and is the first thing your program should do
+upon starting up. Please refer to the LCDCMD command
+description for information on properly initializing the LCD display.
+
The LCDOUT command's OutputData argument is exactly like that
+of the DEBUG and SEROUT command's OutputData argument.
+This means data can be sent as literal text, ASCII character values, repetitive
+values, decimal, hexadecimal and binary translations and string data as in the
+examples below.
The tables below list all the available conversion formatters and special
+formatters available to the LCDOUT command. See the
+DEBUG and SEROUT commands for
+additional information and examples of their use.
+
+
+
Conversion Formatter
+
Type of Number
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally fixed to 1 - 5 digits
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally fixed to 1 - 5 digits
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally fixed to 1 - 4 digits
+
1
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally fixed to 1 - 4 digits
+
1,2
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally fixed to 1 - 4 digits
Indicated binary, optionally fixed to 1 - 16 digits
+
1
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally fixed to 1 - 16 digits
+
1,2
+
+
+
+
Fixed-digit formatters like DEC4 will pad the number with leading 0s if
+ necessary; ex: DEC4 65 sends 0065. If a number is larger than the specified
+ number of digits, the leading digits will be dropped; ex: DEC4 56422 sends
+ 6422.
+
Signed modifiers work under two's complement rules.
+
+
+
+
Special Formatter
+
Action
+
+
+
?
+
Displays "symbol = x' + carriage return; where x is a number. Default
+ format is decimal, but may be combined with conversion formatters (ex: BIN
+ ? x to display "x = binary_number").
+
+
+
ASC ?
+
Displays "symbol = 'x'" + carriage return; where x is an ASCII character.
+
+
+
STR ByteArray {\L}
+
Send character string from an array. The optional \L argument can be used
+ to limit the output to L characters, otherwise, characters will be sent up
+ to the first byte equal to 0 or the end of RAM space is reached.
+
+
+
REP Byte\L
+
Send a string consisting of Byte repeated L times (ex: REP "X"\10 sends
+ "XXXXXXXXXX").
+
+
+
Using the Command Argument
+
The Command argument is useful for proceeding a set of data with a
+special LCD instruction. For example, the code below will move the cursor to
+location 64 (the first character on the second line) and print "Hi":
+ LCDOUT 1, 128 + 64, ["Hi"]
+
+
The next example, below, will turn on the blinking block cursor and print
+"Yo!":
+ LCDOUT 1, 13, ["Yo!"]
+
+
Occasionally, you will want to send data without preceding it with a command.
+To do this, simply use 0 for the Command argument, as in:
+ LCDOUT 1, 0, ["Hello there!"]
+
+
Another use for the LCDOUT command is to access and create custom
+characters. The Hitachi 44780 controller has a built-in character set that is
+similar to the ASCII character set (at least for the first 128 characters).
+Most of these characters are stored in ROM and are not changeable, however, the
+first eight characters (ASCII 0 though 7) are programmable.
+
Each of the programmable characters is five pixels wide and eight pixels tall.
+It takes eight bytes to describe each character; one byte per row (the left-most
+three bits are ignored). For example, the character at ASCII location 0 is defined
+by the bit patterns stored in bytes 0 through 7 of Character Generator RAM (CGRAM).
+The character at ASCII location 1 is defined by the bit patterns stored in bytes
+8 through 15 of CGRAM, and so on.
+
To create a custom character, use some graph paper to plot out the bit pattern
+(on and off pixels) in a 5 x 8 pattern, as shown in below. Then calculate the
+corresponding binary value of the bit pattern for each of the eight rows of
+character data.
+
+
+
+
Character Cell Structure and Data
+
+
+
+
+
+
+
+
+
+
+
After the data is calculated for each character (8 byte values per character),
+use the LCDOUT command with the "Move To CGRAM Address" instruction to
+insert the data into the character's CGRAM locations. For example, the code
+below will store the character shown in above into character 0's CGRAM data
+locations. Then it will place the cursor back on the display (DDRAM) and print
+the character on the screen.
The number 64 in the Command argument is the LCD's "Move to CGRAM Address"
+instruction and the 0 that is added to it is the location of the first row of data
+for the character 0. The LCDOUT command will write the first OutputData
+value (00) to this location, the second OutputData value (10) to location 1,
+etc. If we wanted this custom character to affect character 1, instead of 0, we'd
+have to adjust value of the "Move To..." command, i.e., 64+8. To affect character 2,
+we'd use 64+16.
+
To try the example above, don't forget to execute the LCD initialization code
+(shown in the LCDCMD description) first and never forget
+to move the cursor back to the screen (as with the last command, above) when you're
+done writing the character data to CGRAM.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/LanguageTopics/Commands/LET.htm b/help/BasicStampHelp/Content/LanguageTopics/Commands/LET.htm
new file mode 100644
index 0000000..e9686d9
--- /dev/null
+++ b/help/BasicStampHelp/Content/LanguageTopics/Commands/LET.htm
@@ -0,0 +1,86 @@
+
+
+
+ LET
+
+
+
+
+
LET
+
+
+
+
+
+
+
+
+
+
+
Syntax: {LET}Variable = Value
+
Function
+
Sets Variable equal to the value of Value.
+
+
+
+
Variable is a variable/constant/expression (0-65535).
+
Value is a variable which will be set equal to Value.
+
+
Explanation
+
LET is an optional instruction for the BASIC Stamp 1 that can be used with variable assignment statements, such as A = 5 and B = A + 2, etc. This instruction is not required and only exits on the BASIC Stamp 1. LET was a commonly used command in early forms of BASIC, and was originally included in the BS1 command set to accommodate programmers from that generation. Parallax recommends that all new BASIC Stamp 1 programs use assignment statements without the LET command.
+
The example below demonstrates the use of LET in assignment statements. Note that the Lunchtime and Dinnertime routines do essentially the same type of thing, but the Dinnertime approach is recommended.
Compare Target value to a list of values and store the index number of
+the first value that matches into Variable. If no value in the list matches,
+Variable is left unaffected. On the BS2, BS2e, BS2sx and BS2p, the optional
+ComparisonOp is used as criteria for the match; the default criteria is
+"equal to."
+
+
+
+
Target is a variable/constant/expression* (0 - 65535) to be
+ compared to the values in the list.
+
ComparisonOp is an optional comparison operator (as described
+ below) to be used as the criteria when comparing values. When no
+ ComparisonOp is specified, equal to (=) is assumed. This argument is
+ not available on the BS1.
+
Values are variables/constants/expressions* (0 - 65535) to
+ be compared to Target.
+
Variable is a variable (usually a byte) that will be set to
+ the index (0 - 255) of the matching value in the Values list. If no
+ matching value is found, Variable is left unaffected.
+
+
* Note: expressions are not allowed as arguments on the BS1.
LOOKDOWN works like the index in a book. In an index, you search for a
+topic and get the page number. LOOKDOWN searches for a target value in
+a list, and stores the index number of the first match in a variable. For
+example:
+
+
+
+
+SYMBOL value = B2
+SYMBOL result = B3
+
+Setup:
+ value = 17
+ result = 15
+
+Main:
+ LOOKDOWN value, (26, 177, 13, 1, 0, 17, 99), result
+ DEBUG "Value matches item ", #result, "in list"
+ END
+
+
+
+
+
+value VAR Byte
+result VAR Byte
+
+Setup:
+ value = 17
+ result = 15
+
+Main:
+ LOOKDOWN value, [26, 177, 13, 1, 0, 17, 99], result
+ DEBUG "Value matches item ", DEC result, " in list"
+ END
+
+
DEBUG prints, "Value matches item 5 in list" because the value (17)
+matches item 5 of [26, 177, 13, 1, 0, 17, 99]. Note that index numbers count up
+from 0, not 1; that is, in this list, 26 is item 0.
+
What happens if the value doesn't match any of the items in the list? Try
+changing "value = 17" to "value = 2." Since 2 is not on the list, LOOKDOWN
+leaves result unaffected. Since result contained 15 before LOOKDOWN
+executed, DEBUG prints "Value matches item 15 in list." By strategically
+setting the initial value of result, as we have here, your program can be written
+to detect when an item was not found in the list.
+
Don't forget that text phrases are just lists of byte values, so they too are
+eligible for LOOKDOWN searches, as in this example:
+
+
+
+
+SYMBOL value = B2
+SYMBOL result = B3
+
+Setup:
+ value = "f"
+ result = 255
+
+Main:
+ LOOKDOWN value, ("The quick brown fox"), result
+ DEBUG "Value matches item ", #result, "in list"
+ END
+
+
+
+
+
+value VAR Byte
+result VAR Byte
+
+Setup:
+ value = "f"
+ result = 255
+
+Main:
+ LOOKDOWN value, ["The quick brown fox"], result
+ DEBUG "Value matches item ", DEC result, " in list"
+ END
+
+
DEBUG prints, "Value matches item 16 in list" because the character at
+index item 16 is "f" in the phrase, "The quick brown fox".
+
The examples above show LOOKDOWN working with lists of constants, but
+it also works with variables and expressions also. Note, however, that expressions
+are not allowed as argument on the BS1.
+
+
+
+
+
On the BS2, BS2e, BS2sx, BS2p and BS2pe, the LOOKDOWN command can also
+use another criteria (other than "equal to") for its list. All of the examples
+above use LOOKDOWN's default comparison operator, =, that searches for an
+exact match. The entire list of ComaprisonOps is shown below. The
+"greater than" comparison operator (>) is used in the following example:
+value VAR Byte
+result VAR Byte
+
+Setup:
+ value = 17
+ result = 15
+
+Main:
+ LOOKDOWN value, >[26, 177, 13, 1, 0, 17, 99], result
+ DEBUG "Value greater than item ", DEC result, " in list"
+ END
+
+
DEBUG prints, "Value greater than item 2 in list" because the first
+item the value 17 is greater than is 13 (which is item 2 in the list). Value is
+also greater than items 3 and 4, but these are ignored, because LOOKDOWN
+only cares about the first item that matches the criteria. This can require a
+certain amount of planning in devising the order of the list. To see a complete program, see the
+LOOKDOWN Examples.
+
LOOKDOWN comparison operators use unsigned 16-bit math. They will not
+work correctly with signed numbers, which are represented internally as two's
+complement (large 16-bit integers). For example, the two's complement
+representation of -99 is 65437. So although -99 is certainly less than 0, it
+would appear to be larger than zero to the LOOKDOWN comparison operators.
+The bottom line is: Don't used signed numbers with LOOKDOWN comparisons.
+
+
+
+
ComparisonOp Symbol
+
Description
+
+
+
=
+
Find the first value Target is equal to
+
+
+
<>
+
Find the first value Target is not equal to
+
+
+
>
+
Find the first value Target is greater than
+
+
+
<
+
Find the first value Target is less than
+
+
+
>=
+
Find the first value Target is greater than or equal to
+
+
+
<=
+
Find the first value Target is less than or equal to
+
+
+
+
+
A common application for LOOKDOWN is to use it in conjunction with the
+BRANCH command to create selective jumps based on a simple variable input:
+
+
+
+
+SYMBOL cmd = B2
+
+Setup:
+ cmd = "M"
+
+Main:
+ LOOKDOWN cmd, ("SLMH"), cmd
+ BRANCH cmd, (_Stop, _Low, _Medium, _High)
+ DEBUG "Command not in list"
+ END
+
+_Stop:
+ DEBUG "Stop"
+ END
+
+_Low:
+ DEBUG "Low"
+ END
+
+_Medium:
+ DEBUG "Medium"
+ END
+
+_High:
+ DEBUG "High"
+ END
+
+
+
+
+
+cmd VAR Byte
+
+Setup:
+ cmd = "M"
+
+Main:
+ LOOKDOWN cmd, ["SLMH"], cmd
+ BRANCH cmd, [_Stop, _Low, _Medium, _High]
+ DEBUG "Command not in list"
+ END
+
+_Stop:
+ DEBUG "Stop"
+ END
+
+_Low:
+ DEBUG "Low"
+ END
+
+_Medium:
+ DEBUG "Medium"
+ END
+
+_High:
+ DEBUG "High"
+ END
+
+
In this example, cmd contains "M" (ASCII 77). LOOKDOWN finds that this
+is item 2 of a list of one-character commands and stores 2 into cmd. BRANCHthen goes to item 2 of its list, which is the program label "_Medium" at which
+point DEBUG prints "Medium" on the PC screen. This is a powerful method
+for interpreting user input, and a lot neater than the alternative IF...THENinstructions.
+
Another great use of LOOKDOWN is in combination with LOOKUP to
+"map" non-contiguous sets of numbers together. For example, you may have an
+application where certain numbers are received by the BASIC Stamp and, in response,
+the BASIC Stamp needs to send a specific set of numbers. This may be easy to code
+if the numbers are contiguous, or follow some known algebraic equation... but what
+if they don't? The table below shows some sample, non-contiguous inputs and the
+corresponding outputs the BASIC Stamp needs to respond with:
+
+
+
+
Index
+
Each of these values
+ received (inputs):
+
Needs to result in each of
+ these values sent (outputs):
+
+
+
0
+
5
+
16
+
+
+
1
+
14
+
17
+
+
+
2
+
1
+
18
+
+
+
3
+
43
+
24
+
+
+
4
+
26
+
10
+
+
+
5
+
22
+
12
+
+
+
6
+
30
+
11
+
+
+
+
+
So, if we receive the number 5, we need to output 16. If we received 43, we
+need to output 24, and so on. These numbers are not contiguous and they don't
+appear to be derived from any simple algorithm. We can solve this problem with
+two lines of code, as follows:
Assuming our received number is in value, the first line (LOOKDOWN)
+will find the value in the list and store the index of the location that matches
+back into value. (This step "maps" the non-contiguous numbers: 5, 14, 1, etc,
+to a contiguous set of numbers: 0, 1, 2, etc). The second line (LOOKUP)
+takes our new value, finds the number at that location and stores it back into
+value. If the received value was 14, LOOKDOWN stores 1 into value and
+LOOKUP looks at the value at location 1 and stores 17 in value. The
+number 43 gets mapped to 3, 3 gets mapped to 24, and so on. This is a quick and
+easy fix for a potentially messy problem!
Find the value at location Index and store it in Variable.
+If Index exceeds the highest index value of the items in the list,
+Variable is left unaffected.
+
+
+
+
Index is a variable/constant/expression* (0 - 255) indicating
+ the list item to retrieve.
+
Values are variables/constants/expressions* (0 - 65535).
+
Variables is a variable that will be set to the value at the
+ Index location. If Index exceeds the highest location number, Variable is left unaffected.
+
+
* Note: expressions are not allowed as arguments on the BS1.
+idx VAR Nib
+result VAR Byte
+
+Setup:
+ idx = 3
+ result = 255
+
+Main:
+ LOOKUP idx, [26, 177, 13, 1, 0, 17, 99], result
+ DEBUG "Item ", DEC idx, " is: ", DEC result
+ END
+
+
In this example, DEBUG prints "Item 3 is: 1." Note that the first
+location number is 0. In the list above, item 0 is 26, item 1 is 177, etc.
+
If Index is beyond the end of the list, the result variable is unchanged.
+In the example above, if index were greater than 6, the message would have reported
+the result to be 255, because that's what result contained before LOOKUP
+executed.
+
Don't forget that text phrases are just lists of byte values, so they too are
+eligible for LOOKUP searches, as in this example:
+
+
+
+
+SYMBOL idx = B2
+SYMBOL result = B3
+
+Setup:
+ idx = 16
+ result = "*"
+
+Main:
+ LOOKUP idx, ("The quick brown fox"), result
+ DEBUG @result
+ END
+
+
+
+
+
+iidx VAR Byte
+result VAR Byte
+
+Setup:
+ idx = 16
+ result = "*"
+
+Main:
+ LOOKUP idx, ["The quick brown fox"], result
+ DEBUG ASC? result
+ END
+
+
DEBUG prints, "Result = 'f'" because the character at index item 16 is
+"f" in the phrase, "The quick brown fox".
+
The examples above show LOOKUP working with lists of constants, but it
+also works with variables and expressions also. Note, however, that expressions
+are not allowed as argument on the BS1.
+
A great use of LOOKUP is in combination with LOOKDOWN to "map"
+non-contiguous sets of numbers together. For example, you may have an application
+where certain numbers are received by the BASIC Stamp and, in response, the BASIC
+Stamp needs to send a specific set of numbers. This may be easy to code if the
+numbers are contiguous, or follow some know algebraic equations… but what if they
+don't? The table below shows some sample, non-contiguous inputs and the
+corresponding outputs the BASIC Stamp needs to respond with:
+
+
+
+
Index
+
Each of these values
+ received (inputs):
+
Needs to result in each of
+ these values sent (outputs):
+
+
+
0
+
5
+
16
+
+
+
1
+
14
+
17
+
+
+
2
+
1
+
18
+
+
+
3
+
43
+
24
+
+
+
4
+
26
+
10
+
+
+
5
+
22
+
12
+
+
+
6
+
30
+
11
+
+
+
+
+
So, if we receive the number 5, we need to output 16. If we received 43, we
+need to output 24, and so on. These numbers are not contiguous and they don't
+appear to be derived from any simple algorithm. We can solve this problem with
+two lines of code, as follows:
Assuming our received number is in value, the first line (LOOKDOWN)
+will find the value in the list and store the index of the location that matches
+back into value. (This step "maps" the non-contiguous numbers: 5, 14, 1, etc,
+to a contiguous set of numbers: 0, 1, 2, etc). The second line (LOOKUP)
+takes our new value, finds the number at that location and stores it back into
+value. If the received value was 14, LOOKDOWN stores 1 into value and
+LOOKUP looks at the value at location 1 and stores 17 in value. The
+number 43 gets mapped to 3, 3 gets mapped to 24, and so on. This is a quick and
+easy fix for a potentially messy problem!
The BS2p, BS2pe, and BS2px is available as a 24-pin module that is pin-compatible with the BS2, BS2e, and BS2sx. Also availabe is a 40-pin module called the BS2p40 with an additional 16 I/O pins (for a total of 32). The BS2p40's extra, or auxiliary, I/O pins can be accessed in the same manner as the main I/O pins (by using the IDs 0 to 15) but only after issuing an AUXIO or IOTERM 1 command. The MAINIO command causes the BASIC Stamp to affect the main I/O pins (the default) instead of the auxiliary I/O pins in all further code until the AUXIO or IOTERM 1 command is reached, or the BASIC Stamp is reset or power-cycled.
+
The following example illustrates this:
+ AUXIO
+ HIGH 0
+ MAINIO
+ LOW 0
+
+
The first line of the above example will tell the BASIC Stamp to affect the auxiliary I/O pins in the commands following it. Line 2 sets I/O pin 0 of the auxiliary I/O pins (physical pin 21) high. Afterward, the MAINIO command tells the BASIC Stamp that all commands following it should affect the main I/O pins. The last command, LOW, will set I/O pin 0 of the main I/O pins (physical pin 5) low.
+
Note that the main I/O and auxiliary I/O pins are independent of each other; the states of the main I/O pins remain unchanged while the program affects the auxiliary I/O pins, and vice versa.
Enter sleep mode for a short time. Power consumption is reduced as indicated in
+the table below assuming no loads are being driven.
+
+
+
+
Duration is a variable/constant/expression* (0 - 7) that
+ specifies the duration of the reduced-power "nap." The low-power duration is
+ 2Duration x 18 milliseconds.
+
+
* Note: expressions are not allowed as arguments on the BS1.
-50 to 100% (±10% @ 75°F with stable power supply)
+
+
+
Explanation
+
NAP uses the same shutdown/startup mechanism as SLEEP, with one big
+difference. During SLEEP, the BASIC Stamp automatically compensates for
+variations in the speed of the watchdog timer oscillator that serves as its alarm
+clock. As a result, longer SLEEP intervals are accurate to approximately
+±1 percent.
+
+
+
+
+
+
Duration
+
+
Length of NAP
+
+
+
0
+
18 ms
+
+
+
1
+
36 ms
+
+
+
2
+
72 ms
+
+
+
3
+
144 ms
+
+
+
4
+
288 ms
+
+
+
5
+
576 ms
+
+
+
6
+
1152 ms (1.152 seconds)
+
+
+
7
+
2304 ms (2.304 seconds)
+
+
+
+
+
NAP intervals are directly controlled by the watchdog timer without
+compensation. Variations in temperature, supply voltage, and manufacturing
+tolerance of the BASIC Stamp's interpreter chip can cause the actual timing to
+vary by as much as -50, +100 percent (i.e., a Duration of 0, NAP can range
+from 9 to 36 ms). At room temperature with a fresh battery or other stable power
+supply, variations in the length of a NAP will be less than ±10 percent.
+
One great use for NAP is in a battery-powered application where at least
+some small amount of time is spent doing nothing. For example, you may have a
+program that loops endlessly, performing some task, and pausing for approximately
+100 ms each time through the loop. You could replace your PAUSE 100 with
+NAP 3, as long as the timing of the 100 ms pause was not critical. The
+NAP 3 would effectively pause your program for about 144 milliseconds and,
+at the same time, would place the BASIC Stamp in low-power mode, which would extend
+your battery life.
+
During execution of power conserving commands (END, NAP, POLLWAIT, and SLEEP), current will occasionally be interrupted
+on I/O pins for about 18 ms durations (60 µs on the BS2pe). The reason is that the
+watchdog-timer reset that awakens the BASIC Stamp during these commands also causes all of the pins to
+switch to input mode for approximately 18 ms (60 µs on the BS2pe). When the interpreter
+firmware regains control of the processor, it restores the I/O direction dictated
+by your program.
+
If you plan to use END, NAP, POLLWAIT, or SLEEP in your programs,
+make sure that your loads can tolerate these power outages. The simplest solution
+is often to connect resistors high or low (to +5V or ground) as appropriate to
+ensure a continuing supply of current during the reset.
+
The example program can be used to demonstrate the effects
+of the NAP reset with an LED and resistor.
Store the address of the next instruction after ON..GOSUB, then go to the
+Address specified by offset (if in range) with the intention of returning
+to the stored address. If Offset-1 is greater than the number of elements in
+the address table, the program continues at the line following ON..GOSUB.
+
+
Offset is a variable/constant/expression (0 - 255) that
+ specifies the index of the address, in the list, to branch to (0 - N).
+
Addresses are labels that specify where to go for a given Offset. ON...GOSUB
+ will ignore any list entries beyond offset 255.
+
+
Quick Facts
+
+
+
+
BS2 Family
+
+
+
Limit of Address entries
+
256
+
+
+
Maximum nested GOSUBs
+
4
+
+
+
Maximum GOSUBs per Program
+
255 (each ON...GOSUB counts as as a GOSUB regardless of number of address list entries)
The ON...GOSUB instruction is useful when you want to write something like
+this:
+ IF (value = 0) THEN GOSUB Case_0
+ IF (value = 1) THEN GOSUB Case_1
+ IF (value = 2) THEN GOSUB Case_2
+
+
You can use ON...GOSUB to organize this into a single statement:
+ ON value GOSUB Case_0, Case_1, Case_2
+
+
This works exactly the same as the previous IF…THEN example. If the value isn't in range (in this case if value is greater than 2), ON...GOSUB does nothing and the program continues with the next instruction after ON.
The ON...GOTO instruction is useful when you want to write something like
+this:
+ IF idx = 0 THEN Case_0 ' idx = 0: jump to label "Case_0"
+ IF idx = 1 THEN Case_1 ' idx = 1: jump to label "Case_1"
+ IF idx = 2 THEN Case_2 ' idx = 2: jump to label "Case_2"
+
+
You can use ON...GOTO to organize this into a single statement:
+ ON idx GOTO Case_0, Case_1, Case_2
+
+
This works exactly the same as the previous IF…THEN example. If the value isn't in range (in this case if value is greater than 2), ON...GOSUB does nothing and the program continues with the next instruction after ON.
There are several ways to make a pin an output. Commands that rely on
+output pins, like PULSOUT and SEROUT, automatically change the
+specified pin to output. Writing 1s to particular bits of the variable DIRS
+makes the corresponding pins outputs. And then there’s the OUTPUTcommand.
+
When a pin is an output, your program can change its state by writing to
+the corresponding bit in the OUTS variable (PINS on the BS1). For
+example:
+
+
+
+
+
+
+ OUTPUT 4
+ PIN4 = 1
+
+
+
+
+
+ OUTPUT 4
+ OUT4 = 1
+
+
When your program changes a pin from input to output, whatever state happens to be in the corresponding bit of OUTS (PINS on the BS1) sets the initial state of the pin. To simultaneously make a pin an output and set its state use the HIGH and LOW commands.
Receive data from a device using the Maxim/Dallas Semiconductor 1-Wire®protocol.
+
+
Pin is a variable/constant/expression (0 - 15) that specifies
+ which I/O pin to use. 1-Wire devices require only one I/O pin
+ (called DQ) to communicate. This I/O pin will be toggled between output
+ and input mode during the OWIN command and will be set to input mode
+ by the end of the OWIN command.
+
Mode is a variable/constant/expression (0 - 15) indicating
+ the mode of data transfer. The Mode argument controls placement of
+ reset pulses (and detection of presence pulses) as well as byte vs. bit input
+ and normal vs. high speed. See explanation below.
+
InputData is a list of variables and modifiers that tells
+ OWIN what to do with incoming data. OWIN can store data in a
+ variable or array, interpret numeric text (decimal, binary, or hex) and store
+ the corresponding value in a variable, wait for a fixed or variable sequence
+ of bytes, or ignore a specified number of bytes. These actions can be combined
+ in any order in the InputData list.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Receive Rate
+
Approximately 20 kBits/sec (low speed, not including reset pulse)
+
+
+
Special Notes
+
The DQ pin (specified by Pin) must have a 4.7 kΩ pull-up
+ resist0r.
The 1-Wire protocol is a form of asynchronous serial communication developed by
+Maxim/Dallas Semiconductor. It only requires one I/O pin and that pin can
+be shared between multiple 1-Wire devices. The OWIN command
+allows the BASIC Stamp to receive data from a 1-Wire device.
This code will transmit a "reset" pulse to a 1-Wire device
+(connected to I/O pin 0) and then will detect the device's "presence" pulse and
+then receive one byte and store it in the variable result.
+
The Mode argument is used to control placement of reset pulses (and
+detection of presence pulses) and to designate byte vs. bit input and normal vs.
+high speed†. The tables below show the meaning of each of the
+four bits of Mode and some of the 16 possible values and their effect.
+
Mode Format bits
+
+
+
Bit
+
Function
+
+
+
0
+
Front-End Reset • 0 = No reset • 1 = Generate reset before data
+
+
+
1
+
Back-End Reset • 0 = No reset • 1 = Generate reset after data
+
+
+
2
+
Bit / Byte Transfer • 0 = Byte • 1 = Bit
+
+
+
3
+
Low / High Speed† • 0 = Low • 1 = High
+
+
+
+
+
+
Mode
+
Effect
+
+
+
0
+
No Reset, Byte mode, Low speed
+
+
+
1
+
Reset before data, Byte mode, Low speed
+
+
+
2
+
Reset after data, Byte mode, Low speed
+
+
+
3
+
Reset before and after data, Byte mode, Low speed
+
+
+
4
+
No Reset, Bit mode, Low speed
+
+
+
5
+
Reset before data, Bit mode, Low speed
+
+
+
6
+
Reset after data, Bit mode, Low speed
+
+
+
7
+
Reset before and after data, Bit mode, Low speed
+
+
+
8
+
No Reset, Byte mode, High speed†
+
+
+
9
+
Reset before data, Byte mode, High speed†
+
+
+
† The BS2pe is not capable of High-Speed transfers.
+
+
The proper value for Mode depends on the 1-Wire device
+and the portion of the communication you're working on. Please consult the data
+sheet for the device in question to determine the correct value for Mode. In many
+cases, however, when using the OWIN command, Mode should be set for
+either No Reset (to receive data from a transaction already started by a OWOUTcommand) or a Back-End Reset (to terminate the session after data is received).
+This may vary due to device and application requirements, however.
+
When using the Bit (rather than Byte) mode of data transfer, all variables in
+the InputData argument will only receive one bit. For example, the following
+code could be used to receive two bits using this mode:
+bitOne VAR Bit
+bitTwo VAR Bit
+
+Main:
+ OWIN 0, 6, [bitOne, bitTwo]
+ STOP
+
+
In the code above, we chose the value "6" for Mode. This sets Bit transfer
+and Back-End Reset modes. Also, we could have chosen to make the bitOne and bitTwo
+variables each a byte in size, but they still would only have received one bit each
+in the OWIN command (due to the Mode selected).
+
The OWIN command's InputData argument is similar to the SERINcommand's InputData argument. This means data can be received as ASCII
+character values, decimal, hexadecimal and binary translations and string data as
+in the examples below. (Assume a 1-Wire device is used and that
+it transmits the string, "Value: 3A:101" every time it receives a Front-End Reset
+pulse).
+value VAR Byte(13)
+
+Main:
+ OWIN 0, 1, [value] ' receive ASCII code for "V"
+ OWIN 0, 1, [DEC value] ' receive the number 3
+ OWIN 0, 1, [HEX value] ' receive the number $3A
+ OWIN 0, 1, [BIN value] ' receive the number %101
+ OWIN 0, 1, [STR value\13] ' receive the string "Value: 3A:101"
+ STOP
+
+
The tables below list all the available special formatters and conversion
+formatters available to the OWIN command. See the SERIN command for additional information and examples of their use.
+
+
+
Special Formatter
+
Action
+
+
+
STR ByteArray \L {\E}
+
Input a character string of length L into an array. If specified, an end
+ character E causes the string input to end before reaching length L.
+ Remaining bytes are filled with 0s (zeros).
+
+
+
WAITSTR ByteArray {\L}
+
Wait for a sequence of bytes matching a string stored in an array variable,
+ optionally limited to L characters. If the optional L argument is left off,
+ the end of the array-string must be marked by a byte containing a zero (0).
+
+
+
SKIP Length
+
Ignore Length bytes of characters.
+
+
+
SPSTR Length
+
Buffer Length bytes (up to 126) of serial characters to Scratchpad RAM,
+ starting at location 0. Use GET to retrieve the
+ characters.
+
+
+
+
+
+
+
+
+
Conversion Formatter
+
Type of Number
+
Numeric Characters Accepted
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally limited to 1 - 5 digits
+
0 through 9
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally limited to 1 - 5 digits
+
-, 0 through 9
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally limited to 1 - 4 digits
+
0 through 9, A through F
+
1,3
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally limited to 1 - 4 digits
+
-, 0 through 9, A through F
+
1,2,3
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally limited to 1 - 4 digits
+
$, 0 through 9, A through F
+
1,3,4
+
+
+
ISHEX{1..4}
+
Signed, indicated hexadecimal, optionally limited to 1 - 4 digits
+
-, $, 0 through 9, A through F
+
1,2,3,4
+
+
+
BIN{1..16}
+
Binary, optionally limited to 1 - 16 digits
+
0, 1
+
1
+
+
+
SBIN{1..16}
+
Signed binary, optionally limited to 1 - 16 digits
+
-, 0, 1
+
1,2
+
+
+
IBIN{1..16}
+
Indicated binary, optionally limited to 1 - 16 digits
+
%, 0, 1
+
1,4
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally limited to 1 - 16 digits
+
-, %, 0, 1
+
1,2,4
+
+
+
NUM
+
Generic numeric input; hex or binary number must be indicated
+
$, %, 0 through 9, A through F
+
1,3,4
+
+
+
SNUM
+
Similar to NUM with value treated as signed with range -32768 to +32767
+
-, $, %, 0 through 9, A through F
+
1,2,3,4
+
+
+
+
All numeric conversions will continue to accept new data until receiving
+ either the specified number of digits (ex: three digits for DEC3) or a
+ non-numeric character.
+
To be recognized as part of a number, the minus sign (-) must immediately
+ precede a numeric character. The minus sign character occurring in non-numeric
+ text is ignored and any character (including a space) between a minus and a
+ number causes the minus to be ignored.
+
The hexadecimal formatters are not case-sensitive; "a" through "f" means
+ the same as "A" through "F".
+
Indicated hexadecimal and binary formatters ignore all characters, even
+ valid numerics, until they receive the appropriate prefix ($ for hexadecimal,
+ % for binary). The indicated formatters can differentiate between text and
+ hexadecimal (ex: ABC would be interpreted by HEX as a number but IHEX would
+ ignore it unless expressed as $ABC). Likewise, the binary version can
+ distinguish the decimal number 10 from the binary number %10. A prefix
+ occurring in non-numeric text is ignored, and any character (including a space)
+ between a prefix and a number causes the prefix to be ignored. Indicated, signed
+ formatters require that the minus sign come before the prefix, as in -$1B45.
+
+
The 1-Wire Protocol Format
+
The 1-Wire protocol has a well-defined standard for transaction
+sequences. Every transaction sequence consists of four parts: 1) Initialization, 2)
+ROM Function Command, 3) Memory Function Command, and 4) Transaction/Data.
+Additionally, the ROM Function Command and Memory Function Command are always 8
+bits wide (1 byte in size) and is sent least-significant-bit (LSB) first.
+
The Initialization part consists of a reset pulse (generated by the master)
+and will be followed by a presence pulse (generated by all slave devices). The
+figure below details the reset pulse generated by the BASIC Stamp and a typical
+presence pulse generated by a 1-Wire slave, in response.
+
+
+
+
+
+
This reset pulse is controlled by the lowest two bits of the Mode argument
+in the OWIN command. It can be made to appear before the ROM Function
+Command (ex: Mode = 1), after the Transaction/Data portion (ex: Mode = 2), before
+and after the entire transaction (ex: Mode = 3) or not at all (ex: Mode = 0).
+See the section on Mode, above, for more information.
+
Following the Initialization part is the ROM Function Command. The ROM Function
+Command is used to address the desired 1-Wire device. The table
+below shows common ROM Function Commands. If only a single 1-Wire
+device is connected, the Skip ROM command can be used to address it. If more than
+one 1-Wire device is attached, the BASIC Stamp will ultimately have
+to address them individually using the Match ROM command.
+
+
+
Command
+
Value (HEX)
+
Action
+
+
+
Read ROM
+
$33
+
Reads the 64-bit ID of the 1-Wire device. This command
+ can only be used if there is a single 1-Wire device on the
+ line.
+
+
+
Match ROM
+
$55
+
This command, followed by a 64-bit ID, allows the BASIC Stamp to address
+ a specific 1-Wire device.
+
+
+
Skip ROM
+
$CC
+
Address a 1-Wire device without its 64-bit ID. This
+ command can only be used if there is a single 1-Wire device
+ on the line.
+
+
+
Search ROM
+
$F0
+
Reads the 64-bit IDs of all the 1-Wire devices on the
+ line. A process of elimination is used to distinguish each unique device.
+
+
+
+
The third part, the Memory Function Command, allows the BASIC Stamp to address
+specific memory locations, or features, of the 1-Wire device.
+Refer to the 1-Wire device's data sheet for a list of the available
+Memory Function Commands.
+
Finally, the Transaction/Data section is used to read or write data to the
+1-Wire device. The OWIN command will read data at this
+point in the transaction. A read is accomplished by generating a brief low-pulse
+and sampling the line within 15 ms of the falling edge of the pulse. This is called
+a "Read Slot." The figure below shows typical Read Slots performed by the BASIC
+Stamp. See the OWOUT command for information on Write Slots.
Send data to a device using the Maxim/Dallas Semiconductor 1-Wire®protocol.
+
+
Pin is a variable/constant/expression (0 - 15) that specifies
+ which I/O pin to use. 1-Wire devices require only one I/O
+ pin (called DQ) to communicate. This I/O pin will be toggled between output
+ and input mode during the OWOUT command and will be set to input mode
+ by the end of the OWOUT command.
+
Mode is a variable/constant/expression (0 - 15) indicating
+ the mode of data transfer. The Mode argument controls placement of
+ reset pulses (and detection of presence pulses) as well as byte vs. bit input
+ and normal vs. high† speed. See explanation below.
+
OutputData is a list of variables and modifiers that tells
+ OWOUT how to format outgoing data. OWOUT can transmit individual
+ or repeating bytes, convert values into decimal, hexadecimal or binary text
+ representations, or transmit strings of bytes from variable arrays. These
+ actions can be combined in any order in the OutputData list.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Transmission Rate
+
Approximately 20 kbits/sec (low speed, not including reset pulse)
+
+
+
Special Notes
+
The DQ pin (specified by Pin) must have a 4.7 kΩ pull-up
+ resister.
The 1-Wire protocol is a form of asynchronous serial communication developed by
+Maxim/Dallas Semiconductor. It only requires one I/O pin and that pin can
+be shared between multiple 1-Wire devices. The OWOUT
+command allows the BASIC Stamp to send data to a 1-Wire device.
+
The following is an example of the OWOUT command:
+ OWOUT 0, 1, [$4E]
+
+
This code will transmit a "reset" pulse to a 1-Wire device
+(connected to I/O pin 0) and then will detect the device's "presence" pulse and
+then transmit one byte (the value $4E).
+
The Mode argument is used to control placement of reset pulses (and
+detection of presence pulses) and to designate byte vs. bit input and normal vs.
+high speed†. The tables below show the meaning of each of the
+four bits of Mode and some of the 16 possible values and their effect.
+
+
+
Bit
+
Function
+
+
+
0
+
Front-End Reset • 0 = No reset • 1 = Generate reset
+ before data
+
+
+
1
+
Back-End Reset • 0 = No reset • 1 = Generate reset
+ after data
+
+
+
2
+
Bit / Byte Transfer • 0 = Byte • 1 = Bit
+
+
+
3
+
Low / High Speed† • 0 = Low • 1 = High
+
+
+
+
+
+
Mode
+
Effect
+
+
+
0
+
No Reset, Byte mode, Low speed
+
+
+
1
+
Reset before data, Byte mode, Low speed
+
+
+
2
+
Reset after data, Byte mode, Low speed
+
+
+
3
+
Reset before and after data, Byte mode, Low speed
+
+
+
4
+
No Reset, Bit mode, Low speed
+
+
+
5
+
Reset before data, Bit mode, Low speed
+
+
+
6
+
Reset after data, Bit mode, Low speed
+
+
+
7
+
Reset before and after data, Bit mode, Low speed
+
+
+
8
+
No Reset, Byte mode, High speed†
+
+
+
9
+
Reset before data, Byte mode, High speed†
+
+
+
† The BS2pe is not capable of High Speed transfers.
+
+
The proper value for Mode depends on the 1-Wire device
+and the portion of the communication you're working on. Please consult the data
+sheet for the device in question to determine the correct value for Mode.
+In many cases, however, when using the OWOUT command, Mode should
+be set for a Front-End Reset (to initialize the transaction). This may vary due
+to device and application requirements, however.
+
When using the Bit (rather than Byte) mode of data transfer, all variables in
+the OutputData argument will only transmit one bit. For example, the
+following code could be used to send two bits using this mode:
+bitOne VAR Bit
+bitTwo VAR Bit
+
+Init:
+ bitOne = 0
+ bitTwo = 1
+
+Main:
+ OWOUT 0, 5, [bitOne, bitTwo]
+ STOP
+
+
In the code above, we chose the value "5" for Mode. This sets Bit transfer
+and Front-End Reset modes. Also, we could have chosen to make the bitOne and
+bitTwo variables each a byte in size, but the BASIC Stamp would still only use the
+their lowest bit (Bit0) as the value to transmit in the OWOUT command (due
+to the Mode we chose).
+
The OWOUT command's OutputData argument is similar to the DEBUG
+and SEROUT command's OutputData argument. This means data can be
+sent as literal text, ASCII character values, repetitive values, decimal, hexadecimal
+and binary translations and string data as in the examples below.
+value VAR Byte
+
+Init:
+ value = 65
+
+Main:
+ OWOUT 0, 1, [value] ' send ASCII character "A"
+ OWOUT 0, 1, [REP value\5] ' send "A" 5x, ie: "AAAAA"
+ OWOUT 0, 1, [DEC value] ' send "6" and "5"
+ OWOUT 0, 1, [HEX value] ' send "4" and "1"
+ OWOUT 0, 1, [BIN value] ' send "1000001"
+ STOP
+
+
The tables below list all the available special formatters and conversion
+formatters available to the OWOUT command. See the DEBUG
+ and SEROUT commands
+for additional information and examples of their use.
+
+
+
Special Formatter
+
Action
+
+
+
?
+
Displays "symbol = x' + carriage return; where x is a number. Default
+ format is decimal, but may be combined with conversion formatters (ex: BIN
+ ? x to display "x = binary_number").
+
+
+
ASC ?
+
Displays "symbol = 'x'" + carriage return; where x is an ASCII
+ character.
+
+
+
STR ByteArray {\L}
+
Send character string from an array. The optional \L argument can be
+ used to limit the output to L characters, otherwise, characters will be
+ sent up to the first byte equal to 0 r the end of RAM space is reached.
+
+
+
REP Byte\L
+
Send a string consisting of Byte repeated L times (ex: REP "X"\10 sends
+ "XXXXXXXXXX").
+
+
+
+
+
+
Conversion Formatter
+
Type of Number
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally fixed to 1 - 5 digits
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally fixed to 1 - 5 digits
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally fixed to 1 - 4 digits
+
1
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally fixed to 1 - 4 digits
+
1,2
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally fixed to 1 - 4 digits
Indicated binary, optionally fixed to 1 - 16 digits
+
1
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally fixed to 1 - 16 digits
+
1,2
+
+
+
+
Fixed-digit formatters like DEC4 will pad the number with leading 0s if
+ necessary; ex: DEC4 65 sends 0065. If a number is larger than the specified
+ number of digits, the leading digits will be dropped; ex: DEC4 56422 sends
+ 6422.
+
Signed modifiers work under two's complement rules.
+
+
The 1-Wire Protocol Format
+
The 1-Wire protocol has a well-defined standard for transaction
+sequences. Every transaction sequence consists of four parts: 1) Initialization,
+2) ROM Function Command, 3) Memory Function Command, and 4) Transaction/Data.
+Additionally, the ROM Function Command and Memory Function Command are always 8
+bits wide (1 byte in size) and is sent least-significant-bit (LSB) first.
+
+
The Initialization part consists of a reset pulse (generated by the master)
+and will be followed by a presence pulse (generated by all slave devices). The
+figure below details the reset pulse generated by the BASIC Stamp and a typical
+presence pulse generated by a 1-Wire slave, in response.
+
+
+
+
+
+
This reset pulse is controlled by the lowest two bits of the Mode
+argument in the OWIN command. It can be made to appear before the ROM
+Function Command (ex: Mode = 1), after the Transaction/Data portion (ex: Mode
+= 2), before and after the entire transaction (ex: Mode = 3) or not at all (ex:
+Mode = 0). See the section on Mode, above, for more information.
+
Following the Initialization part is the ROM Function Command. The ROM Function
+Command is used to address the desired 1-Wire device. The table
+below shows common ROM Function Commands. If only a single 1-Wire
+device is connected, the Match ROM command can be used to address it. If more than
+one 1-Wire device is attached, the BASIC Stamp will ultimately
+have to address them individually using the Match ROM command.
+
+
+
Command
+
Value (HEX)
+
Action
+
+
+
Read ROM
+
$33
+
Reads the 64-bit ID of the 1-Wire device. This command
+ can only be used if there is a single 1-Wire device on the
+ line.
+
+
+
Match ROM
+
$55
+
This command, followed by a 64-bit ID, allows the BASIC Stamp to address
+ a specific 1-Wire device.
+
+
+
Skip ROM
+
$CC
+
Address a 1-Wire device without its 64-bit ID. This
+ command can only be used if there is a single 1-Wire device
+ on the line.
+
+
+
Search ROM
+
$F0
+
Reads the 64-bit IDs of all the 1-Wire devices on the
+ line. A process of elimination is used to distinguish each unique device.
+
+
+
+
The third part, the Memory Function Command, allows the BASIC Stamp to address
+specific memory locations, or features, of the 1-Wire device.
+Refer to the 1-Wire device's data sheet for a list of the available
+Memory Function Commands.
+
Finally, the Transaction/Data section is used to read or write data to the
+1-Wire device. The OWOUT command will write data at this
+point in the transaction. A write is accomplished by generating a low-pulse of
+a varying width to indicate a 0 or a 1. This is called a "Write Slot" and must be
+at least 60 us wide. The figure below shows typical Write Slots performed by the
+BASIC Stamp. See the OWIN command for information on Read
+Slots.
Pause the program (do nothing) for the specified Duration.
+
+
+
+
Duration is a variable/constant/expression* (0 - 65535) that
+ specifies the duration of the pause. The unit of time for Duration is
+ one millisecond.
+
+
* Note: expressions are not allowed as arguments on the BS1.
+
Explanation
+
PAUSE delays the execution of the next program instruction for the specified
+number of milliseconds. For example:
This code causes pin 0 to go low for 100 ms, then high for 100 ms. The delays
+produced by PAUSE are as accurate as the ceramic-resonator time base (on
+the BASIC Stamp modules), ±1 percent. When you use PAUSE in timing-critical
+applications, keep in mind the relatively low speed of the PBASIC interpreter.
+This is the time required for the BASIC Stamp to read and interpret an instruction
+stored in the EEPROM.
Pin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin to use. This I/O pin will be set to input mode.
+
State is a variable/constant/expression (0 - 1) that specifies
+ whether to poll the I/O pin for a low (0) or a high (1) level.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Available actions in response to reaching
+ the desired State
+
+
+
Nothing,
+
Set polled-output pins to a specified state,
+
Run another program (in a specified program-slot),
+
Wait (pause program execution) until desired State is reached,
+
Any combination of 2, 3 and 4, above.
+
+
+
+
+
Special Notes
+
+
+
The polled-input pins are monitored (polled) in-between each command
+ within the PBASIC code.
+
On the BS2p40 polled-input pins can be defined on both main and
+ auxiliary I/O pins. These are all active regardless of which group
+ the program happens to be using at the time of a polling event.
+
Polled input pins are stored in special Scratchpad RAM locations. Use
+GET to retrieve.
The POLLIN command is one of a family of unique "polling" commands on the
+BS2p, BS2pe, and BS2px modules. The other commands in this family include POLLMODE,
+POLLOUT, POLLRUN and POLLWAIT. The POLLIN command
+is used to specify an input pin to monitor, or "poll", in-between instructions
+during the rest of the PBASIC program. The BASIC Stamp will then perform some
+activity (in between instructions) when the specified State is detected. The
+activity performed depends on the POLLMODE, POLLOUT and POLLRUNcommands.
+
The "polling" commands allow the BASIC Stamp to respond to certain I/O pin
+events at a faster rate than what is normally possible through manual PBASIC
+programming. The term "poll" comes from the fact that the BASIC Stamp's interpreter
+periodically checks the state of the designated polled-input pins. It "polls"
+these pins after the end of each PBASIC instruction and before it reads the next
+PBASIC instruction from the user program; giving the appearance that it is polling
+"in the background".
+
This feature should not be confused with the concept of interrupts, as
+the BASIC Stamp does not support true interrupts.
+
The following is an example of the POLLIN command:
+ POLLIN 0, 0
+ POLLMODE 2
+
+
The POLLIN command in the above code will cause the BASIC Stamp to set
+I/O pin 0 to an input mode and get ready to poll it for a low (0) state. The
+BASIC Stamp will not actually start polling until it is set to the appropriate
+mode, however. The second line, POLLMODE, initiates the polling process
+(see the POLLMODE description for more information).
+From then on, as the BASIC Stamp executes the rest of the program, it will check
+for a low level (logic 0) on I/O pin 0, in-between instructions.
+
In the code above, no obvious action will be noticed since we didn't tell the
+BASIC Stamp what to do when it detects a change on the I/O pin. One possible
+action the BASIC Stamp can be instructed to take is to change the state of an
+output, called a polled-output. Take a look at the next example:
In this example, in addition to an endless loop, we've added another polling
+command called POLLOUT (see the POLLOUT description
+for more information). Our POLLOUT command tells the BASIC Stamp to set
+I/O pin 1 to an output mode and set it high (1) when it detects the desired poll
+state. The poll state is the low (0) level on I/O pin 0 that POLLIN told
+it to look for. If the polled-input pin is high, it will set polled-output
+pin 1 to low (0), instead.
+
Once the program reaches the endless loop, starting at Main, it will continuously
+print "Looping..." on the PC screen. In between reading the DEBUG command
+and the GOTO command (and vice versa) it will check polled-input pin 0 and
+set polled-output pin 1 accordingly. In this case, when I/O pin 0 is set low,
+the BASIC Stamp will set I/O pin 1 high. When I/O pin 0 is set high, the BASIC
+Stamp will set I/O pin 1 low. It will continue to perform this operation,
+in-between each command in the loop, endlessly.
+
It's important to note that, in this example, only the DEBUG and GOTOcommands are being executed over and over again. The first three lines of code
+are only run once, yet their effects are "remembered" by the BASIC Stamp throughout
+the rest of the program.
+
If the polling commands were not used, the program would have to look like the
+one below in order to achieve the same effect.
In this example, we create the inverse relationship of input pin 0 and output
+pin 1 manually, in-between the DEBUG and GOTO lines. Though the
+effects are the same as when using the polling commands, this program actually
+takes a little longer to run and consumes 7 additional bytes of program (EEPROM)
+space. Clearly, using the polling commands is more efficient.
+
You can have as many polled-input and polled-output pins as you have available.
+If multiple polled-input pins are defined, any one of them can trigger changes on
+the polled-output pins that are also defined. For example:
This code sets I/O pins 0 and 1 to polled-input pins (looking for a high (1)
+state) and sets I/O pin 2 to be a polled-output pin (with a high-active state).
+If either I/O pin 0 or 1 goes high, the BASIC Stamp will set I/O pin 2 high.
+This works similar to a logical OR operation. The truth table below shows all the
+possible states of these two polled-input pins and the corresponding states the
+BASIC Stamp will set the polled-output pin to.
+
+
+
+
Polled-Inputs
+
Polled-Output
+
+
+
0
+
1
+
2
+
+
+
0
+
0
+
0
+
+
+
0
+
1
+
1
+
+
+
1
+
0
+
1
+
+
+
1
+
1
+
1
+
+
+
+
+
Normally, any polled-output pins reflect the state changes continuously, as
+described above. The POLLMODE command supports another feature, however,
+where the polled-output pins will latch the active state; they will change only
+once (when the poll state is reached) and stay in the new state until the PBASIC
+program tells it to change again. See the
+POLLMODE description for more information.
+
Other possible actions in response to polled-input states are: 1) Running
+another program (in a specified program slot), 2) Waiting (pausing program
+execution with or without low-power mode) until the poll state is reached, or 3)
+Any combination of the above-mentioned actions
The POLLMODE command is one of a family of unique "polling" commands on the
+BS2p, BS2pe, and BS2px modules. The other commands in this family include POLLIN,
+POLLOUT, POLLRUN and POLLWAIT. The POLLMODE command
+is used to specify the mode in which polling events and activities are processed.
+This activity will occur in between instructions during the rest of the PBASIC
+program.
+
The "polling" commands allow the BASIC Stamp to respond to certain I/O pin events
+at a faster rate than what is normally possible through manual PBASIC programming.
+The term "poll" comes from the fact that the BASIC Stamp's interpreter periodically
+checks the state of the designated polled-input pins. It "polls" these pins after
+the end of each PBASIC instruction and before it reads the next PBASIC instruction
+from the user program; giving the appearance that it is polling "in the
+background".
+
This feature should not be confused with the concept of interrupts, as the
+BASIC Stamp does not support true interrupts.
+
The POLLMODE command sets one of 15 possible modes for the polling
+commands. It is used mainly before and/or after any POLLIN, POLLOUT
+and POLLRUN commands to disable and enable the polling features as desired.
+The table below shows the mode values and their effect.
+
+
+
Mode
+
Effect
+
+
+
0
+
Deactivate polling, clear polled-input and output configuration.
+
+
+
1
+
Deactivate polling, save polled-input and output configuration.
+
+
+
2
+
Activate polling with polled-output action (and polled-wait) only.
+
+
+
31
+
Activate polling with polled-run action only.
+
+
+
42
+
Activate polling with polled-output/polled-wait and polled-run actions.
+
+
+
53
+
Clear polled-input configuration.
+
+
+
63
+
Clear polled-output configuration.
+
+
+
73
+
Clear polled-input and output configuration.
+
+
+
8 - 15
+
Same at 0 - 7 except polled-output states are latched.
+
+
+
+
+
+
1
+
+
After the polled-run action occurs, the mode switches to 1 (deactivated,
+ saved)
+
+
+
2
+
+
After the polled-run action occurs, the mode switches to 2 (activated,
+ outputs)
+
+
+
3
+
+
These modes do not override the previous mode. Also, the output state of
+ polled-outputs does not change as a result of these modes.
+
+
+
+
The polled-run modes, 3 and 4, are unique. As soon as the polled-run action
+occurs, the mode switches to 1 (deactivated, saved) or 2 (activated, outputs),
+respectively. This is so that the BASIC Stamp doesn't continuously go to the
+start of the designated program slot while the polled-inputs are in the desired
+poll state. Without this "one shot" feature, your program would appear to lock-up
+as long as the polled-inputs are in the designated state.
+
The clear configuration modes, 5, 6 and 7, are also unique. These modes do not
+override the previous mode. For example, if polled-inputs, polled-outputs and a
+polled-run configuration was set and the mode was set to 4 (activated, outputs and
+run) and later the program issued a POLLMODE 6 command, the polled-output
+configuration would be cleared but the mode would switch back to 4... still allowing
+the run action. This also means if, later still, the program issues a POLLOUT
+command, this polled-output would take effect immediately (since the mode is still
+4). Also note that these modes do not change the output state of previously defined
+polled-output pins.
+
The POLLMODE command determines what action, if any, will occur in
+response to a polled-input event. This command works in conjunction with the
+POLLIN, POLLOUT and POLLRUN commands. The following is an
+example of the POLLMODE command:
In this example, the first two lines configure I/O pin 0 as a polled-input
+(looking for a low state) and I/O pin 1 as a polled-output (going high if I/O pin
+0 goes low, and vice versa). The third line, POLLMODE, initiates the
+polling process and configures polled-outputs to be active. From then on, as the
+BASIC Stamp executes the rest of the program, it will check for a low level
+(logic 0) on I/O pin 0 in between instructions and will set I/O pin 1 accordingly.
+
If, in the above example, the poll mode was set to 1 (which means deactivate
+polling but save configuration) I/O pins 0 and 1 would still be defined the same
+way, and I/O pin 1 would still be set to output mode, but no polling would take
+place during the rest of the program.
+
Here's another example that demonstrates mode 1 (deactivate but save
+configuration).
In this case, polling is configured and activated before "Polling configured"
+is printed on the screen. Once we reach the Main routine, however, polling is
+disabled (via the POLLMODE 1 command) and no polling occurs during the
+printing of "No polling allowed here..." or during the 1 second pause afterward.
+Finally, polling is activated again, and since the configuration was saved (because
+of mode 1, before) the polling activity acts just like it did initially for the
+remainder of the program. The ability to temporarily disable polling, without
+changing the configuration, can be a powerful feature for certain "critical" parts
+of a program.
+
The following example contains two programs. The first should be downloaded
+into program slot 0 and the second into program slot 1. We'll assume they are
+called POLL0.BSP and POLL1.BSP, respectively (as defined in the $STAMP directive
+lines).
In this example (containing two programs; one is slot 0 and the other in slot 1)
+program 1 (slot 0) will configure polled-input pin 0 to detect a low state and
+polled-output 1 to go high in response. Program 1 also configures a polled-run
+activity (see the POLLRUN description for more information) to run the
+program in slot 1. The POLLMODE setting activates the polled-output and
+the polled-run. Then, program 1 continuously prints "Program 1" on the PC screen.
+
Once I/O pin 0 goes low, however, the BASIC Stamp will set I/O pin 1 high,
+then execution will be switched to the program in slot 1 (program 2). Program 2
+will first print "Switching..." on the PC screen and then will continuously print
+"Program 2". From this point forward, I/O pin 1 will continue to be set low and
+high in response to changes occurring on I/O pin 0, but the polled-run activity
+is disabled and the BASIC Stamp endlessly runs the code in program 2's Again
+routine.
Pin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin to use. This I/O pin will be set to output mode.
+
State is a variable/constant/expression (0 - 1) that specifies
+ whether to set the I/O pin low (0) or high (1) when a polled-input pin changes
+ to its poll state.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Special Notes
+
+
+
The POLLOUT command will immediately change the I/O pin to an
+ output mode and set its level opposite to that of State,
+ regardless of the polled-input states or the polled mode.
+
Polled-output pins will either change states continuously, just once
+ or not at all, depending on the POLLMODE command.
+
On the BS2p40 polled-output pins can be defined on both main and
+ and auxiliary I/O pins. These are all active regardless of which group
+ the program happens to be using at the time of a polling event.
+
If both polled-outputs and polled-run are active, the polled-output event
+ will occur before the polled-run event.
The POLLOUT command is one of a family of unique "polling" commands on the
+BS2p, BS2pe, and BS2px modules. The other commands in this family include POLLIN,
+POLLMODE, POLLRUN and POLLWAIT. The POLLOUT command
+is used to specify an output pin that changes states in response to changes on
+any of the defined polled-input pins. This activity will occur in between
+instructions during the rest of the PBASIC program.
+
The "polling" commands allow the BASIC Stamp to respond to certain I/O pin
+events at a faster rate than what is normally possible through manual PBASIC
+programming. The term "poll" comes from the fact that the BASIC Stamp's interpreter
+periodically checks the state of the designated polled-input pins. It "polls"
+these pins after the end of each PBASIC instruction and before it reads the next
+PBASIC instruction from the user program; giving the appearance that it is polling
+"in the background".
+
This feature should not be confused with the concept of interrupts, as
+the BASIC Stamp does not support true interrupts.
+
The POLLOUT command achieves one of three possible actions in response
+to a polled-input event. This command works in conjunction with the POLLIN
+and POLLMODE commands. The following is an example of the POLLOUT
+command:
In this example, the POLLOUT command tells the BASIC Stamp to set I/O
+pin 1 to an output mode and set it high (1) when it detects the desired poll state.
+The poll state is the low (0) level on I/O pin 0 that POLLIN told it to
+look for. If the polled-input pin is high, the BASIC Stamp will set
+polled-output pin 1 to low (0), instead. The BASIC Stamp will not actually start
+polling until it is set to the appropriate mode, however. The third line,
+POLLMODE, initiates the polling process (see the
+POLLMODE description for more information). From then
+on, as the BASIC Stamp executes the rest of the program, it will check for a low
+level (logic 0) on I/O pin 0 in between instructions.
+
Once the program reaches the endless loop, at Main, it will continuously
+print "Looping...." on the PC screen. In between reading the DEBUG command
+and the GOTO command (and vice versa) it will check polled-input pin 0 and
+set polled-output pin 1 accordingly. In this case, when I/O pin 0 is set low,
+the BASIC Stamp will set I/O pin 1 high. When I/O pin 0 is set high, the BASIC
+Stamp will set I/O pin 1 low. It will continue to perform this operation,
+in between each command in the loop, endlessly.
+
It's important to note that in this example only the DEBUG and
+GOTO commands are being executed over and over again. The first three
+lines of code are only run once, yet their effects are "remembered" by the BASIC
+Stamp throughout the rest of the program.
+
If the polling commands were not used, the program would have to look like
+the one below in order to achieve the same effect.
In this example, we create the inverse relationship of input pin 0 and output
+pin 1 manually, in-between the DEBUG and GOTO lines. Though the
+effects are the same as when using the polling commands, this program actually
+takes a little longer to run and consumes 7 additional bytes of program (EEPROM)
+space. Clearly, using the polling commands is more efficient.
+
You can have as many polled-input and polled-output pins as you have available.
+If multiple polled-input pins are defined, any one of them can trigger changes on
+the polled-output pins that are also defined. For example:
This code sets I/O pins 0 and 1 to polled-input pins (looking for a high (1)
+state) and sets I/O pin 2 to be a polled-output pin (with a high-active state).
+If either I/O pin 0 or 1 goes high, the BASIC Stamp will set I/O pin 2 high.
+This works similar to a logical OR operation. The truth table below shows all the
+possible states of these two polled-input pins and the corresponding states the
+BASIC Stamp will set the polled-output pin to.
+
+
+
+
Polled-Inputs
+
Polled-Output
+
+
+
0
+
1
+
2
+
+
+
0
+
0
+
0
+
+
+
0
+
1
+
1
+
+
+
1
+
0
+
1
+
+
+
1
+
1
+
1
+
+
+
+
+
Normally, any polled-output pins reflect the state changes continuously, as
+described above. The POLLMODE command supports another feature, however,
+where the polled-output pins will latch the active state; they will change only
+once (when the poll state is reached) and stay in the new state until the PBASIC
+program tells it to change again. See the POLLMODE
+description for more information.
+
A clever use of the "latched" feature is to set a polled-output to be the same
+as the polled-input. For example, suppose an application needed to respond in some
+way if a polled-input pin goes high, but it doesn't need to respond immediately,
+and the other tasks should not be interrupted. In essence, we need a way to know
+if the pin has gone high since the last time we checked it. Look at this
+example:
+idx VAR Byte
+
+Setup:
+ POLLOUT 0, 1 ' pin 0 is polled-output, high
+ POLLIN 0, 1 ' pin 0 back to polled-input, high
+ POLLMODE 10 ' Set mode to latch the polled-output
+
+Work: ' kill time waiting for polled
+ FOR idx = 1 TO 20 ' event
+ DEBUG "Working....", CR
+ NEXT
+ IF (OUT0 = 0) THEN Work
+
+Respond: ' Response message
+ DEBUG CR,
+ "You set my pin high!", CR
+ POLLMODE 10 ' Reset polled-output's latch function
+ GOTO Work
+
+
Here, we set I/O pin 0 to a polled-output, then immediately set it to a
+polled-input. Then we set the polled-mode to latch the polled-outputs. Since
+the POLLIN command occurred after the POLLOUT, I/O pin 0 will be
+an input, but the polling feature will still affect the OUT0 bit (output latch
+for I/O pin 0). Then, the program performs some work, and once in a while, checks
+the state of OUT0. If OUT0 is 0, I/O pin 0 was never seen to go high. If,
+however, OUT0 is 1, I/O pin 0 must have gone high while the program was doing
+other work, and now it can respond in the proper manner. This even works if the
+pin had gone high and then low again before we check it (as long as it was high
+at some point in between the instructions in our Work routine.
+
It is important to note that during the time between the POLLOUT and
+POLLIN commands, I/O pin 0 will be set to an output direction. This can
+cause a temporary short with the circuitry connected to I/O pin 0, so it is
+vital that a large enough series resister (perhaps 220 ohms or greater) be
+inserted on that pin to protect the external device and the BASIC Stamp.
Specify a program to run upon a polled-input event.
+
+
+
+
ProgramSlot is a variable/constant/expression (0 - 7) that
+ specifies the program slot to run when a polled-input event occurs.
+
+
Quick Facts
+
+
+
+
BS2p, BS2pe, and BS2px
+
+
+
Default Slot
+
The default polled-run slot is 0. If no POLLRUN
+ command is given and a poll mode of 3 or 4 is set, the program in slot 0
+ will run in response to a polled-input event.
+
+
+
Special Notes
+
+
+
If both polled-outputs and polled-run are active, the polled-output
+ event will occur before the polled-run event.
+
The POLLRUN command is one of a family of unique "polling" commands on the
+BS2p, BS2pe, and BS2px modules. The other commands in this family include POLLIN,
+POLLMODE, POLLOUT and POLLWAIT. The POLLRUN command
+is used to specify a program slot to run in response to a polled event. This
+activity can occur in between any two instructions within the rest of the PBASIC
+program.
+
The "polling" commands allow the BASIC Stamp to respond to certain I/O pin
+events at a faster rate than what is normally possible through manual PBASIC
+programming. The term "poll" comes from the fact that the BASIC Stamp's interpreter
+periodically checks the state of the designated polled-input pins. It "polls"
+these pins after the end of each PBASIC instruction and before it reads the next
+PBASIC instruction from the user program; giving the appearance that it is polling
+"in the background". This feature should not be confused with the concept of
+interrupts, as the BASIC Stamp does not support true interrupts.
+
The following is a simple example of the POLLRUN command:
+Setup:
+ POLLIN 0, 0
+ POLLRUN 1
+ POLLMODE 3
+
+Main:
+ DEBUG "Waiting in Program Slot 0...", CR
+ GOTO Main
+
+
The first line of the above code will set up I/O pin 0 as a polled-input pin
+looking for a low (0) state. The second line, POLLRUN, tells the BASIC
+Stamp that when I/O pin 0 goes low, it should switch execution over to the
+program residing in program slot 1. The third line, POLLMODE, activates
+the polled-run configuration.
+
Once the BASIC Stamp reaches the Main routine, it will continuously print
+"Waiting in Program Slot 0..." on the PC screen. In between reading the
+DEBUG and GOTO commands, however, the BASIC Stamp will poll I/O
+pin 0 and check for a high or low state. If the state of pin 0 is high,
+it will do nothing and continue as normal. If the state of pin 1 is low, it
+will switch execution over to the program in slot 1 (the second program is not
+shown in this example). The switch to another program slot works exactly like
+with the RUN command; the designated program is run and the BASIC Stamp
+does not "return" to the previous program (similar to a GOTO command).
+
Note that in order for the polled-run activity to occur, the poll mode must
+be set to either 3 or 4 (the two modes that activate polled-run). Also note,
+that the polled-run modes, 3 and 4, are unique. As soon as the polled-run action
+occurs, the mode switches to 1 (deactivated, saved) or 2 (activated, outputs),
+respectively. This is so that the BASIC Stamp doesn't continuously go to the
+start of the designated program slot while the polled-inputs are in the desired
+poll state. Without this "one shot" feature, your program would appear to lock-up
+as long as the polled-inputs are in the designated state.
+
After the program switch takes place, the ProgramSlot value is maintained.
+Any future change to poll mode 3 or 4, without another POLLRUN command, will
+result in the previously defined program slot being used.
Pause program execution, in a low-power mode, in units of Duration until any
+polled-input pin reaches the desired poll state.
+
+
+
+
Duration is a variable/constant/expression (0 - 8) that
+ specifies the duration of the low-power state. The low-power duration is
+ 2Duration x 18 milliseconds. The table below indicates the low-power
+ duration for any given Duration. Using 8 as the Duration is a special
+ case; the BS2p, BS2pe, and BS2px will not go into low-power mode and will
+ respond quicker to polled inputs.
+
+
Quick Facts
+
+
+
+
BS2p
+
BS2pe
+
BS2px
+
+
+
Current draw during POLLWAIT
+
350 µA
+
36 µA
+
450 µA
+
+
+
Response time with Duration set
+ to 8
+
Less than 160 µs
+
Less than 250 µs
+
Less than 100 µs
+
+
+
Special Notes
+
+
+
Poll mode must be 2 or 4 and at least one polled-input must be set
+ to activate POLLWAIT (POLLWAIT will be ignored
+ otherwise).
+
If both polled-wait and polled-run are active, the polled-run event
+ will occur immediately after the polled-wait detects an event.
The POLLWAIT command is one of a family of unique "polling" commands on
+the BS2p and BS2pe modules. The other commands in this family include POLLIN,
+POLLMODE, POLLOUT and POLLRUN. The POLLWAIT command
+is used to pause program execution and go into a low-power state until any
+polled-input pin reaches the desired poll state.
+
The "polling" commands allow the BASIC Stamp to respond to certain I/O pin
+events at a faster rate than what is normally possible through manual PBASIC
+programming. The term "poll" comes from the fact that the BASIC Stamp's interpreter
+periodically checks the state of the designated polled-input pins. It "polls"
+these pins after the end of each PBASIC instruction and before it reads the next
+PBASIC instruction from the user program; giving the appearance that it is polling
+"in the background". This feature should not be confused with the concept of
+interrupts, as the BASIC Stamp does not support true interrupts.
+
The POLLWAIT command is unique among the polling commands in that it
+actually causes execution to halt, until a polled-input pin event occurs.
+The Duration argument is similar to that of the NAP command; using
+the values 0 to 7 specifies the duration of the low-power period. After the
+low-power period is over, the BASIC Stamp polls the polled-input pins and determines
+if any meet the desired poll state. If no polled-input is in the desired state
+(as set by POLLIN command) the BASIC Stamp goes back into low-power mode,
+again, for the same duration as before. If any polled-input is in the desired
+state, however, the BASIC Stamp will continue execution with the next line of
+code.
+
A Duration of 8 makes the BASIC Stamp pause execution in normal running
+mode (not low-power mode) until a polled-input event occurs. The response time
+is indicated in the table below. Since the response time is so fast, this feature
+can be used to synchronize a portion of PBASIC code to an incoming pulse
+
+
+
+
Duration
+
+
Length of Low-Power Mode
+
+
+
0
+
18 ms
+
+
+
1
+
36 ms
+
+
+
2
+
72 ms
+
+
+
3
+
144 ms
+
+
+
4
+
288 ms
+
+
+
5
+
576 ms
+
+
+
6
+
1152 ms (1.152 seconds)
+
+
+
7
+
2304 ms (2.304 seconds)
+
+
+
8
+
No power-down
+
+
+
+
+
The following is a simple example of the POLLWAIT command.
In this example, the POLLIN command sets I/O pin 0 to be a polled-input
+pin looking for a low (0) state. The Main routine immediately runs a POLLWAITcommand and specifies a Duration of 0 (with results in a low-power state of
+18 ms). This means that every 18 milliseconds, the BASIC Stamp wakes-up and checks
+I/O pin 0 for a low. If I/O pin 0 is high, it goes back to sleep for another 18
+milliseconds. If I/O pin 0 is low, it runs the next line of code, which toggles
+the state of I/O pin 1. Then the loop starts all over again.
+
If low-power mode is not required, change the POLLWAIT command in the
+example above to "POLLWAIT 8" instead. This will have the effect of keeping
+the BASIC Stamp in normal running mode (i.e., no low-power glitches) and will also
+cause the TOGGLE command to execute in a much shorter amount of time after
+a polled-input event occurs.
+
Note: Due to the
+nature of low-power mode, I/O pin 1 may occasionally toggle between high and low even if I/O pin 0 stays low. This is an
+artifact of power conserving commands, described below.
+
During execution of power conserving commands (END, NAP, POLLWAIT, and SLEEP), current will occasionally be interrupted
+on I/O pins for about 18 ms durations (60 µs on the BS2pe). The reason is that the
+watchdog-timer reset that awakens the BASIC Stamp during these commands also causes all of the pins to
+switch to input mode for approximately 18 ms (60 µs on the BS2pe). When the interpreter
+firmware regains control of the processor, it restores the I/O direction dictated
+by your program.
+
If you plan to use END, NAP, POLLWAIT, or SLEEP in your programs,
+make sure that your loads can tolerate these power outages. The simplest solution
+is often to connect resistors high or low (to +5V or ground) as appropriate to
+ensure a continuing supply of current during the reset.
Read a 5 kΩ to 50 kΩ potentiometer, thermistor, photocell, or other
+variable resistance.
+
+
Pin is a variable/constant (0 - 7) that specifies the I/O pin
+ to use. This pin will be set to output mode initially, then to input mode.
+
Scale is a variable/constant (0 - 255) used to scale the
+ command's internal 16-bit result. See Explanation below for steps to finding
+ the scale value to use for your circuit.
+
Variable is a variable (usually a byte) where the final result
+ of the reading will be stored. Internally, the POT command calculates
+ a 16-bit value, which is scaled down to an 8-bit value.
POT reads a variable resistance and returns a value (0 - 255) representing
+the amount of time it took to discharge the capacitor through the resistance. Pin
+must be connected to one side of the variable resistance, whose other side is
+connected through a capacitor to ground, as shown below.
+
+
+
+
+
+
POT works by first setting the specified I/O pin to an output and setting
+its state high. This step places +5 volts on one side of the capacitor and ground
+(0 volts) on the other side, which charges the capacitor. POT will hold the
+pin high for 10 milliseconds to charge the capacitor. It is important to select
+component values that will allow the capacitor to charge in this period. If, for
+example, a 50 kΩ potentiometer is used with a 0.1 µF cap, the maximum
+charge time would be:
+
Charge time: 5 x (50 x 103) x (0.1 x 10-6)
+= 25 x 10-3
+
The full charge time (5 TC) is 25 x 10-3 or 25 milliseconds.
+Obviously, the capacitor would never fully charge when the potentiometer is
+at its maximum position. In this case, changing the capacitor to 0.01 µF
+reduces the charge time to 2.5 milliseconds; well within the range of the
+POT function.
+
After the capacitor is charged the I/O pin to an input mode and POTstarts its timer. Initially the I/O pin will see a high (1) that will eventually
+drop to a low (0) when the capacitor discharges past the 1.4-volt threshold.
+The timer stops once the low is seen. The value of the variable resistor affects
+the time it takes to discharge the capacitor from 5 volts to approximately 1.4
+volts.
+
The 16-bit reading is multiplied by (Scale ÷ 256), so a scale
+value of 128 would reduce the range by approximately 50%, a scale of 64 would
+reduce to 25%, and so on. The amount by which the internal value must be scaled
+varies with the size of the resistor being used.
+
Finding the best Scale value:
+
+
Build the circuit shown above and plug the BS1 into the PC.
+
Select Run | POT Scaling. A special calibration window appears, allowing you to find the best value.
+
The window asks for the number of the I/O pin to which the variable resistor
+ is connected. Select the appropriate pin (0 - 7).
+
The editor downloads a short program to the BS1 (this overwrites any program
+ already stored in the BS1).
+
Two numbers will be displayed: scale and value. Adjust the resistor until
+ the smallest number is shown for scale (assuming you can adjust the resistor,
+ as with a potentiometer).
+
Once you've found the smallest number for scale, you're done. This number
+ should be used for the Scale in the POT command.
+
Optionally, you can verify the scale number found above by selecting the
+ POT Value checkbox. This locks the scale and causes the BS1 to read the resistor
+ continuously. The window displays the value. If the scale is good, you should
+ be able to adjust the resistor, achieving a 0-255 reading for the value (or as
+ close as possible). To change the scale value and repeat this step, just
+ uncheck the box. Continue this process until you find the best scale.
Measure the width of a pulse on Pin described by State and store the
+result in Variable.
+
+
+
+
Pin is a variable/constant/expression* (0 - 15) that specifies
+ the I/O pin to use. This pin will be set to input mode.
+
State is a variable/constant/expression* (0 - 1) that specifies
+ whether the pulse to be measured is low (0) or high (1). A low pulse begins
+ with a 1-to-0 transition and a high pulse begins with a 0-to-1 transition.
+
Variable is a variable (usually a word) in which the measured
+ pulse duration will be stored. The unit of time for Variable is
+ described below.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
PULSIN is like a fast stopwatch that is triggered by a change in state
+(0 or 1) on the specified pin. The entire width of the specified pulse (high or
+low) is measured, in units shown above and stored in Variable.
+
Many analog properties (voltage, resistance, capacitance, frequency, duty cycle)
+can be measured in terms of pulse duration. This makes PULSIN a valuable
+form of analog-to-digital conversion.
+
PULSIN will wait for the desired pulse, for up to the maximum pulse
+width it can measure, shown in the table above. If it sees the desired pulse it
+measures the time until the end of the pulse and stores the result in Variable.
+If it never sees the start of the pulse, or the pulse is too long (greater than
+the Maximum Pulse Width shown above), PULSIN "times out" and store 0 in
+Variable. This operation keeps your program from locking-up should the
+desired pulse never occur.
+
Regardless of the size of Variable, PULSIN internally uses a
+16-bit timer. Unless the pulse widths are known to be short enough to fit in an
+8-bit result, it is recommended using a word-sized variable. Not doing so may
+result in strange and misleading results as the BASIC Stamp will only store the
+lower 8-bits into a byte variable.
Generate a pulse on Pin with a width of Duration.
+
+
+
+
Pin is a variable/constant/expression* (0 - 15) that specifies
+ the I/O pin to use. This pin will be set to output mode.
+
Duration is a variable/constant/expression* (0 - 65535) that
+ specifies the duration of the pulse. The unit of time for Duration is
+ described below.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
PULSOUT sets Pin to output mode, inverts the state of that pin;
+waits for the specified Duration; then inverts the state of the pin again;
+returning the bit to its original state. The unit of Duration is described
+above. The following example will generate a 100 µs pulse on I/O pin 5:
+ PULSOUT 5, 50 ' generate a pulse on pin 5
+
+
The polarity of the pulse depends on the state of the pin before the command
+executes. In the example above, if pin 5 was low, PULSOUT would produce
+a positive pulse. If the pin was high, PULSOUT would produce a negative
+pulse.
+
If the pin is an input, the output state bit, OUT5 (PIN5 on the BS1) won't
+necessarily match the state of the pin. What happens then? For example: Pin 7 is
+an input (DIR7 = 0) and pulled high by a resistor as shown below. Suppose that
+pin 7 is low when we execute the instruction:
+ PULSOUT 7, 5 ' generate a pulse on pin 7
+
+
The figure below shows the sequence of events on that pin. Initially, pin 7
+is high. Its output driver is turned off (because it is in input mode), so the
+10 kΩ resistor sets the state on the pin. When PULSOUT executes, it
+turns on the output driver, allowing OUT7 (PIN7 on the BS1) to control the pin.
+
+
+
+
+
+
Since OUT7 (PIN7 on the BS1) is 0, the pin goes low when made an output. After
+a few microseconds of preparation, PULSOUT inverts the state of the pin;
+from low to high. It leaves the pin in that state for the specified time (10µs
+if using a BS2) and then inverts it again, leaving the pin in its original
+(output) state.
Syntax: PUTLocation, {WORD} Value{,{WORD} Value ...}
+
Function
+
Write one or more values to the Scratchpad RAM, starting at Location and
+building upward.
+
+
+
+
Location is a variable/constant/expression (0 – 62 for BS2e
+ and BS2sx, and 0 – 126 for BS2p, BS2pe, and BS2px) that specifies the
+ Scratchpad RAM location to write to.
+
Value is a variable/constant/expression to store
+ in RAM.*
+
+
*Note: The optional arguments require PBASIC 2.5.
+
Quick Facts
+
+
+
+
BS2e and BS2sx
+
BS2p, BS2pe, and BS2px
+
+
+
Scratchpad RAM size and organization
+
64 bytes (0 – 63). Organized as bytes only.
+
136 bytes (0 – 135). Organized as bytes only.
+
+
+
General purpose locations
+
0 - 62
+
0 – 126
+
+
+
Special use location
+
Current program slot number in read-only location 63.
+
Current program slot number in lowest nibble of read-only location 127. Current read/write slot number in highest nibble of location 127.
+
+
+
Additional locations
+
None
+
Locations 128 - 135 (read-only) hold state of polled input pins.
Multiple sequential variables may be read from the Scratchpad RAM.
+
The optional WORD modifier may be specified to retrieve 16-bit values.
+
+
+
+
Explanation
+
The PUT command writes a value into the specified Scratchpad RAM location(s).
+All values in the general-purpose locations can be written to from within any of
+the eight program slots.
+
Scratchpad RAM is useful for passing data to programs in other program slots
+and for additional workspace. It is different than regular RAM in that symbol
+names cannot be assigned directly to locations and each location is always
+configured as a byte only. The following code will write the value 100 to location
+25, read it back out with GET and display it:
+
The following example illustrates this:
+temp VAR Byte
+
+Main:
+ PUT 25, 100
+ GET 25, temp
+ DEBUG DEC temp
+ END
+
+
When using $PBASIC 2.5 syntax, Word-sized variables can be written to the
+Scratchpad RAM with a single PUT statement, as well as multiple items to
+consecutive locations. The Word modifier writes the low-byte first, then the
+high-byte ("Little Endian").
+
+
+
+
+' {$PBASIC 2.5}
+
+value VAR Word
+value2 VAR Word
+addr VAR Word ' EEPROM address
+test VAR Byte ' test byte read back
+
+Main:
+ value = $11
+ value2 = $2003
+ PUT 0, value, Word value2 ' write value to SP location 0
+ ' and value2 to SP locations 1 & 2
+
+ value = $FF ' modify variables
+ value2 = $FFFF
+
+ GET 0, value, Word value2 ' retrieve from Scratchpad
+
+ DEBUG HEX2 ? value ' display
+ DEBUG HEX4 ? value2
+ END
+
+
Most Scratchpad RAM locations are available for general use. The highest
+location (63 for BS2e/BS2sx and 127 for BS2p/BS2pe) is a special, read-only,
+location that always contains the number of the currently running program slot.
+On the BS2p/BS2pe, the upper nibble of location 127 also contains the current
+program slot that will be used for the READ and WRITE commands.
+Any values written to this location will be ignored.
Convert a digital value to analog output via pulse-width modulation.
+
+
+
+
Pin is a variable/constant/expression* (0 - 15) that specifies
+ the I/O pin to use. This pin will be set to output mode initially then set to
+ input mode when the command finishes.
+
Duty is a variable/constant/expression* (0 - 255) that specifies
+ the analog output level as a number of 256ths of 5 V (0 to 4.98 V).
+
Duration is a variable/constant/expression* (0 - 255) that
+ specifies the duration of the PWM output.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
+
Quick Facts
+
+
+
+
BS1
+
BS2 and BS2e
+
BS2sx
+
BS2p
+
BS2pe
+
BS2px
+
+
+
Units in Duration
+
5 ms
+
1 ms
+
0.4 ms
+
0.65 ms
+
1.62 ms
+
0.4 ms
+
+
+
Average voltage equation
+
Average Voltage = (Duty ÷ 256) x 5 volts
+
+
+
Require charge time (Duration ) equation
+
Charge time = 5 x R x C,
+ Duration = Charge time ÷ Units in Duration
+
+
+
Special Notes
+
Pin is set to output initially, and set to input at end
Pulse-width modulation (PWM) allows the BASIC Stamp (a purely digital device)
+to generate an analog voltage. The basic idea is this: If you make a pin output
+high, the voltage at that pin will be close to 5 V. Output low is close to 0 V.
+What if you switched the pin rapidly between high and low so that it was high half
+the time and low half the time? The average voltage over time would be halfway
+between 0 and 5 V (2.5 V). PWM emits a burst of 1s and 0s whose ratio is
+proportional to the duty value you specify.
+
The proportion of 1s to 0s in PWM is called the duty cycle. The duty
+cycle controls the analog voltage in a very direct way; the higher the duty cycle
+the higher the voltage. In the case of the BASIC Stamp, the duty cycle can range
+from 0 to 255. Duty is literally the proportion of 1s to 0s output by the
+PWM command. To determine the proportional PWM output voltage, use
+this formula: (Duty ÷ 256) x 5 V. For example, if Duty
+is 100, (100 ÷ 256) x 5 V = 1.953 V; PWM outputs a train of pulses
+whose average voltage is 1.953 V.
+
In order to convert PWM into an analog voltage we have to filter out the
+pulses and store the average voltage. The resistor/capacitor combination shown
+below will do the job. The capacitor will hold the voltage set by PWM even
+after the instruction has finished. How long it will hold the voltage depends on
+how much current is drawn from it by external circuitry, and the internal leakage
+of the capacitor. In order to hold the voltage relatively steady, a program must
+periodically repeat the PWM instruction to give the capacitor a fresh
+charge.
+
Just as it takes time to discharge a capacitor, it also takes time to charge
+it in the first place. The PWM command lets you specify the charging time
+in terms of PWM duration. The timing for the units in Duration is
+shown in in the table above. So, on the BS2, to charge a capacitor for five
+milliseconds, you would specify five units in Duration.
+
How do you determine how long to charge a capacitor? Use this rule-of-thumb
+formula: Charge time = 5 x R x C. For instance, the circuit below uses a 10 kΩ
+(10 x 103 ohm) resistor and a 1 µF (1 x 10-6 F) capacitor:
+
Charge time = 5 x 10 x 103 x 1 x 10-6 = 50 x 10-3
+seconds, or 50 milliseconds.
+
+
+
+
+
+
Since, on the BS2, each unit in Duration is approximately a millisecond,
+it would take at least 50 units to charge the capacitor. Assuming the circuit is
+connected to P0, here's the complete PWM instruction:
+
+
+
+
+ PWM 0, 100, 50 ' Put a 1.96V charge on cap (BS2, BS2e)
+
+
To charge the same circuit to the same level using a BS2sx, the Durationwould require adjustment as follows:
+
+
+
+
+ PWM 0, 100, 125 ' Put a 1.96V charge on cap (BS2sx)
+
+
After outputting the PWM pulses, the BASIC Stamp leaves the pin in input
+mode (0 in the corresponding bit of DIRS). In input mode, the pin's output driver
+is effectively disconnected. If it were not, the steady output state of the pin
+would change the voltage on the capacitor and undo the voltage setting established
+by PWM. Keep in mind that leakage currents of up to 1 µA can flow into
+or out of this "disconnected" pin. Over time, these small currents will cause the
+voltage on the capacitor to drift. The same applies for leakage current from an
+op-amp's input, as well as the capacitor's own internal leakage. Executing
+PWM occasionally will reset the capacitor voltage to the intended value.
+
PWM charges the capacitor; the load presented by your circuit discharges
+it. How long the charge lasts (and therefore how often your program should repeat
+the PWM command to refresh the charge) depends on how much current the
+circuit draws, and how stable the voltage must be. You may need to buffer PWMoutput with a simple op-amp follower if your load or stability requirements are
+more than the passive circuit can handle.
+
The term "PWM" applies only loosely to the action of the BASIC Stamp's PWM
+command. Most systems that output PWM do so by splitting a fixed period
+of time into an on time (1) and an off time (0). Suppose the interval is 1 ms
+and the duty cycle is 100 ÷ 256. Conventional PWM would turn the
+output on for 0.39 ms and off for 0.61 ms, repeating this process each millisecond.
+The main advantage of this kind of PWM is its predictability; you know the
+exact frequency of the pulses (in this case, 1 kHz), and their widths are
+controlled by the duty cycle.
+
BASIC Stamp's PWMdoes not work this way. It outputs a rapid
+sequence of on/off pulses, as short as 1.6 µs in duration, whose overall proportion
+over the course of a full PWM cycle of approximately a millisecond is equal
+to the duty cycle. This has the advantage of very quickly zeroing in on the desired
+output voltage, but it does not produce the neat, orderly pulses that you might
+expect. All BS2 modules also uses this high-speed PWMtechnique to generate pseudo-sine wave tones with the
+DTMFOUT and FREQOUT
+instructions.
Variable is a variable (usually a word) whose bits will be
+ scrambled to produce a random number. Variable acts as RANDOM's
+ input and its result output. Each pass through RANDOM stores the next
+ number, in the pseudo-random sequence, in Variable.
+
+
Explanation
+
RANDOM generates pseudo-random numbers ranging from 0 to 65535. They're
+called "pseudo-random" because they appear random, but are generated by a logic
+operation that uses the initial value in Variable to "tap" into a sequence
+of 65535 essentially random numbers. If the same initial value, called the "seed",
+is always used, then the same sequence of numbers is generated. The following
+example demonstrates this:
+
+
+
+
+SYMBOL result = W1
+
+Main:
+ result = 11000 ' set initial "seed" value
+ RANDOM result ' generate random number
+ DEBUG result ' show the result on screen
+ GOTO Main
+
+
+
+
+
+result VAR Word
+
+Main:
+ result = 11000 ' set initial "seed" value
+ RANDOM result ' generate random number
+ DEBUG DEC ? result ' show the result on screen
+ GOTO Main
+
+
In this example, the same number would appear on the screen over and over again.
+This is because the same seed value was used each time; specifically, the first
+line of the loop sets result to 11000. The RANDOM command really needs
+a different seed value each time. Moving the "Result =" line out of the loop will
+solve this problem, as in:
+
+
+
+
+SYMBOL result = W1
+
+Setup:
+ result = 11000 ' set initial "seed" value
+
+Main:
+ RANDOM result ' generate random number
+ DEBUG result ' show the result on screen
+ GOTO Main
+ END
+
+
+
+
+
+result VAR Word
+
+Setup:
+ result = 11000 ' set initial "seed" value
+
+Main:
+ RANDOM result ' generate random number
+ DEBUG DEC ? result ' show the result on screen
+ GOTO Main
+ END
+
+
Here, result is only initialized once, before the loop. Each time through the
+loop, the previous value of result, generated by RANDOM, is used as the
+next seed value. This generates a more desirable set of pseudo-random numbers.
+
In applications requiring more apparent randomness, it's necessary to "seed"
+RANDOM with a more random value every time. For instance, in the
+example program, RANDOM is executed continuously
+(using the previous resulting number as the next seed value) while the program
+waits for the user to press a button. Since the user can't control the timing of
+button presses very accurately, the results approach true randomness.
Measure time while Pin remains in State; usually to measure the
+charge/discharge time of resistor/capacitor (RC) circuit..
+
+
+
+
Pin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin to use. This pin will be placed into input mode.
+
State is a variable/constant/expression (0 - 1) that specifies
+ the desired state to measure. Once Pin is not in State, the
+ command ends and stores the result in Variable.
+
Variable is a variable (usually a word) in which the time
+ measurement will be stored. The unit of time for Variable is described
+ below.
RCTIME can be used to measure the charge or discharge time of a
+resistor/capacitor circuit. This allows you to measure resistance or capacitance;
+use R or C sensors such as thermistors or capacitive humidity sensors or respond
+to user input through a potentiometer. In a broader sense, RCTIME can also
+serve as a fast, precise stopwatch for events of very short duration.
+
When RCTIME executes, it starts a counter (who's unit of time is shown
+above). It stops this counter as soon as the specified pin is no longer in
+State (0 or 1). If pin is not in State when the instruction executes,
+RCTIME will return 1 in Variable, since the instruction requires one
+timing cycle to discover this fact. If pin remains in State longer than
+65535 timing cycles RCTIME returns 0.
+
The figure below shows suitable RC circuits for use with RCTIME. Circuits
+A are preferred, because the BASIC Stamp's logic threshold is approximately 1.4
+volts. This means that the voltage seen by the pin will start at 5V then fall
+to 1.4V (a span of 3.6V) before RCTIME stops. With Circuit B, the voltage
+will start at 0V and rise to 1.4V (spanning only 1.4V) before RCTIME stops.
+For the same combination of R and C, Circuits A will yield a higher count, and
+therefore more resolution than Circuit B.
+
+
+
+
+
+
Before RCTIME executes, the capacitor must be put into the state
+specified in the RCTIME instruction. For example, with Circuit A, the
+capacitor must be charged until the top plate at 5V.
+
Here's a typical sequence of instructions for Circuit A (assuming I/O pin
+7 is used):
+result VAR Word
+
+Test:
+ HIGH 7 ' charge the cap
+ PAUSE 1 ' for 1 ms
+ RCTIME 7, 1, result ' measure RC discharge time
+ DEBUG DEC ? result ' display result
+ END
+
+
Using RCTIME is very straightforward, except for one detail: For a given
+R and C, what value will RCTIME return? It's easy to figure, based on a
+value called the RC time constant, or tau (τ) for short. Tau represents the time
+required for a given RC combination to charge or discharge by 63 percent of the
+total change in voltage that they will undergo. More importantly, the value t is
+used in the generalized RC timing calculation. Tau's formula is just R multiplied
+by C:
+
τ = R x C
+
The general RC timing formula uses τ to tell us the time required for an RC
+circuit to change from one voltage to another:
+
time = -τ x ( ln(Vfinal / Vinitial) )
+
In this formula ln is the natural logarithm; it's a key on most scientific
+calculators. Let's do some math. Assume we're interested in a 10 kΩ
+resistor and 0.1 µF capacitor. Calculate τ:
+
τ = (10 x 103) x (0.1 x 10-6) = 1 x 10-3
+
The RC time constant is 1 x 10-3 or 1 millisecond. Now calculate
+the time required for this RC circuit to go from 5V to 1.4V (as in Circuit A):
+
Time = -1 x 10-3 x ( ln(1.4v ÷ 5.0v) ) =
+1.273 x 10-3
+
On the BS2, the unit of time is 2 µs, that time (1.273 x 10-3) works
+out to about 635 units. With a 10 kΩ resistor and 0.1 µF capacitor,
+RCTIME would return a value of approximately 635. Since Vinitialand Vfinal doesn't change, we can use a simplified rule of thumb to
+estimate RCTIME results for Circuit A:
+
RCTIME units = 635 x R (in kΩ) x C (in µF)
+
Another handy rule of thumb can help you calculate how long to charge/discharge
+the capacitor before RCTIME. In the example above that's the purpose of the
+HIGH and PAUSE commands. A given RC charges or discharges 98 percent
+of the way in five time constants (5 x R x C). In Circuits A and B, the
+charge/discharge current passes through the 220 Ω series resistor and the
+capacitor. So if the capacitor were 0.1 µF, the minimum charge/discharge time
+should be:
+
Charge time = 5 x 220 x (0.1 x 10-6) = 110 x 10-6
+
So it takes only 110 µs for the capacitor to charge/discharge, meaning that the
+one millisecond charge/discharge time of the example is plenty.
+
A final note about the circuits above: You may be wondering why the 220 Ω
+resistor is necessary at all. Consider what would happen if resistor R was a
+potentiometer, and were adjusted to 0 Ω. When the I/O pin went high to
+discharge the capacitor, it would see a short direct to ground. The 220 Ω
+series resistor would limit the short circuit current to 5V ÷ 220 Ω
+= 23 mA and protect the BASIC Stamp from damage. (Actual current would be quite
+a bit less due to internal resistance of the pin's output driver, but you get
+the idea.)
Location Location is a variable/constant/expression*
+ (0 - 255 on BS1, 0 - 2047 on all other BASIC Stamp models) that specifies the
+ EEPROM address to read from.
+
Variable is a variable (usually a byte) where the value
+ is stored.*
+
+
* Note: expressions are not allowed as arguments on the BS1.
+
*Note: The optional arguments require PBASIC 2.5.
+
Quick Facts
+
+
+
+
BS1
+
BS2, BS2e, and BS2sx
+
BS2p, BS2pe, and BS2px
+
+
+
Range of EEPROM locations
+
0 to 255
+
0 to 2047
+
0 to 2047 (see notes below)
+
+
+
Special Notes
+
n/a
+
READ only works with current program slot on
+ BS2e and BS2sx.
+
READ works with any program slot as set by the
+ STORE command.
Multiple sequential variables may be read from the Scratchpad RAM, and the optional WORD modifier may be specified to retrieve 16-bit values.
+
+
+
+
Explanation
+
The EEPROM is used for both program storage (which builds downward from address
+255 on BS1, 2047 on all other BASIC Stamp models) and data storage (which builds upward
+from address 0). The READ instruction retrieves a value from any
+EEPROM address and stores it in Variable. When the optional Word modifier
+($PBASIC 2.5 required) is used, the low byte of Variable is read from
+Location, the high byte of Variable from Location + 1.
+
Any location within the EEPROM can be read (including your PBASIC program's
+tokens) at run-time. This feature is mainly used to retrieve long-term data from
+EEPROM; data stored in EEPROM is not lost when the power is removed.
+
The following READ command retrieves the value at location 100 and
+stores it into the variable called Result:
+
+
+
+
+SYMBOL result = B2
+
+Main:
+ READ 100, result
+ END
+
+
+
+
+
+result VAR Byte
+
+Main:
+ READ 100, result
+ END
+
+
The EEPROM is organized as a sequential set of byte-sized memory locations. The READ command retrieves byte-sized values from EEPROM. This does not mean that you can't read word-sized values, however. A word consists of two bytes, called a low-byte and a high-byte. If you wanted to read a word-sized value, you can use two READ commands and a word-size variable (along with some handy modifiers). For example:
+
+
+
+
+SYMBOL result = W1 ' word-sized variable
+SYMBOL resLo = B2 ' low-byte of W1
+SYMBOL resHi = B3 ' high-byte of W1
+
+EEPROM (101, 4) ' Store word-sized value
+
+Main:
+ READ 0, resLo
+ READ 1, resHi
+ DEBUG #result
+ END
+
+
+
+
+
+result VAR Word
+
+DATA Word 1125 ' Store word-sized value
+
+Main:
+ READ 0, result.LowByte
+ READ 1, result.HighByte
+ DEBUG DEC ? result
+ END
+
+
This code uses the EEPROM or DATA directive to write the low-byte
+and high-byte of the number 1125 into locations 0 and 1 during download. When the
+program runs, the two READ commands will read the low-byte and high-byte
+out of EEPROM (reconstructing it in a word-size variable) and then display the
+value on the screen.
+
When using $PBASIC 2.5 syntax, word-sized variables can be retrieved with a single
+READ statement, as well as multiple items from consecutive locations.
+
+
+
+
+' {$PBASIC 2.5}
+
+idNum VAR Word
+score VAR Byte
+
+ID_Rec DATA Word 1125, 75 ' Store multiple items
+
+Main:
+ READ ID_Rec, Word idNum, score ' Read multiple variables
+ DEBUG DEC ? idNum ' Display them
+ DEBUG DEC ? score
+ END
+
+
Note that the EEPROM and DATA directives store data in the EEPROM
+before the program runs, however, the WRITE command can be used to store
+data while the program is running. Additionally, the EEPROM locations can be read
+an unlimited number of times, but EEPROM locations can be worn out by excessive
+writes. See the WRITE command for more information.
+
When using the READ and WRITE commands, take care to ensure that
+your program doesn't overwrite itself. On the BS1, location 255 holds the address
+of the last instruction in your program. Therefore, your program can use any space
+below the address given in location 255. For example, if location 255 holds the
+value 100, then your program can use locations 0-99 for data.
+
+
+
+
+
On other BASIC Stamp models, you'll need to view the Memory Map of the program before
+you download it, to determine the last EEPROM location used.
+
+
+
+
+
On the BS2p, BS2pe, and BS2px the READ and WRITE commands can
+affect locations in any program slot as set by the STORE command. See the
+STORE command for more information.
Unlimited. However, the number of GOSUBs is limited.
+ See GOSUB for more information.
+
+
+
Explanation
+
RETURN sends the program back to the address (instruction) immediately
+following the most recent GOSUB. If RETURN is executed without a
+prior GOSUB, the BASIC Stamp will return to the first executable line of
+the program; usually resulting in a logical bug in the code. See the GOSUBcommand for more information.
+
+ Note: On the BS1, a RETURN without a GOSUB will
+ return the program to the last GOSUB (or will end the program if
+ no GOSUB was executed)
+
The example below will start out by GOSUB-ing to the section of code beginning with the label Hello. It will print "Hello my friend." on the screen then RETURN to the line after the GOSUB, which prints "How are you?" and ENDs.
+Main:
+ GOSUB Hello
+ DEBUG "How are you?", CR
+ END
+
+Hello:
+ DEBUG "Hello my friend.", CR
+ RETURN
+
+
Watch Out For Subroutines That Your Program Can "Fall Into"
+
There's another interesting lesson here; what would happen if we removed the
+END command from this example? Since the BASIC Stamp reads the code from
+left to right, top to bottom (like the English language) once it had returned
+to and run the "How are you?" line, it would naturally "fall into" the Hello
+routine again. Additionally, at the end of the Hello routine, it would see the
+RETURN again (although it didn't GOSUB to that routine this time)
+and because there wasn't a previous place to return to, the BASIC Stamp will start
+the entire program over again. This would cause an endless loop. The important
+thing to remember here is to always make sure your program doesn't allow itself
+to "fall into" a subroutine.
Reverse the data direction of the specified pin.
+
+
+
+
Pin is a variable/constant/expression* (0 – 15) that specifies the
+ I/O pin to use. This pin will be placed into the mode opposite of its current
+ input/output mode.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
Reverse is convenient way to switch the I/O direction of a pin. If the pin
+is an input, Reverse makes it an output; if it's an output, Reversemakes it an input.
+
Remember that "input" really has two meanings: (1) Setting a pin to input
+makes it possible to check the state (1 or 0) of external circuitry connected
+to that pin. The current state is in the corresponding bit of the INS register
+(PINS on the BS1). (2) Setting a pin to input also disconnects the output
+driver, the corresponding bit of OUTS (PINS on the BS1).
+
The example programs illustrate this second fact
+with a two-tone LED blinker, using the circuit below:
RUN is similar to a GOTO...you can not "return" from a RUN
+
+
+
†The BS2pe has 16 slots, but only slots 0 - 7 are available for programs. Slots 8 - 15 may be used for data storage.
+
Explanation
+
The BS2e, BS2sx, BS2p, and BS2px have a total of 16 kilobytes of code space; the BS2pe
+has 16 kilobytes of code space and an additional 16 kilobytes of data space. This
+EEPROM space is organized into slots of 2 kilobytes (2048 bytes) each. Up to eight
+different programs can be downloaded to the BASIC Stamp (one program per slot).
+When the BASIC Stamp powers up, or is reset, the program in slot 0 is executed.
+
The RUN command allows you to activate another program and causes
+the BASIC Stamp to stay in the newly activated program until it receives
+another RUN command, or until a power-down or reset condition occurs.
+The RUN command is similar to a GOTO command in that it allows you
+to "goto" another program. Normally a master-type program will be used
+in program slot 0 (since slot 0 runs first) and will control initial execution
+of the other programs.
+
Look at the following example (there are two programs here, make sure to
+download them into program slots 0 and 1, respectively). See the special use of the $STAMP directive in Defining Multi-File Projects for more information.
+
+
+
Download the following two lines into program slot 0:
+ DEBUG "Hello "
+ RUN 1
+
+
Download the following three lines into program slot 1:
+ DEBUG "World!", CR
+ PAUSE 1000
+ RUN 0
+
+
The above two programs (assuming they have been downloaded into program slots 0 and 1, respectively) will display "Hello World!" on the screen. Program 0 is the first to run and it displays "Hello ", then issues a RUN 1 command. The BASIC Stamp then starts execution of program 1, from its first line of code, which causes "World!" to be displayed. Program 1 then pauses for one second and the runs program 0 again.
+
What Happens To I/O Pins And RAM When Using RUN?
+
The I/O pins retain their current state (directions and output latches) and
+all Variable and Scratchpad RAM locations retain their current data
+during a transition between programs with the RUN command. If sharing
+data between programs within Variable RAM, make sure to keep similar
+variable declarations (defined in the same order) in all programs so that
+the variables align themselves on the proper word, byte, nibble and bit
+boundaries across programs. The following programs illustrate what happens
+with mismatched variable declarations:
+' Download this program to Slot 0
+
+cats VAR Byte
+dogs VAR Byte
+
+Setup:
+ cats = 3
+ dogs = 1
+
+Main:
+ DEBUG "In Slot 0", CR
+ DEBUG ? cats
+ DEBUG ? dogs
+ RUN 1
+
+' Download this program to Slot 1
+
+cats VAR Byte
+dogs VAR Byte
+fleas VAR Word
+
+Main:
+ DEBUG "In Slot 1", CR
+ DEBUG ? cats
+ DEBUG ? dogs
+ DEBUG ? fleas
+ END
+
+
When the Slot 1 program runs you may be surprised to see that cats and dogs
+are now zero and fleas are up to 259! - even though we didn't explicitly define
+them. What happened? The key to remember is that variable names are simply
+pointers to RAM addresses, and the PBASIC compiler assigns variable names to RAM
+in descending order by size. This means that in the Slot 1 program, fleas was
+assigned to RAM locations 0 and 1 which are holding the values 3 and 1
+respectively. Since words are stored low-byte first, the value 259 for fleas
+makes sense (3 + (1 * 256)).
+
Any program number specified above 7 will wrap around and result in
+running one of the 8 programs (RUN 8 will run program 0, RUN 9 will run
+program 1, etc). The current program slot can be read from the last byte of the
+Scratchpad RAM. Example:
+ #SELECT $STAMP
+ #CASE BS2
+ pgmSlot = 0 ' everything in slot 0
+ rwSlot = 0
+ #CASE BS2E, BS2SX
+ READ 63, pgmSlot ' read current slot
+ rwSlot = pgmSlot ' READ/WRITE slot is same
+ #CASE BS2P, BS2PE, BS2PX
+ READ 127, pgmSlot ' get slot control byte
+ rwSlot = rwSlot.HIGHNIB ' READ/WRITE in high nibble
+ pgmSlot = pgmSlot.LOWNIB ' pgm slot in low nibble
+ #ENDSELECT
+
Evaluate Expression and then conditionally execute a block of code based
+on comparison to Condition(s). After executing a block of code the
+program continues at the line that follows ENDSELECT. If no conditions
+are found True and a CASE ELSE block is included, the CASE ELSE
+code statements will execute.
+
+
Expression is a variable, a constant or an expression.
+
Condition is a statement, that can be evaluated as True or
+ False. The Condition can be a very simple or very complex
+ relationship, as described below. Multiple conditions within the same
+ CASE can be separated by commas ( , ).
+
Statement(s) is any valid PBASIC statement or statements.
+ Multiple statements may be placed on the same line (though not recommended)
+ by separating each statement with a colon ( : ).
SELECT...CASE is an advanced decision-making structure and is often used
+to replace compound IF...THEN...ELSE structures. The available comparison
+operators are:
+
+
+
+
Comparison Operator Symbol
+
Definition
+
+
+
=
+
Equal (assumed)
+
+
+
<>
+
Not Equal
+
+
+
>
+
Greater Than
+
+
+
<
+
Less Than
+
+
+
>=
+
Greater Than or Equal To
+
+
+
<=
+
Less Than or Equal To
+
+
+
+
+
Example:
+ SELECT irCmd
+ CASE 0 TO 3
+ HIGH irCmd ' enable selected output
+ FREQOUT Spkr, 50, 880 ' beep
+
+ CASE AllOff, Mute
+ OutA = %0000 ' all outputs off
+
+ CASE ELSE ' invalid command
+ DEBUG "Bad Command", CR
+ ENDSELECT
+
+
Here, the BASIC Stamp will examine the value of variable irCmd. If irCmd is
+between zero and three (inclusive), the associated output (P0 .. P3) will be
+made high and and the speaker will beep. If irCmd is equal to either AllOff or
+Mute (constants), then outputs P0 - P3 will be made low. On any other value of
+irCmd, a message will be displayed that indicates an invalid command.
+
See IF…THEN for additional details on the use of
+comparison and conditional operators.
Receive asynchronous serial data (e.g., RS-232 data).
+
+
+
+
Rpin is a variable/constant/expression* (0 - 16) that specifies
+ the I/O pin through which the serial data will be received. This pin will be
+ set to input mode. On the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px, if Rpin is
+ set to 16, the BASIC Stamp uses the dedicated serial-input pin (SIN, physical
+ pin 2), which is normally used by the Stamp Editor during the download process.
+
Fpin is an optional variable/constant/expression* (0 - 15)
+ that specifies the I/O pin to indicate flow control status on. This pin will
+ be set to output mode.
+
Baudmode is variable/constant/expression* (0 - 7 on the BS1,
+ 0 - 65535 on all other BASIC Stamp models) that specifies serial timing and
+ configuration.
+
Qualifier is an optional variable/constant (0 - 255) indicating
+ data that must be received before execution can continue. Multiple qualifiers
+ can be indicated with commas separating them.
+
Plabel is an optional label indicating where the program should
+ go in the event of a parity error. This argument should only be provided if
+ Baudmode indicates 7 bits, and even parity.
+
Timeout is an optional variable/constant/expression* (0 - 65535)
+ that tells SERIN how long to wait for incoming data. If data does not
+ arrive in time, the program will jump to the address specified by Tlabel.
+
Tlabel is an optional label that must be provided along with
+ Timeout, indicating where the program should go in the event that data
+ does not arrive within the period specified by Timeout.
+
InputData‡ is a list of variables and formatters that
+ tells SERIN what to do with incoming data. SERIN can store data
+ in a variable or array, interpret numeric text (decimal, binary, or hex) and
+ store the corresponding value in a variable, wait for a fixed or variable
+ sequence of bytes, or ignore a specified number of bytes. These actions can
+ be combined in any order in the InputData list.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
+
‡ Note: The BS1's InputData argument can only be a list of variables and the optional decimal modifier (#).
One of the most popular forms of communication between electronic devices is serial
+communication. There are two major types of serial communication; asynchronous and
+synchronous. The SERIN and SEROUT commands are used to receive and
+send asynchronous serial data. See the SHIFTIN and
+SHIFTOUT commands for information on the synchronous
+method.
+
SERIN can wait for, filter and convert incoming data in powerful ways.
+SERIN deserves some lengthy discussion, below, since all this power brings
+some complexity.
+
The term asynchronous means "no clock." More specifically, "asynchronous serial
+communication" means data is transmitted and received without the use of a separate
+"clock" wire. Data can be sent using as little as two wires; one for data and one
+for ground. The PC's serial ports (also called COM ports or RS-232 ports) use
+asynchronous serial communication. Note: the other kind of serial communication,
+synchronous, uses at least three wires; one for clock, one for data and one for
+ground.
+
RS-232 is the electrical specification for the signals that PC serial ports use.
+Unlike normal logic, where a 5 volts is a logic 1 and 0 volts is logic 0, RS-232
+uses -12 volts for logic 1 and +12 volts for logic 0. This specification allows
+communication over longer wire lengths without amplification.
+
Most circuits that work with RS-232 use a line driver/receiver. This component
+does two things: (1) it converts the ±12 volts of RS-232 to TTL-compatible 0 to
+5-volt levels and (2) it inverts the relationship of the voltage levels, so that
+5 volts = logic 1 and 0 volts = logic 0. Note: When connecting a line driver/receiver to the BASIC Stamp, make sure to power the line driver/receiver with 5 volts DC from a regulated source other than BASIC Stamp's 5-volt VDD pin; the BASIC Stamp's on-board regulator may be unable to provide the required amount of current to the line driver/receiver chip.
+
+
+
+
+
+
+
+
+
All BASIC Stamp models (except the BS1) have a line receiver on its SIN pin (Rpin = 16). The SIN pin goes to a PC's serial data-out pin on the DB-9 connector built into BASIC Stamp development boards. The connector is wired to allow both programming and run-time serial communication (unless you are using the Stamp 2 Carrier Board which is only designed for programming). For the built-in serial port set the Rpin argument to 16 in the SERIN command.
+
All BASIC Stamp models (including the BS1) can also receive RS-232 data through any
+of their I/O pins (Rpin = 0 - 7 for BS1, Rpin = 0 - 15 on all other
+BASIC Stamp models). The I/O pins don't need a line receiver, just a 22 kΩ resistor.
+The resistor limits current into the I/O pin's built-in clamping diodes, which keep
+input voltages within a safe range.
+
+
+
+
+
Note: The connections shown in red are normally not necessary. They indicate optional connections to defeat hardware handshaking requirements.
+
Note: A line driver may have to be used between the I/O pin and the receiving serial port to ensure proper communication.
+
+
+
+
+
Function
+
DB-9
+
DB-25
+
+
+
Data Carrier Detect (DCD)
+
1
+
8
+
+
+
Receive Data (RD)
+
2
+
3
+
+
+
Transmit Data (TD)
+
3
+
2
+
+
+
Data Terminal Ready (DTR)
+
4
+
20
+
+
+
Signal Ground (SG)
+
5
+
7
+
+
+
Data Set Ready (DSR)
+
6
+
6
+
+
+
Request To Send (RTS)
+
7
+
4
+
+
+
Clear To Send (CTS)
+
8
+
5
+
+
+
+
+
+
The figure above shows the pinouts of the two styles of PC serial ports and
+how to connect them to the BASIC Stamp's I/O pin (the 22 kΩ resister is not
+needed if connecting to the SIN pin). Though not normally needed, the figure also
+shows loop back connections that defeat hardware handshaking used by some PC
+software. Note that PC serial ports are always male connectors. The 25-pin
+style of serial port (called a DB-25) looks similar to a printer (parallel) port
+except that it is male, whereas a parallel port is female.
+
Asynchronous serial communication relies on precise timing. Both the sender
+and receiver must be set for identical timing, usually expressed in bits per second
+(bps) called baud.
+
On all BASIC Stamp models, SERIN requires a value called Baudmode that tells
+it the important characteristics of the incoming serial data; the bit period,
+number of data and parity bits, and polarity.
+
+
+
+
+
+
On the BS1, serial communication is limited to: no-parity, 8-data bits and
+1-stop bit at one of four different speeds: 300, 600, 1200 or 2400 baud. The
+table below indicates the Baudmode value or symbols to use when selecting
+the desired mode.
+
+
+
+
+
Baudmode Value
+
Symbol
+
Baud Rate
+
Polarity
+
+
+
0
+
T2400
+
2400
+
TRUE
+
+
+
1
+
T1200
+
1200
+
TRUE
+
+
+
2
+
T600
+
600
+
TRUE
+
+
+
3
+
T300
+
300
+
TRUE
+
+
+
4
+
N2400
+
2400
+
INVERTED
+
+
+
5
+
N1200
+
1200
+
INVERTED
+
+
+
6
+
N600
+
600
+
INVERTED
+
+
+
7
+
N300
+
300
+
INVERTED
+
+
+
+
+
+
+
+
+
On the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px, serial communication is very
+flexible. The Baudmode argument for SERIN accepts a 16-bit value
+that determines its characteristics: 1-stop bit, 8-data bits/no-parity or
+7-data bits/even-parity and virtually any speed from as low as 300 baud to
+greater than 100K baud (depending on the BASIC Stamp). The information below
+shows how Baudmode is calculated and show common baud modes for standard
+serial baud rates.
BS2px = INT(4,000,000 ÷ baud rate) - 20 Note: INT means 'Convert to integer.' -- drop the numbers to the right
+ of the decimal point.
+
Set data bits and parity (bit 13)
+
8-bit / No Parity = 0 ($0000)
7-bit / Even Parity = 8192 ($2000)
+
Select polarity bit (bit 14)
+
True = 0 ($0000)
Inverted = 16384 ($4000)
+
+
Baud Rate Tables
+
These tables give common baud rates and their corresponding Baudmode values.
+
+ BS2, BS2e, BS2pe
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
300
+
19697 ($4CF1)
+
3313 ($0CF1)
+
27889 ($6CF1)
+
11505 ($2CF1)
+
+
+
600
+
18030 ($466E)
+
1646 ($066E)
+
26222 ($666E)
+
9838 ($266E)
+
+
+
1200
+
17197 ($432D)
+
813 ($032D)
+
25389 ($632D)
+
9005 ($232D)
+
+
+
2400
+
16780 ($418C)
+
396 ($018C)
+
24972 ($618C)
+
8588 ($218C)
+
+
+
4800
+
16572 ($40BC)
+
188 ($00BC)
+
24764 ($60BC)
+
8380 ($20BC)
+
+
+
9600
+
16468 ($4054)
+
84 ($0054)
+
24660 ($6054)
+
8276 ($2054)
+
+
+
+
Tip: The BS2, BS2e, and BS2pe may have trouble synchronizing with the incoming serial stream at this 4800 baud and higher while using certain complex expressions, arrays, and/or formatters. Try using simple variables and WAIT or WAITSTR formatters to achieve the necessary results.
+
+
+ BS2sx, BS2p
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
1200
+
18447 ($480F)
+
2063 ($080F)
+
26639 ($680F)
+
10255 ($280F)
+
+
+
2400
+
17405 ($43FD)
+
1021 ($03FD)
+
25597 ($63FD)
+
9213 ($23FD)
+
+
+
4800
+
16884 ($41F4)
+
500 ($01F4)
+
25076 ($61F4)
+
8692 ($21F4)
+
+
+
9600
+
16624 ($40F0)
+
240 ($00F0)
+
24816 ($60F0)
+
8432 ($20F0)
+
+
+
+
+
Tip: The BS2sx and BS2p may have trouble synchronizing with the incoming serial stream at this 4800 baud and higher while using certain complex expressions, arrays, and/or formatters. Try using simple variables and WAIT or WAITSTR formatters to achieve the necessary results.
+
+
+
+ BS2px
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
1200
+
19697 ($4CF1)
+
3313 ($0CF1)
+
27889 ($6CF1)
+
11505 ($2CF1)
+
+
+
2400
+
18030 ($466E)
+
1646 ($066E)
+
26222 ($666E)
+
9838 ($266E)
+
+
+
4800
+
17197 ($432D)
+
813 ($032D)
+
25389 ($632D)
+
9005 ($232D)
+
+
+
9600
+
16780 ($418C)
+
396 ($018C)
+
24972 ($618C)
+
8588 ($218C)
+
+
+
+
If you're communicating with existing software or hardware, its speed(s) and
+mode(s) will determine your choice of baud rate and mode. In general,
+7-bit/even-parity (7E) mode is used for text, and 8-bit/no-parity (8N) for
+byte-oriented data. Note: the most common mode is 8-bit/no-parity, even when
+the data transmitted is just text. Most devices that use a 7-bit data mode do
+so in order to take advantage of the parity feature. Parity can detect some
+communication errors, but to use it you lose one data bit. This means that
+incoming data bytes transferred in 7E (even-parity) mode can only represent
+values from 0 to 127, rather than the 0 to 255 of 8N (no-parity) mode.
+
Usually a device requires only one stop bit per byte. Occasionally, however,
+you may find a device that requires 2 or more stop bits. Since a stop bit is
+really just a delay between transmitted bytes (leaving the line in a resting state)
+the BASIC Stamp can receive transmissions with multiple stop bits per byte without
+any trouble. In fact, sometimes it is desirable to have multiple stop bits (see
+the "SERIN Troubleshooting" section, below, for more information).
+
The example below will receive a single byte through I/O pin 1 at 2400 baud,
+8N1, inverted:
+sData VAR Byte
+
+Main:
+ SERIN 1, 16780, [sData] ' baudmode set for BS2
+ END
+
+
Here, SERIN will wait for and receive a single byte of data through pin
+1 and store it in the variable sData. If the BASIC Stamp were connected to a PC
+running a terminal program (set to the same baud rate) and the user pressed the
+"A" key on the keyboard, after the SERIN command executed, the variable
+sData would contain 65, the ASCII code for the letter "A".
+
What would happen if, using the example above, the user pressed the "1" key?
+The result would be that sData would contain the value 49 (the ASCII code for
+the character "1"). This is a critical point to remember: every time you press
+a character on the keyboard, the computer receives the ASCII value of that
+character. It is up to the receiving side (in serial communication) to interpret
+the values as necessary. In this case, perhaps we actually wanted sData to end
+up with the value 1, rather than the ASCII code 49.
+
The SERIN command provides a formatter, called the decimal formatter,
+which will interpret this for us. Look at the following code:
+sData VAR Byte
+
+Main:
+ SERIN 1, 16780, [DEC sData]
+ END
+
+
Notice the decimal formatter in the SERIN command. It is the "#" (for
+the BS1) or "DEC" (for the other BASIC Stamp models) that appears just to the left of
+the sData variable. This tells SERIN to convert incoming text representing
+decimal numbers into true-decimal form and store the result in sData. If the
+user running the terminal software pressed the "1", "2" and then "3" keys followed
+by a space or other non-numeric text, the value 123 will be stored in sData.
+Afterwards, the program can perform any numeric operation on the number just like
+with any other number. Without the decimal formatter, however, you would have been
+forced to receive each character ("1", "2" and "3") separately, and then would
+still have to do some manual conversion to arrive at the number 123 (one hundred
+twenty three) before you can do the desired calculations on it.
+
Decimal Formatter Specifics
+
The decimal formatter is designed to seek out text that represents decimal numbers.
+The characters that represent decimal numbers are the characters "0" through "9".
+Once the SERIN command is asked to use the decimal formatter for a particular
+variable, it monitors the incoming serial data, looking for the first decimal
+character. Once it finds the first decimal character, it will continue looking
+for more (accumulating the entire multi-digit number) until is finds a non-decimal
+numeric character. Keep in mind that it will not finish until it finds at least
+one decimal character followed by at least one non-decimal character.
+
To further illustrate this, consider the following examples (assuming we're
+using the same code example as above):
+
+
Serial input: ABC Result: The BASIC Stamp halts at the SERIN command, continuously
+ waiting for decimal text.
+
Serial input: 123 (with no characters following it) Result: The BASIC Stamp halts at the SERIN command. It recognizes
+ the characters "1", "2" and "3" as the number one hundred twenty three, but
+ since no characters follow the "3", it waits continuously, since there's no
+ way to tell whether 123 is the entire number or not.
+
Serial input: 123 (followed by a space character) Result: Similar to example 2, above, except once the space character
+ is received, the BASIC Stamp knows the entire number is 123, and stores this
+ value in sData. The SERIN command then ends, allowing the next line of code,
+ if any, to run.
+
Serial input: 123A Result: Same as example 3, above. The "A" character, just like the
+ space character, is the first non-decimal text after the number 123, indicating
+ to the BASIC Stamp that it has received the entire number.
+
Serial input: ABCD123EFGH Result: Similar to examples 3 and 4 above. The characters "ABCD" are ignored
+ (since they're not decimal text), the characters "123" are evaluated to be the
+ number 123 and the following character, "E", indicates to the BASIC Stamp that
+ it has received the entire number.
+
+
Of course, as with all numbers in the BASIC Stamp, the final result is limited
+to 16 bits (up to the number 65535). If a number larger than this is received by
+the decimal formatter, the end result will look strange because the result
+rolled-over the maximum 16-bit value.
+
While BS1 is limited to the decimal formatter (#) shown above, the BS2, BS2e,
+BS2sx, BS2p, BS2pe, and BS2px have many more conversion formatters available for the
+SERIN command. If not using a BS1, see the "Additional Conversion Formatters"
+section below for more information.
+
The SERIN command can also be configured to wait for specified data
+before it retrieves any additional input. For example, suppose a device that is
+attached to the BASIC Stamp is known to send many different sequences of data,
+but the only data you desire happens to appear right after the unique characters,
+"XYZ". The BS1 has optional Qualifier arguments for this purpose. On the
+BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px a special formatter called WAIT can be
+used for this.
+sData VAR Byte
+
+Main:
+ SERIN 1, 16780, [WAIT("XYZ"), DEC sData]
+ END
+
+
The above code waits for the characters "X", "Y" and "Z" to be received, in
+that order, and then it looks for a decimal number to follow. If the device in
+this example were to send the characters "XYZ100" followed by a carriage return
+or some other non-decimal numeric character, the sData variable would end up with
+the number 100 after the SERIN line finishes. If the device sent some data
+other than "XYZ" followed by a number, the BASIC Stamp would continue to wait at
+the SERIN command.
+
The BS1 will accept an unlimited number of Qualifiers. The BS2, BS2e, BS2sx,
+BS2p, BS2pe, and BS2px will only accept up to six bytes (characters) in the WAITformatter.
+
Keep in mind that when we type "XYZ" into the SERIN command, the BASIC
+Stamp actually uses the ASCII codes for each of those characters for its tasks.
+We could also have typed: 88, 89, 90 in place of "XYZ" and the code would run the
+same way since 88 is the ASCII code for the "X" character, 89 is the ASCII code
+for the "Y" character, and so on. Also note, serial communication with the BASIC
+Stamp is case sensitive. If the device mentioned above sent, "xYZ" or "xyZ", or
+some other combination of lower and upper-case characters, the BASIC Stamp would
+have ignored it because we told it to look for "XYZ" (all capital letters).
+
The BS1's SERIN command is limited to previously-mentioned features. If
+you are not using a BS1, please continue reading about the additional features
+below.
+
The decimal formatter is only one of a whole family of conversion formatters
+available with SERIN on the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px. See the
+table below for a list of available conversion formatters. All of the conversion
+formatters work similar to the decimal formatter (as described in the "Decimal
+Formatter Specifics" section, above). The formatters receive bytes of data,
+waiting for the first byte that falls within the range of characters they accept
+(e.g., "0" or "1" for binary, "0" to "9" for decimal, "0" to "9" and "A" to "F"
+for hex, and "+" or "-" for signed variations of any type). Once they receive a
+numeric character, they keep accepting input until a non-numeric character arrives
+or (in the case of the fixed length formatters) the maximum specified number of
+digits arrives.
+
While very effective at filtering and converting input text, the formatters
+aren't completely foolproof. As mentioned before, many conversion formatters will
+keep accepting text until the first non-numeric text arrives, even if the resulting
+value exceeds the size of the variable. After SERIN, a byte variable will
+contain the lowest 8 bits of the value entered and a word would contain the lowest
+16 bits. You can control this to some degree by using a formatter that specifies
+the number of digits, such as DEC2, which would accept values only in the range of
+0 to 99.
+
+ Conversion Formatter Table
+
+
+
Conversion Formatter
+
Type of Number
+
Numeric Characters Accepted
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally limited to 1 - 5 digits
+
0 through 9
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally limited to 1 - 5 digits
+
-, 0 through 9
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally limited to 1 - 4 digits
+
0 through 9, A through F
+
1,3
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally limited to 1 - 4 digits
+
-, 0 through 9, A through F
+
1,2,3
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally limited to 1 - 4 digits
+
$, 0 through 9, A through F
+
1,3,4
+
+
+
ISHEX{1..4}
+
Signed, indicated hexadecimal, optionally limited to 1 - 4 digits
+
-, $, 0 through 9, A through F
+
1,2,3,4
+
+
+
BIN{1..16}
+
Binary, optionally limited to1 - 16 digits
+
0, 1
+
1
+
+
+
SBIN{1..16}
+
Signed binary, optionally limited to 1 - 16 digits
+
-, 0, 1
+
1,2
+
+
+
IBIN{1..16}
+
Indicated binary, optionally limited to 1 - 16 digits
+
%, 0, 1
+
1,4
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally limited to 1 - 16 digits
+
-, %, 0, 1
+
1,2,4
+
+
+
NUM
+
Generic numeric input; hex or binary number must be indicated
+
$, %, 0 through 9, A through F
+
1,3,4
+
+
+
SNUM
+
Similar to NUM with value treated as signed with range -32768 to +32767
+
-, $, %, 0 through 9, A through F
+
1,2,3,4
+
+
+
+
All numeric conversions will continue to accept new data until receiving
+ either the specified number of digits (ex: three digits for DEC3) or a non-numeric character.
+
To be recognized as part of a number, the minus sign (-) must immediately
+ precede a numeric character. The minus sign character occurring in non-numeric
+ text is ignored and any character (including a space) between a minus and a
+ number causes the minus to be ignored.
+
The hexadecimal formatters are not case-sensitive; "a" through "f" means
+ the same as "A" through "F".
+
Indicated hexadecimal and binary formatters ignore all characters, even
+ valid numerics, until they receive the appropriate prefix ($ for hexadecimal,
+ % for binary). The indicated formatters can differentiate between text and
+ hexadecimal (ex: ABC would be interpreted by HEX as a number but IHEX would
+ ignore it unless expressed as $ABC). Likewise, the binary version can
+ distinguish the decimal number 10 from the binary number %10. A prefix
+ occurring in non-numeric text is ignored, and any character (including a
+ space) between a prefix and a number causes the prefix to be ignored. Indicated,
+ signed formatters require that the minus sign come before the prefix, as in
+ -$1B45.
+
+
Special Formatter Tables
+
The BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px also have special formatters
+for handling a string of characters, a sequence of characters and undesirable
+characters. See the table below for a list of these special formatters.
+
+
+
+
+
+
+
+
+
+
+
Special Formatter
+
Action
+
+
+
STR ByteArray \L {\E}
+
Input a character string of length L into an array. If specified, an end
+ character E causes the string input to end before reaching length L.
+ Remaining bytes are filled with 0s (zeros).
+
+
+
WAIT (Value)
+
Wait for a sequence of bytes specified by value. Value can be numbers
+ separated by commas or quoted text (ex: 65, 66, 67 or "ABC"). The WAIT
+ formatter is limited to a maximum of six characters.
+
+
+
WAITSTR ByteArray {\L}
+
Wait for a sequence of bytes matching a string stored in an array variable,
+ optionally limited to L characters. If the optional L argument is left off,
+ the end of the array-string must be marked by a byte containing a zero (0).
+
+
+
SKIP Length
+
Ignore Length bytes of characters.
+
+
+
+
+
+
+
+
+
+
+
Special Formatter
+
Action
+
+
+
SPSTR L
+
Buffer length L bytes (up to 126) of serial characters to Scratchpad RAM,
+ starting at location 0. Use GET to retrieve the
+ characters.
+
+
+
+
The string formatter is useful for receiving a string of characters into a byte
+array variable. A string of characters is a set of characters that are arranged
+or accessed in a certain order. The characters "ABC" could be stored in a string
+with the "A" first, followed by the "B" and then followed by the "C." A byte
+array is a similar concept to a string; it contains data that is arranged in a
+certain order. Each of the elements in an array is the same size. The string
+"ABC" could be stored in a byte array containing three bytes (elements).
+
Here is an example that receives nine bytes through I/O pin 1 at 9600 bps,
+N81/inverted and stores them in a 10-byte array:
+
+
+
+
+serStr VAR Byte(10) ' Make a 10-byte array
+
+Main:
+ serStr(9) = 0 ' Put 0 in last byte
+ SERIN 1, 16468, [STR serStr\9] ' Get 9-byte string
+ DEBUG STR serString ' Display the string
+ END
+
+
If the serial input were "hello*" DEBUG would display "hello" since it
+collects bytes up to (but not including) the end character. It fills the unused
+bytes up to the specified length with 0s. DEBUG's normal STR formatter
+understands a 0 to mean end-of-string. However, if you use DEBUG's
+fixed-length string modifier, STR ByteArray\L, you will inadvertently clear the
+DEBUG screen. The fixed-length specification forces DEBUG to read
+and process the 0s at the end of the string, and 0 is equivalent to DEBUG's
+CLS (clear-screen) instruction! Be alert for the consequences of mixing fixed-
+and variable-length string operations.
+
As shown before, SERIN can compare incoming data with a predefined
+sequence of bytes using the WAIT formatter. The simplest form waits for a sequence
+of up to six bytes specified as part of the InputData list, like so:
+
+
+
+
+ SERIN 1, 16468, [WAIT ("SESAME")] ' Wait for word SESAME
+ DEBUG "Password accepted"
+
+
SERIN will wait for that word, and the program will not continue until
+it is received. Since WAIT is looking for an exact match for a sequence of bytes,
+it is case-sensitive-"sesame" or "SESAmE" or any other variation from "SESAME"
+would be ignored.
+
SERIN can also wait for a sequence that matches a string stored in an
+array variable with the WAITSTR formatter. In the example below, we'll capture a
+string with STR then have WAITSTR look for an exact match:
+
+
+
+
+serStr VAR Byte(10) ' Make a 10-byte array
+
+Main:
+ serString(9) = 0 ' Put 0 in last byte
+ SERIN 1, 16468, [STR serStr\9\"!"] ' Input password string
+ DEBUG "Waiting for: ", STR serString, CR
+ SERIN 1, 16468, [WAITSTR serStr] ' Wait for the password
+ DEBUG "Password accepted!", CR
+ END
+
+
You can also use WAITSTR with fixed-length strings as in the following
+example:
+
+
+
+
+
+
+
+
+serStr VAR Byte(4) ' Make a 4-byte array
+
+Main:
+ DEBUG "Enter a 4-character password", CR
+ SERIN 1, 16468, [STR serStr\4] ' Get the string
+ DEBUG "Waiting for: ", STR serStr\4, CR
+ SERIN 1, 16468, [WAITSTR serStr\4] ' Wait for a match
+ DEBUG "Password accepted!", CR
+ END
+
+
SERIN's InputData can be structured as a sophisticated list of
+actions to perform on the incoming data. This allows you to process incoming data
+in powerful ways. For example, suppose you have a serial stream that contains
+"pos: xxxx yyyy" (where xxxx and yyyy are 4-digit numbers) and you want to capture
+just the decimal y value. The following code would do the trick:
+
+
+
+
+yCoord VAR Word ' y coordinate
+
+Main:
+ SERIN 1, 16468, [WAIT ("pos: "), SKIP 4, DEC yCoord]
+ DEBUG ? yCoord
+ END
+
+
The items of the InputData list work together to locate the label "pos: ",
+skip over the four-byte x data, then convert and capture the decimal y data. This
+sequence assumes that the x data is always four digits long; if its length varies,
+the following code would be more appropriate:
+
+
+
+
+yCoord VAR Word
+
+Main:
+ SERIN 1, 16468, [WAIT ("pos: "), DEC yCoord, DEC yCoord]
+ DEBUG ? yOffset
+ END
+
+
The unwanted x data is stored in yCoord then replaced by the desired y data.
+This is a sneaky way to filter out a number of any size without using an extra
+variable. With a little creativity, you can combine the InputData modifiers
+to filter and extract almost any data.
+
Parity is a simple error-checking feature. When a serial sender is set for even
+parity (the mode the BASIC Stamp modules support) it counts the number of 1s in an outgoing
+byte and uses the parity bit to make that number even. For instance, if it is sending
+the 7-bit value: %0011010, it sets the parity bit to 1 in order to make an even
+number of 1s (four).
+
The receiver also counts the data bits to calculate what the parity bit should
+be. If it matches the parity bit received, the serial receiver assumes that the
+data was received correctly. Of course, this is not necessarily true, since two
+incorrectly received bits could make parity seem correct when the data was wrong,
+or the parity bit itself could be bad when the rest of the data was okay.
+
Many systems that work exclusively with text use (or can be set for)
+7-bit/even-parity mode. The tables above show appropriate BaudMode settings
+for different BASIC Stamp models. For example, with the BS2, to receive one data byte
+through pin 1 at 9600 baud, 7E, inverted:
+
+
+
+
+sData VAR Byte
+
+Main:
+ SERIN 1, 24660, [sData]
+ END
+
+
That instruction will work, but it doesn't tell the BS2 what to do in the event
+of a parity error. Here's an improved version that uses the optional Plabelargument:
If the parity matches, the program continues at the DEBUG instruction
+after SERIN. If the parity doesn't match, the program goes to the label
+Bad_Data. Note that a parity error takes precedence over other InputData
+specifications (as soon as an error is detected, SERIN aborts and goes to
+the Plabel routine).
+
In all the examples above, the only way to end the SERIN instruction
+(other than RESET or power-off) is to give SERIN the serial data it wants.
+If no serial data arrives, the program is stuck. However, you can tell the BASIC
+Stamp to abort SERIN if it doesn't receive data within a specified number
+of milliseconds. For instance, to receive a decimal number through pin 1 at 9600
+baud, 8N, inverted and abort SERIN after two seconds (2000 milliseconds)
+of inactivity on the serial input.
If no data arrives within two seconds, the program aborts SERIN and
+continues at the label No_Data. Note that on multi-byte input, the timeout timer
+is reset after the receipt of any valid data byte; with long timeout values this
+factor could have an adverse affect on program operation if data packets are
+transmitted with gaps between individual data bytes. Finally, be cautious when
+using very short timeout values. Without external flow control, very short
+timeout values may cause the program to branch to the Tlabel address
+unnecessarily.
+
Here's a very important concept: this timeout feature is not picky about the
+kind of data SERIN receives; if any serial data is received, it prevents
+the timeout. In the example above, SERIN wants a decimal number. But even
+if SERIN received letters "ABCD..." at intervals of less than two seconds,
+it would never abort.
+
You can combine parity and serial timeout. Here is an example for the BS2
+designed to receive a decimal number through pin 1 at 2400 baud, 7E, inverted
+with a 10-second timeout:
+
+
+
+
+result VAR Byte
+
+Again:
+ SERIN 1, 24660, Bad_Data, 10000, No_Data, [DEC result]
+ DEBUG CLS, ? result
+ GOTO Again
+
+No_Data:
+ DEBUG CLS, "Timed out"
+ GOTO Again
+
+Bad_Data:
+ DEBUG CLS, "Parity error"
+ GOTO Again
+
+
When you design an application that requires serial communication between BASIC
+Stamp modules, you have to work within these limitations:
+
+
When the BASIC Stamp is sending or receiving data, it can't execute other
+ instructions.
+
When the BASIC Stamp is executing other instructions, it can't send or
+ receive data. The BASIC Stamp does not have a serial buffer as there is in
+ PCs. At most serial rates, the BASIC Stamp cannot receive data via SERIN,
+ process it, and execute another SERIN in time to catch the next chunk
+ of data, unless there are significant pauses between data transmissions.
+
+
These limitations can sometimes be addressed by using flow control; the
+Fpin option for SERIN and SEROUT (at baud rates of up to the
+limitation shown above). Through Fpin, SERIN can tell a BASIC Stamp
+sender when it is ready to receive data. (For that matter, Fpin flow control
+follows the rules of other serial handshaking schemes, but most computers other
+than the BASIC Stamp cannot start and stop serial transmission on a byte-by-byte
+basis. That's why this discussion is limited to communication between BASIC
+Stamp modules).
+
Here's an example using flow control on the BS2 (data through I/O pin 1, flow
+control through I/O pin 0, 9600 baud, N8, non-inverted):
When SERIN executes, I/O pin 1 (Rpin) is made an input in
+preparation for incoming data, and I/O pin 0 (FPin) is made output low,
+to signal "go" to the sender. After SERIN finishes receiving, I/O pin 0
+goes high to tell the sender to stop. If an inverted BaudMode had been
+specified, the FPin's responses would have been reversed. Here's the
+relationship of serial polarity to FPin states.
+
+
+
+
+
+
Ready to Receive ("Go")
+
Not Ready to Receive ("Stop")
+
+
+
Inverted
+
Fpin is High (1)
+
Fpin is Low (0)
+
+
+
Non-Inverted
+
Fpin is Low (0)
+
Fpin is High (1)
+
+
+
+
+
+
See the example program for a flow control example
+using two BS2s. In the demo program example, without flow control, the sender would
+transmit the whole word "HELLO!" in about 1.5 ms. The receiver would catch the first
+byte at most; by the time it got back from the first 1-second PAUSE, the
+rest of the data would be long gone. With flow control, communication is flawless
+since the sender waits for the receiver to catch up.
+
In the figure below, I/O pin 0, FPin, is pulled to ground through a 10
+kΩ resistor. This is to ensure that the sender sees a stop signal (0 for
+inverted communications) when the receiver is being programmed.
+
+
+
+
+
+ SERIN Troubleshooting
+
Serial communication, because of its complexity, can be very difficult to work
+with at times. Please follow these guidelines when developing a project using the
+SERIN and SEROUT commands:
+
+
Always build your project in steps.
+
Start with small, manageable pieces of code, that deals with serial
+ communication) and test them, one at a time.
Add more and more small pieces, testing them each time, as you go.
Never write a large portion of code that works with serial communication
+ without testing its smallest workable pieces first.
+
Pay attention to timing.
+
Be very careful to calculate and overestimate the amount of time
+ operations should take within the BASIC Stamp. Misunderstanding the
+ timing constraints is the source of most problems with code that
+ communicate serially.
If the serial communication in your project is bidirectional, the
+ above statement is even more critical.
+
Pay attention to wiring.
+
Take extra time to study and verify serial communication wiring diagrams.
+ A mistake in wiring can cause strange problems in communication, or no
+ communication at all. Make sure to connect the ground pins (Vss) between
+ the devices that are communicating serially.
+
Verify port setting on the PC and in the SERIN/SEROUT commands.
+
Unmatched settings on the sender and receiver side will cause garbled
+ data transfers or no data transfers. If the data you receive is unreadable,
+ it is most likely a baud rate setting error.
+
If receiving data from another device that is not a BASIC Stamp, try to use
+ baud rates of 4800 and below.
+
Because of additional overhead in the BASIC Stamp, and the fact that
+ the BASIC Stamp has no hardware receive buffer for serial communication,
+ received data may sometimes be missed or garbled. If this occurs, try
+ lowering the baud rate (if possible), adding extra stop bits, and not
+ using formatters in the SERIN command. Using simple variables
+ (not arrays) and no formatters will increase the chance that the BASIC
+ Stamp can receive the data properly.
+
Be sure to study the effects of SERIN formatters
+
Because of additional overhead in the BASIC Stamp, and the fact that
+ the BASIC Stamp has no hardware receive buffer for serial communication,
+ received data may sometimes be missed or garbled. If this occurs, try
+ lowering the baud rate (if possible), adding extra stop bits, and not
+ using formatters in the SERIN command. Using simple variables
+ (not arrays) and no formatters will increase the chance that the BASIC
+ Stamp can receive the data properly.
+
When using a BS2-family module, you can simplify Baudmode parameter
+ selection by using conditional compilation. The example below can be
+ included in the standard programming template and will handle most serial
+ IO requirements. Remember that defining constants does not affect compiled
+ program space, and yet does make program debugging easier.
+
+
+
+
+
+
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T4800 CON 188
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T4800 CON 500
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T4800 CON 813
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+SevenBit CON $2000
+Inverted CON $4000
+Open CON $8000
+
+Baud CON T9600 + Inverted ' match DEBUG
+
Transmit asynchronous serial data (e.g., RS-232 data).
+
+
+
+
Tpin is a variable/constant/expression* (0 - 16) that specifies
+ the I/O pin through which the serial data will be transmitted. This pin will
+ be set to output mode. On the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px, if
+ Tpin is set to 16, the BASIC Stamp uses the dedicated serial-output
+ pin (SOUT, physical pin 1), which is normally used by the Stamp Editor during
+ the download process.
+
Fpin is an optional variable/constant/expression* (0 - 15) that
+ specifies the I/O pin to monitor for flow control status. This pin will be set
+ to input mode. NOTE: Fpin must be specified to use the optional
+ Timeout and Tlabel arguments in the SEROUT command.
+
Baudmode is variable/constant/expression* (0 - 7 on the BS1,
+ 0 - 65535 on all other BASIC Stamp models) that specifies serial timing and
+ configuration.
+
Pace is an optional variable/constant/expression (0 - 65535)
+ that determines the length of the pause between transmitted bytes. NOTE:
+ Pace cannot be used simultaneously with Timeout.
+
Timeout is an optional variable/constant/expression* (0 - 65535)
+ that tells SEROUT how long to wait for Fpin permission to send.
+ If permission does not arrive in time, the program will jump to the address
+ specified by Tlabel. NOTE: Fpin must be specified to use the
+ optional Timeout and Tlabel arguments in the SEROUT
+ command.
+
Tlabel is an optional label that must be provided along with
+ Timeout. Tlabel indicates where the program should go in the event
+ that permission to send data is not granted within the period specified by
+ Timeout.
+
OutputData‡ is a list of variables, constants, expressions
+ and formatters that tells SEROUT how to format outgoing data. SEROUTcan transmit individual or repeating bytes, convert values into decimal, hex
+ or binary text representations, or transmit strings of bytes from variable
+ arrays. These actions can be combined in any order in the OutputData list.
+
+
* Note: expressions are not allowed as arguments on the BS1. The range
+ of the Pin argument on the BS1 is 0–7.
+
‡Note: The BS1's OutputData argument can only be a list of variables and the optional decimal modifier (#).
One of the most popular forms of communication between electronic devices is serial
+communication. There are two major types of serial communication; asynchronous and
+synchronous. The SERIN and SEROUT commands are used to receive and
+send asynchronous serial data. See the SHIFTIN and
+SHIFTOUT commands for information on the synchronous
+method.
+
Tip: Don't let your BASIC Stamp be mistaken for a mouse!
+
+ Connecting USB-based boards to your PC may cause the BASIC Stamp to reset. If your BASIC Stamp program immediately starts sending serial data to the computer via a DEBUG or SEROUT command, your computer's operating system may mistake it for a mouse or other serial plug-and-play device. To avoid this, place a 1-second pause at the beginning of the program.
+
The following information is supplemental to what is discussed in the
+SERIN command section. Please read through the SERIN command
+section for additional information.
+
+
+
+
+
All BASIC Stamp models (except the BS1) have a line driver on its SOUT pin (Tpin =
+16).
+The SOUT pin goes to a PC's serial data-in pin on the DB-9 connector built into
+BASIC Stamp development boards. The connector is wired to allow both programming
+and run-time serial communication (unless you are using the Stamp 2 Carrier Board
+which is only designed for programming). For the built-in serial port set the
+Tpin argument to 16 in the SEROUT command.
+
All BASIC Stamp models (including the BS1) can also transmit RS-232 data through any
+of their I/O pins (Tpin = 0 - 7 for BS1, Tpin = 0 - 15 on all other BASIC Stamp models).
+The I/O pins only provide a 0 to +5 volt swing (outside of RS-232 specs) and may
+need to be connected through a line driver for proper operation with all serial
+ports. Most serial ports are able to recognize a 0 to +5 volt swing, however. See
+the figure below sample wiring.
+
+
+
+
+
Note: The connections shown in red are normally not necessary. They indicate optional connections to defeat hardware handshaking requirements.
+
Note: A line driver may have to be used between the I/O pin and the receiving serial port to ensure proper communication.
+
+
+
+
+
Function
+
DB-9
+
DB-25
+
+
+
Data Carrier Detect (DCD)
+
1
+
8
+
+
+
Receive Data (RD)
+
2
+
3
+
+
+
Transmit Data (TD)
+
3
+
2
+
+
+
Data Terminal Ready (DTR)
+
4
+
20
+
+
+
Signal Ground (SG)
+
5
+
7
+
+
+
Data Set Ready (DSR)
+
6
+
6
+
+
+
Request To Send (RTS)
+
7
+
4
+
+
+
Clear To Send (CTS)
+
8
+
5
+
+
+
+
+
+
The figure above shows the pinouts of the two styles of PC serial ports and how
+to connect them to the BASIC Stamp's I/O pin. Though not normally needed, the
+figure also shows loop back connections that defeat hardware handshaking used by
+some PC software. Note that PC serial ports are always male connectors. The 25-pin
+style of serial port (called a DB-25) looks similar to a printer (parallel) port
+except that it is male, whereas a parallel port is female.
+
Asynchronous serial communication relies on precise timing. Both the sender and
+receiver must be set for identical timing, usually expressed in bits per second
+(bps) called baud.
+
On all BASIC Stamp models, SEROUT requires a value called Baudmode that tells
+it the important characteristics of the outgoing serial data; the bit period, number
+of data and parity bits, and polarity.
+
+
+
+
+
On the BS1, serial communication is limited to: no-parity, 8-data bits and 1-stop
+bit at one of four different speeds: 300, 600, 1200 or 2400 baud. The table below
+indicates the Baudmode value or symbols to use when selecting the desired
+mode.
+
+
+
+
+
Baudmode Value
+
Symbol
+
Baud Rate
+
Polarity
+
+
+
0
+
T2400
+
2400
+
TRUE (always driven)
+
+
+
1
+
T1200
+
1200
+
TRUE (always driven)
+
+
+
2
+
T600
+
600
+
TRUE (always driven)
+
+
+
3
+
T300
+
300
+
TRUE (always driven)
+
+
+
4
+
N2400
+
2400
+
INVERTED (always driven)
+
+
+
5
+
N1200
+
1200
+
INVERTED (always driven)
+
+
+
6
+
N600
+
600
+
INVERTED (always driven)
+
+
+
7
+
N300
+
300
+
INVERTED (always driven)
+
+
+
8
+
OT2400
+
2400
+
TRUE (open drain, driven high)
+
+
+
9
+
OT1200
+
1200
+
TRUE (open drain, driven high)
+
+
+
10
+
OT600
+
600
+
TRUE (open drain, driven high)
+
+
+
11
+
OT300
+
300
+
TRUE (open drain, driven high)
+
+
+
12
+
ON2400
+
2400
+
INVERTED (open source, driven low)
+
+
+
13
+
ON1200
+
1200
+
INVERTED (open source, driven low)
+
+
+
14
+
ON600
+
600
+
INVERTED (open source, driven low)
+
+
+
15
+
N300
+
300
+
INVERTED (open source, driven low)
+
+
+
+
+
+
+
+
+
On the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px, serial communication is very flexible.
+The Baudmode argument for SEROUT accepts a 16-bit value that determines
+its characteristics: 1-stop bit, 8-data bits/no-parity or 7-data bits/even-parity
+and virtually any speed from as low as 300 baud to greater than 100K baud (depending
+on the BASIC Stamp). The information below shows how Baudmode is calculated
+and show common baud modes for standard serial baud rates.
BS2px = INT(4,000,000 ÷ baud rate) - 20 Note: INT means 'Convert to integer.' -- drop the numbers to the right
+ of the decimal point.
+
Set data bits and parity (bit 13)
+
8-bit / No Parity = 0 ($0000)
7-bit / Even Parity = 8192 ($2000)
+
Select polarity bit (bit 14)
+
True = 0 ($0000)
Inverted = 16384 ($4000)
+
Select driven or open output (bit 15)
+
Driven = 0 ($0000)
Open = 32768 ($8000)
+
+
Common Baud Rates and Corresponding Baudmode Values
+
+ BS2, BS2e, BS2pe
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
300
+
19697 ($4CF1)
+
3313 ($0CF1)
+
27889 ($6CF1)
+
11505 ($2CF1)
+
+
+
600
+
18030 ($466E)
+
1646 ($066E)
+
26222 ($666E)
+
9838 ($266E)
+
+
+
1200
+
17197 ($432D)
+
813 ($032D)
+
25389 ($632D)
+
9005 ($232D)
+
+
+
2400
+
16780 ($418C)
+
396 ($018C)
+
24972 ($618C)
+
8588 ($218C)
+
+
+
4800
+
16572 ($40BC)
+
188 ($00BC)
+
24764 ($60BC)
+
8380 ($20BC)
+
+
+
9600
+
16468 ($4054)
+
84 ($0054)
+
24660 ($6054)
+
8276 ($2054)
+
+
+
+
+
+
+ BS2sx, BS2p
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
1200
+
18447 ($480F)
+
2063 ($080F)
+
26639 ($680F)
+
10255 ($280F)
+
+
+
2400
+
17405 ($43FD)
+
1021 ($03FD)
+
25597 ($63FD)
+
9213 ($23FD)
+
+
+
4800
+
16884 ($41F4)
+
500 ($01F4)
+
25076 ($61F4)
+
8692 ($21F4)
+
+
+
9600
+
16624 ($40F0)
+
240 ($00F0)
+
24816 ($60F0)
+
8432 ($20F0)
+
+
+
+
+
+
+ BS2px
+
+
+
Baud Rate
+
8-bit No Parity INVERTED
+
8-bit No Parity TRUE
+
7-bit Even Parity INVERTED
+
7-bit Even Parity TRUE
+
+
+
1200
+
19697 ($4CF1)
+
3313 ($0CF1)
+
27889 ($6CF1)
+
11505 ($2CF1)
+
+
+
2400
+
18030 ($466E)
+
1646 ($066E)
+
26222 ($666E)
+
9838 ($266E)
+
+
+
4800
+
17197 ($432D)
+
813 ($032D)
+
25389 ($632D)
+
9005 ($232D)
+
+
+
9600
+
16780 ($418C)
+
396 ($018C)
+
24972 ($618C)
+
8588 ($218C)
+
+
+
+
Tip: For "open" baudmodes used in networking, add 32768 ($8000) to the values from the tables above. If the dedicated serial port (Tpin = 16) is used the data is inverted and driven regardless of the Baudmode setting.
+
If you're communicating with existing software or hardware, its speed(s) and
+mode(s) will determine your choice of baud rate and mode. See the SERIN
+command description for more information.
+
The example below will transmit a single byte through I/O pin 1 at 2400 baud,
+8N1, inverted:
+
+
+
+
+ SEROUT 1, N2400, (65)
+
+
+
+
+
+ SEROUT 1, 16780, [65] ' baudmode set for BS2/e/pe
+
+
+
+
+
+ SEROUT 1, 17405, [65] ' baudmode set for BS2sx/p
+
+
Here, SEROUT will transmit a byte equal to 65 (the ASCII value of the
+character "A") through pin 1. If the BASIC Stamp were connected to a PC running
+a terminal program (set to the same baud rate) the character "A" would appear on
+the screen.
+
What if you really wanted the value 65 to appear on the screen? If you remember
+from the discussion in the SERIN command, "It is up to the receiving side
+(in serial communication) to interpret the values..." In this case, the PC is
+interpreting the byte-sized value to be the ASCII code for the character "A".
+Unless you're also writing the software for the PC, you can't change how the PC
+interprets the incoming serial data, so to solve this problem, the data needs
+to be translated before it is sent.
+
The SEROUT command provides a formatter, called the decimal formatter,
+which will translate the value 65 to two ASCII codes for the characters "6" and
+"5" and then transmit them. Look at the following code:
+
+
+
+
+ SEROUT 1, N2400, (#65)
+
+
+
+
+
+ SEROUT 1, 16780, [DEC 65]
+
+
+
+
+
+ SEROUT 1, 17405, [DEC 65]
+
+
Notice the decimal formatter in the SEROUT command. It is the "#" (for
+the BS1) or "DEC" (for the other BASIC Stamp models) that appears just to the left of
+the number 65. This tells SEROUT to convert the number into separate ASCII
+characters which represent the value in decimal form. If the value 65 in the code
+were changed to 123, the SEROUT command would send three bytes (49, 50 and
+51) corresponding to the characters "1", "2" and "3".
+
The BS2, BS2e, BS2sx, BS2p, BS2pev and BS2px have many more conversion formatters
+available for the SEROUT command. See below for more information.
+
The SEROUT command sends quoted text exactly as it appears in the
+OutputData list:
The above code will display "HELLO" on one line and "Num = 100" on the next
+line. Notice that you can combine data to output in one SEROUT command,
+separated by commas. In the example above, we could have written it as one line
+of code, with "HELLO", CR, "Num = ", DEC 100 in the OutputData list.
+
+
+
+
+
The BS1's SEROUT command is limited to above-mentioned features. If you
+are not using a BS1, please continue reading about the additional features below.
+
+
+
+
+
The SEROUT command can also be configured to pause between transmitted
+bytes. This is the purpose of the optional Pace argument. For example
+(9600 baud N8, inverted):
+ SEROUT 1, 16468, 1000, ["Slowly"] ' baudmode set for BS2
+
+
Here, the BASIC Stamp transmits the word "Slowly" with a 1 second delay between
+each character. See the table above for units of the Pace argument. One
+good reason to use the Pace feature is to support devices that require more than
+one stop bit. Normally, the BASIC Stamp sends data as fast as it can (with a
+minimum of 1 stop bit between bytes). Since a stop bit is really just a resting
+state in the line (no data transmitted), using the Pace option will
+effectively add multiple stop bits. Since the requirement for 2 or more stop bits
+(on some devices) is really just a "minimum" requirement, the receiving side should
+receive this data correctly.
+
Keep in mind that when we type something like "XYZ" into the SEROUT
+command, the BASIC Stamp actually uses the ASCII codes for each of those characters
+for its tasks. We could also typed: 88, 89, 90 in place of "XYZ" and the program
+would run the same way since 88 is the ASCII code for the "X" character, 89 is the
+ASCII code for the "Y" character, and so on.
+
The decimal formatter is only one of a whole family of conversion formatters
+available with SEROUT on the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px. See
+the table below for a list of available conversion formatters. All of the conversion
+formatters work similar to the decimal formatter. The formatters translate the
+value into separate bytes of data until the entire number is translated or until
+the indicated number of digits (in the case of the fixed length formatters) is
+translated.
+
+
+
+
+
+
+
Conversion Formatter
+
Type of Number
+
Notes
+
+
+
DEC{1..5}
+
Decimal, optionally fixed to 1 - 5 digits
+
1
+
+
+
SDEC{1..5}
+
Signed decimal, optionally fixed to 1 - 5 digits
+
1,2
+
+
+
HEX{1..4}
+
Hexadecimal, optionally fixed to 1 - 4 digits
+
1
+
+
+
SHEX{1..4}
+
Signed hexadecimal, optionally fixed to 1 - 4 digits
+
1,2
+
+
+
IHEX{1..4}
+
Indicated hexadecimal, optionally fixed to 1 - 4 digits
Indicated binary, optionally fixed to 1 - 16 digits
+
1
+
+
+
ISBIN{1..16}
+
Signed, indicated binary, optionally fixed to 1 - 16 digits
+
1,2
+
+
+
+
Fixed-digit formatters like DEC4 will pad the number with leading 0s if
+ necessary; ex: DEC4 65 sends 0065. If a number is larger than the specified
+ number of digits, the leading digits will be dropped; ex: DEC4 56422 sends
+ 6422.
+
Signed modifiers work under two's complement rules.
+
+
The BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px also have special formatters for
+outputting a string of characters, repeated characters and undesirable
+characters.
+
+
+
+
+
+
+
Special Formatter
+
Action
+
+
+
?
+
Displays "symbol = x' + carriage return; where x is a number. Default
+ format is decimal, but may be combined with conversion formatters (ex: BIN
+ ? x to display "x = binary_number").
+
+
+
ASC ?
+
Displays "symbol = 'x'" + carriage return; where x is an ASCII character.
+
+
+
STR ByteArray {\L}
+
Send character string from an array. The optional \L argument can be used
+ to limit the output to L characters, otherwise, characters will be sent up
+ to the first byte equal to 0 or the end of RAM space is reached.
+
+
+
REP Byte\L
+
Send a string consisting of Byte repeated L times (ex: REP "X"\10 sends
+ "XXXXXXXXXX").
+
+
+
+
The string formatter is useful for transmitting a string of characters from a
+byte array variable. A string of characters is a set of characters that are
+arranged or accessed in a certain order. The characters "ABC" could be stored in
+a string with the "A" first, followed by the "B" and then followed by the "C."
+A byte array is a similar concept to a string; it contains data that is arranged
+in a certain order. Each of the elements in an array is the same size. The string
+"ABC" could be stored in a byte array containing three bytes (elements).
+
Here is an example that transmits five bytes (from a byte array) through I/O
+pin 1 at 9600 bps, N81/inverted:
Note that we use the optional \L argument of STR. If we didn't specify this,
+the BASIC Stamp would try to keep sending characters until it found a byte equal
+to 0. Since we didn't specify a last byte of 0 in the array, we chose to tell it
+explicitly to only send 5 characters.
+
Parity is a simple error-checking feature. When the SEROUT command's
+Baudmode is set for even parity it counts the number of 1s in the outgoing
+byte and uses the parity bit to make that number even. For instance, if it is
+sending the 7-bit value: %0011010, it sets the parity bit to 1 in order to make
+an even number of 1s (four).
+
The receiver also counts the data bits to calculate what the parity bit should
+be. If it matches the parity bit received, the serial receiver assumes that the
+data was received correctly. Of course, this is not necessarily true, since two
+incorrectly received bits could make parity seem correct when the data was wrong,
+or the parity bit itself could be bad when the rest of the data was OK. Parity
+errors are only detected on the receiver side. Generally, the receiver determines
+how to handle the error. In a more robust application, the receiver and transmitter
+might be set up such that the receiver can request a re-send of data that was
+received with a parity error.
+
When you design an application that requires serial communication between BASIC
+Stamp modules, you have to work within these limitations:
+
+
When the BASIC Stamp is sending or receiving data, it can't execute other
+ instructions.
+
When the BASIC Stamp is executing other instructions, it can't send or
+ receive data. The BASIC Stamp does not have a serial buffer as there is in
+ PCs. At most serial rates, the BASIC Stamp cannot receive data via SERIN,
+ process it, and execute another SERIN in time to catch the next chunk
+ of data, unless there are significant pauses between data transmissions.
+
+
These limitations can sometimes be addressed by using flow control; the Fpinoption for SERIN and SEROUT (at baud rates of up to the limitation
+shown above). Through Fpin, SERIN can tell a BASIC Stamp sender when
+it is ready to receive data and SEROUT (on the sender) will wait for
+permission to send. (For that matter, Fpin flow control follows the rules
+of other serial handshaking schemes, but most computers other than the BASIC Stamp
+cannot start and stop serial transmission on a byte-by-byte basis. That's why this
+discussion is limited to communication between BASIC Stamp modules.)
+
Here's an example using flow control on the BS2 (data through I/O pin 1, flow
+control through I/O pin 0, 9600 baud, N8, non-inverted):
+
+
+
+
+sData VAR Byte
+
+Main:
+ SEROUT 1\0, 84, [sData] ' baudmode set for BS2
+
+
When SEROUT executes, I/O pin 1 (Tpin) is made an output, and
+I/O pin 0 (Fpin) is made an input, to wait for the "go" signal from the
+receiver. Here's the relationship of serial polarity to Fpin states.
+
+
+
+
+
+
Ready to Receive ("Go")
+
Not Ready to Receive ("Stop")
+
+
+
Inverted
+
Fpin is High (1)
+
Fpin is Low (0)
+
+
+
Non-Inverted
+
Fpin is Low (0)
+
Fpin is High (1)
+
+
+
+
+
+
See the SEROUT Examples for a flow control example
+using two BS2s. In the demo program example, without flow control, the sender would
+transmit the whole word "HELLO!" in about 6 ms. The receiver would catch the first
+byte at most; by the time it got back from the first 1-second PAUSE, the
+rest of the data would be long gone. With flow control, communication is flawless
+since the sender waits for the receiver to catch up.
+
In the figure below, I/O pin 0, Fpin, is pulled to ground through a 10
+kΩ resistor. This is to ensure that the sender sees a stop signal (0 for
+inverted communications) when the receiver is being programmed.
+
+
+
+
+
+
In the flow control examples above, the only way the SEROUT instruction
+will end (other than RESET or power-off) is if the receiver allows it to send the
+entire OutputData list. If Fpin permission never occurs, the program
+is stuck. However, you can tell the BASIC Stamp to abort SEROUT if it doesn't
+receive Fpin permission within a specified time period. For instance, to
+transmit a decimal number through pin 1 at 9600 baud, 8N, inverted and abort
+SEROUT after 2 seconds (2000 ms) if no Fpin permission arrives on
+I/O pin 0:
If no Fpin permission arrives within 2 seconds, the program aborts
+SEROUT and continues at the label NoPermission.
+
The SEROUT command supports open-drain and open-source output, which
+makes it possible to network multiple BASIC Stamp modules on a single pair of wires. These
+"open baudmodes" only actively drive the Tpin in one state (for the other
+state, they simply disconnect the pin; setting it to an input mode). If two BASIC
+Stamp modules in a network had their SEROUT lines connected together (while a third
+device listened on that line) and the BASIC Stamp modules were using always-driven
+baudmodes, they could simultaneously output two opposite states (i.e., +5 volts and
+ground). This would create a short circuit. The heavy current flow would likely
+damage the I/O pins or the BASIC Stamp modules themselves. Since the open baudmodes only
+drive in one state and float in the other, there's no chance of this kind of short.
+
The polarity selected for SEROUT determines which state is driven and
+which is open as shown below:
+
+
+
+
+
+
State (0)
+
State (1)
+
Resistor pulled to...
+
+
+
Inverted
+
Open
+
Driven
+
Gnd (Vss)
+
+
+
Non-Inverted
+
Driven
+
Open
+
+5V (Vdd)
+
+
+
+
+
+
Since open baudmodes only drive to one state, they need a resistor to pull the
+networked line into the other state, as shown in the table above and the figures
+below.
+
Open baudmodes allow the BASIC Stamp to share a line, but it is up to your
+program to resolve other networking issues such as who talks when and how to
+detect, prevent and fix data errors.
+
+
+
+
+
SEROUT Open-Drain circuit:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
SEROUT Open-Source circuit:
+
+
+
+
+
+
+
+
+
+
+
SEROUT Troubleshooting
+
Serial communication, because of its complexity, can be very difficult to work
+with at times. Please follow these guidelines when developing a project using the
+SERIN and SEROUT commands:
+
+
Always build your project in steps.
+
Start with small, manageable pieces of code, that deals with serial
+ communication) and test them, one at a time.
Add more and more small pieces, testing them each time, as you go.
Never write a large portion of code that works with serial communication
+ without testing its smallest workable pieces first.
+
Pay attention to timing.
+
Be very careful to calculate and overestimate the amount of time
+ operations should take within the BASIC Stamp. Misunderstanding the timing
+ constraints is the source of most problems with code that communicate
+ serially.
If the serial communication in your project is bidirectional, the above
+ statement is even more critical.
+
Pay attention to wiring.
+
Take extra time to study and verify serial communication wiring diagrams.
+ A mistake in wiring can cause strange problems in communication, or no
+ communication at all. Make sure to connect the ground pins (Vss) between
+ the devices that are communicating serially.
+
Verify port setting on the PC and in the SERIN/SEROUT commands.
+
Unmatched settings on the sender and receiver side will cause garbled
+ data transfers or no data transfers. If the data you receive is unreadable,
+ it is most likely a baud rate setting error.
+
If data transmitted to the Stamp Editor's Debug Terminal is garbled, verify
+ the output format.
+
A common mistake is to send data with SEROUT in ASCII format. For
+ example, SEROUT 16, 84, [ 0 ] instead of SEROUT 16, 84,
+ [ DEC 0 ]. The first example will send a byte equal to 0 to the PC,
+ resulting in the DEBUG Terminal clearing the screen (since 0 is
+ the control character for a clear-screen action).
+
When using a BS2-family module, you can simplify Baudmode parameter
+ selection by using conditional compilation. The example below can be
+ included in the standard programming template and will handle most serial
+ IO requirements. Remember that defining constants does not affect compiled
+ program space, and yet does make program debugging easier.
+
+
+
+
+
+
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T4800 CON 188
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T4800 CON 500
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T4800 CON 813
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+SevenBit CON $2000
+Inverted CON $4000
+Open CON $8000
+
+Baud CON T9600 + Inverted ' match DEBUG
+
Shift data in from a synchronous serial device.
+
+
+
+
Dpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin that will be connected to the synchronous serial device's data
+ output. This pin will be set to input mode.
+
Cpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin that will be connected to the synchronous serial device's clock
+ input. This pin will be set to output mode.
+
Mode is a variable/constant/expression (0 - 3), or one of four
+ predefined symbols, that tells SHIFTIN the order in which data bits are
+ to be arranged and the relationship of clock pulses to valid data. See the
+ table below for value and symbol definitions.
+
Variable is a variable in which incoming data bits will be
+ stored.
+
Bits is an optional variable/constant/expression (1 - 16)
+ specifying how many bits are to be input by SHIFTIN. If no Bits
+ entry is given, SHIFTIN defaults to 8 bits.
SHIFTIN and SHIFTOUT provide an easy method of acquiring data from
+synchronous serial devices. Synchronous serial differs from asynchronous serial
+(like SERIN and SEROUT) in that the timing of data bits (on a data
+line) is specified in relationship to clock pulses (on a clock line). Data bits
+may be valid after the rising or falling edge of the clock line. This kind of
+serial protocol is commonly used by controller peripherals like ADCs, DACs, clocks,
+memory devices, etc.
+
At their heart, synchronous-serial devices are essentially shift-registers;
+trains of flip-flops that pass data bits along in a bucket brigade fashion to a
+single data output pin. Another bit is output each time the appropriate edge
+(rising or falling, depending on the device) appears on the clock line.
+
The SHIFTIN instruction first causes the clock pin to output low and
+the data pin to switch to input mode. Then, SHIFTIN either reads the data
+pin and generates a clock pulse (PRE mode) or generates a clock pulse then reads
+the data pin (POST mode). SHIFTIN continues to generate clock pulses and
+read the data pin for as many data bits as are required.
+
Making SHIFTIN work with a particular device is a matter of matching
+the mode and number of bits to that device's protocol. Most manufacturers use a
+timing diagram to illustrate the relationship of clock and data. Items to look
+for include: 1) which bit of the data arrives first; most significant bit (MSB)
+or least significant bit (LSB) and 2) is the first data bit ready before the
+first clock pulse (PRE) or after the first clock pulse (POST). The table below
+shows the values and symbols available for the Mode argument.
+
+
+
Symbol
+
Value
+
Meaning
+
+
+
MSBPRE
+
0
+
Data is MSB-first; sample bits before clock pulse
+
+
+
LSBPRE
+
1
+
Data is lsb-first; sample bits before clock pulse
+
+
+
MSBPOST
+
2
+
Data is MSB-first; sample bits after clock pulse
+
+
+
LSBPOST
+
3
+
Data is LSB-first; sample bits after clock pulse
+
+
+
SHIFTIN Timing
+
+
+
+
+
Here is a simple example:
+result VAR Byte
+
+Main:
+ SHIFTIN 0, 1, MSBPRE, [result]
+ END
+
+
Here, the SHIFTIN command will read I/O pin 0 (the Dpin) and will
+generate a clock signal on I/O 1 (the Cpin). The data that arrives on the
+Dpin depends on the device connected to it. Let's say, for example, that a shift
+register is connected and has a value of $AF (10101111) waiting to be sent.
+Additionally, let's assume that the shift register sends out the most significant
+bit first, and the first bit is on the Dpin before the first clock pulse
+(MSBPRE). The SHIFTIN command above will generate eight clock pulses and
+sample the data pin (Dpin) eight times. Afterward, the result variable
+will contain the value $AF.
+
By default, SHIFTIN acquires eight bits, but you can set it to shift
+any number of bits from 1 to 16 with the Bits argument. For example:
+result VAR Byte
+
+Main:
+ SHIFTIN 0, 1, MSBPRE, [result\4]
+ END
+
+
Will only input the first 4 bits. In the example discussed above, the result
+variable will be left with %1010.
+
Some devices return more than 16 bits. For example, most 8-bit shift registers
+can be daisy-chained together to form any multiple of 8 bits; 16, 24, 32, 40...
+To solve this, you can use a single SHIFTIN instruction with multiple
+variables. Each variable can be assigned a particular number of bits with the
+Bits argument. As in:
+dataLo VAR Word
+dataHi VAR Byte
+
+Main:
+ SHIFTIN 0, 1, MSBPRE, [dataHi\4, dataLo\16]
+ STOP
+
+
The code above will first shift in four bits into dataHi and then 16 bits
+into dataLo. The two variables together make up a 20 bit value.
Shift data out to a synchronous serial device.
+
+
+
+
Dpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin that will be connected to the synchronous serial device's data
+ input. This pin will be set to output mode.
+
Cpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin that will be connected to the synchronous serial device's clock
+ input. This pin will be set to output mode.
+
Mode is a variable/constant/expression (0 - 1), or one of two
+ predefined symbols, that tells SHIFTOUT the order in which data bits
+ are to be arranged. See the table below for value and symbol definitions.
+
OutputData is a variable/constant/expression containing the
+ data to be sent.
+
Bits is an optional variable/constant/expression (1 - 16)
+ specifying how many bits are to be output by SHIFTOUT. If no Bitsentry is given SHIFTOUT defaults to 8 bits. When the Bits entry
+ is given, the BASIC Stamp transmits the rightmost number of bits specified,
+ regardless of the Mode.
SHIFTIN and SHIFTOUT provide an easy method of acquiring data from
+synchronous serial devices. Synchronous serial differs from asynchronous serial
+(like SERIN and SEROUT) in that the timing of data bits (on a data
+line) is specified in relationship to clock pulses (on a clock line). Data bits
+may be valid after the rising or falling edge of the clock line. This kind of
+serial protocol is commonly used by controller peripherals like ADCs, DACs, clocks,
+memory devices, etc.
+
At their heart, synchronous-serial devices are essentially shift-registers;
+trains of flip-flops that pass data bits along in a bucket brigade fashion to a
+single data output pin. Another bit is output each time the appropriate edge
+(rising or falling, depending on the device) appears on the clock line.
+
The SHIFTOUT instruction first causes the clock pin to output low and
+the data pin to switch to output mode. Then, SHIFTOUT sets the data pin
+to the next bit state to be output and generates a clock pulse. SHIFTOUTcontinues to generate clock pulses and places the next data bit on the data pin
+for as many data bits as are required for transmission.
+
Making SHIFTOUT work with a particular device is a matter of matching
+the mode and number of bits to that device's protocol. Most manufacturers use a
+timing diagram to illustrate the relationship of clock and data. One of the most
+important items to look for is which bit of the data should be transmitted first;
+most significant bit (MSB) or least significant bit (LSB). The table below shows
+the values and symbols available for the Mode argument
+
+
+
Symbol
+
Value
+
Meaning
+
+
+
LSBFIRST
+
0
+
Data is shifted out LSB-first
+
+
+
MSBFIRST
+
1
+
Data is shifted out MSB-first
+
+
+
+
(MSB is most-significant bit; the highest or left-most bit of a Nibble, Byte,
+or Word. LSB is the least-significant bit; the lowest or right-most bit of a
+Nibble, Byte, or Word.)
+
SHIFTOUT Timing
+
+
+
+
+
Here is a simple example:
+ SHIFTOUT 0, 1, MSBFIRST, [250]
+
+
Here, the SHIFTOUT command will write to I/O pin 0 (the Dpin) and will
+generate a clock signal on I/O 1 (the Cpin). The SHIFTOUT command
+will generate eight clock pulses while writing each bit (of the 8-bit value 250)
+onto the data pin (Dpin). In this case, it will start with the most
+significant bit first as indicated by the Mode value of MSBFIRST.
+
By default, SHIFTOUT transmits eight bits, but you can set it to shift
+any number of bits from 1 to 16 with the Bits argument. For example:
+ SHIFTOUT 0, 1, MSBFIRST, [250\4]
+
+
Will output only the lowest (rightmost) four bits (%1010 in this case). But
+what if you want to output the leftmost bits of a given value? By adding the
+right-shift operator (>>) to the code you can adjust the output as required:
+ SHIFTOUT 0, 1, MSBFIRST, [(250 >> 2)\6]
+
+
...will output the upper six bits (%111110 in this case).
+
Some devices require more than 16 bits. To solve this, you can use a single
+SHIFTOUT command with multiple values. Each value can be assigned a
+particular number of bits with the Bits argument. As in:
+ SHIFTOUT 0, 1, MSBFIRST, [250\4, 1045\16]
+
+
The preceding example will first shift out four bits of the number 250 (%1010)
+and then 16 bits of the number 1045 (%0000010000010101). The two values together
+make up a 20 bit value.
+
In the examples above, specific numbers were entered as the data to transmit,
+but, of course, the SHIFTOUT command will accept variables and expressions
+for the OutputData and even for the Bits argument.
Put the BASIC Stamp into low-power mode for a specified period of time.
+
+
+
+
Duration is a variable/constant/expression* (1 - 65535) that
+ specifies the duration of sleep. The unit of time for Duration is one
+ second, though the BASIC Stamp rounds up to the nearest multiple of 2.3
+ seconds.
+
+
* Note: expressions are not allowed as arguments on the BS1.
SLEEP allows the BASIC Stamp to turn itself off, then turn back on after
+a programmed duration. The length of SLEEP can range from 2.3 seconds
+to slightly over 18 hours. Power consumption is reduced to the amount described
+in the table above, assuming no loads are being driven.
+
Sleep Units vs Sleep Resolution
+
The units for Duration are 1 second, but the resolution of the
+SLEEP instruction is 2.304 seconds. SLEEP rounds the specified
+number of seconds up to the nearest multiple of 2.304. Because of this, Duration values below 10 are not very accurate.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
When the Duration value is...
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
+
+
Sleep time (in seconds) is approximately...
+
2.304
+
2.304
+
4.608
+
4.608
+
6.912
+
6.912
+
9.216
+
9.216
+
9.216
+
11.52
+
+
+
+
+
To estimate the actual sleeping period for any Duration value, use this equation:
+
+
+
+
The open-bottom square brackets indicate the ceiling function, which essentially means "round up the quantity inside to the next integer."
+
For example, SLEEP 1 sleeps for 2.304 seconds:
+
+
+
+
And, SLEEP 10 sleeps for approximately 11.52 seconds:
+
+
+
+
+
The Watchdog Timer Improves Sleep Accuracy Automatically
+
Pins retain their previous I/O directions during SLEEP. However, outputs
+are interrupted every 2.3 seconds during SLEEP due to the way the chip keeps
+time. The alarm clock that wakes the BASIC Stamp up is called the watchdog timer.
+The watchdog is a resistor/capacitor oscillator built into the interpreter chip.
+During SLEEP, the chip periodically wakes up and adjusts a counter to
+determine how long it has been asleep. If it isn't time to wake up, the chip "hits
+the snooze bar" and goes back to sleep.
+
To ensure accuracy of SLEEP intervals, the BASIC Stamp periodically
+compares the watchdog timer to the more-accurate resonator time base. It calculates
+a correction factor that it uses during SLEEP. As a result, longer
+SLEEP intervals are accurate to approximately ±1 percent.
+
During execution of power conserving commands (END, NAP, POLLWAIT, and SLEEP), current will occasionally be interrupted
+on I/O pins for about 18 ms durations (60 µs on the BS2pe). The reason is that the
+watchdog-timer reset that awakens the BASIC Stamp during these commands also causes all of the pins to
+switch to input mode for approximately 18 ms (60 µs on the BS2pe). When the interpreter
+firmware regains control of the processor, it restores the I/O direction dictated
+by your program.
+
If you plan to use END, NAP, POLLWAIT, or SLEEP in your programs,
+make sure that your loads can tolerate these power outages. The simplest solution
+is often to connect resistors high or low (to +5V or ground) as appropriate to
+ensure a continuing supply of current during the reset.
+
The SLEEP Example can be used to demonstrate the
+effects of this reset with an LED and resistor.
Generate square-wave tones for a specified duration.
+
+
+
+
Pin is a variable/constant (0 - 7) that specifies the I/O pin
+ to use. This pin will be set to output mode.
+
Note is a variable/constant (0 - 255) specifying the type and
+ frequency of the tone. 1 - 127 are ascending tones and 128 - 255 are ascending
+ white noises ranging from buzzing (128) to hissing (255).
+
Duration is a variable/constant (1 - 255) specifying the amount
+ of time to generate the tone(s). The unit of time for Duration is 12
+ ms.
SOUND generates one of 255 square-wave frequencies on an I/O pin. The output
+pin should be connected as shown in the circuits below.
+
The tones produced by SOUND can vary in frequency from 94.8 Hz (1) to
+10,550 Hz (127). If you need to determine the frequency corresponding to a given
+note value, or need to find the note value that will give you best approximation
+for a given frequency, use the equations below.
STOP prevents the BASIC Stamp from executing any further instructions
+until it is reset. The following actions will reset the BASIC Stamp:
+
+
Pressing and releasing the RESET button on the development board.
+
Driving the RES pin low then letting it float (high).
+
Downloading a new program.
+
Disconnecting then reconnecting the power.
+
+
STOP differs from END in two respects:
+
+
STOP does not put the BASIC Stamp into low-power mode. The BASIC
+ Stamp draws just as much current as if it were actively running program
+ instructions.
+
The output glitch that occurs after a program has been halted with END does not occur after a program that uses STOP.
Designate a program slot for the READ and WRITE instructions to
+operate upon.
+
+
+
+
ProgramSlot is a variable/constant/expression (BS2p and
+ BS2px: 0 – 7, BS2pe: 0 - 15) that specifies the program slot†to use for READ and WRITE instructions.
+
+
† Note: On the BS2pe, slots 8 - 15 are only available
+for data (READ and WRITE); they cannot be used to run programs.
+
+
STORE tells the BS2p, BS2pe, or BS2px which program slot to use
+when a READ or WRITE instruction is executed. The STORE command
+only affects the READ and WRITE instructions.
+
The STORE command allows a program to access all EEPROM locations that
+exist on the BS2p, BS2pe, and BS2px, regardless of which program is running or which
+program slot is active. The READ and WRITE commands can only access
+locations 0 to 2047 within a single program slot. The STORE command
+switches the program slot that the READ and WRITE commands operate
+on. This short subroutine demonstrates the use of STORE:
+Move_Block:
+ FOR idx = 0 TO (blockLen - 1) ' move blockLen bytes
+ STORE srcSlot ' point to source slot
+ READ srcAddr + idx, eeByte ' read source byte
+ STORE tgtSlot ' point to target slot
+ WRITE tgtAddr + idx, eeByte ' write byte to target slot
+ NEXT
+ RETURN
+
+
The default program slot that the READ and WRITE instructions
+operate on is the currently running program. The STORE command can be used
+to temporarily change this, to any program slot. The change will remain in effect
+until another STORE command is issued, or until another program slot is
+executed. The current slot used by READ and WRITE (as set by
+STORE) can be read from byte 127 of the Scratchpad RAM. Example:
+ #SELECT $STAMP
+ #CASE BS2
+ pgmSlot = 0 ' everything in slot 0
+ rwSlot = 0
+ #CASE BS2E, BS2SX
+ GET 63, pgmSlot ' read current slot
+ rwSlot = pgmSlot ' READ/WRITE slot is same
+ #CASE BS2P, BS2PE, BS2PX
+ GET 127, pgmSlot ' get slot control byte
+ rwSlot = rwSlot.HIGHNIB ' READ/WRITE in high nibble
+ pgmSlot = pgmSlot.LOWNIB ' pgm slot in low nibble
+ #ENDSELECT
+
TOGGLE sets a pin to output mode and inverts the output state of the pin,
+changing 0 to 1 and 1 to 0.
+
In some situations TOGGLE may appear to have no effect on a pin's state.
+For example, suppose pin 2 is in input mode and pulled to +5V by a 10 kΩ
+resistor. Then the following code executes:
+
+
+
+
+Main:
+ DIR2 = 0 ' pin 2 in input mode
+ PIN2 = 0 ' pin 2 output driver low
+ DEBUG PIN2 ' show state of pin 2
+ TOGGLE 2 ' toggle pin 2
+ DEBUG PIN2 ' show state of pin 2
+ END
+
+
+
+
+
+Main:
+ DIR2 = 0 ' pin 2 in input mode
+ OUT2 = 0 ' pin 2 output driver low
+ DEBUG ? IN2 ' show state of pin 2
+ TOGGLE 2 ' toggle pin 2
+ DEBUG ? IN2 ' show state of pin 2
+ END
+
+
The state of pin 2 doesn't change; it's high (due to the pull-up resistor)
+before TOGGLE, and it's high (due to the pin being output high) afterward.
+The point is that TOGGLE works on the OUTS register, which may not match
+the pin's state when the pin is initially an input. To guarantee that the state
+actually changes, regardless of the initial input or output mode, do this:
+
+
+
+
+ PIN2 = PIN2 ' make output driver match pin state
+ TOGGLE 2 ' then toggle
+
+
+
+
+
+ OUT2 = IN2 ' make output driver match pin state
+ TOGGLE 2 ' then toggle
+
Write Value into Location in EEPROM. On the BS2 family, multiple
+Value may be written to consecutive locations.‡
+
+
+
+
Location is a variable/constant/expression* (0 - 255 on BS1,
+ 0 - 2047 on all other BASIC Stamp modules) that specifies the EEPROM address to
+ write to.
+
Value is a variable/constant/expression* (0 - 255, or 0 - 65535 if using the optional Word modifier‡) specifying the
+ value to be stored.
+
+
* Note: expressions are not allowed as arguments on the BS1.
+
‡Note: The optional arguments require PBASIC 2.5.
+
Quick Facts
+
+
+
+
+
+
+
+
+
BS1
+
BS2
+
BS2e and BS2sx
+
BS2p, BS2pe, and BS2px
+
+
+
Range of EEPROM locations
+
0 to 255
+
0 to 2047
+
0 to 2047
+
0 to 2047 (see notes below)
+
+
+
Maximum number of writes per location
+
10 million
+
10 million
+
100,000
+
100,000
+
+
+
Special Notes
+
N/A
+
N/A
+
WRITE only works with current program slot on BS2e
+ and BS2sx.
+
WRITE works with any program slot as set by the
+ STORE command.
Multiple sequential variables may be writtten to the Scratch Pad RAM, and the optional WORD modifier may be specified to store 16-bit values.
+
+
+
Explanation
+
The EEPROM is used for both program storage (which builds downward from address
+255 on BS1, 2047 on all other BASIC Stamp models) and data storage (which builds upward
+from address 0). The WRITE instruction stores a value to any EEPROM
+address. Any location within the EEPROM can be written to (including your PBASIC
+program's locations) at run-time. This feature is mainly used to store long-term
+data to EEPROM; data stored in EEPROM is not lost when the power is removed.
+
The following WRITE command stores the value 245 at location 100:
+ WRITE 100, 245
+
+
The EEPROM is organized as a sequential set of byte-sized memory locations.
+With the BS1, the WRITE instruction only stores byte-sized values into
+EEPROM. This does not mean that you can't write word-sized values, however.
+A word consists of two bytes, called a low-byte and a high-byte. If you wanted
+to write a word-sized value, you'll need to use two WRITE commands and a
+word-size value or variable (along with some handy modifiers). For example:
+
+
+
+
+SYMBOL value = W1 ' word-sized variable
+SYMBOL valLo = B2 ' B2 is the low-byte of W1
+SYMBOL valHi = B3 ' B3 is the high-byte of W1
+
+Main:
+ value = 1125
+
+ WRITE 0, valLo
+ WRITE 1, valHi
+ END
+
+
+
+
+
+value VAR Word
+
+Main:
+ value = 1125
+ WRITE 0, value.LowByte
+ WRITE 1, value.HighByte
+ END
+
+
When this program runs, the two WRITE commands will store the low-byte
+and high-byte of the number 1125 into EEPROM.
+
With the BS2 family, the Word modifier can be used to write 16-bit values.
+The low byte of the value will be written to Location, the high byte will
+be written to Location + 1 ("Little Endian" ).
+
+
+
+
+' {$PBASIC 2.5}
+
+value VAR Word
+value2 VAR Word
+addr VAR Word ' EEPROM address
+test VAR Byte ' test byte read back
+
+Main:
+ value = $1125
+ value2 = $2003
+ WRITE 0, Word value, Word value2 ' write value at locations 0 & 1
+ ' and value2 at locations 2 & 3
+
+ FOR addr = 0 TO 3 ' display "25 11 03 20"
+ READ addr, test
+ DEBUG HEX2 test, " "
+ NEXT
+
+ END
+
+
EEPROM differs from RAM, the memory in which variables are stored, in several
+respects:
+
+
Writing to EEPROM takes more time than storing a value in a variable.
+ Depending on many factors, it may take several milliseconds for the EEPROM to
+ complete a write. RAM storage is nearly instantaneous.
+
The EEPROM can only accept a finite number of write cycles per location
+ before it wears out. The table above indicates the guaranteed number of writes
+ before failure. If a program frequently writes to the same EEPROM location,
+ it makes sense to estimate how long it might take to exceed the guaranteed
+ maximum. For example, on the BS2, at one write per second (86,400 writes/day)
+ it would take nearly 116 days of continuous operation to exceed 10 million.
+
The primary function of the EEPROM is to store programs (data is stored in
+ leftover space). If data overwrites a portion of your program, the program
+ will most likely crash.
+
+
Check the program's memory map to determine what portion of memory your program
+occupies and make sure that EEPROM writes cannot stray into this area. You may also
+use the DATA directive on the BS2, BS2e, BS2sx, BS2p, and BS2pe to set aside EEPROM
+space.
+
+
+
+
+
On the BS1, location 255 holds the address of the last instruction in your
+program. Therefore, your program can use any space below the address given in
+location 255. For example, if location 255 holds the value 100, then your program
+can use locations 0-99 for data.
+
+
+
+
+
On other BASIC Stamp models, you'll need to view the Memory Map of the program before
+you download it, to determine the last EEPROM location used.
+
+
+
+
+
On the BS2p, BS2pe and BS2px the READ and WRITE commands can
+affect locations in any program slot as set by the STORE command. See the STORE command for more information.
Send an X-10 power-line control command (through the appropriate power-line interface).
+
+
+
+
Mpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin to output X-10 signals (modulation) to the power-line interface
+ device. This pin will be set to output mode.
+
Zpin is a variable/constant/expression (0 - 15) that specifies
+ the I/O pin that inputs the zero-crossing signal from the power-line interface
+ device. This pin will be set to input mode.
+
House is a variable/constant/expression (0 - 15) that specifies
+ the X-10 house code (values 0 - 15 representing letters A through P).
+
Command is a variable/constant/expression (0 - 30) that specifies
+ the command to send. Values 0 - 15 correspond to unit codes 1 - 16. Other
+ commands are shown below.
+
Cyclesis an optional variable/constant/expression (1 - 255)
+ specifying the number of times to transmit a given key or command. If no
+ I>Cycles entry is used, XOUT defaults to two. The Cycles entry
+ should be used only with the DIM and BRIGHT command codes.
+
+
Quick Facts
+
+
+
+
All BS2 Models
+
+
+
Compatible power-line interfaces
+
PL-513 and TW-523
+
+
+
Special Notes
+
The XOUT command will stop the BASIC Stamp program
+ until it is able to send the transmission. If there is no AC power to the
+ power-line interface, the BASIC Stamp program will halt forever.
+
+
+
Explanation
+
XOUT lets you control appliances via signals sent through household AC wiring
+to X-10 modules. The appliances plugged into these modules can be switched on or
+off; lights may also be dimmed. Each module is assigned a house code and unit code
+by setting dials or switches on the module. To talk to a particular module,
+XOUT sends the appropriate house code and unit code. The module with the
+corresponding code listens for its house code again followed by a command (on,
+off, dim, or bright).
+
X-10 signals are digital codes imposed on a 120 kHz carrier that is transmitted
+during zero crossings of the AC line. To send X-10 commands, a controller must
+synchronize to the AC line frequency with 50 ms precision, and transmit an 11-bit
+code sequence representing the command.
+
XOUT interfaces to the AC power-line through an approved interface device
+such as a PL-513 or TW-523, available from Parallax or X-10 dealers. The hookup
+requires a length of four-conductor phone cable and a standard modular phone-base
+connector (6P4C type). Connections are shown below.
+
+
+
+
+
+
+
Command
+
Value
+
Function
+
+
+
UnitOn
+
%10010
+
Turn on the currently selected unit.
+
+
+
UnitOff
+
%11010
+
Turn off the currently selected unit.
+
+
+
UnitsOff
+
%11100
+
Turn off all modules in this house code.
+
+
+
LightsOn
+
%10100
+
Turn on all lamp modules in this house code.
+
+
+
Dim
+
%11110
+
Reduce brightness of currently selected lamp.
+
+
+
Bright
+
%10110
+
Increase brightness of currently selected lamp.
+
+
+
+
Tip: In most applications, it's not necessary to know the code for a
+given X-10 instruction. Just use the command constant (UnitOn, Dim, etc.) instead.
+But knowing the codes leads to some interesting possibilities. For example, XORing
+a UnitOn command with the value %1000 turns it into a UnitOff command, and vice-versa.
+This makes it possible to write the equivalent of an X-10 "toggle" instruction.
+
Here is an example of the XOUT instruction:
+Mpin PIN 1 ' modulation pin
+Zpin PIN 0 ' zero-cross input
+
+HouseA CON 0 ' House code A = 0
+Unit1 CON 0 ' Unit code 1 = 0
+
+Main:
+ XOUT Mpin, Zpin, [HouseA\Unit1] ' Get unit 1's attention..
+ XOUT Mpin, Zpin, [HouseA\UnitOn] ' ..and tell it to turn on
+ END
+
+
You can combine those two XOUT instructions into one like so:
Note that to complete the attention-getting code HouseA\Unit1 we tacked on the
+normally optional cycles entry \2 to complete the command before beginning the next
+one. Always specify two cycles in multiple commands unless you're adjusting the
+brightness of a lamp module.
+
Here is an example of a lamp-dimming instruction:
+Mpin PIN 1 ' modulation pin
+Zpin PIN 0 ' zero-cross input
+
+HouseA CON 0 ' House code A = 0
+Unit1 CON 0 ' Unit code 1 = 0
+
+Main:
+ ' Get unit 1's attention
+ XOUT Mpin, Zpin, [HouseA\Unit1]
+ ' Dim halfway
+ XOUT Mpin, Zpin, [HouseA\UnitOff\2, HouseA\Dim\10]
+ END
+
+
The dim/bright commands support 19 brightness levels. Lamp modules may also be
+turned on and off using the standard UnitOn and UnitOff commands. In the example
+instruction above, we dimmed the lamp by first turning it completely off, then
+sending 10 cycles of the Dim command. This may seem odd, but it follows the
+peculiar logic of the X-10 system.
Note: This program was written for the BS2p but can also run on the BS2pe or BS2px with a change of the $STAMP directive, however, its effects can only be seen on the BS2p40.
+' AUX_MAIN_TERM.BSP
+' This program demonstrates the use of the AUXIO, MAINIO AND IOTERM
+' commands to affect I/O pins in the auxiliary and main I/O groups.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2SX
+ #ERROR "Program requires BS2p40"
+ #CASE BS2P, BS2PE, BS2PX
+ DEBUG "Note: This program designed for the BS2p40", CR
+#ENDSELECT
+
+port VAR Bit
+
+
+Main:
+ DO
+ MAINIO ' Switch to main I/O pins
+ TOGGLE 0 ' Toggle state of I/O pin P0
+ PWM 1, 100, 40 ' Generate PWM on I/O pin P1
+
+ AUXIO ' Switch to auxiliary I/O pins
+ TOGGLE 0 ' Toggle state of I/O pin P0
+ PULSOUT 1, 1000 ' Generate a pulse on I/O pin P1
+ PWM 2, 100, 40 ' Generate PWM on I/O pin P2
+
+ IOTERM port ' Switch to main or aux I/Os
+ ' -- depending on port
+ TOGGLE 3 ' Toggle state of I/O pin P3
+ ' -- on main and aux, alternately
+ port = ~port ' Invert port
+ PAUSE 1000 ' 1 second delay
+ LOOP
+ END
' BUTTON.BS1
+' Connect an active-low circuit to pin P0 of the BS1. When you press the
+' button, the DEBUG screen will display an asterisk (*). The program, as
+' shown below, will print an asterisk at the first button press, then
+' delay approximately one second (200 x 5 ms PAUSE) before auto-repeating
+' at a rate of approximately 100 ms (5 x 20 ms). Feel free to modify the
+' program to see the effects of your changes on the way BUTTON responds.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL Btn = 0
+
+SYMBOL btnWrk = B2
+
+
+Main:
+ ' Try changing the Delay value (255) in BUTTON to see the effect of
+ ' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat;
+ ' 255 = no auto-repeat (only one action per button press)
+ '
+ ' The BUTTON instruction will cause the program to branch to
+ ' No_Press unless P0 = 0
+
+ PAUSE 5
+ BUTTON Btn, 0, 200, 20, btnWrk, 0, No_Press
+ DEBUG "*"
+
+No_Press:
+ GOTO Main
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' BUTTON.BS2
+' Connect an active-low circuit to pin P0 of the BS2. When you press the
+' button, the DEBUG screen will display an asterisk (*). The program, as
+' shown below, will print an asterisk at the first button press, then
+' delay approximately one second (200 x 5 ms PAUSE) before auto-repeating
+' at a rate of approximately 100 ms (5 x 20 ms). Feel free to modify the
+' program to see the effects of your changes on the way BUTTON responds.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Btn PIN 0
+
+btnWrk VAR Byte
+
+
+Main:
+ ' Try changing the Delay value (255) in BUTTON to see the effect of
+ ' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat;
+ ' 255 = no auto-repeat (only one action per button press)
+ '
+ ' The BUTTON instruction will cause the program to branch to
+ ' No_Press unless P0 = 0
+
+ PAUSE 5
+ BUTTON Btn, 0, 200, 20, btnWrk, 0, No_Press
+ DEBUG "*"
+
+No_Press:
+ GOTO Main
+
' COMPARE.BPX
+' This example demonstrates the use of the COMPARE command.
+' Connect two variable voltage sources (0 to 5 volts) on I/O pins
+' P1 and P2 (or a button on each pin connected to ground). Run the
+' program and watch the Debug Terminal display as you adjust the
+' variable voltage or press the buttons.
+
+' {$STAMP BS2px}
+' {$PBASIC 2.5}
+
+#IF $STAMP <> BS2PX #THEN
+ #ERROR "This program requires a BS2px."
+#ENDIF
+
+result VAR Bit
+
+Setup:
+ ' P0 = output, all others = input
+ CONFIGPIN DIRECTION, %0000000000000001
+ ' Enable pull-ups on P1 and P2
+ CONFIGPIN PULLUP, %0000000000000110
+
+ DEBUG CLS,
+ "BS2px Comparator Demonstration", CR,
+ "==============================", CR,
+ CR,
+ "Input Voltage: P1 > P2", CR,
+ "Output State: P0 = 0"
+
+Main:
+ DO ' Display P1/P2 comparison
+ COMPARE 1, result
+ IF (result = 0) THEN
+ DEBUG CRSRXY, 18, 3, ">"
+ ELSE
+ DEBUG CRSRXY, 18, 3, "<"
+ ENDIF
+ DEBUG CRSRXY, 19, 4, BIN1 result
+ LOOP
' CONFIGPIN.BPX
+' This example demonstrates the use of the CONFIGPIN command.
+' All I/O pins are set to inputs with various combinations of
+' Pull-Up Resistor, Logic Threshold and Schmitt-Trigger properties.
+' While running, this program will constantly display the state of all
+' input pins along with an indication of the configuration for each group
+' of pins. Try connecting different input signals to the I/O pins (such as
+' buttons, a function generator with a slowing sweeping signal (0 to 5
+' VDC)) or simply running your fingers across the I/O pins and note how
+' they react based upon their configured property.
+
+' {$STAMP BS2px}
+' {$PBASIC 2.5}
+
+#IF $STAMP <> BS2PX #THEN
+ #ERROR "This program requires a BS2px."
+#ENDIF
+
+
+Setup:
+ CONFIGPIN DIRECTION, %0000000000000000 ' Set all I/O pins to inputs
+ CONFIGPIN PULLUP, %1111111111110000 ' Enable pull-ups on pins 4 - 15
+ CONFIGPIN THRESHOLD, %0000111100000000 ' Set P8-P11 to CMOS, others TTL
+ CONFIGPIN SCHMITT, %1111000000000000 ' Enable Schmitt-Triggers P12-P15
+
+ DEBUG CLS,
+ " BS2px INPUT PIN CONFIGURATION TEST", CR,
+ "=========================================================", CR,
+ " P15-P12: Pull-Up Resistors, TTL & Schmitt-Triggers ", CR,
+ " / ", CR,
+ " / P11-P8: Pull-Up Resistors & CMOS ", CR,
+ " / / ", CR,
+ " | / P7-P4: Pull-Up Resistors & TTL ", CR,
+ " | | / ", CR,
+ " | | | P3-P0: Normal ", CR,
+ " | | | / ", CR,
+ " | | | | ", CR,
+ "---- ---- ---- ---- "
+Main:
+ DO
+ ' Display input pin states
+ DEBUG CRSRXY, 0, 12 ,
+ BIN4 IND, " ", BIN4 INC, " ", BIN4 INB, " ", BIN4 INA
+ LOOP
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' COUNT.BS2
+' Connect an active-low button circuit shown to pin P0 of the BS2. The
+' DEBUG screen will prompt you to press the button as quickly as possible
+' for a 1-second count. When the count is done, the screen will display
+' your "score," the total number of cycles registered by COUNT. Note that
+' this score will almost always be greater than the actual number of presses
+' because of switch contact bounce.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+PushBtn PIN 0 ' pushbutton on P0
+
+#SELECT $STAMP
+ #CASE BS2, BS2E
+ DurAdj CON $100 ' / 1
+ #CASE BS2SX
+ DurAdj CON $280 ' / 0.400
+ #CASE BS2P, BS2PX
+ OneSec CON $37B ' / 0.287
+ #CASE BS2PE
+ OneSec CON $163 ' / 0.720
+#ENDSELECT
+
+Capture CON 1000 ' 1 second
+
+cycles VAR Word ' counted cycles
+
+
+Main:
+ DO
+ DEBUG CLS,
+ "How many times can you press the button in 1 second?", CR
+ PAUSE 1000
+ DEBUG "Ready, set... "
+ PAUSE 500
+ DEBUG "GO!", CR
+ COUNT PushBtn, (Capture */ DurAdj), cycles
+ DEBUG CR, "Your score: ", DEC cycles, CR
+ PAUSE 3000
+ DEBUG "Press button to go again."
+ DO : LOOP UNTIL (PushBtn = 0) ' wait for button press
+ LOOP
+ END
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' DATA.BS2
+' This program stores a number of large text strings into EEPROM with the
+' DATA directive and then sends them, one character at a time via the DEBUG
+' command. This is a good demonstration of how to save program space by
+' storing large amounts of data in EEPROM directly, rather than embedding
+' the data into DEBUG commands.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+idx VAR Word ' current location number
+phrase VAR Nib ' current phrase number
+char VAR Byte ' character to print
+
+' ----- Define all text phrases (out of order, just for fun!) -----
+'
+Text1 DATA "Here is the first part of a large chunk of textual "
+ DATA "data ", CR, "that needs to be transmitted. There's "
+ DATA "a 5 second delay", CR, "between text paragraphs. ", CR
+ DATA CR, 0
+
+Text3 DATA "The alternative (having multiple DEBUGs or SEROUTs, "
+ DATA "each ", CR, "with their own line of text) consumes "
+ DATA "MUCH more EEPROM ", CR, "(program) space. ", CR
+ DATA CR, 0
+
+Text6 DATA "The 255 is used by this program to indicate we've "
+ DATA "reached the ", CR, "End of Text. The Main routine "
+ DATA "pauses in between each block of ", CR, "text, and then "
+ DATA "uses a LOOKUP command TO retrieve the location ", CR
+ DATA "of the next desired block of text to print. ", 0
+
+Text4 DATA CLS, "This program also demonstrates retrieving data "
+ DATA "out of order ", CR, "in relation TO the way it is "
+ DATA "stored in EEPROM. Additionally, ", CR, "control codes "
+ DATA "(like carriage-returns, clear-screens, etc) can ", CR
+ DATA "be embedded right in the data, as it is here. ", CR
+ DATA CR, 0
+
+Text2 DATA "This is an example of a good way to save space in "
+ DATA "your ", CR, "BASIC Stamp's program by storing data "
+ DATA "into EEPROM and ", CR, "retrieving it, one byte at a "
+ DATA "time, and transmitting it ", CR, "with just a single "
+ DATA "DEBUG (or SEROUT) command.", CR, CR, 0
+
+Text5 DATA "The Print_It routine simply takes the Index variable, "
+ DATA "retrieves ", CR, "the character at the EEPROM location "
+ DATA "pointed to by it, and ", CR, "prints it to the screen "
+ DATA "unti it finds a byte with a value of 255.", CR, CR, 0
+
+
+Main:
+ DEBUG CLS ' Clear DEBUG window
+ FOR phrase = 1 TO 6 ' Print blocks one by one
+ LOOKUP (phrase - 1),
+ [Text1, Text2, Text3, Text4, Text5, Text6], idx
+ GOSUB Print_It
+ PAUSE 5000 ' Pause for 5 seconds
+ NEXT
+ END
+
+Print_It:
+ DO
+ READ idx, char ' Get next character
+ idx = idx + 1 ' Point to next location
+ IF (char = 0) THEN EXIT ' If 0, we're done with block
+ DEBUG char ' Otherwise, transmit it
+ LOOP
+ RETURN ' Return to the main routine
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' DEBUG_DEBUGIN.BS2
+' This program demonstrates the ability to accept user input from the
+' Debug Terminal, and to accept numeric entry in any valid format.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+myNum VAR Word
+
+
+Main:
+ DO
+ DEBUG CLS, "Enter any number: " ' prompt user
+ DEBUGIN SNUM myNum ' accept number in any format
+
+ DEBUG CRSRXY, 0, 2, ' display in all formats
+ SDEC ? myNum,
+ SHEX ? myNum,
+ SBIN ? myNum
+ PAUSE 3000
+ LOOP ' do it again
+ END
+
' DEBUG.BAS
+' Demonstrates the use of the BS1 DEBUG instruction. The BS1 DEBUG defaults
+' to decimal output and provides the name of the variable unless directed
+' otherwise.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL addr = B2 ' EEPROM address
+SYMBOL char = B3 ' character to print
+
+Messages:
+ EEPROM ("The Parallax BASIC Stamp 1", 13, 0)
+
+
+Main:
+ char = "A"
+
+ DEBUG CLS ' clear screen
+ DEBUG char, CR ' standard decimal output
+ DEBUG $char, CR ' hex ($)
+ DEBUG %char, CR ' binary (%)
+ DEBUG #char, CR ' value only (#)
+ DEBUG "Your grade is: " ' string
+ DEBUG #@char, CR, CR ' value only, as ASCII (@)
+
+ addr = 0 ' point to message
+ GOSUB Print_It
+ DEBUG "The Parallax BASIC Stamp 1" ' same message -- fast
+
+ END
+
+' This subroutine can be used to transmit a string stored in EEPROM to
+' the DEBUG window. Note that this is very SLOW as for each character the
+' entire DEBUG packet (97 bytes!) must be transmitted -- which means that
+' you can transmit about five characters per second with this method.
+'
+' A better alternative to this subroutine is to BRANCH to DEBUG statements
+' containing the entire string.
+
+Print_It:
+ READ addr, char ' get character from EEPROM
+ addr = addr + 1 ' point to next location
+ IF char = 0 THEN Print_Done ' if 0, terminate printing
+ DEBUG #@char ' character to DEBUG window
+ GOTO Print_It ' loop again
+
+Print_Done:
+ RETURN
+
+
+
This next demonstration illustrates sending information to and retrieving information from the Debug Terminal window. Also illustrated is the unique ability to accept any valid numeric format using the NUM modifier. To enter binary or hexadecimal values, the number must be preceded by "%" (binary) or "$" (hex).
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' DEBUG_DEBUGIN.BS2
+' This program demonstrates the ability to accept user input from the
+' Debug Terminal, and to accept numeric entry in any valid format.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+myNum VAR Word
+
+
+Main:
+ DO
+ DEBUG CLS, "Enter a any number: " ' prompt user
+ DEBUGIN SNUM myNum ' accept number in any format
+
+ DEBUG CRSRXY, 0, 2, ' display in all formats
+ SDEC ? myNum,
+ SHEX ? myNum,
+ SBIN ? myNum
+ PAUSE 3000
+ LOOP ' do it again
+ END
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' DO-LOOP.BS2
+' This program creates a little guessing game. It starts by creating
+' a (psuedo) random number between 1 and 10. The inner loop will run
+' until the answer is guessed or 10 tries have been attempted. The
+' outer loop has no condition and will cause the inner loop code to
+' run until the BASIC Stamp is reprogrammed.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+rVal VAR Word ' random value
+answer VAR Byte ' game answer
+guess VAR Byte ' player guess
+tries VAR Nib ' number of tries
+
+
+Main:
+ DO
+ RANDOM rVal
+ answer = rVal.LOWBYTE */ 10 + 1 ' create 1 - 10 answer
+ tries = 0
+
+ DO ' get answer until out of tries
+ DEBUG CLS,
+ "Guess an number (1 - 10): ",
+ CLREOL
+ DEBUGIN DEC guess ' get new guess
+ tries = tries + 1 ' update tries count
+ LOOP UNTIL ((tries = 10) OR (guess = answer))
+
+ IF (guess = answer) THEN ' test reason for loop end
+ DEBUG CR, "You got it!"
+ ELSE
+ DEBUG CR, "Sorry ... the answer was ", DEC answer, "."
+ ENDIF
+ PAUSE 1000
+ LOOP ' run again
+ END
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
DTMFOUT.BS2
+' This demo program is a rudimentary memory dialer. Since DTMF digits fit
+' within a nibble (four bits), the program below packs two DTMF digits into
+' each byte of three EEPROM data tables. The end of a phone number is marked
+' by the nibble $F, since this is not a valid phone-dialing digit.
+' Conditional compilation sets the timing adjustment factor so that the
+' output will sound the same on any BS2 module.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Spkr PIN 10 ' DTMF output on pin 10
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ TmAdj CON $100 ' x 1.0 (time adjust)
+ #CASE BS2SX
+ TmAdj CON $280 ' x 2.5
+ #CASE BS2P
+ TmAdj CON $3C5 ' x 3.77
+ #CASE BS2PX
+ TmAdj CON $605 ' x 6.02
+#ENDSELECT
+
+eeLoc VAR Byte ' EEPROM address of stored number
+eeByte VAR Byte ' Byte containing two DTMF digits
+dtDig VAR eeByte.NIB1 ' Digit to dial
+phone VAR Nib ' Pick a phone #
+hiLo VAR Bit ' Bit to select upper and lower nib
+
+Parallax DATA $19,$16,$62,$48,$33,$3F ' Phone: 1-916-624-8333
+ParallaxFax DATA $19,$16,$62,$48,$00,$3F ' Phone: 1-916-624-8003
+Information DATA $15,$20,$55,$51,$21,$2F ' Phone: 1-520-555-1212
+
+
+Main:
+ FOR phone = 0 TO 2
+ ' retrieve address
+ LOOKUP phone, [Parallax, ParallaxFax, Information], eeLoc
+ GOSUB Dial_Number
+ PAUSE 2000
+ NEXT
+ END
+
+Dial_Number:
+ DO
+ READ eeLoc, eeByte ' Retrieve byte from EEPROM
+ eeLoc = eeLoc + 1 ' point to next pair of digits
+ FOR hiLo = 0 TO 1 ' Dial upper and lower digits
+ IF (dtDig = $F) THEN EXIT ' Hex $F is end-of-number flag
+ DTMFOUT Spkr, ' dial digit
+ 150 */ TmAdj, 25, [dtDig] ' 150 ms on, 25 ms off
+ eeByte = eeByte << 4 ' Shift in next digit
+ NEXT
+ LOOP UNTIL (dtDig = $F)
+ RETURN
+
' EEPROM.BS1
+' This program stores a couple of text strings into EEPROM with the EEPROM
+' directive and then sends them, one character at a time via the SEROUT
+' command. This is a good demonstration of how to save program space by
+' storing large amounts of data in EEPROM directly, rather than embedding
+' the data into SEROUT commands.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL SOut = 0 ' serial output
+
+SYMBOL idx = B2 ' Holds current location number
+SYMBOL phrase = B3
+SYMBOL char = B4 ' Holds current character to print
+
+Phrases:
+ EEPROM ("Here is a long message that needs to be transmitted.", 13, 0)
+ EEPROM ("Here is some more text to be transmitted.", 13, 0)
+
+
+Main:
+ idx = 0
+ FOR phrase = 1 TO 2 ' select phrase
+ GOSUB Print_It ' print the phrase
+ PAUSE 3000 ' Pause for 3 seconds
+ NEXT
+ END
+
+Print_It:
+ READ idx, char ' get next character
+ idx = idx + 1 ' point to next EEPROM location
+ IF char = 0 THEN Print_Done ' if 0, we're done with this block
+ SEROUT SOut, N2400, (char) ' otherwise, transmit it
+ 'DEBUG #@char ' -- for demo with DEBUG (slower)
+ GOTO Print_It
+
+Print_Done:
+ RETURN ' return to caller
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' EXIT.BS2
+' This program demonstrates the early termination of DO...LOOP and
+' FOR..NEXT loop structures. IF...THEN is used to test a condition
+' and when true, EXIT will terminate the loop.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+col VAR Nib
+row VAR Nib
+
+
+Setup:
+ col = 0
+
+Main:
+ DO WHILE (col < 10) ' attempt 10 iterations
+ FOR row = 0 TO 15 ' attempt 16 iterations
+ IF (row > 9) THEN EXIT ' terminate when row > 9
+ DEBUG CRSRXY, (col * 8), row, ' print col/row at location
+ DEC col, "/", DEC row, CR
+ NEXT
+ col = col + 1 ' update column
+ IF (col = 3) THEN EXIT ' terminate when col = 3
+ LOOP
+ END
+
' FOR-NEXT.BS1
+' This example uses a FOR...NEXT loop to churn out a series of sequential
+' squares (numbers 1, 2, 3, 4... raised to the second power) by using a
+' variable to set the FOR...NEXT stepValue, and incrementing stepValue within
+' the loop. Sir Isaac Newton is generally credited with the discovery of
+' this technique.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL square = B2 ' FOR/NEXT counter
+SYMBOL stepSize = B3 ' step size, increase by 2 each loop
+
+
+Setup:
+ stepSize = 1
+ square = 1
+
+Main:
+ FOR square = 1 TO 250 STEP stepSize ' show squares up to 250
+ DEBUG square ' display on screen
+ stepSize = stepSize + 2 ' add 2 to stepSize
+ NEXT ' loop until square > 250
+ END
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' FOR-NEXT.BS1
+' This example uses a FOR...NEXT loop to churn out a series of sequential
+' squares (numbers 1, 2, 3, 4... raised to the second power) by using a
+' variable to set the FOR...NEXT stepValue, and incrementing stepValue within
+' the loop. Sir Isaac Newton is generally credited with the discovery of
+' this technique.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL square = B2 ' FOR/NEXT counter
+SYMBOL stepSize = B3 ' step size, increase by 2 each loop
+
+
+Setup:
+ stepSize = 1
+ square = 1
+
+Main:
+ FOR square = 1 TO 250 STEP stepSize ' show squares up to 250
+ DEBUG square ' display on screen
+ stepSize = stepSize + 2 ' add 2 to stepSize
+ NEXT ' loop until square > 250
+ END
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' FREQOUT.BS2
+' This program demonstrates a sound-effects generation by the BASIC Stamp.
+' Conditional compilation sets timing and frequency adjustment factors so
+' that the output will sound the same on any BS2 module.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Spkr PIN 10 ' output pin for FREQOUT
+
+#SELECT $STAMP
+ #CASE BS2, BS2E
+ TmAdj CON $100 ' x 1.0 (time adjust)
+ FrAdj CON $100 ' x 1.0 (freq adjust)
+ #CASE BS2SX
+ TmAdj CON $280 ' x 2.5
+ FrAdj CON $066 ' x 0.4
+ #CASE BS2P
+ TmAdj CON $3C5 ' x 3.77
+ FrAdj CON $044 ' x 0.265
+ #CASE BS2PE
+ TmAdj CON $100 ' x 1.0
+ FrAdj CON $0A9 ' x 0.66
+ #CASE BS2PX
+ TmAdj CON $607 ' x 6.02
+ FrAdj CON $02A ' x 0.166
+#ENDSELECT
+
+
+Main:
+ DEBUG "Let's make a call...", CR
+ ' combine 350 Hz & 440 Hz for dial tone
+ FREQOUT Spkr, 2000 */ TmAdj, 350 */ FrAdj, 440 */ FrAdj
+ ' dial number (digits 150 ms on, 25 ms off)
+ DTMFOUT Spkr, 150 */ TmAdj, 25, [5, 5, 5, 1, 2, 1, 2]
+ PAUSE 500
+
+ ' bad connection (SIT sequence)
+ FREQOUT Spkr, 375 */ TmAdj, 985 */ FrAdj
+ FREQOUT Spkr, 375 */ TmAdj, 1371 */ FrAdj
+ FREQOUT Spkr, 375 */ TmAdj, 1777 */ FrAdj
+
+ DEBUG "Oops! -- try again...", CR
+ PAUSE 1000
+ DTMFOUT Spkr, 150 */ TmAdj, 25, [5, 5, 5, 2, 2, 2, 2]
+ DEBUG "Ringing"
+ FREQOUT Spkr, 2000 */ TmAdj, 440 */ FrAdj, 480 */ FrAdj
+ PAUSE 4000
+ FREQOUT Spkr, 2000 */ TmAdj, 440 */ FrAdj, 480 */ FrAdj
+ INPUT Spkr
+ DEBUG CLS, "Done."
+ END
+
NOTE: This is written for the BS2sx and will also run on the BS2e, BS2p, BS2pe, and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2p, BS2pe, or BS2px.
' GET_PUT1.BSX
+' This example demonstrates the use of the GET AND PUT commands. First,
+' slot location is read using GET to display the currently running program
+' number. Then a set of values are written (PUT) into locations 0 TO 9.
+' Afterwards, program number 1 is RUN. This program is a BS2SX project
+' consisting of GET_PUT1.BSX and GET_PUT2.BSX, but will run on the BS2e,
+' BS2p, BS2pe, and BS2px without modification.
+
+' {$STAMP BS2sx, GET_PUT2.BSX}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2
+ #ERROR "BS2e or greater required."
+ #CASE BS2E, BS2SX
+ Slot CON 63
+ #CASE BS2P, BS2PE, BS2PX
+ Slot CON 127
+#ENDSELECT
+
+value VAR Byte
+idx VAR Byte
+
+
+Setup:
+ GET Slot, value
+ DEBUG "Program Slot #", DEC value.NIB0, CR
+
+Main:
+ FOR idx = 0 TO 9
+ value = (idx + 3) * 8
+ PUT idx, value
+ DEBUG " Writing: ", DEC2 value, " to location: ", DEC2 idx, CR
+ NEXT
+ DEBUG CR
+ RUN 1
+ END
+
+
' GET_PUT2.BSX
+' This example demonstrates the use of the GET and PUT commands. First,
+' the Slot location is read using GET to display the currently running
+' program number. Then a set of values are read (GET) from locations
+' 0 to 9 and displayed on the screen for verification. This program is a
+' BS2SX project consisting of GET_PUT1.BSX and GET_PUT2.BSX, but will run
+' on the BS2e, BS2p, BS2pe, and BS2px without modification.
+
+' {$STAMP BS2sx}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2
+ #ERROR "BS2e or greater required."
+ #CASE BS2E, BS2SX
+ Slot CON 63
+ #CASE BS2P, BS2PE, BS2PX
+ Slot CON 127
+#ENDSELECT
+
+value VAR Byte
+idx VAR Byte
+
+
+Setup:
+ GET Slot, value
+ DEBUG "Program Slot #", DEC value.NIB0, CR
+
+Main:
+ FOR idx = 0 TO 9
+ GET idx, value
+ DEBUG " Reading: ", DEC2 value, " from location: ", DEC2 idx, CR
+ NEXT
+ END
+
' GOSUB.BS1
+' This program is a guessing game that generates a random number in a
+' subroutine called Pick_A_Number. It is written to stop after three
+' guesses. To see a common bug associated with GOSUB, delete or comment
+' out the line beginning with END after the FOR-NEXT loop. This means
+' that after the loop is finished, the program will wander into the
+' Pick_A_Number subroutine. When the RETURN at the end executes, the
+' program will go back to the beginning of the program. This will cause
+' the program to execute endlessly. Make sure that your programs can't
+' accidentally execute subroutines!
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL rounds = B2 ' number of reps
+SYMBOL numGen = W0 ' random number holder
+SYMBOL myNum = B3 ' random number, 1-10
+
+
+Setup:
+ numGen = 11500 ' initialize random "seed"
+
+Main:
+ FOR rounds = 1 TO 10
+ DEBUG CLS, "Pick a number from 1 to 10", CR
+ GOSUB Pick_A_Number
+ PAUSE 2000 ' dramatic pause
+ DEBUG "My number was: ", #myNum ' show the number
+ PAUSE 1000 ' another pause.
+ NEXT
+ DEBUG CLS, "Done"
+ END ' end program
+
+' Random-number subroutine. A subroutine is just a piece of code with
+' the RETURN instruction at the end. Always make sure your program enters
+' subroutines with a GOSUB. If you don't, the RETURN won't have the
+' correct address, and your program will have a bug!
+
+Pick_A_Number:
+ RANDOM numGen ' stir up the bits of NumGen.
+ DEBUG numGen, CR
+ myNum = numGen / 6550 MIN 1 ' scale to fit 1-10 range.
+ RETURN ' go back to 1st instruction
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' GOSUB.BS2
+' This program is a guessing game that generates a random number in a
+' subroutine called Pick_A_Number. It is written to stop after three
+' guesses. To see a common bug associated with GOSUB, delete or comment
+' out the line beginning with END after the FOR-NEXT loop. This means
+' that after the loop is finished, the program will wander into the
+' Pick_A_Number subroutine. When the RETURN at the end executes, the
+' program will go back to the beginning of the program. This will cause
+' the program to execute endlessly. Make sure that your programs can't
+' accidentally execute subroutines!
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+rounds VAR Byte ' number of reps
+numGen VAR Word ' random number holder
+myNum VAR Byte ' random number, 1-10
+
+
+Setup:
+ numGen = 11500 ' initialize random "seed"
+
+Main:
+ FOR rounds = 1 TO 10
+ DEBUG CLS, "Pick a number from 1 to 10", CR
+ GOSUB Pick_A_Number
+ PAUSE 2000 ' dramatic pause
+ DEBUG "My number was: ", DEC myNum ' show the number
+ PAUSE 1000 ' another pause.
+ NEXT
+ DEBUG CLS, "Done"
+ END ' end program
+
+' Random-number subroutine. A subroutine is just a piece of code with
+' the RETURN instruction at the end. Always make sure your program enters
+' subroutines with a GOSUB. If you don't, the RETURN won't have the
+' correct address, and your program will have a bug!
+
+Pick_A_Number:
+ RANDOM numGen ' stir up the bits of NumGen.
+ DEBUG DEC ? numGen
+ myNum = numGen / 6550 MIN 1 ' scale to fit 1-10 range.
+ RETURN ' go back to 1st instruction
+ ' after GOSUB that got us here
+
NOTE: This is written for the BS2 and will run on any BASIC Stamp module. Modify the $STAMP directive (as required) before downloading to the BS1, BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' GOTO.BS2
+' This program isn't practical at all, but demonstrates the use of GOTO to
+' jump around the code. This code jumps between three different routines,
+' each of which print something different on the screen. The routines are
+' out of order for this example.
+
+' {$STAMP BS2}
+
+
+Start:
+ GOTO Routine1
+
+Routine2:
+ DEBUG "We're in routine #2", CR
+ PAUSE 1000
+ GOTO Routine3
+
+Routine1:
+ DEBUG "We're in routine #1", CR
+ PAUSE 1000
+ GOTO Routine2
+
+Routine3:
+ DEBUG "We're in routine #3", CR
+ PAUSE 1000
+ GOTO Routine1
NOTE: This is written for the BS2 and will run on any BASIC Stamp module. Modify the $STAMP directive (as required) before downloading to the BS1, BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' HIGH_LOW.BS2
+' This simple program sets I/O pin 0 high for 1/2 second and low for
+' 1/2 second in an endless loop. Connect an LED to P0 for a simple
+' blinker.
+
+' {$STAMP BS2}
+
+
+Main:
+ HIGH 0
+ PAUSE 500
+ LOW 0
+ PAUSE 500
+ GOTO Main
+ END
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' I2C.BSP
+' This program demonstrates writing and reading every location in a 24LC16B
+' EEPROM using the BS2p/BS2pe.BS2px's I2C commands. Connect the BS2p, BS2pe,
+' or BS2px to the 24LC16B DIP EEPROM as shown in the diagram in the I2CIN
+' or I2COUT command description.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#IF ($STAMP < BS2P) #THEN
+ #ERROR "Program requires BS2p, BS2pe, or BS2px."
+#ENDIF
+
+SDA PIN 0 ' I2C SDA pin
+SCL PIN SDA + 1
+
+addr VAR Word ' internal address
+block VAR Nib ' block address in 24LC16
+value VAR Byte ' value to write
+check VAR Nib ' for checking retuned values
+result VAR Byte(16) ' array for returned value
+
+
+Write_To_EEPROM:
+ DEBUG "Writing...", CR
+ PAUSE 2000
+ FOR addr = 0 TO 2047 STEP 16 ' loop through all addresses
+ block = addr.NIB2 << 1 ' calculate block address
+ value = addr >> 4 ' create value from upper 8 bits
+ ' write 16 bytes
+ I2COUT SDA, $A0 | block, addr, [REP value\16]
+ PAUSE 5
+ DEBUG "Addr: ", DEC4 addr, "-", DEC4 addr + 15, " ",
+ "Value: ", DEC3 value, CR
+ NEXT
+ PAUSE 2000
+
+Read_From_EEPROM:
+ DEBUG CR, "Reading...", CR
+ PAUSE 2000
+ FOR addr = 0 TO 2047 STEP 16
+ block = addr.NIB2 << 1
+ value = addr >> 4
+ I2CIN SDA, $A1 | block, addr, [STR result\16]
+ FOR check = 0 TO 15
+ IF (result(check) <> value) THEN Error
+ NEXT
+ DEBUG "Addr: ", DEC4 addr, "-", DEC4 addr + 15, " ",
+ "Value: ", DEC3 result, CR
+ NEXT
+ PAUSE 100
+ DEBUG CR, "All locations passed"
+ END
+
+
+Error:
+ DEBUG "Error at location: ", DEC4 addr + check, CR,
+ "Found: ", DEC3 result(check), ", Expected: ", DEC3 value
+ END
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' IF-THEN-ELSE.BS2
+' The program below generates a series of 16-bit random numbers and tests
+' each to determine whether they're evenly divisible by 3. If a number is
+' evenly divisible by 3, then it is printed, otherwise, the program generates
+' another random number. The program counts how many numbers it prints, and
+' quits when this number reaches 10.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5} ' version 2.5 required
+
+sample VAR Word ' Random number to be tested
+hits VAR Nib ' Number of hits
+misses VAR Word ' Number of misses
+
+
+Setup:
+ sample = 11500
+
+Main:
+ DO
+ RANDOM sample ' Put a random number into sample
+ IF ((sample // 3) = 0) THEN ' divisible by 3?
+ DEBUG DEC5 sample, ' - yes, print value and message
+ " is divisible by 3", CR
+ hits = hits + 1 ' count hits (divisble by 3)
+ ELSE
+ misses = misses + 1 ' count misses
+ ENDIF
+ LOOP UNTIL (hits = 10) ' quit after 10 hits
+
+ DEBUG CR,
+ "All done.", CR, CR, ' display results
+ "Hits: ", DEC hits, CR,
+ "Misses: ", DEC misses, CR,
+ "Samples: ", DEC (hits + misses)
+ END
+
' IF-THEN.BS1
+' The program below generates a series of 16-bit random numbers and tests
+' each to determine whether they're evenly divisible by 3. If a number is
+' evenly divisible by 3, then it is printed, otherwise, the program generates
+' another random number. The program counts how many numbers it prints, and
+' quits when this number reaches 10.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL sample = W0 ' Random number to be tested
+SYMBOL samps = B2 ' Number of samples taken
+SYMBOL temp = B3 ' Temporary workspace
+
+
+Setup:
+ sample = 11500
+
+Mult3:
+ RANDOM sample ' Put a random number into sample
+ temp = sample // 3
+ IF temp <> 0 THEN Mult3 ' Not multiple of 3? -- try again
+ DEBUG #sample, "divides by 3", CR ' show sample divisible by 3
+ samps = samps + 1 ' Count multiples of 3
+ IF samps = 10 THEN Done ' Quit with 10 samples
+ GOTO Mult3 ' keep checking
+
+Done:
+ DEBUG CR, "All done."
+ END
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' IF-THEN.BS2
+' The program below generates a series of 16-bit random numbers and tests
+' each to determine whether they're evenly divisible by 3. If a number is
+' evenly divisible by 3, then it is printed, otherwise, the program generates
+' another random number. The program counts how many numbers it prints, and
+' quits when this number reaches 10.
+
+' {$STAMP BS2}
+' {$PBASIC 2.0}
+
+sample VAR Word ' Random number to be tested
+samps VAR Nib ' Number of samples taken
+temp VAR Nib ' Temporary workspace
+
+
+Setup:
+ sample = 11500
+
+Mult3:
+ RANDOM sample ' Put a random number into sample
+ temp = sample // 3
+ IF (temp <> 0) THEN Mult3 ' Not multiple of 3? -- try again
+ DEBUG DEC5 sample, " divides by 3", CR
+ samps = samps + 1 ' Count multiples of 3
+ IF samps = 10 THEN Done ' Quit with 10 samples
+ GOTO Mult3 ' keep checking
+
+Done:
+ DEBUG CR, "All done."
+ END
+
' INPUT_OUTPUT.BS1
+' This program demonstrates how the input/output direction of a pin is
+' determined by the corresponding bit of DIRS. It also shows that the
+' state of the pin itself (as reflected by the corresponding bit of PINS)
+' is determined by the outside world when the pin is an input, and by the
+' corresponding bit of PINS when it's an output. To set up the demo,
+' connect a 10k resistor from +5V to P7 on the BASIC Stamp. The resistor
+' to +5V puts a high (1) on the pin when it's an input. The BASIC Stamp
+' can override this state by writing a low (0) to bit 7 of OUTS and
+' changing the pin to output.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+
+Main:
+ INPUT 7 ' Make P7 an input
+ DEBUG "State of P7: ", #PIN7, CR
+
+ PIN7 = 0 ' Write 0 to output latch
+ DEBUG "After 0 written to OUT7: "
+ DEBUG #PIN7, CR
+
+ OUTPUT 7 ' Make P7 an output
+ DEBUG "After P7 changed to output: "
+ DEBUG #PIN7
+ END
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' INPUT_OUTPUT.BS2
+' This program demonstrates how the input/output direction of a pin is
+' determined by the corresponding bit of DIRS. It also shows that the
+' state of the pin itself (as reflected by the corresponding bit of PINS)
+' is determined by the outside world when the pin is an input, and by the
+' corresponding bit of PINS when it's an output. To set up the demo,
+' connect a 10k resistor from +5V to P7 on the BASIC Stamp. The resistor
+' to +5V puts a high (1) on the pin when it's an input. The BASIC Stamp
+' can override this state by writing a low (0) to bit 7 of OUTS and
+' changing the pin to output.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+
+Main:
+ INPUT 7 ' Make P7 an input
+ DEBUG "State of P7: ",
+ BIN1 IN7, CR
+
+ OUT7 = 0 ' Write 0 to output latch
+ DEBUG "After 0 written to OUT7: ",
+ BIN1 IN7, CR
+
+ OUTPUT 7 ' Make P7 an output
+ DEBUG "After P7 changed to output: ",
+ BIN1 IN7
+ END
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' LCDCMD.BSP
+' This program demonstrates initialization and printing on a 2 x 16
+' character LCD display. The set of "LCD constants", below, are provided
+' as pre-defined and useful LCD commands, though not all are actually
+' used in this program.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#IF ($STAMP < BS2P) #THEN
+ #ERROR "Program requires BS2p, BS2pe, or BS2px."
+#ENDIF
+
+Lcd PIN 0
+
+LcdCls CON $01 ' clear the LCD
+LcdHome CON $02 ' move cursor home
+LcdCrsrL CON $10 ' move cursor left
+LcdCrsrR CON $14 ' move cursor right
+LcdDispL CON $18 ' shift chars left
+LcdDispR CON $1C ' shift chars right
+LcdDDRam CON $80 ' Display Data RAM
+LcdCGRam CON $40 ' Character Generator RAM
+LcdLine1 CON $80 ' DDRAM address of line 1
+LcdLine2 CON $C0 ' DDRAM address of line 2
+
+
+Init_LCD:
+ PAUSE 1000 ' allow LCD to self-initialize first
+ LCDCMD Lcd, %00110000 ' send wakeup sequence to LCD
+ PAUSE 5 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00100000 ' set data bus to 4-bit mode
+ LCDCMD Lcd, %00101000 ' set to 2-line mode with 5x8 font
+ LCDCMD Lcd, %00001100 ' display on without cursor
+ LCDCMD Lcd, %00000110 ' auto-increment cursor
+
+Main:
+ DO
+ LCDOUT Lcd, LcdCls, ["Hello, World!"]
+ LCDOUT Lcd, LcdLine2, ["How are you?"]
+ PAUSE 3000
+ LCDCMD Lcd, LcdCls
+ PAUSE 500
+ LOOP
+ END
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' LCDIN.BSP
+' This program demonstrates initialization, printing and reading from
+' a 2 x 16 character LCD display.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#IF ($STAMP < BS2P) #THEN
+ #ERROR "Program requires BS2p, BS2pe, or BS2px."
+#ENDIF
+
+Lcd PIN 0
+
+LcdCls CON $01 ' clear the LCD
+LcdHome CON $02 ' move cursor home
+LcdCrsrL CON $10 ' move cursor left
+LcdCrsrR CON $14 ' move cursor right
+LcdDispL CON $18 ' shift chars left
+LcdDispR CON $1C ' shift chars right
+LcdDDRam CON $80 ' Display Data RAM
+LcdCGRam CON $40 ' Character Generator RAM
+LcdLine1 CON $80 ' DDRAM address of line 1
+LcdLine2 CON $C0 ' DDRAM address of line 2
+
+char VAR Byte(16)
+
+
+Init_LCD:
+ PAUSE 1000 ' allow LCD to self-initialize first
+ LCDCMD Lcd, %00110000 ' send wakeup sequence to LCD
+ PAUSE 5 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00100000 ' set data bus to 4-bit mode
+ LCDCMD Lcd, %00101000 ' set to 2-line mode with 5x8 font
+ LCDCMD Lcd, %00001100 ' display on without cursor
+ LCDCMD Lcd, %00000110 ' auto-increment cursor
+
+Main:
+ DO
+ LCDOUT Lcd, LcdCls, ["Hello!"]
+ GOSUB Read_LCD_Screen
+ PAUSE 3000
+ LCDOUT Lcd, LcdCls, ["I'm a 2x16 LCD!"]
+ GOSUB Read_LCD_Screen
+ PAUSE 3000
+ LOOP
+ END
+
+Read_LCD_Screen:
+ DEBUG "LCD now says: "
+ LCDIN Lcd, LcdLine1, [STR char\16]
+ DEBUG STR char\16, CR
+ RETURN
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' LCDOUT.BSP
+' This program demonstrates initialization and printing on a 2x16
+' character LCD display.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#IF ($STAMP < BS2P) #THEN
+ #ERROR "Program requires BS2p, BS2pe, or BS2px."
+#ENDIF
+
+Lcd PIN 0
+
+LcdCls CON $01 ' clear the LCD
+LcdHome CON $02 ' move cursor home
+LcdCrsrL CON $10 ' move cursor left
+LcdCrsrR CON $14 ' move cursor right
+LcdDispL CON $18 ' shift chars left
+LcdDispR CON $1C ' shift chars right
+LcdDDRam CON $80 ' Display Data RAM
+LcdCGRam CON $40 ' Character Generator RAM
+LcdLine1 CON $80 ' DDRAM address of line 1
+LcdLine2 CON $C0 ' DDRAM address of line 2
+
+
+Init_LCD:
+ PAUSE 1000 ' allow LCD to self-initialize first
+ LCDCMD Lcd, %00110000 ' send wakeup sequence to LCD
+ PAUSE 5 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00110000
+ PAUSE 0 ' pause required by LCD specs
+ LCDCMD Lcd, %00100000 ' set data bus to 4-bit mode
+ LCDCMD Lcd, %00101000 ' set to 2-line mode with 5x8 font
+ LCDCMD Lcd, %00001100 ' display on without cursor
+ LCDCMD Lcd, %00000110 ' auto-increment cursor
+
+ LCDOUT Lcd, LcdCGRam, ' load custom chracter map
+ [$00, $0A, $0A, $00, $11, $0E, $06, $00]
+
+Main:
+ DO
+ LCDOUT Lcd, LcdCls, ["Hello my friend."]
+ PAUSE 750
+ LCDOUT Lcd, LcdLine2, ["How are you?"]
+ PAUSE 1500
+ LCDCMD Lcd, LcdCls
+ LCDOUT Lcd, LcdLine1 + 1, ["I'm doing just"]
+ LCDOUT Lcd, LcdLine2 + 4, ["fine! ", 0]
+ PAUSE 2000
+ LOOP
+ END
+
' LOOKDOWN.BS1
+' This program uses LOOKDOWN followed by LOOKUP to map the numbers:
+' 0, 10, 50, 64, 71 and 98 to 35, 40, 58, 62, 79, and 83, respectively.
+' All other numbers are mapped to 255.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL num = W0 ' holds current number
+SYMBOL result = W1 ' holds mapped result
+
+
+Main:
+ FOR num = 0 TO 100
+ result = 255 ' default value for no match
+ LOOKDOWN num, (0, 10, 50, 64, 71, 98), result
+ LOOKUP result, (35, 40, 58, 62, 79, 83), result
+ DEBUG "Num = ", #num, "Result = ", #result, CR
+ PAUSE 100
+ NEXT
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' LOOKDOWN.BS2
+' This program uses LOOKDOWN to determine the number of decimal digits in
+' a number. Since LOOKDOWN uses a zero-indexed table, the output will be
+' the number of digits minus one, so this gets corrected in the following
+' line. Note that zero is considered a valid number and has one digit.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+aNum VAR Word ' random number
+stpSz VAR Word ' FOR-NEXT step size
+numDig VAR Nib ' digits in aNum
+
+
+Setup:
+ stpSz = 2
+
+Main:
+ FOR aNum = 0 TO 15000 STEP stpSz
+ LOOKDOWN aNum, <[0, 10, 100, 1000, 10000, 65535], numDig
+ ' right-justify output
+ DEBUG "aNum = ", REP " "\(5-numDig), DEC aNum, TAB,
+ "Digits = ", DEC numDig, CR
+ PAUSE 250
+ LOOKDOWN aNum, <[0, 10, 100, 1000, 10000, 65535], stpSz
+ LOOKUP stpSz, [2, 2, 5, 25, 250, 500, 1000], stpSz
+ NEXT
+ END
+
+
' LOOKUP.BS1
+' This program uses LOOKUP to create a Debug-window animation of a spinning
+' propeller. The animation consists of the four ASCII characters | / - \
+' which, when printed rapidly in order at a fixed location, appear to spin.
+' A little imagination helps a lot here....
+
+' {$STAMP BS1}
+' {$PBAsic 1.0}
+
+SYMBOL idx = B2
+SYMBOL frame = B3
+
+
+Spinner:
+ LOOKUP idx, ("|/-\"), frame ' lookup current frame character
+ DEBUG CLS, "Spinner: ", #@frame ' display
+ idx = idx + 1 // 4 ' update frame index (0..3)
+ GOTO Spinner ' loop forever
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' LOOKUP.BS2
+' This program uses LOOKUP to create a Debug-window animation of a spinning
+' propeller. The animation consists of the four ASCII characters | / - \
+' which, when printed rapidly in order at a fixed location, appear to spin.
+' A little imagination helps a lot here....
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+idx VAR Nib
+frame VAR Byte
+
+
+Spinner:
+ DO
+ LOOKUP idx, ["|/-\"], frame ' lookup current frame character
+ DEBUG HOME, "Spinner: ", frame ' display
+ PAUSE 150 ' pause between frames
+ idx = idx + 1 // 4 ' update frame index (0..3)
+ LOOP ' loop forever
+ END
Connect an LED and 470 Ω resistor as shown below for the demo program.
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' NAP.BS2
+' The program below lights an LED by placing a low on pin 0. This completes
+' the circuit from +5V, through the LED and resistor, to ground. During the
+' NAP interval, the LED stays lit, but blinks off for a fraction of a second.
+' This blink is caused by the NAP wakeup mechanism. During wakeup, all pins
+' briefly slip into input mode, effectively disconnecting them from loads.
+
+' {$STAMP BS2}
+
+
+Setup:
+ LOW 0 ' turn LED on
+
+Snooze:
+ NAP 4 ' nap for 288 ms
+ GOTO Snooze
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' ON-GOSUB.BS2
+' This program demonstrates a simple task manager that can be used in
+' a variety of applications. It is particularly useful in robotics and
+' industrial applications. The advantage of this design is that task
+' code modules may be called from other places in the program, including
+' other tasks, and the overal program flow is maintained.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+task VAR Nib
+
+
+Main:
+ DO
+ ON task GOSUB Task_0, Task_1, Task_2 ' run current task
+ task = task + 1 // 3 ' update task pointer
+ PAUSE 1000
+ LOOP
+ END
+
+Task_0:
+ DEBUG "Running Task 0", CR
+ RETURN
+
+Task_1:
+ DEBUG "Running Task 1", CR
+ RETURN
+
+Task_2:
+ DEBUG "Running Task 2", CR
+ RETURN
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' ON-GOTO.BS2
+' This program shows how the value of idx controls the destination of the
+' ON...GOTO instruction.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+idx VAR Byte
+
+
+Main:
+ DEBUG "idx: ", DEC idx, " "
+ ON idx GOTO Case_0, Case_1, Case_2 ' if idx = 0..2 goto label
+ DEBUG "ON..GOTO target error.", CR ' message if idx is out of range
+
+Update:
+ idx = idx + 1 // 4 ' force idx to be 0..3
+ PAUSE 1000
+ GOTO Main
+
+Case_0:
+ DEBUG "Running Case_0 routine", CR
+ GOTO Update
+
+Case_1:
+ DEBUG "Running Case_1 routine", CR
+ GOTO Update
+
+Case_2:
+ DEBUG "Running Case_2 routine", CR
+ GOTO Update
+
This program uses a Dallas Semiconductor DS1820 Digital Thermometer device connected as follows. Note that the 4.7 kΩ pull-up resistor is required for proper operation.
+
+
+
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' OWIN_OWOUT.BSP
+' This program demonstrates interfacing to a Dallas Semiconductor DS1822
+' 1-Wire Digital Thermometer chip using the BS2p's 1-Wire commands. Connect
+' the BS2p/BS2pe/BS2px to the DS1822 as shown in the diagram in the OWIN or
+' OWOUT command description. This program uses a simplified approach that
+' ignores the fractional portion of the temperature.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+DQ PIN 0 ' 1-Wire buss pin
+
+RdROM CON $33 ' read serial number
+MatchROM CON $55 ' match SN -- for multiple devices
+SkipROM CON $CC ' ignore SN -- use for one device
+CvrtTmp CON $44 ' start temperature conversion
+RdSP CON $BE ' read DS1822 scratchpad
+
+tempIn VAR Word ' raw temperature
+sign VAR tempIn.BIT11 ' 1 = negative temperature
+tLo VAR tempIn.BYTE0
+tHi VAR tempIn.BYTE1
+tSign VAR Bit ' saved sign bit
+tempC VAR Word ' final Celsius temp
+tempF VAR Word ' final Fahrenheit temp
+
+
+Main:
+ DO
+ GOSUB Get_Temperature ' read temperature from DS1822
+ DEBUG HOME, ' display
+ "DS1822", CR,
+ "------", CR,
+ SDEC tempC, " C ", CR,
+ SDEC tempF, " F "
+ PAUSE 1000
+ LOOP
+ END
+
+Get_Temperature:
+ OWOUT DQ, 1, [SkipROM, CvrtTmp] ' send convert temperatrue command
+ DO ' wait on conversion
+ PAUSE 25 ' small loop pad
+ OWIN DQ, 4, [tempIn] ' check status (bit transfer)
+ LOOP UNTIL (tempIn) ' 1 when complete
+ OWOUT DQ, 1, [SkipROM, RdSP] ' read DS1822 scratchpad
+ OWIN DQ, 2, [tLo, tHi] ' get raw temp data
+ tSign = sign ' save sign bit
+ tempC = tempIn >> 4 ' round to whole degrees
+ tempC.BYTE1 = $FF * tSign ' correct 2's compliment bits
+ tempF = (ABS tempC) * 9 / 5 ' start F conversion
+ IF (tSign) THEN ' finish F conversion
+ tempF = 32 - tempF ' C was negative
+ ELSE
+ tempF = tempF + 32 ' C was positive
+ ENDIF
+ RETURN
+
NOTE: This is written for the BS2 and will run on any BASIC Stamp module. Modify the $STAMP directive (as required) before downloading to the BS1, BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' PAUSE.BS2
+' This program demonstrates the PAUSE command's time delays. Once a second,
+' the program will put the message, "Paused..." on the screen.
+
+' {$STAMP BS2}
+
+Main:
+ DEBUG "Paused...", CR
+ PAUSE 1000
+ GOTO Main
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' POLL.BSP
+' This program demonstrates POLLIN, POLLOUT, and the use of the POLLMODE
+' instruction. Connect active-low inputs to pins 0, 1, 2, and 3. Then
+' connect an LED to pin 7. The program will print "." to the Debug
+' window until one of the alarm buttons are pressed. This will cause
+' the termination of the main loop. At this point the program will
+' save the latched bits, clear them (and the polling process), then
+' report the input(s) that triggered the alarm.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+
+FDoor PIN 0
+BDoor PIN 1
+Patio PIN 2
+Rst PIN 3
+AlarmLed PIN 7
+
+alarms VAR Byte ' alarm bits
+idx VAR Nib ' loop control
+
+
+Setup:
+ POLLIN FDoor, 0 ' define alarm inputs
+ POLLIN BDoor, 0
+ POLLIN Patio, 0
+ POLLOUT AlarmLed, 1 ' alarm indicator
+ POLLMODE 10 ' activate latched polling
+ DEBUG CLS,
+ "Alarms Activated", CR
+
+Main:
+ DO
+ DEBUG "." ' foreground activity
+ PAUSE 50
+ LOOP UNTIL (AlarmLed = 1) ' loop until LED is on
+ GET 128, alarms ' get alarm bits
+ POLLMODE 0 ' deactivate polling
+
+Report:
+ DEBUG CLS, ' alarms report
+ "Front Door : ", CR,
+ "Back Door : ", CR,
+ "Patio : ", CR
+
+ FOR idx = 0 TO 2 ' scan alarm bits
+ DEBUG CRSRXY, 13, idx ' move cursor
+ IF (alarms.LOWBIT(idx)) THEN ' report each bit status
+ DEBUG "Alarm", CR
+ ELSE
+ DEBUG "-", CR
+ ENDIF
+ NEXT
+ DEBUG CR, "Press RESET to clear..."
+ DO : LOOP UNTIL (Rst = 0) ' wait until Rst pressed
+ GOTO Setup
+ END
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' POLLRUN0.BSP
+' This program demonstrates the POLLRUN command. It is intended to be
+' downloaded to program slot 0, and the program called PROGRUN1.BSP
+' should be downloaded to program slot 1. I/O pin 0 is set to watch for
+' a low signal. Once the Main routine starts running, the program
+' continuously prints it's program slot number to the screen. If I/O
+' pin 0 goes low, the program in program slot 1 (which should be
+' POLLRUN1.BSP) is run.
+
+' {$STAMP BS2p, POLLRUN1.BSP}
+' {$PBASIC 2.5}
+
+pgmSlot VAR Byte
+
+Setup:
+ POLLIN 0, 0 ' polled-input, look for 0
+ POLLRUN 1 ' run slot 1 on polled activation
+ POLLMODE 3 ' enable polling
+
+Main:
+ GET 127, pgmSlot
+ DEBUG "Running Program #", DEC pgmSlot.LOWNIB, CR
+ GOTO Main
+ END
+
' POLLRUN1.BSP
+' This program demonstrates the POLLRUN command. It is intended to be
+' downloaded to program slot 1, and the program called PROGRUN0.BSP
+' should be downloaded to program slot 0. This program is run when
+' program 0 detects a low on I/O pin 0 via the polled commands.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+pgmSlot VAR Byte
+
+Main:
+ GET 127, pgmSlot
+ DEBUG "Running Program #", DEC pgmSlot.LOWNIB, CR
+ GOTO Main
+ END
+
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' POLLWAIT.BSP
+' This program demonstrates the POLLWAIT command. I/O pin 0 is set to
+' watch for a low signal. Once the Main routine starts running, the
+' POLLWAIT command causes the program to halt until the polled event
+' happens (I/O pin is low) then it prints a message on the PC screen.
+' It will do nothing until I/O pin is low.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+
+Setup:
+ POLLIN 0, 0 ' polled-input, look for 0
+ POLLMODE 2 ' enable polling
+
+Main:
+ POLLWAIT 8 ' Wait for polled event
+ DEBUG "I/O pin 0 is LOW!", CR ' Print message
+ GOTO Main
+
+
' POT.BS1
+' This program demonstrates the use of the POT command. Connect one side
+' of a 10K potiometer to P0. To the other side of the potentiomenter
+' connect a 0.1 uF capacitor, and then connect the second side of the
+' capacitor to Vss (ground). Before running demo program, use the
+' Run | POT Scaling dialog to determine the best Scale factor.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL PotPin = 0 ' 10K pot connected to P0
+SYMBOL Scale = 110 ' scale value for test circuit
+
+SYMBOL level = B2 ' storage of pot "level"
+
+Main:
+ POT PotPin, Scale, level ' read pot level
+ DEBUG CLS, "Level = ", #level ' display
+ PAUSE 50 ' short delay
+ GOTO Main ' repeat forever
+ END
+
+
' PULSIN.BS1
+' This program uses PULSIN to measure a pulse generated by discharging a
+' 0.1 uF capacitor through a 1K resistor. Pressing the switch generates
+' the pulse, which should ideally be approximately 120 us (12 PULSIN units
+' of 10 us) long. Variations in component values may produce results that
+' are up to 10 units off from this value. For more information on calculating
+' resistor-capacitor timing, see the RCTIME command.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL Pulse = 7 ' pulse input pin
+
+SYMBOL time = W1 ' pulse width (10 uS units)
+
+
+Main:
+ PULSIN Pulse, 1, time ' measure positive pulse
+ IF time = 0 THEN Main ' if 0, try again
+ DEBUG CLS, time ' else display result
+ GOTO Main
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' PULSIN.BS2
+' This program uses PULSIN to measure a pulse generated by discharging a
+' 0.1 uF capacitor through a 1K resistor. Pressing the switch generates
+' the pulse, which should ideally be approximately 120 us (60 PULSIN units
+' of 2 us) long (for BS2 and BS2e). Variations in component values may
+' produce results that are up to 10 units off from this value. For more
+' information on calculating resistor-capacitor timing, see the RCTIME
+' command.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Pulse PIN 7 ' pulse input pin
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ Scale CON $200 ' 2.0 us per unit
+ #CASE BS2SX
+ Scale CON $0CD ' 0.8 us per unit
+ #CASE BS2P
+ Scale CON $0C0 ' 0.75 us per unit
+ #CASE BS2PX
+ Scale CON $0CF ' 0.81 us per unit
+#ENDSELECT
+
+time VAR Word
+
+
+Main:
+ PULSIN Pulse, 1, time ' measure positive pulse
+ IF (time > 0) THEN ' if not 0
+ DEBUG HOME,
+ DEC time, " units ", CLREOL ' display raw input
+ time = time */ Scale ' adjust for Stamp
+ DEBUG CR,
+ DEC time, " us " ' display microseconds
+ ELSE
+ DEBUG CLS, "Out of Range" ' else error message
+ ENDIF
+ PAUSE 200
+ GOTO Main
+ END
Connect an LED and 470 Ω resistor as shown below for the demo program.
' PULSOUT.BS1
+' This program blinks an LED on for 25 ms at 1-second intervals. Connect an
+' LED (active-low) to I/O pin 0.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+
+Setup:
+ HIGH 0 ' make P0 high (LED off)
+
+Main:
+ PULSOUT 0, 2500 ' flash LED for 25 ms
+ PAUSE 1000 ' one second delay
+ GOTO Main
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' PULSOUT.BS2
+' This program blinks an LED on for 25 ms at 1-second intervals. Connect an
+' LED (active-low) to I/O pin 0.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ Scale CON 500 ' to ms for 2 us per unit
+ #CASE BS2SX, BS2P, BS2PX
+ Scale CON 1250 ' to ms for 0.8 us per unit
+#ENDSELECT
+
+Flash CON 25 * Scale ' 25 milliseconds
+
+
+Setup:
+ HIGH 0 ' make P0 high (LED off)
+
+Main:
+ PULSOUT 0, Flash ' flash LED
+ PAUSE 1000 ' one second delay
+ GOTO Main
+ END
+
' PWM.BS1
+' Connect a voltmeter (such as a digital multimeter set to its voltage
+' range) to the output of the circuit shown in the figure for the PWM
+' command (in the manual). Run the program and observe the readings on
+' the meter. They should come very close to 1.96V, then decrease slightly
+' as the capacitor discharges. Try varying the interval between PWM bursts
+' (by changing the PAUSE value) and the number of PWM cycles to see their
+' effect.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+
+Main:
+ PWM 0, 100, 10 ' PWM at 100/255 duty (~50 ms)
+ PAUSE 1000 ' wait one second
+ GOTO Main
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' PWM.BS2
+' Connect a voltmeter (such as a digital multimeter set to its voltage
+' range) to the output of the circuit shown in the figure for the PWM
+' command (in the manual). Run the program and observe the readings on
+' the meter. They should come very close to 1.96V, then decrease slightly
+' as the capacitor discharges. Try varying the interval between PWM bursts
+' (by changing the PAUSE value) and the number of PWM cycles to see their
+' effect.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E
+ CycAdj CON $100 ' x 1.0, cycle ajustment (for ms)
+ #CASE BS2SX
+ CycAdj CON $280 ' x 2.5
+ #CASE BS2P
+ CycAdj CON $187 ' x 1.53
+ #CASE BS2PE
+ CycAdj CON $09E ' x 0.62
+ #CASE BS2PX
+ CycAdj CON $280 ' x 2.5
+#ENDSELECT
+
+Cycles CON 50
+
+
+Main:
+ PWM 0, 100, (Cycles */ CycAdj) ' PWM at 100/255 duty (~50 ms)
+ PAUSE 1000 ' wait one second
+ GOTO Main
+ END
+
+
' RANDOM.BS1
+' Connect a button to I/O pin 7 as shown in the figure in the RANDOM
+' command description and run this program. This program uses RANDOM to
+' simulate a coin toss. After 100 trials, it reports the total number of
+' heads and tails thrown.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL Btn = 7 ' button input
+
+SYMBOL flip = W0 ' a random number
+SYMBOL coin = BIT0 ' a bit from random number
+SYMBOL trials = B2 ' number of flips
+SYMBOL heads = B3 ' throws that come up heads
+SYMBOL tails = B4 ' throws that come up tails
+SYMBOL btnWrk = B5 ' workspace for BUTTON
+
+
+Start:
+ DEBUG CLS, "Press the button to toss coin.", CR
+
+Main:
+ FOR trials = 1 TO 100 ' flip coin 100 times
+
+Hold:
+ RANDOM flip ' randomize while waiting
+ BUTTON Btn, 0, 250, 100, btnWrk, 0, Hold ' wait for button press
+ BRANCH coin, (Head, Tail) ' 0 = heads, 1 = tails
+
+Head:
+ DEBUG CR, "Heads!"
+ heads = heads + 1 ' increment heads counter
+ GOTO Next_Toss
+
+Tail:
+ DEBUG CR, "Tails..."
+ tails = tails + 1 ' increment heads counter
+
+Next_Toss:
+ NEXT
+
+ DEBUG CR, CR, "Heads: ", #heads, CR, "Tails: ", #tails
+ END
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' RANDOM.BS2
+' Connect a button to I/O pin 7 as shown in the figure in the RANDOM
+' command description and run this program. This program uses RANDOM to
+' simulate a coin toss. After 100 trials, it reports the total number of
+' heads and tails thrown.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Btn PIN 7 ' button input
+
+flip VAR Word ' a random number
+coin VAR flip.BIT0 ' Bit0 of the random number
+trials VAR Byte ' number of flips
+heads VAR Byte ' throws that come up heads
+tails VAR Byte ' throws that come up tails
+btnWrk VAR Byte ' workspace for BUTTON
+
+
+Start:
+ DEBUG CLS, "Press button to start"
+
+Main:
+ FOR trials = 1 TO 100 ' flip coin 100 times
+
+Hold:
+ RANDOM flip ' randomize while waiting
+ BUTTON Btin, 0, 250, 100, btnWrk, 0, Hold ' wait for button press
+ IF (coin = 0) THEN ' 0 = heads, 1 = tails
+ DEBUG CR, "Heads!"
+ heads = heads + 1 ' increment heads counter
+ ELSE
+ DEBUG CR, "Tails..."
+ tails = tails + 1 ' increment tails counter
+ ENDIF
+ NEXT
+
+Done:
+ DEBUG CR, CR, "Heads: ", DEC heads, " Tails: ", DEC tails
+ END
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
+
+
+
+
' RCTIME1.BS2
+' This program shows the standard use of the RCTIME instruction measuring
+' an RC charge/discharge time. Use the circuit in the RCTIME description
+' (in the manual) with R = 10K pot and C = 0.1 uF. Connect the circuit to
+' pin 7 and run the program. Adjust the pot and watch the value shown on
+' the Debug screen change.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+RC PIN 7
+
+result VAR Word
+
+
+Main:
+ DO
+ HIGH RC ' charge the cap
+ PAUSE 1 ' for 1 ms
+ RCTIME RC, 1, result ' measure RC discharge time
+ DEBUG HOME, DEC result ' display value
+ PAUSE 50
+ LOOP
+ END
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
+
+
+
+
' RCTIME2.BS2
+' This program illustrates the use of RCTIME as a fast stopwatch. The
+' program energizes a relay coil, then measures how long it takes for the
+' relay contacts to close. The circuit for this program can be found in
+' the manual. Note that RCTIME doesn't start timing instantly -- as with
+' all PBASIC instructions, it must be fetched from program EEPROM before
+' it can execute.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Coil PIN 6
+RC PIN 7
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ Adjust CON $200 ' x 2 us per unit
+ #CASE BS2SX
+ Adjust CON $0CC ' x 0.8 us per unit
+ #CASE BS2P
+ Adjust CON $0C0 ' x 0.75 us per unit
+ #CASE BS2PX
+ Adjust CON $0C0 ' x 0.75 us per unit
+#ENDSELECT
+
+result VAR Word
+
+
+Main:
+ DO
+ LOW Coil ' energize relay coil
+ RCTIME RC, 1, result ' measure time to contact closure
+ result = result */ Adjust ' adjust for device
+ DEBUG "Time to close: ",
+ DEC Result, CR
+ HIGH Coil ' release relay
+ PAUSE 1000 ' wait one second
+ LOOP
+ END
+
' READ.BS1
+' This program reads a string of data stored in EEPROM. The EEPROM data is
+' downloaded to the BS1 at compile-time and remains there (even with the
+' power off) until overwritten. Put ASCII characters into EEPROM, followed
+' by 0, which will serve as the end-of-message marker. For programs with
+' multiple strings, use the Memory Map window to find the starting character
+' address.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL strAddr = B2
+SYMBOL char = B3
+
+Msg1:
+ EEPROM ("BS1", 13, "EEPROM Storage!", 0)
+
+
+Main:
+ strAddr = 0 ' set to start of message
+ GOSUB String_Out
+ END
+
+String_Out:
+ READ strAddr, char ' read byte from EEPROM
+ strAddr = strAddr + 1 ' point to next character
+ IF char = 0 THEN StrOut_Exit ' if 0, exit routine
+ DEBUG #@char ' otherwise print char
+ GOTO String_Out ' get next character
+
+StrOut_Exit:
+ RETURN
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' READ.BS2
+' This program reads a string of data stored in EEPROM. The EEPROM data is
+' downloaded to the BS2 at compile-time and remains there (even with the
+' power off) until overwritten. Put ASCII characters into EEPROM, followed
+' by 0, which will serve as the end-of-message marker.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+strAddr VAR Word
+char VAR Byte
+
+Msg1 DATA "BS2", CR, "EEPROM Storage!", 0
+
+
+Main:
+ strAddr = Msg ' set to start of message
+ GOSUB String_Out
+ END
+
+String_Out:
+ DO
+ READ strAddr, char ' read byte from EEPROM
+ strAddr = strAddr + 1 ' point to next character
+ IF (char = 0) THEN EXIT ' if 0, exit routine
+ DEBUG char ' otherwise print char
+ LOOP
+ RETURN
+
+
NOTE: This is written for the BS2 and will run on any BASIC Stamp module. Modify the $STAMP directive (as required) before downloading to the BS1, BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' RETURN.BS2
+' This program demonstrates a potential bug caused by allowing a program to
+' "fall into" a subroutine. The program was intented to indicate that it
+' is "Starting...", then "Executing Subroutine,", then "Returned..." from
+' the subroutine and stop. Since we left out the END command (indicated in
+' the comments), the program then falls into the subroutine, displays
+' "Executing..." again and then RETURNs to the start of the program and
+' runs continuously in an endless loop.
+
+' {$STAMP BS2}
+
+
+Reset:
+ DEBUG "Starting Program", CR ' show start-up
+
+Main:
+ PAUSE 1000
+ GOSUB Demo_Sub ' call the subroutine
+ PAUSE 1000
+ DEBUG "Returned from Subroutine", CR ' show that we're back
+ PAUSE 1000
+ ' <-- Forgot to put END here
+
+Demo_Sub:
+ DEBUG " Executing Subroutine", CR ' show subroutine activity
+ RETURN
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/LanguageTopics/ExampleTopics/ReverseEx.htm b/help/BasicStampHelp/Content/LanguageTopics/ExampleTopics/ReverseEx.htm
new file mode 100644
index 0000000..00af3fc
--- /dev/null
+++ b/help/BasicStampHelp/Content/LanguageTopics/ExampleTopics/ReverseEx.htm
@@ -0,0 +1,112 @@
+
+
+
+ REVERSE Examples
+
+
+
+
+
REVERSE Examples
+
+
+
+
+
+
+
+
+
+ {PBASIC 2.5}
+
+
+
Example
+
+
+
+
+
Connect an LED and two resistors as shown below for the demo program.
+
+
+
' REVERSE.BS1
+' Connect the circuit shown in the REVERSE command description to I/O pin
+' 0 and run this program. The LED will alternate between two states, dim
+' and bright. The BASIC Stamp is using the REVERSE command to toggling I/O
+' pin 0 between input and output states. When pin 0 is an input, current
+' flows through R1, through the LED, through R2 to ground. Pin 0 is
+' effectively disconnected and doesn't play a part in the circuit. The total
+' resistance encountered by current flowing through the LED is R1 + R2 = 1220
+' ohms. When pin 0 is reversed to an output, current flows through R1, through
+' the LED, and into pin 0 to ground (because of the 0 written to PIN0). The
+' total resistance encountered by current flowing through the LED is R1,
+' 220 ohms. With only 20% of the resistance, the LED glows brighter.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+
+Setup:
+ PIN0 = 0 ' Put a low in the pin 0
+ ' output driver
+Main:
+ PAUSE 250 ' 1/4th second pause
+ REVERSE 0 ' reverse pin 0 I/O direction
+ GOTO Main ' do forever
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
REVERSE.BS2
+' Connect the circuit shown in the REVERSE command description to I/O pin
+' 0 and run this program. The LED will alternate between two states, dim
+' and bright. The BASIC Stamp is using the REVERSE command to toggling I/O
+' pin 0 between input and output states. When pin 0 is an input, current
+' flows through R1, through the LED, through R2 to ground. Pin 0 is
+' effectively disconnected and doesn't play a part in the circuit. The total
+' resistance encountered by current flowing through the LED is R1 + R2 = 1220
+' ohms. When pin 0 is reversed to an output, current flows through R1, through
+' the LED, and into pin 0 to ground (because of the 0 written to OUT0). The
+' total resistance encountered by current flowing through the LED is R1,
+' 220 ohms. With only 20% of the resistance, the LED glows brighter.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+
+Setup:
+ OUT0 = 0 ' Put a low in the pin 0
+ ' output driver
+Main:
+ PAUSE 250 ' 1/4th second pause
+ REVERSE 0 ' reverse pin 0 I/O direction
+ GOTO Main ' do forever
+
NOTE: This is written for the BS2sx and will also run on the BS2e, BS2p, BS2pe, and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2p, BS2pe, or BS2px.
' RUN1.BSX
+' This example demonstrates the use of the RUN command. First, the SPRAM
+' location that holds the current slot is read using the GET command to
+' display the currently running program number. Then a set of values (based
+' on the program number) are displayed on the screen. Afterwards, program
+' number 1 is run. This program is a BS2sx project consisting of RUN1.BSX
+' and RUN2.BSX, but will run on all multi-slot BASIC Stamp models.
+
+' {$STAMP BS2sx, RUN2.BSX}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP ' set SPRAM of slot number
+ #CASE BS2
+ #ERROR "Multi-slot BASIC Stamp required."
+ #CASE BS2E, BS2SX
+ Slot CON 63
+ #CASE BS2P, BS2PE, BS2PX
+ Slot CON 127
+#ENDSELECT
+
+slotNum VAR Nib ' current slot
+idx VAR Nib ' loop counter
+value VAR Byte ' value from EEPROM
+
+EEtable DATA 100, 40, 80, 32, 90
+ DATA 200, 65, 23, 77, 91
+
+
+Setup:
+ GET Slot, slotNum ' read current slot
+ DEBUG "Program #", DEC slotNum, CR ' display
+
+Main:
+ FOR idx = 0 TO 4 ' read/display table values
+ READ (slotNum * 5) + idx, value
+ DEBUG DEC3 value, " "
+ NEXT
+ DEBUG CR
+ PAUSE 1000
+
+ RUN 1 ' run Slot 1 pgm
+
+
+
' RUN2.BSX
+' This example demonstrates the use of the RUN command. First, the SPRAM
+' location that holds the current slot is read using the GET command to
+' display the currently running program number. Then a set of values (based
+' on the program number) are displayed on the screen. Afterwards, program
+' number 0 is run. This program is a BS2sx project consisting of RUN1.BSX
+' and RUN2.BSX, but will run on all multi-slot BASIC Stamp models.
+
+' {$STAMP BS2sx}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP ' set SPRAM of slot number
+ #CASE BS2
+ #ERROR "Multi-slot BASIC Stamp required."
+ #CASE BS2E, BS2SX
+ Slot CON 63
+ #CASE BS2P, BS2PE, BS2PX
+ Slot CON 127
+#ENDSELECT
+
+slotNum VAR Nib ' current slot
+idx VAR Nib ' loop counter
+value VAR Byte ' value from EEPROM
+
+EEtable DATA 100, 40, 80, 32, 90
+ DATA 200, 65, 23, 77, 91
+
+
+Setup:
+ GET Slot, slotNum ' read current slot
+ DEBUG "Program #", DEC slotNum, CR ' display
+
+Main:
+ FOR idx = 0 TO 4 ' read/display table values
+ READ (slotNum * 5) + idx, value
+ DEBUG DEC3 value, " "
+ NEXT
+ DEBUG CR
+ PAUSE 1000
+
+ RUN 0 ' back to Slot 0 pgm
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' SELECT-CASE.BS2
+' This program generates a series of 16-bit random numbers and tests each
+' to determine odd or even, and where it falls in the possible range:
+' lower third, middle third, or upper third. The program is useful for
+' testing various seed values for RANDOM.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+test VAR Byte ' counter for tests
+sample VAR Word ' random number to be tested
+odd VAR Byte ' odd throws
+even VAR Byte ' even throws
+isLo VAR Byte ' sample in lower third
+isMid VAR Byte ' in middle thrid
+isHi VAR Byte ' in upper third
+
+
+Main:
+ sample = 11000 ' initialize seed
+ FOR test = 1 TO 100 ' "throw" 100 times
+ RANDOM sample ' randomize
+
+ IF (sample.BIT0) THEN ' check odd/even bit
+ odd = odd + 1 ' increment odd count
+ ELSE
+ even = even + 1 ' increment even count
+ ENDIF
+
+ SELECT sample
+ CASE <= 21845 ' test lower third
+ isLo = isLo + 1
+
+ CASE 21846 TO 43691 ' test middle third
+ isMid = isMid + 1
+
+ CASE ELSE ' otherwise upper third
+ isHi = isHi + 1
+ ENDSELECT
+ NEXT
+
+Show_Results:
+ DEBUG CLS,
+ "Odd Throws.... ", DEC odd, "%", CR,
+ "Even Throws... ", DEC even, "%", CR,
+ "Low........... ", DEC isLo, "%", CR,
+ "Mid........... ", DEC isMid, "%", CR,
+ "High.......... ", DEC isHi, "%", CR
+ END
' SERIN.BS1
+' This program waits for the characters "A", "B", "C", and "D" to arrive
+' at the serial input (inverted, 2400 baud, N81), followed by a number,
+' then a carriage-return or some other non-number character. The number is
+' then displayed in the Debug window.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL SIn = 0
+SYMBOL Baud = N2400
+
+SYMBOL result = W1
+
+
+Main:
+ SERIN SIn, Baud, ("ABCD"), #result
+ DEBUG #result, CR
+ GOTO Main
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
+
+
+
' SERIN_SEROUT1.BS2
+' Using two BS2-IC's, connect the circuit shown in the SERIN command
+' description and run this program on the BASIC Stamp designated as the
+' Sender. This program demonstrates the use of Flow Control (FPin).
+' Without flow control, the sender would transmit the whole word "Hello!"
+' in about 1.5 ms. The receiver would catch the first byte at most; by the
+' time it got back from the first 1-second PAUSE, the rest of the data
+' would be long gone. With flow control, communication is flawless since
+' the sender waits for the receiver to catch up.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+SO PIN 1 ' serial output
+FC PIN 0 ' flow control pin
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+Inverted CON $4000
+Open CON $8000
+Baud CON T38K4 + Inverted
+
+
+Main:
+ DO
+ SEROUT SO\FC, Baud, ["Hello!", CR] ' send the greeting
+ PAUSE 2500 ' wait 2.5 seconds
+ LOOP ' repeat forever
+ END
+
+
' SERIN_SEROUT2.BS2
+' Using two BS2-IC's, connect the circuit shown in the SERIN command
+' description and run this program on the BASIC Stamp designated as the
+' Receiver. This program demonstrates the use of Flow Control (FPin).
+' Without flow control, the sender would transmit the whole word "Hello!"
+' in about 1.5 ms. The receiver would catch the first byte at most; by the
+' time it got back from the first 1-second PAUSE, the rest of the data
+' would be long gone. With flow control, communication is flawless since
+' the sender waits for the receiver to catch up.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+SI PIN 1 ' serial input
+FC PIN 0 ' flow control pin
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+Inverted CON $4000
+Open CON $8000
+Baud CON T38K4 + Inverted
+
+letter VAR Byte
+
+
+Main:
+ DO
+ SERIN SI\FC, Baud, [letter] ' recieve one byte
+ DEBUG letter ' display on screen
+ PAUSE 1000 ' wait one second
+ LOOP ' repeat forever
+ END
+
+
' SEROUT.BS1
+' This program transmits the string "ABCD" followed by a number and a
+' carriage-return at 2400 baud, inverted, N81 format.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL SOut = 1
+SYMBOL Baud = N2400
+
+SYMBOL value = W1
+
+
+Setup:
+ value = 1
+
+Main:
+ SEROUT SOut, Baud, ("ABCD", #value)
+ value = value + 1
+ PAUSE 250
+ GOTO Main
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
+
+
+
' SERIN_SEROUT1.BS2
+' Using two BS2-IC's, connect the circuit shown in the SERIN command
+' description and run this program on the BASIC Stamp designated as the
+' Sender. This program demonstrates the use of Flow Control (FPin).
+' Without flow control, the sender would transmit the whole word "Hello!"
+' in about 1.5 ms. The receiver would catch the first byte at most; by the
+' time it got back from the first 1-second PAUSE, the rest of the data
+' would be long gone. With flow control, communication is flawless since
+' the sender waits for the receiver to catch up.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+SO PIN 1 ' serial output
+FC PIN 0 ' flow control pin
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+Inverted CON $4000
+Open CON $8000
+Baud CON T38K4 + Inverted
+
+
+Main:
+ DO
+ SEROUT SO\FC, Baud, ["Hello!", CR] ' send the greeting
+ PAUSE 2500 ' wait 2.5 seconds
+ LOOP ' repeat forever
+ END
+
+' SERIN_SEROUT2.BS2
+
+
' SERIN_SEROUT2.BS2
+' Using two BS2-IC's, connect the circuit shown in the SERIN command
+' description and run this program on the BASIC Stamp designated as the
+' Receiver. This program demonstrates the use of Flow Control (FPin).
+' Without flow control, the sender would transmit the whole word "Hello!"
+' in about 1.5 ms. The receiver would catch the first byte at most; by the
+' time it got back from the first 1-second PAUSE, the rest of the data
+' would be long gone. With flow control, communication is flawless since
+' the sender waits for the receiver to catch up.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+SI PIN 0 ' serial input
+FC PIN 1 ' flow control pin
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2PE
+ T1200 CON 813
+ T2400 CON 396
+ T9600 CON 84
+ T19K2 CON 32
+ T38K4 CON 6
+ #CASE BS2SX, BS2P
+ T1200 CON 2063
+ T2400 CON 1021
+ T9600 CON 240
+ T19K2 CON 110
+ T38K4 CON 45
+ #CASE BS2PX
+ T1200 CON 3313
+ T2400 CON 1646
+ T9600 CON 396
+ T19K2 CON 188
+ T38K4 CON 84
+#ENDSELECT
+
+Inverted CON $4000
+Open CON $8000
+Baud CON T38K4 + Inverted
+
+letter VAR Byte
+
+
+Main:
+ DO
+ SERIN SI/FC, Baud, [letter] ' recieve one byte
+ DEBUG letter ' display on screen
+ PAUSE 1000 ' wait one second
+ LOOP ' repeat forever
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' SHIFTIN.BS2
+' This program uses the SHIFTIN instruction to interface with the ADC0831
+' 8-bit analog-to-digital converter from National Semiconductor.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+CS PIN 0 ' chip select
+AData PIN 1 ' data pin
+Clk PIN 2 ' clock pin
+
+adcRes VAR Byte ' ADC result
+
+
+Setup:
+ HIGH CS ' deselect ADC
+
+' In the loop below, just three lines of code are required to read the
+' ADC0831. The SHIFTIN command does most of the work. The mode argument in
+' the SHIFTIN command specifies MSB or LSB-first and whether to sample data
+' before or after the clock. In this case, we chose MSB-first, post-clock.
+' The ADC0831 precedes its data output with a dummy bit, which we take care
+' of by specifying 9 bits of data instead of 8.
+
+Main:
+ DO
+ LOW CS ' activate the ADC0831
+ SHIFTIN AData, Clk, MSBPOST, [adcRes\9] ' shift in the data
+ HIGH CS ' deactivate ADC0831
+ DEBUG ? adcRes ' show conversion result
+ PAUSE 1000 ' wait one second
+ LOOP ' repeat
+ END
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' SHIFTOUT.BS2
+' This program uses the SHIFTOUT command to interface to the 74HC595 shift
+' register as an 8-bit output port. The '595 requires a minimum of three
+' inputs: data, clock, and latch. See the figure in the SHIFTOUT command
+' description in the manual for wiring information. SHIFTOUT automatically
+' handles the data and clock, pulsing the clock to shift data bits into the
+' '595. An extra step (pulsing the latch input) is required to move the
+' shifted bits in parallel onto the '595's output pins. Note: this code does
+' not control the output-enable or reset lines of the '595. This means that
+' before the BASIC Stamp first sends, the '595's output latches are turned
+' on and may contain random data. In critical applications, you should hold
+' output-enable high (disabled) until the BASIC Stamp can take control.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Dpin PIN 0 ' data pin to 74HC595
+Clk PIN 1 ' shift clock to 74HC595
+Latch PIN 2 ' latch 74HC595 outputs
+
+counter VAR Byte
+
+
+Setup:
+ LOW Latch ' initialize latch output
+
+' This loop moves the 8-bit value 'counter' onto the output lines of the
+' '595, pauses, then increments counter and repeats. The data is shifted
+' MSB first so that the MSB appears on pin QH and the lsb on QA. Changing
+' MSBFIRST to LSBFIRST causes the data to appear backwards on the outputs.
+
+Main:
+ DO
+ SHIFTOUT Dpin, Clk, MSBFIRST, [counter] ' send the bits
+ PULSOUT Latch, 1 ' transfer to outputs
+ PAUSE 100 ' Wait 0.1 seconds
+ counter = counter + 1 ' increment counter
+ LOOP
+ END
Connect an LED and 470 Ω resistor as shown below for the demo program.
+
+
+
+
NOTE: This is written for the BS2 and will run on any BASIC Stamp module. Modify the $STAMP directive (as required) before downloading to the BS1, BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' SLEEP.BS2
+' This program lights an LED and then goes to sleep. Connect an LED to pin
+' 0 as shown in the description of SLEEP in the manual and run the program.
+' The LED will turn on, then the BASIC Stamp will go to sleep. During sleep,
+' the LED will remain on, but will blink at intervals of approximately 2.3
+' seconds due to the watchdog timeout and reset.
+
+' {$STAMP BS2}
+
+
+Setup:
+ LOW 0 ' turn LED on
+
+Snooze:
+ SLEEP 10 ' sleep for approximately 10 seconds
+ GOTO Snooze
+ END
+
' SOUND.BS1
+' This program generates a constant tone 25 followed by an ascending tones.
+' Both the tones have the same duration.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL tone = B2
+
+
+Main:
+ FOR tone = 0 TO 255
+ SOUND 0, (25, 10, tone, 10)
+ NEXT
+ END
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' STOP.BS2
+' This program is similar to SLEEP.BS2 except that the LED will not blink
+' since the BASIC Stamp does not go into low power mode. Use the circuit
+' shown in the description of the SLEEP command for this example.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+
+Main:
+ LOW 0 ' turn LED on
+ STOP
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' STORE0.BSP
+' This program demonstrates the STORE command and how it affects the READ
+' and WRITE commands. This program "STORE0.BSP" is intended to be down-
+' loaded into program slot 0. It is meant to work with STORE1.BSP and
+' STORE2.BSP. Each program is very similar (they display the current
+' Program Slot and READ/WRITE Slot numbers and the values contained in the
+' first five EEPROM locations. Each program slot will have different data
+' due to different DATA commands in each of the programs downloaded.
+
+' {$STAMP BS2p, STORE1.BSP, STORE2.BSP}
+' {$PBASIC 2.5}
+
+#IF ($STAMP < BS2P) #THEN
+ #ERROR "This program requires BS2p, BS2pe, or BS2px"
+#ENDIF
+
+idx VAR Word ' index
+value VAR Byte
+
+LocalData DATA @0, 1, 2, 3, 4, 5
+
+
+Main:
+ GOSUB Show_Slot_Info ' show slot info/data
+ PAUSE 2000
+ STORE 1 ' point READ/WRITE to Slot 1
+ GOSUB Show_Slot_Info
+ PAUSE 2000
+ RUN 1 ' run program in Slot 1
+ END
+
+Show_Slot_Info:
+ GET 127, value
+ DEBUG CR, "Pgm Slot: ", DEC value.NIB0,
+ CR, "R/W Slot: ", DEC value.NIB1,
+ CR, CR
+
+ FOR idx = 0 TO 4
+ READ idx, value
+ DEBUG "Location: ", DEC idx, TAB,
+ "Value: ", DEC3 value, CR
+ NEXT
+ RETURN
+
+
' STORE1.BSP
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+idx VAR Word ' index
+value VAR Byte
+
+LocalData DATA @0, 6, 7, 8, 9, 10
+
+
+Main:
+ GOSUB Show_Slot_Info ' show slot info/data
+ PAUSE 2000
+ STORE 0 ' point READ/WRITE to Slot 0
+ GOSUB Show_Slot_Info
+ PAUSE 2000
+ RUN 2 ' run program in Slot 2
+ END
+
+Show_Slot_Info:
+ GET 127, value
+ DEBUG CR, "Pgm Slot: ", DEC value.NIB0,
+ CR, "R/W Slot: ", DEC value.NIB1,
+ CR, CR
+
+ FOR idx = 0 TO 4
+ READ idx, value
+ DEBUG "Location: ", DEC idx, TAB,
+ "Value: ", DEC3 value, CR
+ NEXT
+ RETURN
+
+
' STORE2.BSP
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+idx VAR Word ' index
+value VAR Byte
+
+LocalData DATA @0, 11, 12, 13, 14, 15
+
+
+Main:
+ GOSUB Show_Slot_Info ' show slot info/data
+ PAUSE 2000
+ STORE 0 ' point READ/WRITE to Slot 0
+ GOSUB Show_Slot_Info
+ END
+
+Show_Slot_Info:
+ GET 127, value
+ DEBUG CR, "Pgm Slot: ", DEC value.NIB0,
+ CR, "R/W Slot: ", DEC value.NIB1,
+ CR, CR
+
+ FOR idx = 0 TO 4
+ READ idx, value
+ DEBUG "Location: ", DEC idx, TAB,
+ "Value: ", DEC3 value, CR
+ NEXT
+ RETURN
+
+
+
+
The next program, STOREALL.BSP, is not related to the previous three programs. STOREALL.BSP demonstrates the use of the STORE command to treat contiguous program slots as one block of memory (14 kBytes for the BS2p and BS2px, 30 kBytes for the BS2pe). This illustrates one of the most powerful uses of the STORE command.
+
NOTE: This is written for the BS2p and will also run on the BS2pe and BS2px. Modify the $STAMP directive (as required) before downloading to the BS2pe or BS2px.
' STOREALL.BSP
+' This program demonstrates the STORE command and how it can be used to
+' "flatten" the EEPROM space for applications requiring a lot of storage.
+' This program writes to EEPROM locations within program slots 1 through 7
+' on the BS2p and BS2px, and 1 through 15 on the BS2pe, thus, has access
+' to 14- or 30-kBytes of space.
+
+' {$STAMP BS2p}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2, BS2E, BS2SX
+ #ERROR "This program requires BS2p, BS2pe, or BS2px"
+ #CASE BS2P, BS2PX
+ HiSlot CON 7
+ #CASE BS2PE
+ HiSlot CON 15
+#ENDSELECT
+
+LoSlot CON 1 ' first slot for "flat" EE
+MemSize CON HiSlot - LoSlot + 1 * 2048
+
+eeAddr VAR Word ' address pointer
+value VAR Word ' cell value
+slot VAR Byte ' current R/W slot
+
+
+Main:
+ DEBUG "Flat Memory", CR,
+ "---------------------", CR,
+ "First Slot..... ", DEC LoSlot, CR,
+ "Last Slot...... ", DEC HiSlot, CR,
+ "Flat EE Size... ", DEC MemSize, CR, CR
+
+ PAUSE 2000
+ DEBUG "Writing to flat Memory...", CR
+ PAUSE 1000
+ FOR eeAddr = 0 TO (MemSize - 1) STEP 128 ' step through "flat" EE
+ value = eeAddr * 2 ' generate value
+ GOSUB Write_Word ' write it
+ GET 127, slot ' get R/W slot
+ DEBUG "--> Location: ", DEC5 eeAddr, " ", ' show "flat" address
+ "Value: ", DEC5 value, " ", ' show value
+ "(", DEC slot.NIB1, ")", CR ' show slot
+ NEXT
+ DEBUG CR
+
+ DEBUG "Reading from flat Memory...", CR
+ PAUSE 1000
+ FOR eeAddr = 0 TO (MemSize - 1) STEP 128
+ GOSUB Read_Word ' read value from EE
+ GET 127, slot ' get W/R slot
+ DEBUG "<-- Location: ", DEC5 eeAddr, " ",
+ "Value: ", DEC5 value, " ",
+ "(", DEC slot.NIB1, ") "
+ IF (value <> (2 * eeAddr)) THEN ' verify location
+ DEBUG "- Error"
+ ENDIF
+ DEBUG CR
+ NEXT
+ END
+
+Write_Word:
+ STORE (eeAddr >> 11) + LoSlot ' set slot
+ WRITE eeAddr, Word value ' write value
+ RETURN
+
+Read_Word:
+ STORE (eeAddr >> 11) + LoSlot ' set slot
+ READ eeAddr, Word value ' read value
+ RETURN
+
+
Connect four LEDs and four 470 Ω resistors as show below for the demo program.
+
+
+
' TOGGLE.BS1
+' Connect LEDs to pins 0 through 3 as shown in the TOGGLE command descrip-
+' tion in the manual and run this program. The TOGGLE command will treat
+' you to a light show. You may also run the demo without LEDs. The Debug
+' window will show you the states of pins 0 through 3.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL thePin = B0 ' pin 0 - 3
+
+
+Setup:
+ DIRS = %1111 ' make LEDs output, low
+
+Main:
+ FOR thePin = 0 TO 3 ' loop through pins
+ TOGGLE thePin ' toggle current pin
+ DEBUG CLS, %PINS ' show on Debug
+ PAUSE 100 ' short delay
+ NEXT
+ GOTO Main ' repeat forever
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' TOGGLE.BS2
+' Connect LEDs to pins 0 through 3 as shown in the TOGGLE command descrip-
+' tion in the manual and run this program. The TOGGLE command will treat
+' you to a light show. You may also run the demo without LEDs. The Debug
+' window will show you the states of pins 0 through 3.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+thePin VAR Nib ' pin 0 - 3
+
+
+Setup:
+ DIRA = %1111 ' make LEDs output, low
+
+Main:
+ DO
+ FOR thePin = 0 TO 3 ' loop through pins
+ TOGGLE thePin ' toggle current pin
+ DEBUG HOME, BIN4 OUTA ' show on Debug
+ PAUSE 250 ' short delay
+ NEXT
+ LOOP ' repeat forever
+ END
+
' WRITE.BS1
+' This program writes a few bytes to EEPROM and then reads them back out
+' and displays them in the Debug window.
+
+' {$STAMP BS1}
+' {$PBASIC 1.0}
+
+SYMBOL addr = B2 ' address
+SYMBOL value = B3 ' value
+
+
+Main:
+ WRITE 0, 100 ' write some data to locations 0 - 3
+ WRITE 1, 200
+ WRITE 2, 45
+ WRITE 3, 28
+
+Read_EE:
+ FOR addr = 0 TO 3
+ READ addr, value ' read value from address
+ DEBUG #addr, ": ", #value, CR ' display address and value
+ NEXT
+ END
+
+
+
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' WRITE.BS2
+' This program writes some data to EEPROM and then reads them back out
+' and displays the data in the Debug window.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+idx VAR Byte ' loop control
+value VAR Word(3) ' value(s)
+
+
+Main:
+ WRITE 0, 100 ' single byte
+ WRITE 1, Word 1250 ' single word
+ WRITE 3, 45, 90, Word 725 ' multi-value write
+
+Read_EE:
+ FOR idx = 0 TO 6 ' show raw bytes in EE
+ READ idx, value
+ DEBUG DEC1 idx, " : ", DEC value, CR
+ NEXT
+ DEBUG CR
+
+ ' read values as stored
+
+ READ 0, value
+ DEBUG DEC value, CR
+ READ 1, Word value
+ DEBUG DEC value, CR
+ READ 3, value(0), value(1), Word value(2)
+ FOR idx = 0 TO 2
+ DEBUG DEC value(idx), CR
+ NEXT
+ END
+
NOTE: The example below is written for the BS2 and will run on any of the BS2-family modules. Modify the $STAMP directive (as required) before downloading to the BS2e, BS2sx, BS2p, BS2pe, or BS2px.
' XOUT.BS2
+' This program--really two program fragments--demonstrates the syntax and
+' use of the XOUT command. XOUT works like pressing the buttons on an X-10
+' control box; first you press one of 16 keys to identify the unit you want
+' to control, then you press the key for the action you want that unit to
+' take (turn ON, OFF, Bright, or Dim). There are also two group-action keys,
+' Lights ON and All OFF. Lights ON turns all lamp modules on without
+' affecting appliance modules. All OFF turns off all modules, both lamp and
+' appliance types. Connect the BASIC Stamp to a power-line interface as
+' shown in the XOUT command description in the manual.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+Mpin PIN 1 ' modulation pin
+Zpin PIN 0 ' zero-cross input
+
+HouseA CON 0 ' House code A = 0
+Unit1 CON 0 ' Unit code 1 = 0
+Unit2 CON 1 ' Unit code 2 = 1
+
+' This first example turns a standard (appliance or non-dimmer lamp) module
+' ON, then OFF. Note that once the Unit code is sent, it need not be repeated
+' --subsequent instructions are understood to be addressed to that unit.
+
+Main:
+ XOUT Mpin, Zpin, [HouseA\Unit1\2] ' select Unit1 (appliance module)
+ XOUT Mpin, Zpin, [HouseA\UNITON] ' turn it on
+
+ PAUSE 1000 ' wait one second
+
+ XOUT Mpin, Zpin, [HouseA\UNITOFF] ' then turn it off
+
+' The next example talks to a lamp module using the dimmer feature. Dimmers
+' go from full ON to dimmed OFF in 19 steps. Because dimming is relative to
+' the current state of the lamp, the only guaranteed way to set a predefined
+' brightness level is to turn the dimmer fully OFF, then ON, then dim to the
+' desired level.
+
+ XOUT Mpin, Zpin, [HouseA\Unit2\2] ' select Unit2 (lamp module)
+
+' This example shows the use of the optional Cycles argument. Here we DIM
+' for 10 cycles.
+
+ XOUT Mpin, Zpin, [HouseA\UNITOFF\2, HouseA\DIM\10]
+ STOP
+
Parallax provides PBASIC code examples for many applications and devices, and many more examples can be found on the Parallax forums and other web sites. While some code examples include compiler directives that make them compatible with any 24-pin BASIC Stamp model, others are written for a single model, most often the BS2. If your BASIC Stamp model is different from the one the code is written for, portions of the program may need to be adjusted to accommodate differences in processor speed. This page provides some tips and examples of how to do this.
+
About Time-Sensitive Commands
+
Many BASIC Stamp 2 application examples make use of time-sensitive commands, those which have one or more arguments that depend on some attribute of time such as frequency, duration, baud rate, decay time, or pulse duration. If the command generates a signal, one or more of its arguments may contain values that affect the signal’s timing. Likewise, if the command measures a signal, one or more of its arguments may affect the result. When executed by different BASIC Stamp 2 models, the units for each time-sensitive argument may differ, so if the program is not adjusted to account for these differences, signals may be generated or measured at different rates.
If the BS2 application does not utilize any of the time-sensitive commands listed above, all that needs to change is the $STAMP directive. Here is an example BASIC Stamp 2 program that has no time-sensitive commands.
With this program, the only change that would need to be made to get this program to run properly with a BS2sx (for example), would be to update the $STAMP directive from BS2 to BS2sx. You can either manually modify the $STAMP directive, or click the BS2sx button on the BASIC Stamp Editor’s toolbar (recommended).
+
+
+
+
Tip: The BASIC Stamp Editor can detect if you are trying to load a program into a BASIC Stamp model that’s different from the one indicated in the program’s $STAMP directive. When this happens, it will ask you if you want it to automatically update the directive. Keep in mind that this directive update does not automatically update any time-sensitive command arguments.
+
Adapting Code that has Time-sensitive Commands
+
In addition to updating the $STAMP directive, each line of code that uses a time-sensitive command will need to be examined and possibly adjusted. The PBASIC Command Reference has links to the documentation for each command, including Quick Facts tables with the units of time-based attributes for each BASIC Stamp model. In most cases, you can use the units for the model the code is written for along with the units for the new target model to make a fraction for converting a given time-sensitive command argument. The units value for the “Convert from” model should be in the numerator, and the units for the “Convert to” model should be in the denominator. Make sure to round the “New Argument Value” to the nearest integer before using it as a command argument in a time-sensitive PBASIC command.
+
+
+
+
Tip: The SERIN and SEROUT commands have baud rate arguments that don't use this adjustment method. The Quick Facts tables for SERIN and SEROUT have common baud rates listed, and the documentation also provides directions for calculating custom baud rates for all BASIC Stamp 2 models.
+
The “Old Argument Value” to “New Argument Value” calculation can be used in three different approaches for updating your code:
+
+
Update time-sensitive command argument constants, and/or constants that are compared to results stored in variables by time-sensitive commands.
+
Calculate a re-usable multiplier for all instances of a command's argument.
+
Use the results of #1 and/or #2 to set up conditional compilation directives, so the program can be run on whichever BASIC Stamp models you choose to make compatible code for.
+
+
Let’s take a look at how each approach can be used with the time-sensitive FREQOUT command as an example, with the BS2 as the “Convert From” model and the BS2sx as the “Convert To” model.
+
Approach 1- Update Time Sensitive Argument Constants
+
Let’s say a speaker circuit is connected to BASIC Stamp I/O pin P6. If the BS2 executes the command:
FREQOUT 6, 100, 4500
+
... it sends a high-pitched alarm tone to the speaker for 100 ms at a frequency of 4500 Hz. A FREQOUT command with the same arguments executed by the BS2sx sends a tone that only last 40 ms at a frequency of 11,250 Hz. That’s a much shorter duration tone with a much higher pitch!
+
The FREQOUT command’s Quick Facts table indicates that the FREQOUTDuration argument is in terms of 1 ms units for the BS2, and in terms of 0.4 ms units for the BS2sx. Likewise, the BS2 units for Freq1 are 1 Hz, while the BS2sx Freq1 units are 2.5 Hz. You can use those values and the “Old Argument Value” to “New Argument Value” equation to convert a BS2 command like:
FREQOUT 6, 100, 4500
+
...for use with a BS2sx. In the figure below, the existing Duration argument of 100 gets multiplied by 1.0/0.4 with a result of 250. Likewise, the 4500 Freq1 argument gets multiplied by 1.0/2.5 with a nearest integer result of 1800. With these new values, the BS2sx version of the FREQOUT command is:
FREQOUT 6, 250, 1800
+
This command is now updated to make the BS2sx deliver a 4.5 kHz tone for 100 ms.
+
+
+
+
Approach 2 - Calculate a Re-usable Multiplier
+
You can incorporate expressions with */ (Multiply Middle) operators to perform the conversions from approach 1 right inside a PBASIC program. The */ operator allows you to multiply a constant, variable or expression result by a number of 256ths. For example, 1/4 is the same as 64/256ths, so value */ 64 is the same as multiplying a value by 1/4.
+
Each of the fractions determined with the Quick Facts table above can also be expressed as a number of 256ths. The result is “*/Constant” that you can use to scale a constant, variable or expression result to adjust a command's argument for a different BASIC Stamp model.
+
*/Constant = Integer(256 x (Units in “Convert From” Model / Units in “Convert To” model))
+
Continuing the FREQOUT command example, the “*/Constant” to convert Duration from BS2 to BS2sx units would be Integer(256 x (1/0.4)) = 640. So, a BS2 Duration value */ 640 results in an approximate BS2sx Duration value.
+
Likewise, the“*/Constant” for converting Freq1 from BS2 to BS2sx is Integer(256 x (1/2.5)) = 102, and a BS2 Freq1*/ 102 results in an approximate BS2sx Freq1 value. You can incorporate these */ operations directly into a FREQOUT command’s Duration and Freq1 arguments like this:
FREQOUT 6, 100 */ 640, 4500 */ 102
+
Keep in mind that this approach works with constants (like 100 and 4500), and it also works with variables and expression results. The only caveat is that it does take a little extra code space and execution time for each added */ operation. A test program for the BS2sx with the updated FREQOUT command might look like this:
Declaring constants for each of these */ multipliers makes it possible to update values once at the beginning for the program for multiple FREQOUT commands. With the constant declaration approach, our example program would looks like this:
' Tenth Second 4.5 kHz Tone StarSlash With Constants.bsx
+' {$STAMP BS2sx}
+' {$PBASIC 2.5}
+
+DurFactr CON 640
+FreqFactr CON 102
+
+FREQOUT 6, 100*/DurFactr, 4500*/FreqFactr
+
+END
+
+
Use the ** Operator for Greater Precision
+
The ** (Multiply High) operator multiplies a constant, variable or expression by a number of 65536ths, up to 65535. For fractional values less than one, it provides higher resolution than the */ operator. Since the fractional value for converting the FREQOUT command’s Freq1 argument is less than 1, the ** operator can provide a more precise conversion.
+
** Constant = Integer(65536 x (Units in “Convert From” Model / Units in “Convert To” model))
+
We can apply this to our BS2 to BS2sx Freq1 argument conversion with:
+
** Constant = Integer(65536 x (1 / 2.5)) = 26214
+
Now, the FREQOUT command with a more precise Freq1 argument conversion is:
FREQOUT 6, 100 */ 640, 4500 ** 26214
+
How much more precise is it? The BASIC Stamp always truncates to the integer in a calculation, so
+
4500 */ 102 = 4500 x 102 ÷ 256 = 1792
+
...truncated to the integer. For the BS2sx, that results in a frequency of 1792 x 2.5 Hz = 4480 Hz. That’s an error of 20 Hz, which is enough to be audible to sensitive ears or equipment. In contrast,
+
4500 ** 26214 = 4500 x 26214 ÷ 65536 = 1799
+
...truncated to the integer. This time, the BS2sx transmits a frequency of 1799 x 2.5 Hz = 4497.5 Hz, so the propagated error is now only 2.5 Hz! Here is a program that compares the tones:
' Tenth Second 4.5 kHz Tone Compare StarSlash and StarStar.bsx
+' {$STAMP BS2sx}
+' {$PBASIC 2.5}
+
+DurFactr CON 640
+FreqFactr VAR Word
+
+
+FREQOUT 6, 250, 1800 ' Calculated by hand
+PAUSE 100
+
+FreqFactr = 102 ' Multiplier for */
+FREQOUT 6, 100*/DurFactr, 4500*/FreqFactr
+PAUSE 100
+
+FreqFactr = 26214 ' Multiplier for **
+FREQOUT 6, 100*/DurFactr, 4500**FreqFactr
+
+END
+
Tip: If you can't hear the difference in the tones, try multiplying each Duration argument by 4 with "4*" to increase the length time you hear each tone.
+
Approach 3 - Use Results from 1 or 2 to Set up Conditional Compilation
+
The results from approaches 1 and 2 can be incorporated into Conditional Compilation directives. Especially when the target BASIC Stamp module could be one of several different models, conditional compilation makes it possible to use the $STAMP directive to select which segments of code get compiled and downloaded to the BASIC Stamp. For example, code from approaches 1 and 2 can be nested into conditional compilation directives. Then, the code can be set to run in a BS2 and BS2sx by simply updating the $STAMP directive.
+
In this first example, the $STAMP directive identifies which BASIC Stamp model is being used at compile time, and then only the FREQOUT command for the model identified gets downloaded. Note that the FREQOUT command for the BS2sx uses the Duration and Freq1 argument values we determined earlier in approach 1.
In this second example (below), the */ operator is used to define constants as multipliers to apply to the Duration and Freq1 arguments. These same constant symbols could be applied to any other FREQOUT commands added to the program, regardless of the Duration and Freq1 arguments used, which could be variables, constants, or even expressions.
+' Tenth Second 4.5 kHz Tone Select Case With Constants.bs2
+' {$STAMP BS2sx}
+' {$PBASIC 2.5}
+
+#SELECT $STAMP
+ #CASE BS2
+ DurFactr CON 256
+ FreqFactr CON 256
+ #CASE BS2sx
+ DurFactr CON 640
+ FreqFactr CON 102
+#ENDSELECT
+
+FREQOUT 6, 100*/DurFactr, 4500*/FreqFactr
+
+END
+
More example PBASIC programs that demonstrate conditional compilation for time-sensitive commands are included with the BASIC Stamp Editor. Just click File -> Open From -> Default BS2 directory, and select a program with a name like FREQOUT, PULSIN, or any of the other time-sensitive commands listed earlier.
+
This chart includes the first 128 ASCII characters. Note that the control codes (lowest 32 ASCII characters) have no standardized screen symbols. The characters listed for them are just names used in referring to these codes. For example, to move the cursor to the beginning of the next line of a printer or terminal often requires sending line feed and carriage return codes. This common pair is referred to as "LF/CR."
In order to facilitate the creation of programs that can be compiled for and
+downloaded to the connected model of BASIC Stamp2, several conditional compile directives
+have been added to PBASIC 2.5: #DEFINE, #IF...#THEN...#ELSE, #SELECT...#CASE, and #ERROR. Conditional compile directives are evaluated
+before the program is compiled, so variables and named constants cannot be
+referenced within a conditional compilation definition.
+
#DEFINE
+
Syntax: #DEFINESymbol {= Value}
+
#DEFINE allows the programmer to create custom symbols for use within
+conditional compilation control structures.
+
+
Symbol is a string (up to 32 characters).
+
Value is an optional constant/expression specifying the value
+ of the defined symbol. If the value parameter is omitted, Symbol is
+ defined as True.
+
+
Example:
#DEFINE DebugMode = 1
+
In the example above, the "= 1" is optional. Note that when the compiler
+encounters an undefined symbol it will evaluate that symbol as False (0). You
+can define a symbol as False by removing the definition with a comment character
+( ' ) or change its value to zero (recommended)
Evaluate Expression and then conditionally compile a block of code based
+on comparison to Condition(s). If no conditions are found True and a
+#CASE ELSE block is included, the #CASE #ELSE code statements will
+compiled.
+
+
Expression is a variable, a constant or an expression.
+
Condition is a statement, that can be evaluated as True or
+ False. Multiple conditions within the same #CASE can be separated by
+ commas ( , ).
+
Statement(s) is any valid PBASIC statement or statements.
#ERROR allows the programmer to create custom a custom error dialog.
+
+
Message is the error message string.
+
+
Example:
+#DEFINE I2CReady = (($STAMP = BS2p) OR ($STAMP = BS2pe))
+#IF NOT I2CReady #THEN
+ #ERROR "BS2p or BS2pe is required for this program."
+#ENDIF
+
+
The example above will halt the program and display the dialog below if you
+attempt to compile the program and run it on a BASIC Stamp other than the BS2p or
+BS2pe:
Suppose you’re working on a program called "Three Cheers" that flashes LEDs,
+makes hooting sounds, and activates a motor that crashes cymbals together, all in
+sets of three. A portion of your PBASIC program might contain something like:
+
+
+
+ FOR counter = 1 TO 3
+ GOSUB Make_Cheers
+ NEXT
+
+ FOR counter = 1 TO 3
+ GOSUB Blink_LEDs
+ NEXT
+
+ FOR counter = 1 TO 3
+ GOSUB Crash_Cymbals
+ NEXT
+
+
The numbers 1 and 3 in the code above are called constants. They are constants
+because, while the program is running, nothing can happen to change those numbers.
+This distinguishes constants from variables, which can change while the program
+is running.
+
PBASIC allows you to use several numbering systems. By default, it assumes that
+numbers are in decimal (base 10), our everyday system of numbers. But you can also
+use binary and hexadecimal (hex) numbers by identifying them with prefixes. And
+PBASIC will automatically convert quoted text into the corresponding ASCII code(s).
+For example:
+
+
+
99
+
decimal
+
+
+
%1010
+
binary
+
+
+
$FE
+
hex
+
+
+
"A"
+
ASCII code for A (65)
+
+
+
+
You can assign names to constants in a similar fashion to how variables are
+declared. On a BS1, it is identical to variable declarations and on the other
+BASIC Stamp modelss you use the CON directive. Here is the syntax:
+
+
+
+SYMBOL Name = ConstantValue
+
+
+
+
+Name CON ConstantValue
+
+
Once created, named constants may be used in place of the numbers they
+represent. For example:
+
+
+
+SYMBOL Cheers = 3
+
+SYMBOL idx = B2
+
+Main:
+ FOR idx = 1 TO Cheers
+ GOSUB Make_Cheers
+ NEXT
+
+
+
+
+Cheers CON 3
+
+idx VAR Nib
+
+Main:
+ FOR idx = 1 TO Cheers
+ GOSUB Make_Cheers
+ NEXT
+
+
That code would work exactly the same as the previous FOR...NEXT loops. The
+editor software would substitute the number 3 for the constant named Cheers
+throughout your program. Like variable names, labels and instructions, constant
+names are not case sensitive; CHEERS, and ChEErs would all be processed as
+identical to Cheers.
Using named constants does not increase the amount of code downloaded to the
+BASIC Stamp, and it often improves the clarity of the program. Weeks after a
+program is written, you may not remember what a particular number was supposed to
+represent—using a name may jog your memory (or simplify the detective work needed
+to figure it out).
+
Named constants also have another benefit. Suppose the "Three Cheers" program
+had to be upgraded to "Five Cheers." In the original example you would have to
+change all of the 3s to 5s. Search and replace would help, but you might
+accidentally change some 3s that weren't numbers of cheers, too. However, if you
+made smart use of a named constant, all you would have to do is change 3 to 5 in
+one place, the constant's declaration:
+
+
+
+SYMBOL Cheers = 5
+
+
+
+
+Cheers CON 5
+
+
Now, assuming that you used the constant cheers wherever your program needed
+'the number of cheers,' your upgrade would be done.
+
+
+
+
On the BS2-family you can take this idea a step further by defining constants
+with expressions; groups of math and/or logic operations that the editor software
+solves (evaluates) at compile time (the time right after you start the download
+and before the BASIC Stamp starts running your program). For example, suppose the
+"Cheers" program also controls a pump to fill glasses with champagne. Perhaps the
+number of glasses to fill is always twice the number of cheers, minus 1 (another
+constant):
+Cheers CON 5 ' # of cheers
+Glasses CON Cheers * 2 - 1 ' # of glasses
+
+
As you can see, one constant can be defined in terms of another. That is, the
+number glasses depends on the number cheers.
The tables below contain the conversion formatters available for the commands DEBUGIN, I2CIN, LCDIN, OWIN and SERIN and demonstrates, through various input/output data examples, exactly what will be received when using these formatters.
+
The following tables show data examples (characters received) across the top and formatters across the left side, with the results of that combination shown in the target cell.
+
For example, with the following code:
Value VAR WORD
+DEBUGIN SDEC Value
+
...the Decimal Formatters table shows us that if the characters -123 (followed by a carriage return) are received, the SDEC formatter will translate that to the word-sized decimal number -123 and will store that value into the Value variable.
+
NOTE: In all tables below, values in target cells represent the number base of the formatter (decimal for DEC, hexadecimal for HEX, etc) except where noted. Additionally, “--“ means no valid data (or not enough valid data) was received so the command will halt forever unless additional data is received or SERIN’s Timeout argument is used.
+
Decimal Formatters
+
+
+
Decimal
+ Formatters
+
+
Characters Received
+
+
+
+
‡
+
+
123
+
+
123‡
+
-123‡
+
‡123‡
+
12345‡
+
65536‡
+
255255‡
+
+
+
DEC
+
+
--
+
+
--
+
+
123
+
+
123
+
+
123
+
+
12345
+
+
0
+
+
58647
+
+
+
+
DEC1
+
+
--
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
6
+
+
2
+
+
+
+
DEC2
+
+
--
+
+
12
+
+
12
+
+
12
+
+
12
+
+
12
+
+
65
+
+
25
+
+
+
+
DEC3
+
+
--
+
+
123
+
+
123
+
+
123
+
+
123
+
+
123
+
+
655
+
+
255
+
+
+
+
DEC4
+
+
--
+
+
--
+
+
123
+
+
123
+
+
123
+
+
1234
+
+
6553
+
+
2552
+
+
+
+
DEC5
+
+
--
+
+
--
+
+
123
+
+
123
+
+
123
+
+
12345
+
+
0
+
+
25525
+
+
+
+
SDEC
+
+
--
+
+
--
+
+
123
+
+
-123
+
+
123
+
+
12345
+
+
0
+
+
-6889
+
+
+
+
SDEC1
+
+
--
+
+
1
+
+
1
+
+
-1
+
+
1
+
+
1
+
+
6
+
+
2
+
+
+
+
SDEC2
+
+
--
+
+
12
+
+
12
+
+
-12
+
+
12
+
+
12
+
+
65
+
+
25
+
+
+
+
SDEC3
+
+
--
+
+
123
+
+
123
+
+
-123
+
+
123
+
+
123
+
+
655
+
+
255
+
+
+
+
SDEC4
+
+
--
+
+
--
+
+
123
+
+
-123
+
+
123
+
+
1234
+
+
6553
+
+
2552
+
+
+
+
SDEC5
+
+
--
+
+
--
+
+
123
+
+
-123
+
+
123
+
+
12345
+
+
0
+
+
25525
+
+
+
+
‡Means any non-decimal-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (Decimal numerics are: 0,1,2,3,4,5,6,7,8 and 9)
+
Hexadecimal Formatters
+
+
+
Hexadecimal Formatters
+
+
Characters Received
+
+
+
+
‡
+
+
1F
+
+
1F‡
+
-1F‡
+
‡1F‡
+
15AF‡
+
10000‡
+
3E517‡
+
+
+
HEX
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15AF
+
+
0
+
+
E517
+
+
+
+
HEX1
+
+
--
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
3
+
+
+
+
HEX2
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
1F
+
+
15
+
+
10
+
+
3E
+
+
+
+
HEX3
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15A
+
+
100
+
+
3E5
+
+
+
+
HEX4
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15AF
+
+
1000
+
+
3E51
+
+
+
+
SHEX
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15AF
+
+
0
+
+
-1AE9
+
+
+
+
SHEX1
+
+
--
+
+
1
+
+
1
+
+
-1
+
+
1
+
+
1
+
+
1
+
+
3
+
+
+
+
SHEX2
+
+
--
+
+
1F
+
+
1F
+
+
-1F
+
+
1F
+
+
15
+
+
10
+
+
3E
+
+
+
+
SHEX3
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15A
+
+
100
+
+
3E5
+
+
+
+
SHEX4
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15AF
+
+
1000
+
+
3E51
+
+
+
+
Note: The HEX formatters are not case sensitive. For example, 1F is the same as 1f. ‡Means any non-hexadecimal-numeric characters such as letters (greater than F), spaces, minus signs, carriage returns, control characters, etc. (Hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).
+
Additional Hexadecimal Formatters
+
+
+
Additional Hexadecimal Formatters
+
+
Characters Received
+
+
+
+
‡
+
+
1F
+
+
1F‡
+
$1F
+
+
$1F‡
+
-$1F‡
+
‡$1F‡
+
$15AF‡
+
+
+
IHEX
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15AF
+
+
+
+
IHEX1
+
+
--
+
+
--
+
+
--
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
+
+
IHEX2
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
1F
+
+
15
+
+
+
+
IHEX3
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15A
+
+
+
+
IHEX4
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15AF
+
+
+
+
ISHEX
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15AF
+
+
+
+
ISHEX1
+
+
--
+
+
--
+
+
--
+
+
1
+
+
1
+
+
-1
+
+
1
+
+
1
+
+
+
+
ISHEX2
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
1F
+
+
-1F
+
+
1F
+
+
15
+
+
+
+
ISHEX3
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15A
+
+
+
+
ISHEX4
+
+
--
+
+
--
+
+
--
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15AF
+
+
+
+
NOTE: The HEX formatters are not case sensitive. For example, 1F is the same as 1f. ‡Means any non-hexadecimal-numeric characters such as letters (greater than F), spaces, minus signs, carriage returns, control characters, etc. (Hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).
+
Binary Formatters
+
+
+
Binary
+ Formatters
+
+
Characters Received
+
+
+
+
‡
+
+
11
+
+
11‡
+
-11‡
+
‡11‡
+
101‡
+
3E517‡
+
+
+
BIN
+
+
--
+
+
--
+
+
11
+
+
11
+
+
11
+
+
101
+
+
1
+
+
+
+
BIN1
+
+
--
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
+
+
BIN2
+
+
--
+
+
11
+
+
11
+
+
11
+
+
11
+
+
10
+
+
1
+
+
+
+
BIN3 – BIN16
+
+
--
+
+
--
+
+
11
+
+
11
+
+
11
+
+
101
+
+
1
+
+
+
+
SBIN
+
+
--
+
+
--
+
+
11
+
+
-11
+
+
11
+
+
101
+
+
1
+
+
+
+
SBIN1
+
+
--
+
+
1
+
+
1
+
+
-1
+
+
1
+
+
1
+
+
1
+
+
+
+
SBIN2
+
+
--
+
+
11
+
+
11
+
+
-11
+
+
11
+
+
10
+
+
1
+
+
+
+
SBIN3 – SBIN16
+
+
--
+
+
--
+
+
11
+
+
-11
+
+
11
+
+
101
+
+
1
+
+
+
+
‡Means any non-binary-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (Binary numerics are: 0 and 1).
+
Additional Binary Formatters
+
+
+
Additional Binary Formatters
+
+
Characters Received
+
+
+
+
‡
+
+
11
+
+
11‡
+
%11
+
+
%11‡
+
-%11‡
+
‡%11‡
+
%101‡
+
+
+
IBIN
+
+
--
+
+
--
+
+
--
+
+
--
+
+
11
+
+
11
+
+
11
+
+
101
+
+
+
+
IBIN1
+
+
--
+
+
--
+
+
--
+
+
1
+
+
1
+
+
1
+
+
1
+
+
1
+
+
+
+
IBIN2
+
+
--
+
+
--
+
+
--
+
+
11
+
+
11
+
+
11
+
+
11
+
+
10
+
+
+
+
IBIN3 – IBIN16
+
+
--
+
+
--
+
+
--
+
+
--
+
+
11
+
+
11
+
+
11
+
+
101
+
+
+
+
ISBIN
+
+
--
+
+
--
+
+
--
+
+
--
+
+
11
+
+
-11
+
+
11
+
+
101
+
+
+
+
ISBIN1
+
+
--
+
+
--
+
+
--
+
+
1
+
+
1
+
+
-1
+
+
1
+
+
1
+
+
+
+
ISBIN2
+
+
--
+
+
--
+
+
--
+
+
11
+
+
11
+
+
-11
+
+
11
+
+
10
+
+
+
+
ISBIN3 – ISBIN16
+
+
--
+
+
--
+
+
--
+
+
--
+
+
11
+
+
-11
+
+
11
+
+
101
+
+
+
+
‡Means any non-binary-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (Binary numerics are: 0 and 1).
+
NUM and SNUM with Decimal Data
+
+
+
General (Dec. Data)
+
+
Characters Received
+
+
+
+
‡
+
+
123
+
+
123‡
+
-123‡
+
‡123‡
+
12345‡
+
65536‡
+
255255‡
+
+
+
NUM
+
+
--
+
+
--
+
+
123
+
+
123
+
+
123
+
+
12345
+
+
0
+
+
58647
+
+
+
+
SNUM
+
+
--
+
+
--
+
+
123
+
+
-123
+
+
123
+
+
12345
+
+
0
+
+
-6889
+
+
+
+
‡Means any non-decimal-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (Decimal numerics are: 0,1,2,3,4,5,6,7,8 and 9).
+
NUM and SNUM with Hexadecimal Data
+
+
+
General (Hex. Data)
+
+
Characters Received
+
+
+
+
‡
+
+
1F
+
+
1F‡
+
$1F
+
+
$1F‡
+
-$1F‡
+
‡$1F‡
+
$15AF‡
+
+
+
NUM
+
+
--
+
+
1*
+
+
1*
+
+
--
+
+
1F
+
+
1F
+
+
1F
+
+
15AF
+
+
+
+
SNUM
+
+
--
+
+
1*
+
+
1*
+
+
--
+
+
1F
+
+
-1F
+
+
1F
+
+
15AF
+
+
+
+
NOTE: Hexadecimal data is not case sensitive. For example, 1F is the same as 1f. ‡Means any non-hexadecimal-numeric characters such as letters (greater than F), spaces, minus signs, carriage returns, control characters, etc. (Hexadecimal numerics are: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F). *Invalid data; treated as decimal number one because no $ preceded it and non-decimal digit followed it.
+
NUM and SNUM with Binary Data
+
+
+
General
+ (Bin. Data)
+
+
Characters Received
+
+
+
+
‡
+
+
11
+
+
11‡
+
+
%11
+
+
%11‡
+
+
-%11‡
+
‡%11‡
+
%101‡
+
+
+
NUM
+
+
--
+
+
--
+
+
11*
+
+
--
+
+
11
+
+
11
+
+
11
+
+
101
+
+
+
+
SNUM
+
+
--
+
+
--
+
+
11*
+
+
--
+
+
11
+
+
-11
+
+
11
+
+
101
+
+
+
+
‡Means any non-binary-numeric characters such as letters, spaces, minus signs, carriage returns, control characters, etc. (Binary numerics are: 0 and 1). *Invalid data; treated as decimal number eleven because no % preceded it.
The $STAMP directive is a special command that is included (usually
+at the top) in a program to indicate the model of BASIC Stamp targeted. Buttons on the editor
+tool bar simplify adding or modifying the $STAMP directive:
+
+
+
+
The
+line below is an example of the $STAMP directive (in this case, it indicates that
+the program is intended for a BASIC Stamp 2):
+' {$STAMP BS2}
+
+
This line should be entered into your code, usually near the top, on a line
+by itself. Note that the directive appears on a comment line (the apostrophe (')
+indicates this) for compatibility with the DOS versions of the editor.
+
The 'BS2' in the example above should be changed to indicate the appropriate
+model of the BASIC Stamp you are using. For example, to use other BASIC Stamp
+module, enter one (just one) of the following lines into your code:
The directive itself must be enclosed in brackets, {...}. There should not be
+any spaces between the dollar sign, $, and the word STAMP, however, the directive
+may contain additional spaces in certain other areas.
+
The $STAMP directive is read and acted upon by the BASIC Stamp Windows Editor
+any time a source code file is loaded, tokenized, downloaded (run) or viewed in
+the Memory Map.
+
Defining Multi-File Projects
+
The BS2e, BS2sx, BS2p and BS2pe modules support multi-file projects, which require a modified syntax for the $STAMP directive. A project is a set of up to eight files that
+should all be downloaded to the BASIC Stamp for a single application. See Multi-File Projects for details.
+
Conditional Compilation
+
To create source code that is usable on multiple BS2 models, but requires changing as set of constants, symbols, or conditions depending on that model, see Conditional Compilation.
+
$PBASIC
+
The $PBASIC directive allows the programmer to specify the syntax level for
+the compiler to use. Buttons on the editor tool bar simplify adding or
+modifying the $PBASIC directive:
+
+
+
+
Examples:
+' {$PBASIC 1.0} ' use version 1.0 syntax (BS1 only)
+' {$PBASIC 2.0} ' use version 2.0 syntax
+' {$PBASIC 2.5} ' use version 2.5 syntax
+
+
Note that if the $PBASIC directive is omitted, the compiler will assume
+version 2.0 syntax, unless a $STAMP BS1 directive is present.
+
$PORT
+
The purpose of the $PORT directive is to direct a PBASIC program towards a
+specific serial port. The syntax is as follows:
+' {$PORT COM#}
+
+
...where # is a valid port number. When any PBASIC program containing this
+directive is downloaded, all other ports will be ignored. This directive is
+especially important if using two of the same BASIC Stamp models (such as two BS2s)
+on two COM ports and you have two different PBASIC programs to download (one to
+each BS2). Without this directive, developing and downloading in this case would
+be a tedious task of always answering the "which Stamp?" prompt. The Port directive
+can be automatically inserted or modified by selecting the appropriate port from
+the Directive -> Port menu. The COM ports listed in the Directive -> Port menu
+are automatically updated any time a change is made to the exiting computer hardware
+or to the available ports list (in preferences).
Like most versions of the BASIC programming language, PBASIC is very forgiving
+and the compiler enforces no particular formatting style. As long as the source
+code is syntactically correct, it will compile and download to the BASIC Stamp
+without trouble.
+
Why, then, would one suggest a specific style for PBASIC? Consider this: Over
+three million BASIC Stamp modules have been sold and there are several thousand
+members that participate in the
+Parallax online forums.
+This makes it highly likely that you'll be sharing your PBASIC code
+with someone, if not co-developing a BASIC Stamp project. Writing code in an
+organized, predictable manner will save you -- and your potential colleagues --
+a lot of time; in analysis, in troubleshooting and especially when you return to
+a project after a long break.
+
The style guidelines presented here are just that: guidelines. They have
+been developed from style guidelines used by professional programmers using other
+high-level languages such as Visual Basic®, C/C++, and Java™.
+Use these guidelines as-is, or modify them to suit your individual needs. The key
+is selecting a style the works well for you or your organization, and then
+sticking to it.
+
PBASIC Style Guidelines
+
1. Do It Right The First Time
+
Many programmers, especially new ones, fall into the "I'll knock it out now
+and fix it later." trap. Invariably, the "fix it later" part never
+happens and sloppy code makes its way into production projects. If you don't
+have time to do it right, when will you find time to do it again?
+
Start clean and you'll be less likely to introduce errors in your code. And
+if errors do pop up, clean and organized formatting will make them easier to find
+and fix.
+
2. Be Organized and Consistent
+
Using a blank program template will help you organize your programs and establish
+a consistent presentation.
+
3. Use Meaningful Names
+
Be verbose when naming constants, variables and program labels. The compiler will
+allow names up to 32 characters long. Using meaningful names will reduce the
+number of comments and make your programs easier to read, debug and maintain.
+
4. Naming I/O Pins
+
BASIC Stamp I/O pins are a special case as various elements of the PBASIC language
+require a pin to be constant value, an input variable or an output variable. To
+prevent redundant definitions, use the PIN type.
+
+HeaterCtrl PIN 15
+
+
Since connections don't change during the program run, I/O pins are named like
+constants using mixed-case, beginning with an uppercase letter.
+
5. Naming Constants
+
Begin constant names with an uppercase letter and use mixed case, using uppercase
+letters at the beginning of new words within the name.
+
+SYMBOL AlarmCode = 25
+
+
+AlarmCode CON 25
+
+
6. Naming Variables
+
Begin variable names with a lowercase letter and use mixed case, using uppercase
+letters at the beginning of new words within the name.
+
BS1: Avoid using W0 (B0 and B1) so that bit variables (Bit0..Bit15) are
+available for use in your programs. Bit variables 0..15 overlay W0, so the use
+of W0 may cause undesired effects.
+
+SYMBOL waterLevel = W1
+
+
BS2: Avoid the use of internal variable names (such as B0 or W1) in your
+programs. Allow the compiler to automatically assign RAM space by declaring a
+variable of specific type.
+
+waterLevel VAR Word
+
+
7. Variable Type Declarations
+
When using the BS1, variable type is declared by aliasing the SYMBOL name to an
+internal variable of a specific size.
+bitValue VAR Bit ' 0 - 1
+nibValue VAR Nib ' 0 - 15
+byteValue VAR Byte ' 0 - 255
+wordValue VAR Word ' 0 - 65535
+
8. Program Labels
+
Begin program labels with an uppercase letter, used mixed case, separate words
+within the label with an underscore character and begin new words with a number
+or uppercase letter. Labels should be preceded by at least one blank line, begin
+in column 1 and must be terminated with a colon (except after GOTO and THEN
+[in classic PBASIC] where they appear at the end of the line and without a colon).
All PBASIC language keywords, including SYMBOL, CON, VAR, PIN and serial/debugging
+format modifiers (DEC, HEX, BIN) and constants (CR, LF) should be uppercase. (Although PBASIC
+is not case-sensitive, the BASIC Stamp Editor's Syntax Highlighting feature will automatically make
+these keywords all caps
+
+Main:
+ DEBUG "BASIC Stamp", CR
+ END
+
+
10. Indent Nested Code
+
Nesting blocks of code improves readability and helps reduce the introduction of
+errors. Indenting each level with two spaces is recommended to make the code
+readable without taking up too much space.
+
Note:The dots are used to illustrate the level of nesting and are
+not a part of the code.
+
+Main:
+..FOR testLoop = 1 TO 10
+....IF checkLevel >= Threshold THEN LED_Okay
+....lowLevel = lowLevel + 1
+....GOTO Loop_Delay
+
+LED_Okay:
+....LEDokay = IsOn
+
+Loop_Delay:
+....PAUSE 100
+..NEXT
+..IF testMode = Yes THEN Main
+
+
+Main:
+..DO
+....FOR testLoop = 1 TO 10
+......IF (checkLevel < Threshold) THEN
+........lowLevel = lowLevel + 1
+......ELSE
+........LEDokay = IsOn
+......ENDIF
+......PAUSE 100
+....NEXT
+..LOOP WHILE (testMode = Yes)
+
+
11. Condition Statements
+
Enclose condition statements in parentheses for clarity (BS2 only - parenthesis
+are not allowed when using the BS1).
+
+Check_Temp:
+ IF (indoorTemp >= setPoint) THEN
+ AcCtrl = IsOn
+ ELSE
+ lowLevel = lowLevel + 1
+ ENDIF
+
+Fill_Water_Tank:
+ DO WHILE (waterLevel = IsLow)
+ TankFill = IsOn
+ PAUSE 250
+ LOOP
+
+Get_Delay:
+ DO
+ DEBUG HOME, "Enter time (5 - 30)... ", CLREOL
+ DEBUGIN DEC2 tmDelay
+ LOOP UNTIL ((tmDelay >= 5) AND (tmDelay =< 30))
+
+
12. Be Generous With White Space
+
White space (spaces and blank lines) does not affect compiler performance or BASIC
+Stamp execution speed, so be generous with it to make listings easier to read. Allow at least one blank line before program labels (two blanks
+lines before a subroutine label is recommended). Separate items in a parameter list
+with a space.
An exception to this guideline is with the bits parameter used with SHIFTIN
+and SHIFTOUT, the REP modifier for DEBUG and SEROUT, and the byte count and
+terminating byte value for SERIN. In these cases, format without spaces.
The BASIC Stamp has two kinds of memory; RAM (for variables used by your
+program) and EEPROM (for storing the program itself). EEPROM may also be used to
+store long-term data in much the same way that desktop computers use a hard drive
+to hold both programs and files.
+
An important distinction between RAM and EEPROM is this:
+
+
RAM loses its contents when the BASIC Stamp loses power; when power returns,
+ all RAM locations are cleared to 0s.
+
EEPROM retains the contents of memory, with or without power, until it is
+ overwritten (such as during the program-downloading process or with a
+ WRITE instruction.)
+
+
+
+ BASIC Stamp 1 RAM Organization
+
The BS1 has 16 bytes (8 words) of RAM space arranged as shown in the table
+below. The first word, called PORT, is used for I/O pin control. It consists of
+two bytes, PINS and DIRS. The bits within PINS correspond to each of the
+eight I/O pins on the BS1. Reading PINS effectively reads the I/O pins
+directly, returning an 8-bit set of 1's and 0's corresponding to the high and
+low state of the respective I/O pin at that moment. Writing to PINS will
+store a high or low value on the respective I/O pins (though only on pins
+that are set to outputs).
+
+
+
Word Name
+
Byte Names
+
Bit Name
+
Special Notes
+
+
+
PORT
+
PINS DIRS
+
PIN0 - PIN7 DIR0 - DIR7
+
I/O pins; bit addressable I/O pins directions; bit addressable
+
+
+
W0
+
B0 B1
+
BIT0 - BIT7 BIT8 - BIT15
+
Bit addressable Bit addressable
+
+
+
W1
+
B2 B3
+
+
+
+
+
W2
+
B4 B5
+
+
+
+
+
W3
+
B6 B7
+
+
+
+
+
W4
+
B8 B9
+
+
+
+
+
W5
+
B10 B11
+
+
+
+
+
W6
+
B12 B13
+
+
Used by GOSUB instruction Used by GOSUB instruction
+
+
+
+
The second byte of PORT, DIRS, controls the direction of the I/O pins. Each
+bit within DIRS corresponds to an I/O pin's direction. A high bit (1) sets the
+corresponding I/O pin to an output direction and a low bit (0) sets the
+corresponding I/O pin to an input direction.
+
The remaining words (W0 – W6) are available for general-purpose use. Each word
+consists of separately addressable bytes and the first two bytes (B0 and B1) are
+bit addressable as well. You may assign other names (symbols) to these RAM registers
+as shown in section "Defining and Using Variables", below.
+
When the BS1 is powered up, or reset, all memory locations are cleared to 0,
+so all pins are inputs (DIRS = %00000000). Also, if the PBASIC program sets all
+the I/O pins to outputs (DIRS = %11111111), then they will initially output low,
+since the output latch (PINS) is cleared to all zeros upon power-up or reset, as
+well.
+
+ BASIC Stamp 2 Series RAM Organization
+
The BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px have 32 bytes of Variable RAM space arranged as
+shown in the table below. Of these, the first six bytes are reserved for input,
+output, and direction control of the I/O pins. The remaining 26 bytes are available
+for general-purpose use as variables.
+
Note: There are 16 words, consisting of two bytes each for a total
+of 32 bytes. All bits are individually addressable through modifiers and the bits
+within the upper three words are also individually addressable through the
+pre-defined names shown.
+
+
+
Word Name
+
Byte Names
+
Nibble Names
+
Bit Name
+
Special Notes
+
+
+
INS
+
INL INH
+
INA, INB INC, IND
+
IN0 - IN7 IN8 - IN15
+
Input pins
+
+
+
OUTS
+
OUTL OUTH
+
OUTA, OUTB OUTC, OUTD
+
OUT0 - OUT7 OUT8 - OUT15
+
Output pins
+
+
+
DIRS
+
DIRL DIRH
+
DIRA, DIRB DIRC, DIRD
+
DIR0 - DIR7 DIR8 - DIR15
+
I/O pin direction control
+
+
+
W0
+
B0 B1
+
+
+
+
+
+
W1
+
B2 B3
+
+
+
+
+
+
W2
+
B4 B5
+
+
+
+
+
+
W3
+
B6 B7
+
+
+
+
+
+
W4
+
B8 B9
+
+
+
+
+
+
W5
+
B10 B11
+
+
+
+
+
+
W6
+
B12 B13
+
+
+
+
+
+
W7
+
B14 B15
+
+
+
+
+
+
W8
+
B16 B17
+
+
+
+
+
+
W9
+
B18 B19
+
+
+
+
+
+
W10
+
B20 B21
+
+
+
+
+
+
W11
+
B22 B23
+
+
+
+
+
+
W12
+
B24 B25
+
+
+
+
+
+
+
The INS variable always shows the state of the I/O pins themselves, regardless
+of the direction of each I/O pin. We call this, "reading the pins." If a pin was
+set to an input mode (within DIRS) and an external circuit connected the I/O pin
+to ground, the corresponding bit of INS would be zero. If a pin was set to be an
+output and the pin's state was set to a high level (within OUTS), the corresponding
+bit of INS would be high. If, however, that same pin was externally connected
+directly to ground, the corresponding bit of INS would be low; since we're reading
+the state of the pin itself and the BASIC Stamp cannot override a pin that is
+driven to ground or 5 volts externally. Note: The final example is an error; it
+will cause a direct short and can cause damage to the BASIC Stamp! Do not
+intentionally connect output pins directly to Vss (Ground) or Vdd (positive supply)
+or you risk destroying your BASIC Stamp module.
+
To summarize: DIRS determines whether a pin's state is set by external
+circuitry (input, 0) or by the state of OUTS (output, 1). INS always matches the
+actual states of the I/O pins, whether they are inputs or outputs. OUTS holds bits
+that will only appear on pins whose DIRS bits are set to output.
+
In programming the BASIC Stamp, it's often more convenient to deal with
+individual bytes, nibbles or bits of INS, OUTS and DIRS rather than the entire
+16-bit words. PBASIC has built-in names for these elements, shown in table above.
+
Here's an example of what is described in the table above. The INS register is
+16-bits (corresponding to I/O pins 0 through 15). The INS register consists of
+two bytes, called INL (the Low byte) and INH (the High byte). INL corresponds to
+I/O pins 0 through 7 and INH corresponds to I/O pins 8 through 15. INS can also be
+thought of as containing four nibbles, INA, INB, INC and IND. INA is I/O pins 0
+through 3, INB is I/O pins 4 through 7, etc. In addition, each of the bits of INS
+can be accessed directly using the names IN0, IN1, IN2... IN15.
+
The same naming scheme holds true for the OUTS and DIRS variables as well.
+
As the table shows, the BASIC Stamp's memory is organized into 16 words of 16
+bits each. The first three words are used for I/O. The remaining 13 words are
+available for use as general-purpose variables.
+
Just like the I/O variables, the general-purpose variables have predefined
+names: W0 through W12 and B0 through B25. B0 is the low byte of W0; B1 is the high
+byte of W0; and so on through W12 (B24=low byte, B25=high byte). Unlike I/O
+variables, there's no reason that your program variables have to be stuck in a
+specific position in the BASIC Stamp's physical memory. A byte is a byte regardless
+of its location. And if a program uses a mixture of variables of different sizes,
+it can be a pain in the neck to logically dole them out or allocate storage.
+
More importantly, mixing fixed variables with automatically allocated
+variables is an invitation to bugs. A
+fixed variable can overlap an allocated variable, causing data meant for one
+variable to show up in another! The fixed variable names (of the general-purpose
+variables) are only provided for power users who require absolute access to a
+specific location in RAM.
+
We recommend that you avoid using the fixed variables in most situations.
+Instead, let PBASIC allocate variables as described in the next section. The
+editor software will organize your storage requirements to make optimal use of
+the available memory.
+
+
+ Scratch Pad RAM
+
The BS2e, BS2sx, BS2p, BS2pe, and BS2px have some additional RAM called
+Scratch Pad RAM. The BS2e and BS2sx have are 64 bytes of Scratch Pad RAM (0 – 63),
+and the BS2p, BS2pe, and BS2px have 128 bytes of Scratch Pad RAM (0 – 127).
+Scratch Pad RAM can only be accessed with the GET and PUT commands (see the
+GET and PUT command descriptions
+for more information) and cannot have variable names assigned to it.
+
The highest location in Scratch Pad RAM (location 63 on the BS2e and BS2sx,
+location 127 on the BS2p, BS2pe, and BS2px) is read-only, and always contains
+the number of the currently running program slot. This can be handy for programs
+that need to know which program slot they exist in.
For BS2e, BS2sx, BS2p, BS2pe, and BS2px programs, each editor page can be a separate
+project, or part of a single project. A project is a set of up to eight files that
+should all be downloaded to the BASIC Stamp for a single application. Each of the
+files within the project is downloaded into a separate "program slot". Only the
+BASIC Stamp 2e, 2sx, 2p, 2pe, and 2px modules support multi-file projects.
+
$STAMP Directive for a Multi-File Project
+
For BASIC Stamp projects (consisting of multiple programs), the $STAMP directive
+has an option to specify additional filenames. The syntax below demonstrates this
+form of the $STAMP directive:
+' {$STAMP BS2e, file2, file3, ..., file8}
+
+
Use this form of the $STAMP directive if a project, consisting of multiple files, is desired. This form of the directive must be entered only into the first program (to be downloaded into program slot 0). The file2, file3, etc. items should be the actual name (and optionally the path) of the other files in the project. File2 refers to the program that should be downloaded into program slot 1, file3 is the program that should be downloaded into program slot 2, etc. If no path is given, the filename is given the path of program 0 when loading them into the editor.
+
Up to seven filenames can be included, bringing the total to eight files in the project all together. Upon loading, tokenizing, running or viewing program 0 in the Memory Map, the editor will read the $STAMP directive, determine if the indicated files exist, will load them if necessary and change their captions to indicate the project they belong to and their associated program number. After the directive is tokenized properly, and all associated files are labeled properly, tokenizing, running or viewing any program in the Memory Map will result in that program’s entire project being tokenized, downloaded or viewed.
+
When program #0 of a multi-file project is opened from diskette, the entire project will be loaded (all referenced files) as well. When a file that is part of a multi-file project is closed, the entire project (all the associated files) will be closed as well.
+
Creating a Multi-File Project
+
To create a project consisting of multiple files, follow these steps:
+
+
Create the first file in the editor and save it (we'll call it Sample.bsx). This will be the program that is downloaded into program slot 0.
+
Create at least one other file in the editor and save it also (we'll call it NextProgram.bsx).
+
+
Note: At this point the editor tabs will be:
+
0:Sample.bsx and 0:NextProgram.bsx.
+
...indicating that there are two unrelated files open "Sample.bsx" and "NextProgram.bsx" and each will be downloaded into program slot 0.
+
+
Go back to the first program and enter or modify the $STAMP directive using the project format. Use "NextProgram" as the File2 argument. For example:
+
+
' {$STAMP BS2sx, NextProgram.bsx}
+
+
Then tokenize the code by pressing F7 or selecting Run → Check Syntax from the menu.
+
+
At this point, the BASIC Stamp Editor will see the $STAMP directive and realize that this file (Sample.bsx) is the first file in a project and that the second file should be NextProgram.bsx. It will then search for the file on the hard drive (to verify its path is correct), will see that it is already loaded, and then will change the editor tabs to indicate the project relationship. At this point the editor tabs will be:
+
0:Sample.bsx and [Sample] 1:NextProgram.bsx.
+
...indicating that there are two related files open; "Sample.bsx" and "NextProgram.bsx". NextProgram.bsx belongs to the "Sample" project and it will be downloaded into program slot 1 and Sample.bsx will be downloaded into program slot 0.
(See Operator Precedence for details of the sequence in which expression operators are evaluated.)
+
Binary and Unary Operators
+
There are two types of operators in PBASIC, binary operators which require two arguments (such as the addition operator in 2 + 3) and unary operators which require one argument (such as the negate operator in -5). All the PBASIC operators are shown below, grouped under binary operators or unary operators. Click on any operator to see a full description on the Binary Operator or Unary Operator page.
+
Notes about the 16-bit workspace
+
Many of the operator descriptions will say something like "computes (some function) of a 16-bit number." This does not mean that the operator does not work on smaller byte or nibble values, but rather that the computation is done in a 16-bit workspace. If the value is smaller than 16 bits, the BASIC Stamp pads it with leading 0s to make a 16-bit value. If the 16-bit result of a calculation is to be packed into a smaller variable, the higher-order bits are discarded (truncated).
(See PBASIC Operators for a complete list of all PBASIC operators, with links to explanations of each.)
+
+
Left-to-Right Evaluation
+
The BASIC Stamp solves math problems in the order they are written;
+from left to right. The result of each operation is fed into the next
+operation. So to compute:
+
12 + 3 * 2 / 4
+
+
...the BASIC Stamp goes through a
+sequence like this:
+
12 + 3 = 15 15 * 2 = 30 30 / 4 = 7
+
+
Note that since the BASIC Stamp performs integer math (whole numbers
+only) 30 / 4 results in 7, not 7.5.
+
Some other dialects of BASIC would compute that same expression based
+on their precedence of operators, which requires that multiplication and
+division be done before addition. So the result would be:
+
3 * 2 = 6 6 / 4 = 1 12 + 1 = 13
+
+
Once again, because of integer math, the fractional portion of 6 / 4 is
+dropped, so we get 1 instead of 1.5.
+
Unary operators (those with one argument) take precedence over binary operators (those with two arguments); the unary operation is always performed first. For example, on all BS2 models, SQR is the unary operator for square root. In the expression:
+
10 - SQR 16
+
...the BASIC Stamp first takes the square root of 16, then subtracts it from 10.
+
Using Parentheses
+
+
+
The BS1 does not allow parentheses in expressions. Unfortunately, all
+expressions have to be written so that they evaluate as intended strictly
+from left to right. The negative operator is the only unary operator for the BS1.
+
+
+
The BS2 family modules, however, allow parentheses to be
+used to change the order of evaluation. Enclosing a math operation in
+parentheses gives it priority over other operations. To make the BASIC Stamp
+compute the previous expression in the conventional way, you would write it
+as 12 + (3 * 2 / 4). Within the parentheses, the BASIC Stamp works from left
+to right. If you wanted to be even more specific, you could write 12 +
+((3 * 2) / 4). When there are parentheses within parentheses, the BASIC
+Stamp works from the innermost parentheses outward. Parentheses
+placed within parentheses are called nested parentheses.
+
Integer Math
+
The BASIC Stamp performs all math operations by the rules of positive integer math. That is, it handles only whole numbers, and drops any fractional portions from the results of computations. The BASIC Stamp handles negative numbers using two's complement rules.
+
All BS2 models can interpret two's complement negative numbers correctly in DEBUG and SEROUT instructions using formatters like SDEC (for signed decimal). In calculations, however, it assumes that all values are positive. This yields correct results with two's complement negative numbers for addition, subtraction, and multiplication, but not for division.
Many of the operator descriptions will say something like "computes (some function) of a 16-bit number." This does not mean that the operator does not work on smaller byte or nibble values, but rather that the computation is done in a 16-bit workspace. If the value is smaller than 16 bits, the BASIC Stamp pads it with leading 0s to make a 16-bit value. If the 16-bit result of a calculation is to be packed into a smaller variable, the higher-order bits are discarded (truncated).
The Addition operator (+) adds variables and/or constants, returning a 16-bit
+result. It works exactly as you would expect with unsigned integers from 0 to 65535.
+If the result of addition is larger than 65535, the carry bit will be lost. If the
+values added are signed 16-bit numbers and the destination is a 16-bit variable,
+the result of the addition will be correct in both sign and value.
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ value1 = -99
+ value2 = 100
+ value1 = value1 + value2 ' Add the numbers
+ DEBUG value1 ' Show the result (1)
+ END
+
+
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ value1 = -1575
+ value2 = 976
+ value1 = value1 + value2 ' Add the numbers
+ DEBUG SDEC ? value1 ' Show the result (-599)
+ END
+
The Subtraction operator (-) subtracts variables and/or constants, returning
+a 16-bit result. It works exactly as you would expect with unsigned integers from 0
+to 65535. If the result is negative, it will be correctly expressed as a signed
+16-bit number.
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ value1 = 199
+ value2 = 100
+ value1 = value1 - value2 ' Subtract value2 from value1
+ DEBUG value1 ' Show the result (99)
+ END
+
+
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ value1 = 1000
+ value2 = 1999
+ value1 = value1 - value2 ' Subtract value2 from value1
+ DEBUG SDEC ? value1 ' Show the result (-999)
+ END
+
The Multiply operator (*) multiplies variables and/or constants, returning
+the low 16 bits of the result. It works exactly as you would expect with
+unsigned integers from 0 to 65535. If the result of multiplication is larger
+than 65535, the excess bits will be lost. Multiplication of signed variables
+will be correct in both number and sign, provided that the result is in the
+range -32767 to +32767.
+
+
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ value1 = 1000
+ value2 = 19
+ value1 = value1 * value2 ' Multiply the numbers
+ DEBUG value1 ' Show the result (19000)
+ END
+
+
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ value1 = 1000
+ value2 = 19
+ value1 = value1 * value2 ' Multiply the numbers
+ DEBUG SDEC ? value1 ' Show the result (19000)
+ END
+
The Multiply High operator (**) multiplies variables and/or constants,
+returning the high 16 bits of the result. When you multiply two 16-bit
+values, the result can be as large as 32 bits. Since the largest variable
+supported by PBASIC is 16 bits, the highest 16 bits of a 32-bit
+multiplication result are normally lost. The ** (double-star) operator gives you these upper 16 bits. For example, suppose you multiply 65000
+($FDE8) by itself. The result is 4,225,000,000 or $FBD46240. The * (star, or
+normal multiplication) operator would return the lower 16 bits, $6240.
+The ** operator returns $FBD4.
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ value1 = $FDE8
+ value1 = value1 ** value1 ' Multiply value1 by itself
+ DEBUG HEX ? value1 ' Show upper 16 bits
+ END
+
+
An interesting application of the ** operator is to multiply by a known
+fractional value less than one. The fraction value is expressed in units
+of 1/65536. To find the fractional ** parameter, multiply the fraction part
+by 65536. Example:
+
+SYMBOL Frac = 47554 ' = 0.72562 x 65536
+SYMBOL value = W0
+
+Test:
+ value = 10000
+ value = value ** Frac ' Multiply 10000 by 0.72562
+ DEBUG value ' Show result (7256)
+
+
+Frac CON 47554 ' = 0.72562 x 65536
+value VAR Word
+
+Test:
+ value = 10000
+ value = value ** Frac ' Multiply 10000 by 0.72562
+ DEBUG ? value ' Show result (7256)
+
The Multiply Middle operator (*/) multiplies variables and/or constants,
+returning the middle 16 bits of the 32-bit result. This has the effect of
+multiplying a value by a whole number and a fraction. The whole number
+is the upper byte of the multiplier (0 to 255 whole units) and the fraction is
+the lower byte of the multiplier (0 to 255 units of 1/256 each). The */ (star-slash)
+operator gives you an excellent workaround for the BASIC Stamp's integer-only
+math. Suppose you want to multiply a value by 1.5. The whole number, and therefore
+the upper byte of the multiplier, would be 1, and the lower byte (fractional part)
+would be 128, since 128/256 = 0.5. It may be clearer to express the */ multiplier
+in hex—as $0180—since hex keeps the contents of the upper and lower bytes separate.
+
+
+
+
+
+
+value1 VAR Word
+
+Main:
+ value1 = 100
+ value1= value1 */ $0180 ' Multiply by 1.5 [1 + (128/256)]
+ DEBUG ? value1 ' Show result (150)
+ END
+
+
To calculate constants for use with the */ operator, take the desired (mixed) target multiplier and multiply it by 256, then convert the result to a whole integer: INT(mixed * 256). For instance, if our target multiplier is Pi
+(3.14159), the resulting constant to represent that value for the */ operator is INT(3.13159 * 256) = INT(804.25) = 804 ($0324). Notice that the upper byte is $03 (decimal 3; the whole number), and the lower
+byte is $24 (decimal 36; the fractional part that means 36/256). So the constant Pi for use with */
+would be $0324. This isn’t a perfect match for Pi, but the error is only
+about 0.1%.
The Division operator (/) divides variables and/or constants, returning a
+16-bit result. It works exactly as you would expect with unsigned integers
+from 0 to 65535. Use / only with positive values; signed values do not
+provide correct results. Here’s an example of unsigned division:
+
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ value1 = 1000
+ value2 = 5
+ value1 = value1 / value2 ' Divide the numbers
+ DEBUG value1 ' Show the result (200)
+ END
+
+
+value1 VAR Word
+Value2 VAR Word
+
+Main:
+ value1 = 1000
+ value2 = 5
+ value1 = value1 / value2 ' Divide the numbers
+ DEBUG DEC ? value1 ' Show the result (200)
+ END
+
+
A workaround to the inability to divide signed numbers is to have your
+program divide absolute values, then negate the result if one (and only
+one) of the operands was negative. All values must lie within the range of
+-32767 to +32767.
+
+sign VAR Bit ' bit to hold the sign
+value1 VAR Word
+Value2 VAR Word
+
+Main:
+ value1 = 100
+ value2 = -3200
+ sign = value1.Bit15 ^ value2.Bit15 ' determine result sign
+ value2 = ABS value2 / ABS value1 ' divide absolute values
+ IF (sign = 1) THEN value2 = -value2 ' correct sign if negative
+ DEBUG SDEC ? value2 ' show the result (-32)
+ END
+
The Modulus operator (//) returns the remainder left after dividing one
+value by another. Some division problems don’t have a whole-number
+result; they return a whole number and a fraction. For example, 1000 / 6 =
+166.667. Integer math doesn’t allow the fractional portion of the result, so
+1000 / 6 = 166. However, 166 is an approximate answer, because 166 * 6 =
+996. The division operation left a remainder of 4. The // (double-slash)
+operator returns the remainder of a given division operation. Naturally, numbers
+that divide evenly, such as 1000 / 5, produce a remainder of 0.
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ value1 = 1000
+ value2 = 6
+ value1 = value1 // value2 ' get remainder of value1 / value2
+ DEBUG value1 ' show the result (4)
+ END
+
+
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ value1 = 1000
+ value2 = 6
+ value1 = value1 // value2 ' get remainder of value1 / value2
+ DEBUG DEC ? value1 ' show the result (4)
+ END
+
The Minimum operator (MIN) limits a value to a specified 16-bit positive
+minimum. The syntax of MIN is:
+
Value MIN Limit
+
+
+
Where Value is a constant or variable value to perform the MIN function
+upon and Limit is the minimum Value that value is allowed to be. When used in a statement like result = Value MIN Limit, its
+logic is, 'if Value is less than Limit, then make result =
+Limit; if Value is greater than or equal to Limit, make
+result = Value.' MIN works in positive math only; its comparisons are not
+valid when used on two’s complement negative numbers, since the positive-integer representation of a number like -1 ($FFFF in hexadecimal or 65535 in unsigned decimal) is larger
+than that of a number like 10 ($000A hexadecimal or 10 decimal). Use MIN only with unsigned
+integers. Because of the way fixed-size integers work, you should be careful when
+using an expression involving MIN 0. For example, result = 0 - 1 MIN 0 will result in
+65535 because 0 - 1 = -1 (65535 in two's compliment math) and 65535 is greater the minimum boundary 0.
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ FOR value1 = 100 TO 0 STEP -10 ' walk value1 from 100 to 0
+ value2 = value1 MIN 50 ' use MIN to clamp at 50
+ DEBUG value2 ' show "clamped" value
+ NEXT
+ END
+
+
+value1 VAR Word
+value2 VAR Word
+
+Main:
+ FOR value1 = 100 TO 0 STEP 10 ' walk value1 from 100 to 0
+ value2 = value1 MIN 50 ' use MIN to clamp at 50
+ DEBUG DEC ? value2 MIN 50 ' show "clamped" value
+ NEXT
+ END
+
The Maximum operator (MAX) limits a value to a specified 16-bit positive maximum.
+The syntax of MAX is:
+
Value MAX Limit
+
...where Value is a constant or variable value to perform the MAX function
+upon and Limit is the maximum value that Value is allowed to be. When used in a statement like result = Value MAX Limit, its
+logic is, ‘if Value is greater than Limit, then make result =
+Limit; if Value is less than or equal to Limit, make result =
+Value.’ MAX works in positive math only; its comparisons are not valid when
+used on two’s complement negative numbers, since the positive-integer representation
+of a number like -1 ($FFFF in hexadecimal or 65535 in unsigned decimal) is larger than that of a
+number like 10 ($000A hexadecimal or 10 decimal). Use MAX only with unsigned integers. Because
+of the way fixed-size integers work, you should be careful when using an expression
+involving MAX 65535. For example, result = 65535+1 MAX 65535 will result in 0 because 65535 + 1 = 0 (in 16-bits) and 0 is less than the maximum boundary 65535.
+
+SYMBOL value1 = W0
+SYMBOL value2 = W1
+
+Main:
+ FOR value1 = 0 TO 100 STEP 10 ' Walk value1 from 0 to 100
+ value2 = value1 MAX 50 ' Use MAX to clamp at 50
+ DEBUG value2 ' Show "clamped" value
+ NEXT
+ END
+
+
+value VAR Word
+
+Main:
+ FOR value = 0 TO 100 STEP 10 ' Walk value from 0 to 100
+ DEBUG ? value MAX 50 ' Show "clamped" value
+ NEXT
+ END
+
The Digit operator (DIG) returns the specified decimal digit of a 16-bit positive
+value. Digits are numbered from 0 (the right-most digit) to 4 (the left-most digit
+of a 16-bit number; 0 to 65535).
+
+
+
+
+
+value VAR Word
+idx VAR Nib
+
+Main:
+ value = 9742
+ DEBUG ? value DIG 2 ' Show digit 2 (7)
+
+ FOR idx = 0 TO 4
+ DEBUG ? value DIG idx ' Show digits 0 - 4 of 9742
+ NEXT
+ END
+
The Reverse operator (REV) returns a reversed (mirrored) copy of a specified number
+of bits of a value, starting with the rightmost bit (LSB). For instance,
+%10101101 REV 4 would return %1011, a mirror image of the least significant four bits of the
+value.
+
+
The Shift Left operator (<<) shifts the bits of a value to the left a
+specified number of places. Bits shifted off the left end of a number are lost;
+bits shifted into the right end of the number are 0s. Shifting the bits of a
+value left n number of times has the same effect as multiplying that number by 2
+to the nth power. For instance 100 << 3 (shift the bits of the decimal
+number 100 left three places) is equivalent to 100 * 23.
+
+
+
+
+
+value VAR Word
+idx VAR Byte
+
+Main:
+ value = %1111111111111111
+
+ FOR idx = 1 TO 16 ' loop 16 times
+ DEBUG BIN16 ? Value << idx ' display shifted value
+ NEXT
+ END
+
The Shift Right operator (>>) shifts the bits of a variable to the right a
+specified number of places. Bits shifted off the right end of a number are lost;
+bits shifted into the left end of the number are 0s. Shifting the bits of a value
+right n number of times has the same effect as dividing that number (unsigned) by 2 to the
+nth power. For instance 100 >> 3 (shift the bits of the decimal number 100 right
+three places) is equivalent to 100 / 23.
+
+value VAR Word
+idx VAR Byte
+
+Main:
+ value = %1111111111111111
+
+ FOR idx = 1 TO 16 ' loop 16 times
+ DEBUG BIN16 ? Value >> idx ' display shifted value
+ NEXT
+ END
+
The Bitwise AND (&) operator returns the bit pattern of the logical AND of each bit pair in two binary values. Each bit of these values is subject to the following logic:
0 & 0 = 0
+ 0 & 1 = 0
+ 1 & 0 = 0
+ 1 & 1 = 1
+
+
The result returned by & will contain 1s in only those bit positions in which
+both input values contain 1s.
+
+SYMBOL value1 = B0
+SYMBOL value2 = B1
+SYMBOL result = B2
+
+Main:
+ value1 = %00001111
+ value2 = %10101101
+ result = value1 & value2
+ DEBUG %result ' Show AND result (%00001101)
+ END
+
+
+ DEBUG BIN8 ? %00001111 & %10101101 ' Show AND result (%00001101)
+
The Bitwise OR (|) operator returns the bit pattern of the logical OR of each bit pair in two binary values. Each bit of the values is subject to the following logic:
0 | 0 = 0
+ 0 | 1 = 1
+ 1 | 0 = 1
+ 1 | 1 = 1
+
+
The result returned by | will contain 1s in any bit positions in which one or
+the other (or both) input values contain 1s.
+
+SYMBOL value1 = B0
+SYMBOL value2 = B1
+SYMBOL result = B2
+
+Main:
+ value1 = %00001111
+ value2 = %10101001
+ result = value1 | value2
+ DEBUG %result ' Show OR result (%10101111)
+ END
+
+
+ DEBUG BIN8 ? %00001111 | %10101001 ' Show OR result (%10101111)
+
The Bitwise Exclusive OR operator (|) returns the bit pattern of the logical XOR of each bit pair in two binary values. Each bit of the values is subject to the following logic:
0 ^ 0 = 0
+ 0 ^ 1 = 1
+ 1 ^ 0 = 1
+ 1 ^ 1 = 0
+
+
The result returned by ^ will contain 1s in any bit positions in which one or
+the other (but not both) input values contain 1s.
+
+SYMBOL value1 = B0
+SYMBOL value2 = B1
+SYMBOL result = B2
+
+Main:
+ value1 = %00001111
+ value2 = %10101001
+ result = value1 ^ value2
+ DEBUG %result ' Show OR result (%10100110)
+ END
+
+
+ DEBUG BIN8 ? %00001111 ^ %10101001 ' Show OR result (%10100110)
+
The Bitwise AND NOT operator (&/) returns the bit pattern of the logical AND NOT of each bit pair in two binary values. Each bit of the values is subject to the following logic:
The Bitwise XOR NOT operator (^/) returns the bit pattern of the logical XOR NOT of each bit pair in two binary values. Each bit of
+the values is subject to the following logic:
+
+
The AND operator returns the logical AND of two values or expressions. Note that
+in the BASIC Stamp, a non-zero value is considered True (T), zero is considered
+False (F). The values/expressions are subject to the following logic:
+
F AND F = F
+ F AND T = F
+ T AND F = F
+ T AND T = T
+
+
The result returned by AND will be True or False.
+
+score VAR Byte
+avg VAR Byte
+
+Main:
+ score = 93
+ avg = 89
+
+ IF (score > 80) AND (avg > 70) THEN
+ DEBUG "Promote to next grade." ' both conditions are True
+ ELSE
+ DEBUG "Consider additional tutoring." ' at least one condition is False
+ ENDIF
+ END
+
The OR operator returns the logical OR of two values or expressions. Note that
+in the BASIC Stamp, a non-zero value is considered True (T), zero is considered
+False (F). The values/expressions are subject to the following logic:
F OR F = F
+ F OR T = T
+ T OR F = T
+ T OR T = T
+
+
The result returned by OR will be True or False.
+
+score VAR Byte
+avg VAR Byte
+
+Main:
+ score = 63
+ avg = 89
+
+ IF (score < 80) OR (avg < 70) THEN
+ DEBUG "Consider additional tutoring." ' at least one condition is True
+ ELSE
+ DEBUG "Promote to next grade." ' both conditions are False
+ ENDIF
+ END
+
The XOR operator returns the logical Exclusive OR of two values or expressions.
+Note that in the BASIC Stamp, a non-zero value is considered True (T), zero is
+considered False (F). The values/expressions are subject to the following logic:
F XOR F = F
+ F XOR T = T
+ T XOR F = T
+ T XOR T = F
+
+
The XOR operator can be confusing at first. An easy way to remember the logic
+is: If one or the other is True -- but not both -- then the result is True,
+otherwise the result is False.
+
The result returned by XOR will be True or False.
+
+turnL VAR Bit
+turnR VAR Bit
+
+Main:
+ turnL = 0
+ turnR = 1
+
+ IF (turnL = 1) XOR (turnR = 1) THEN ' one or other is True
+ DEBUG "Turning - ", "L" + ("R" - "L" * turnR)
+ ELSE
+ DEBUG "Continue straight." ' both True or both False
+ ENDIF
+ END
+
The Arctangent operator (ATN) returns the angle to the vector specified by X and
+Y coordinate values. In the BASIC Stamp, the angle is returned in binary radians
+(0 to 255) instead of degrees (0 to 359). Coordinate input values are limited from
+-127 to 127 (signed bytes) as shown in the diagram below:
+
+
+
+
+
+
+
+idx VAR Nib ' loop counter
+xCoord VAR Byte ' x coordinate of vector
+yCoord VAR Byte ' y coordinate of vector
+brads VAR Word ' angle in brads
+degr VAR Word ' angle in degrees
+
+Main:
+ FOR idx = 0 TO 7 ' load vector data
+
+ LOOKUP idx, [ 1, 1, 0, -1, -1, -1, 0, 1], xCoord
+ LOOKUP idx, [ 0, 1, 1, 1, 0, -1, -1, -1], yCoord
+
+ brads = xCoord ATN yCoord ' get angle of vector
+ degr = brads * 180 / 128 ' convert to degrees
+
+ DEBUG DEC (idx + 1), ": ",
+ "ATN (", SDEC xCoord, ", ", SDEC yCoord, ")",
+ CRSRX, 18, "= ", DEC brads, " (", DEC degr, ")", CR
+ NEXT
+ END
+
The Hypotenuse operator (HYP) returns the length of the hypotenuse of a right
+triangle with sides of length A and B. Side length (vector) input values are
+limited to -127 to 127 (signed bytes).
Many of the operator descriptions will say something like "computes (some function) of a 16-bit number." This does not mean that the operator does not work on smaller byte or nibble values, but rather that the computation is done in a 16-bit workspace. If the value is smaller than 16 bits, the BASIC Stamp pads it with leading 0s to make a 16-bit value. If the 16-bit result of a calculation is to be packed into a smaller variable, the higher-order bits are discarded (truncated).
The Absolute Value operator (ABS) converts a signed (two’s complement)
+16-bit number to its absolute value. The absolute value of a number is a
+positive number representing the difference between that number and 0.
+For example, the absolute value of -99 is 99. The absolute value of 99 is
+also 99. ABS works on two’s complement negative numbers. Here's an example
+of ABS at work:
+
+result VAR Word
+
+Main:
+ result = -99
+ DEBUG SDEC ? result ' Display -99
+ DEBUG SDEC ? ABS result ' Display 99
+ END
+
The Negative operator (-) negates a 16-bit number (converts to its two’s
+complement).
+
+SYMBOL result = W1
+
+Main:
+ result = -99 ' Initialize result
+ result = result + 100 ' Add 100 to it
+ DEBUG result ' Display result (1)
+ END
+
+
+result VAR Word
+
+Main:
+ result = -99 ' Initialize result
+ DEBUG SDEC result ' Display result (-99)
+ result = result + 100 ' Add 100 to it
+ DEBUG SDEC result ' Display result (1)
+ END
+
The Inverse operator (~) complements (inverts) the bits of a number. Each bit that contains a 1 is changed to 0 and each bit containing 0 is changed to
+1. This process is also known as a "bitwise NOT" and one's complement.
+
~0 = 1
+ ~1 = 0
+
+
+result VAR Byte
+
+Main:
+ result = %11110001 ' Store bits in result
+ DEBUG BIN8 ? result ' Display %11110001
+ result = ~result ' Complement result
+ DEBUG BIN8 ? result ' Display %00001110
+ END
+
The Decoder operator (DCD) is a 2n-power decoder of a four-bit
+value. DCD accepts a value from 0 to 15, and returns a 16-bit number with the
+bit, described by value, set to 1.
+
+result VAR Word
+
+Main:
+ result = DCD 12 ' Set bit 12.
+ DEBUG BIN ? result ' Display %0001000000000000
+ END
+
The Encoder operator (NCD) is a "priority" encoder of a 16-bit value. NCD
+takes a 16-bit value, finds the highest bit containing a 1 and returns the bit
+position plus one (1 through 16). If no bit is set (the input value is 0) NCD
+returns 0. NCD is a fast way to get an answer to the question "What is the
+largest power of two that this value is greater than or equal to?" The
+value NCD returns will be that power, plus one.
+
+result VAR Nib
+
+Main:
+ result = %1101 ' Highest bit set is bit 3
+ DEBUG ? NCD result ' Show the NCD of Result (4)
+ END
+
The Sine operator (SIN) returns the two’s complement, 16-bit Sine of an
+angle specified as an 8-bit (0 to 255) value. To understand the SIN operator
+more completely, let’s look at a typical Sine function. By definition: given a
+circle with a radius of 1 unit (known as a unit circle), the Sine is the y-coordinate
+distance from the center of the circle to its edge at a given
+angle. Angles are measured relative to the 3-o'clock position on the circle,
+increasing as you go around the circle counterclockwise.
+
At the origin point (0 degrees) the Sine is 0, because that point has the
+same y (vertical) coordinate as the circle center. At 45 degrees the Sine is
+0.707. At 90 degrees, Sine is 1. At 180 degrees, Sine is 0 again. At 270
+degrees, Sine is -1.
+
The BASIC Stamp SIN operator breaks the circle into 0 to 255 units instead
+of 0 to 359 degrees. Some textbooks call this unit a binary radian or brad.
+Each brad is equivalent to 1.406 degrees. And instead of a unit circle,
+which results in fractional Sine values between 0 and 1, BASIC Stamp SIN
+is based on a 127-unit circle. Results are given in two’s complement form
+in order to accommodate negative values. So, at the origin, SIN is 0. At 45
+degrees (32 brads), Sine is 90. At 90 degrees (64 brads), Sine is 127. At 180
+degrees (128 brads), Sine is 0 again. At 270 degrees (192 brads), Sine is -127.
+
See the image below for the relationship between degrees and brads and how the SIN
+function values relate to to the 127-unit circle.
+
+
+
+
+
+
+
+degr VAR Word
+sine VAR Word
+
+Main:
+ FOR degr = 0 TO 359 STEP 45 ' Use degrees
+ sine = SIN (degr * 128 / 180) ' Convert to brads, do SIN
+ DEBUG "Angle: ", DEC degr, TAB ' Display results
+ DEBUG "Sine: ", SDEC sine, CR
+ NEXT
+ END
+
The Cosine operator (COS) returns the two’s complement, 16-bit Cosine of an
+angle specified as an 8-bit (0 to 255) value. To understand the COS operator
+more completely, let’s look at a typical Cosine function. By definition: given a
+circle with a radius of 1 unit (known as a unit circle), the Cosine is the x-coordinate
+distance from the center of the circle to its edge at a given angle. Angles are
+measured relative to the 3-o'clock position on the circle, increasing as you go
+around the circle counterclockwise.
+
At the origin point (0 degrees) the Cosine is 1, because that point has the
+same x (horizontal) coordinate as the circle radius. At 45 degrees the Cosine is
+0.707. At 90 degrees, Cosine is 0. At 180 degrees, Cosine is -1. At 270
+degrees, Cosine is 0 again.
+
The BASIC Stamp COS operator breaks the circle into 0 to 255 units instead
+of 0 to 359 degrees. Some textbooks call this unit a binary radian or brad.
+Each brad is equivalent to 1.406 degrees. And instead of a unit circle,
+which results in fractional Cosine values between 0 and 1, BASIC Stamp COS
+is based on a 127-unit circle. Results are given in two’s complement form
+in order to accommodate negative values. So, at the origin, COS is 127. At 45
+degrees (32 brads), COS is 90. At 90 degrees (64 brads), COS is 0. At 180
+degrees (128 brads), Cosine is -127. At 270 degrees (192 brads), Cosine is 0 again.
+
See the image below for the relationship between degrees and brads and how the COS
+function values relate to to the 127-unit circle.
+
+
+
+
+
+
+degr VAR Word
+cosine VAR Word
+
+Main:
+ FOR degr = 0 TO 359 STEP 45 ' Use degrees
+ cosine = COS (degr * 128 / 180) ' Convert to brads, do COS
+ DEBUG "Angle: ", DEC degr, TAB ' Display results
+ DEBUG "Cosine: ", SDEC cosine, CR
+ NEXT
+ END
+
The Square Root operator (SQR) computes the integer square root of an
+unsigned 16-bit number. (The number must be unsigned since the square
+root of a negative number is an 'imaginary' number.) Remember that most
+square roots have a fractional part that the BASIC Stamp discards when
+doing its integer-only math. So it computes the square root of 100 as 10
+(correct), but the square root of 99 as 9 (the actual is close to 9.95).
The NOT operator returns the logical NOT of an expression. Note that in the
+BASIC Stamp, a non-zero value is considered True (T), zero is considered
+False (F). The expression is subject to the following logic:
+
NOT F = T
+ NOT T = F
+
+
The result returned by NOT will be True or False.
+
+speed VAR Byte
+
+Main:
+ DEBUG CLS, "Enter speed: "
+ DEBUGIN DEC speed
+ IF NOT (speed < 65) THEN ' speed must be less than 65
+ DEBUG CR, "Sorry ... too fast!"
+ ELSE
+ DEBUG CR, "Enjoy your trip."
+ ENDIF
+ END
+
With the introduction of PBASIC 2.5 syntax comes the PIN directive. The
+purpose of the PIN directive is to give an alias to an I/O pin and let the
+compiler determine whether a given line of code requires a numeric value for the
+pin, the output bit for that pin, or the input bit for that pin. Using the PIN directive simplifies I/O pin aliasing in sophisticated programs.
+
PIN Syntax
+
Syntax: PIN_SymbolPINPin_Number
+
+
PIN_Symbol is a unique symbol name that will be
+ used as an alias for the I/O pin number Pin_Number.
+
Pin_Number is an I/O pin number (0 to 15)
+
+
Summary of PIN Behaviors in Context
+
PIN_Symbol behaves like a constant:
+
+
...when used in a command’s Pin argument. Example:
+
OUTPUT PIN_Symbol
+
+
...when used in the index of an array. Example:
+
myArray(PIN_Symbol) = 25
+
PIN_Symbol behaves like an input variable (INx):
+
+
...when used in a command’s non-Pin argument that expects to read a variable/constant/expression. Example:
+
DEBUG BIN PIN_Symbol
+
+
...when used in a command’s Condition argument. Example:
+
IF PIN_Symbol = 1 THEN…
+
+
...when used to the right of the equal sign (=) in an assignment statement. Example:
+
myVariable = PIN_Symbol + 1
+
PIN_Symbol behaves like an output variable (OUTx):
+
+
...when used in a command’s non-Pin argument that expects to write a result to a variable. Example:
+
LOOKUP index, [0, 1, 1, 0, 1], PIN_Symbol
+
+
...when used to the left of the equal sign (=) in an assignment statement. Example:
+
PIN_Symbol = 1
+
PIN Examples
+
Using the PIN declaration is similar to CON:
+' {$PBASIC 2.5}
+
+RedLED PIN 0 ' red LED is connected to pin 0
+
+IsOn CON 1 ' LED is active high
+IsOff CON 0
+
+Setup:
+ OUTPUT RedLED ' same as OUTPUT 0
+
+Main:
+ DO
+ RedLED = IsOn ' same as Out0 = 1
+ PAUSE 1000
+ RedLED = IsOff ' same as Out0 = 0
+ PAUSE 1000
+ LOOP
+
+
Most programs will work like the example above where a given I/O pin will
+either be an input or an output. There are times, however, when a change in
+function is required mid program. Prior to PBASIC 2.5, programmers wishing to
+use named constants were forced to create redundant definitions or complicated
+modifiers. For example:
+' {$PBASIC 2.0}
+
+SDA CON 8 ' I2C data I/O
+SCL CON 9 ' I2C clock output
+
+...
+
+I2C_Start:
+ INPUT SDA
+ INPUT SCL
+ LOW SDA
+
+Clock_Hold: ' monitor device clock hold
+ IF (INS.LOWBIT(SCL) = 0) THEN Clock_Hold ' <-- tricky modifiers
+ RETURN
+
+
With PBASIC 2.5 the tricky modifiers can be eliminated:
+' {$PBASIC 2.5}
+
+SDA PIN 8 ' I2C data I/O
+SCL PIN 9 ' I2C clock output
+
+...
+
+I2C_Start:
+ INPUT SDA
+ INPUT SCL
+ LOW SDA
+
+Clock_Hold: ' monitor device clock hold
+ DO : LOOP WHILE (SCL = 0) ' easier, same as "IN9 = 0"
+ RETURN
+
+
The compiler is "smart" and knows how to replace a PIN directive with a
+constant value, an INS register bit or and OUTS register bit. Note that as in
+the example above, the programmer is still responsible for setting the DIRS bit
+of the I/O pin as required by the program.
Here are complete listings of the reserved words for PBASIC 1.0, PBASIC 2.0, and PBASIC 2.5. The reserved word lists have been organized into 5 tables, because it varies with each BASIC Stamp model and version of PBASIC.
+
+ BASIC Stamp 1
+
The table below shows the reserved words for the BASIC Stamp 1, using the required PBASIC 1.0.
+
+
+
BS1
+
+
+
+
AND
+
+
GOSUB
+
+
N2400
+
+
PIN0..PIN7
+
+
SOUND
+
+
+
+
B0..B13
+
+
GOTO
+
+
NAP
+
+
PINS
+
+
STEP
+
+
+
+
BIT0..BIT15
+
+
HIGH
+
+
NEXT
+
+
PORT
+
+
SYMBOL
+
+
+
+
BRANCH
+
+
IF
+
+
ON300
+
+
POT
+
+
T300
+
+
+
+
BSAVE
+
+
INPUT
+
+
ON600
+
+
PULSIN
+
+
T600
+
+
+
+
BUTTON
+
+
LET
+
+
ON1200
+
+
PULSOUT
+
+
T1200
+
+
+
+
CLS
+
+
LOOKDOWN
+
+
ON2400
+
+
PWM
+
+
T2400
+
+
+
+
CR
+
+
LOOKUP
+
+
OR
+
+
RANDOM
+
+
THEN
+
+
+
+
DEBUG
+
+
LOW
+
+
OT300
+
+
READ
+
+
TO
+
+
+
+
DIR0..DIR7
+
+
MAX
+
+
OT600
+
+
RETURN
+
+
TOGGLE
+
+
+
+
DIRS
+
+
MIN
+
+
OT1200
+
+
REVERSE
+
+
W0..W6
+
+
+
+
EEPROM
+
+
N300
+
+
OT2400
+
+
SERIN
+
+
WRITE
+
+
+
+
END
+
+
N600
+
+
OUTPUT
+
+
SEROUT
+
+
+
+
+
+
FOR
+
+
N1200
+
+
PAUSE
+
+
SLEEP
+
+
+
+
+
+
+
+ All BASIC Stamp 2 models
+
The table below lists the reserved words common to all BS2 models, including those for PBASIC 2.0 and PBASIC 2.5. Words that are only reserved when using PBASIC 2.5 are marked with (2.5).
+
+
+
All BS2 Models
+
+
+
+
#CASE2.5
+
CRSRX2.5
+
INC
+
+
PULSIN
+
+
+
+
#DEFINE2.5
+
CRSRXY2.5
+
IND
+
+
PULSOUT
+
+
+
+
#ELSE2.5
+
CRSRY2.5
+
INH
+
+
PWM
+
+
+
+
#ENDIF2.5
+
DATA
+
+
INL
+
+
RANDOM
+
+
+
+
#ENDSELECT2.5
+
DCD
+
+
INPUT
+
+
RCTIME
+
+
+
+
#ERROR2.5
+
DEBUG
+
+
INS
+
+
READ
+
+
+
+
#IF2.5
+
DEBUGIN2.5
+
ISBIN
+
+
REP
+
+
+
+
#SELECT2.5
+
DEC
+
+
ISBIN1...ISBIN16
+
+
RETURN
+
+
+
+
#THEN2.5
+
DEC1...DEC5
+
+
ISHEX
+
+
REV
+
+
+
+
$PBASIC
+
+
DIG
+
+
ISHEX1...ISHEX4
+
+
REVERSE
+
+
+
+
$PORT
+
+
DIM
+
+
LF2.5
+
SBIN
+
+
+
+
$STAMP
+
+
DIR0...DIR15
+
+
LIGHTSON
+
+
SBIN1...SBIN16
+
+
+
+
ABS
+
+
DIRA
+
+
LOOKDOWN
+
+
SDEC
+
+
+
+
AND
+
+
DIRB
+
+
LOOKUP
+
+
SDEC1...SDEC5
+
+
+
+
ASC
+
+
DIRC
+
+
LOOP2.5
+
SELECT2.5
+
+
+
ATN
+
+
DIRD
+
+
LOW
+
+
SERIN
+
+
+
+
B0...B25
+
+
DIRH
+
+
LOWBIT
+
+
SEROUT
+
+
+
+
BELL
+
+
DIRL
+
+
LOWBYTE
+
+
SHEX
+
+
+
+
BIN
+
+
DIRS
+
+
LOWNIB
+
+
SHEX1...SHEX4
+
+
+
+
BIN1...BIN16
+
+
DO2.5
+
LSBFIRST
+
+
SHIFTIN
+
+
+
+
BIT
+
+
DTMFOUT
+
+
LSBPOST
+
+
SHIFTOUT
+
+
+
+
BIT0...BIT15
+
+
ELSE2.5
+
LSBPRE
+
+
SIN
+
+
+
+
BKSP
+
+
ELSEIF2.5
+
MAX
+
+
SKIP
+
+
+
+
BRANCH
+
+
END
+
+
MIN
+
+
SLEEP
+
+
+
+
BRIGHT
+
+
ENDIF2.5
+
MSBFIRST
+
+
SNUM
+
+
+
+
BS1
+
+
ENDSELECT2.5
+
MSBPOST
+
+
SQR
+
+
+
+
BS2
+
+
EXIT2.5
+
MSBPRE
+
+
STEP
+
+
+
+
BS2E
+
+
FOR
+
+
NAP
+
+
STOP
+
+
+
+
BS2P
+
+
FREQOUT
+
+
NCD
+
+
STR
+
+
+
+
BS2PE
+
+
GOSUB
+
+
NEXT
+
+
TAB
+
+
+
+
BS2SX
+
+
GOTO
+
+
NIB
+
+
THEN
+
+
+
+
BUTTON
+
+
HEX
+
+
NIB0...NIB3
+
+
TO
+
+
+
+
BYTE
+
+
HEX1...HEX4
+
+
NOT
+
+
TOGGLE
+
+
+
+
BYTE0
+
+
HIGH
+
+
NUM
+
+
UNITOFF
+
+
+
+
BYTE1
+
+
HIGHBIT
+
+
ON2.5
+
UNITON
+
+
+
+
CASE2.5
+
HIGHBYTE
+
+
OR
+
+
UNITSOFF
+
+
+
+
CLRDN2.5
+
HIGHNIB
+
+
OUT0...OUT15
+
+
UNTIL2.5
+
+
+
CLREOL2.5
+
HOME
+
+
OUTA
+
+
VAR
+
+
+
+
CLS
+
+
HYP
+
+
OUTB
+
+
W0...W12
+
+
+
+
CON
+
+
IBIN
+
+
OUTC
+
+
WAIT
+
+
+
+
COS
+
+
IBIN1...IBIN16
+
+
OUTD
+
+
WAITSTR
+
+
+
+
COUNT
+
+
IF
+
+
OUTH
+
+
WHILE2.5
+
+
+
CR
+
+
IHEX
+
+
OUTL
+
+
WORD
+
+
+
+
CRSRDN2.5
+
IHEX1...IHEX4
+
+
OUPUT
+
+
WRITE
+
+
+
+
CRSRLF2.5
+
IN0...IN15
+
+
OUTS
+
+
XOR
+
+
+
+
CRSRRT2.5
+
INA
+
+
PAUSE
+
+
XOUT
+
+
+
+
CRSRUP2.5
+
INB
+
+
PIN2.5
+
+
+
+
+
+
+ BS2e and BS2sx
+
The BS2e and BS2sx have all the reserved words shown in the All BASIC Stamp 2 Modules table, above, plus those shown in the table below. These additional words are reserved in both PBASIC 2.0 and PBASIC 2.5.
+
+
+
BS2e and BS2sx
+
+
+
+
GET
+
+
PUT
+
+
RUN
+
+
+
+
+
+ BS2p and BS2pe
+
The BS2p and BS2pe have all the reserved words shown in the All BASIC Stamp 2 Modules table, above, plus those shown in the table below. These additional words are reserved in both PBASIC 2.0 and PBASIC 2.5.
+
+
+
BS2p and BS2pe
+
+
+
+
AUXIO
+
+
LCDCMD
+
+
OWOUT
+
+
POLLWAIT
+
+
+
+
GET
+
+
LCDIN
+
+
POLLIN
+
+
PUT
+
+
+
+
I2CIN
+
+
LCDOUT
+
+
POLLMODE
+
+
RUN
+
+
+
+
I2COUT
+
+
MAINIO
+
+
POLLOUT
+
+
SPSTR
+
+
+
+
IOTERM
+
+
OWIN
+
+
POLLRUN
+
+
STORE
+
+
+
+
+
+ BS2px
+
The BS2px has all the reserved words shown in the All BASIC Stamp 2 Modules table, above, plus those shown in the table below. These additional words are reserved in both PBASIC 2.0 and PBASIC 2.5.
Before you can use a variable in a PBASIC program you must declare it.
+"Declare" means letting the BASIC Stamp know that you plan to use a variable,
+what you want to call it, and how big it is. Although PBASIC does have predefined
+variables that you can use without declaring them first (see Memory Organization ),
+the preferred way to set up variables is to use the directive SYMBOL (for the BS1)
+or VAR (for all other BASIC Stamp models). Here is the syntax for a variable declaration:
+
+
+
+SYMBOL name = RegisterName
+
+
+
+
+name VAR VarType
+
+
...where name is the name by which you will refer to the variable,
+RegisterName is the "fixed" name for the register and VarType indicates
+the type (Bit, Nib, Byte, or Word) of storage for the variable. NOTE: The top
+example is for the BS1 and the bottom example is for all BASIC Stamp 2 models.
+
The Rules of Symbol Names
+
There are certain rules regarding symbol names. Symbols must start with a
+letter, can contain a mixture of letters, numbers, and underscore (_) characters,
+and must not be the same as PBASIC keywords or labels used in your program.
+Additionally, symbols can be up to 32 characters long. See the PBASIC Command Reference for a list of PBASIC keywords. PBASIC
+does not distinguish between upper and lower case, so the names MYVARIABLE,
+myVariable, and MyVaRiAbLe are all equivalent.
For the BS1, the RegisterName is one of the predefined "fixed" variable
+names, such as W0, W1, B0, B1, etc. Here are a few examples of variable
+declarations on the BS1:
+SYMBOL temp = W0 ' value can be 0 to 65535
+SYMBOL cntr = B1 ' value can be 0 to 255
+SYMBOL result = B2 ' value can be 0 to 255
+
+
The above example will create a variable called temp whose contents
+will be stored in the RAM location called W0. Also, the variable cntrwill be located at RAM location B1 and result at location B2. Note that
+temp is a word-sized variable (because that's what size W0 is) while the
+other two are both byte-sized variables. Throughout the rest of the program, we
+can use the names temp, cntr, and result instead of W0, B1
+and B2, respectively. This makes the code much more readable; it's easier to
+determine what cntr is used for than it would be to figure out what the
+name B1 means. Please note, that cntr resides at location B1, and B1
+happens to be the high byte of W0. This means than changing cntr will also
+change temp since they overlap. A situation like this usually is a mistake
+and results in strange behavior, but is also a powerful feature if used carefully.
+
+
+
+
For the BS2-family, the Size argument has four choices: 1) Bit (1 bit),
+2) Nib (nibble; 4 bits), 3) Byte (8 bits), and 4) Word (16 bits). Here are some
+examples of variable declarations on the BS2-family:
+mouse VAR Bit ' Value can be 0 or 1
+cat VAR Nib ' Value can be 0 to 15
+dog VAR Byte ' Value can be 0 to 255
+rhino VAR Word ' Value can be 0 to 65535
+
+
The example above will create a bit-sized variable called mouse, and
+nibble-sized variable called cat, a byte-size variable called dog
+and a word-sized variable called rhino. Unlike in the BS1, these variable
+declarations don't point to a specific location in RAM. Instead, we only specified
+the desired size for each variable; the BASIC Stamp will arrange them in RAM as
+it sees fit. Throughout the rest of the program, we can use the names mouse, cat,
+dog and rhino to set or retrieve the contents of these variables.
+
+
+
+
+
A variable should be given the smallest size that will hold the largest value
+that will ever be stored in it. If you need a variable to hold the on/off status
+(1 or 0) of switch, use a bit. If you need a counter for a FOR...NEXT loop
+that will count from 1 to 100, use a byte. And so on.
+
If you assign a value to a variable that exceeds its size, the excess bits will
+be lost. For example, suppose you use the nibble variable cat, from the
+example above, and write cat = 260 (%100000100 binary). What will catcontain? It will hold only the lowest 4 bits of 260: %0100 (4 decimal).
+
+
+
+
On the BS2-family, you can also define multi-part variables called arrays. An
+array is a group of variables of the same size, and sharing a single name, but
+broken up into numbered cells, called elements. You can define an array using the
+following syntax:
+name VAR Size(n)
+
+
where name and Size are the same as described earlier. The new argument,
+(n), tells PBASIC how many elements you want the array to have. For example:
+myList VAR Byte(10) ' Create a 10-byte array
+
+
Once an array is defined, you can access its elements by number. Numbering
+starts at 0 and ends at n–1. For example:
+ myList(3) = 57
+ DEBUG ? myList(3)
+
+
This code will display "myList(3) = 57" on the PC screen. The real power
+of arrays is that the index value can be a variable itself. For example:
+myBytes VAR Byte(10) ' Define 10-byte array
+idx VAR Nib ' Define nibble variable
+
+Main:
+ FOR idx = 0 TO 9 ' Repeat with idx= 0, 1...9
+ myBytes(idx) = idx * 13 ' Write idx*13 to array
+ NEXT
+
+ FOR idx = 0 TO 9 ' Repeat with idx= 0, 1...9
+ DEBUG "myBytes(", DEC idx, ")= ", DEC myBytes(idx), CR ' Show contents of each cell
+ NEXT
+ STOP
+
+
If you run this program, DEBUG will display each of the 10 values stored
+in the elements of the array: myBytes(0) = 0 * 13 = 0, myBytes(1) = 1 * 13 = 13,
+myBytes(2) = 2 * 13 = 26 ... myBytes(9) = 9 * 13 = 117.
+
A word of caution about arrays: If you're familiar with other BASICs and have
+used their arrays, you have probably run into the "subscript out of range" error.
+Subscript is another term for the index value. It is out-of-range when it exceeds
+the maximum value for the size of the array. For instance, in the example above,
+myBytes is a 10-cell array. Allowable index numbers are 0 through 9. If
+your program exceeds this range, PBASIC will not respond with an error message.
+Instead, it will access the next RAM location past the end of the array. If you
+are not careful about this, it can cause all sorts of bugs.
+
If accessing an out-of-range location is bad, why does PBASIC allow it? Unlike
+a desktop computer, the BASIC Stamp doesn't always have a display device connected
+to it for displaying error messages. So it just continues the best way it knows
+how. It's up to the programmer (you!) to prevent bugs.
+
Another unique property of PBASIC arrays is this: You can refer to the 0th
+(first) cell of the array by using just the array's name without an index value.
+For example:
+
+
+
+myBytes VAR Byte(10) ' Define 10-byte array
+
+Main:
+ myBytes(0) = 17 ' Store 17 to 0th (first) cell
+ DEBUG ? myBytes(0) ' Display contents of 0th cell
+ DEBUG ? myBytes ' Also displays contents of 0th cell
+
+
This feature is how the "string" capabilities of the DEBUG and SEROUT command expect to work, that is, referencing the variable name only and not a specific
+element. A string is simply a byte array used to store text. See the "Displaying
+Strings (Byte Arrays)" section in the DEBUG command
+description for more information.
+
An alias is an alternative name for an existing variable. For
+example:
+
+
+
+SYMBOL cat = B0 ' Create a byte-sized variable
+SYMBOL tabby = cat ' Create alias for cat
+
+
+
+
+cat VAR Byte ' Create a byte-sized variable
+tabby VAR cat ' Create alias for cat
+
+
In this example, tabby is an alias to the variable cat. Anything
+stored in cat shows up in tabby and vice versa. Both names refer to
+the same physical piece of RAM. This kind of alias can be useful when you want to
+reuse a temporary variable in different places in your program, but also want the
+variable's name to reflect its function in each place. Use caution, because it is
+easy to forget about the aliases; during debugging, you might end up asking 'How
+did that value get here?!' The answer is that it was stored in the variable's
+alias.
+
+
+
+
On the BS2-family an alias can also serve as a window into a portion of another
+variable. This is done using "modifiers." Here the alias is assigned with a
+modifier that specifies what part:
+rhino VAR Word ' A 16-bit variable
+head VAR rhino.HIGHBYTE ' Highest 8 bits of rhino
+tail VAR rhino.LOWBYTE ' Lowest 8 bits of rhino
+
+
Given that example, if you write the value %1011000011111101 to rhino,
+then head would contain %10110000 and tail would contain %11111101.
+
The table below lists all the variable modifiers. PBASIC2 lets you apply these
+modifiers to any variable name and to combine them in any fashion that makes sense.
+For example, it will allow:
+rhino VAR Word ' A 16-bit variable
+eye VAR rhino.HIGHBYTE.LOWNIB.BIT1 ' A bit
+
+
+
+
+
+
Symbol
+
Definitions
+
+
+
LOWBYTE
+
Low byte of a word
+
+
+
HIGHBYTE
+
High byte of a word
+
+
+
BYTE0
+
Low byte of a word
+
+
+
BYTE1
+
High byte of a word
+
+
+
LOWNIB
+
Low nibble of a word or byte
+
+
+
HIGHNIB
+
High nibble of a word or byte
+
+
+
NIB0
+
Nibble 0 of a word or byte
+
+
+
NIB1
+
Nibble 1 of a word or byte
+
+
+
NIB2
+
Nibble 2 of a word
+
+
+
NIB3
+
Nibble 3 of a word
+
+
+
LOWBIT
+
Low bit (LSB) of a word, byte, or nibble
+
+
+
HIGHBIT
+
High bit (MSB) of a word, byte, or nibble
+
+
+
BIT0
+
Bit 0 (LSB) of a word, byte, or nibble
+
+
+
BIT1
+
Bit 1 of a word, byte, or nibble
+
+
+
BIT2
+
Bit 2 of a word, byte, or nibble
+
+
+
BIT3
+
Bit 3 of a word, byte, or nibble
+
+
+
BIT4 ... BIT7
+
Bits 4 through 7 of a word or byte
+
+
+
BIT8 ... BIT15
+
Bits 8 through 15 of a word
+
+
+
+
+
+
The commonsense rule for combining modifiers is that they must get progressively
+smaller from left to right. It would make no sense to specify, for instance, the
+low byte of a nibble, because a nibble is smaller than a byte! And just because
+you can stack up modifiers doesn't mean that you should unless it is the clearest
+way to express the location of the part you want get at. The example above might
+be improved:
+rhino VAR Word ' A 16-bit variable
+eye VAR rhino.BIT9 ' A bit
+
+
Although we've only discussed variable modifiers in terms of creating alias
+variables, you can also use them within program instructions:
+rhino VAR Word ' A 16-bit variable
+head VAR rhino.HIGHBYTE ' Highest 8 bits of rhino
+
+Main:
+ rhino = 13567
+ DEBUG ? head ' Show the value of alias variable head
+ DEBUG ? rhino.HIGHBYTE ' rhino.HIGHBYTE works too
+ STOP
+
+
Modifiers also work with arrays. For example:
+myBytes VAR Byte(10) ' Define 10-byte array
+
+Main:
+ myBytes(0) = $AB ' Hex $AB into 0th byte
+ DEBUG HEX ? myBytes.LOWNIB(0) ' Show low nib ($B)
+ DEBUG HEX ? myBytes.LOWNIB(1) ' Show high nib ($A)
+
+
If you looked closely at that example, you probably thought it was a misprint.
+Shouldn't myBytes.LowNib(1) give you the low nibble of byte 1 of the array rather
+than the high nibble of byte 0? Well, it doesn't. The modifier changes the meaning
+of the index value to match its own size. In the example above, when myBytes() is
+addressed as a byte array, it has 10 byte-sized cells numbered 0 through 9. When
+it is addressed as a nibble array, using myBytes.LowNib(), it has 20 nibble-sized
+cells numbered 0 through 19. You could also address it as individual bits using
+myBytes.LowBit(), in which case it would have 80 bit-sized cells numbered 0
+through 79.
+
What if you use something other than a “low” modifier, say myBytes.HighNib()?
+That will work, but its effect will be to start the nibble array with the high
+nibble of myBytes(0). The nibbles you address with this nib array will all be
+contiguous, one right after the other, as in the previous example.
+myBytes VAR Byte(10) ' Define 10-byte array
+
+Main:
+ myBytes(0) = $AB ' Hex $AB into 0th byte
+ myBytes(1) = $CD ' Hex $CD into next byte
+ DEBUG HEX ? myBytes.HIGHNIB(0) ' Show high nib of cell 0 ($A)
+ DEBUG HEX ? myBytes.HIGHNIB(1) ' Show next nib ($D)
+
+
This property of modified arrays makes the names a little confusing. If you
+prefer, you can use the less-descriptive versions of the modifier names; Bit0
+instead of LowBit, Nib0 instead of LowNib, and Byte0 instead of LowByte. These
+have exactly the same effect, but may be less likely to be misconstrued.
+
You may also use modifiers with the 0th cell of an array by referring to just
+the array name without the index value in parentheses. It's fair game for aliases
+and modifiers, both in VAR directives and in instructions.
";
+CMCAddCommentDialog.prototype.OnInitializing=function(){
+this.base.OnInitializing.call(this);
+var commentNode=this.mWindow.document.getElementById("MCComment");
+if(commentNode.firstChild){
+commentNode.removeChild(commentNode.firstChild);}
+if(this.mAnonymousEnabled){
+var username=null;
+if(FMCIsHtmlHelp()){
+username=FMCLoadUserData("LiveHelpUsername");}
+else{
+username=FMCReadCookie("LiveHelpUsername");}
+if(username){
+this.mWindow.document.getElementById("MCUsername").value=username;
+this.mWindow.document.getElementById("MCSubject").focus();}
+else{
+this.mWindow.document.getElementById("MCUsername").focus();}}
+else{
+var tr=this.mWindow.document.getElementById("MCUsername").parentNode.parentNode;
+tr.parentNode.removeChild(tr);
+this.mWindow.document.getElementById("MCSubject").focus();}};
+CMCAddCommentDialog.prototype.LoadStyles=function(){
+this.base.LoadStyles.call(this);
+var userNameLabel=CMCFlareStylesheet.LookupValue("Dialog",this.StyleClass,"UserNameLabel",this.UserNameLabel);
+var subjectLabel=CMCFlareStylesheet.LookupValue("Dialog",this.StyleClass,"SubjectLabel",this.SubjectLabel);
+var commentLabel=CMCFlareStylesheet.LookupValue("Dialog",this.StyleClass,"CommentLabel",this.CommentLabel);
+document.getElementById("MCUserNameLabel").firstChild.nodeValue=userNameLabel;
+document.getElementById("MCSubjectLabel").firstChild.nodeValue=subjectLabel;
+document.getElementById("MCCommentLabel").firstChild.nodeValue=commentLabel;
+this.CommentLengthExceeded=CMCFlareStylesheet.LookupValue("Dialog",this.StyleClass,"CommentLengthExceeded",this.CommentLengthExceeded);};
+CMCAddCommentDialog.prototype.OK=function(){
+var topicID=FMCGetMCAttribute(this.mWindow.document.documentElement,"MadCap:liveHelp");
+var userGuid=null;
+if(FMCIsHtmlHelp()){
+userGuid=FMCLoadUserData("LiveHelpUserGuid");}
+else{
+userGuid=FMCReadCookie("LiveHelpUserGuid");}
+var username=null;
+if(this.mAnonymousEnabled){
+username=this.mWindow.document.getElementById("MCUsername").value;
+if(username==null||username.length==0){
+alert("Please enter a user name.");
+return false;}
+if(FMCIsHtmlHelp()){
+FMCSaveUserData("LiveHelpUsername",username);}
+else{
+FMCSetCookie("LiveHelpUsername",username,36500);}}
+var subject=this.mWindow.document.getElementById("MCSubject").value;
+var comment=this.mWindow.document.getElementById("MCComment").value;
+if(subject==null||subject.length==0){
+alert("Please enter a subject.");
+return false;}
+else if(comment==null||comment.length==0){
+alert("Please enter a comment.");
+return false;}
+try{
+gServiceClient.AddComment(topicID,userGuid,username,subject,comment,null);}
+catch(ex){
+var message=this.CommentLengthExceeded.replace(/{n}/g,ex.Data.ExceedAmount);
+alert(message);
+return false;}
+return true;};
+CMCAddCommentDialog.prototype.Cancel=function(){};
+function CMCRegisterUserDialog(winNode,dialogMode,version){
+CMCRegisterUserDialog.InCheckUserStatusMode=false;
+CMCDialog.call(this,winNode);
+this.mItemInfos=new Array();
+this.mDialogMode=dialogMode;
+this.mVersion=version;
+this.StyleClass="RegisterUser";
+this.FontFamily="Arial";
+this.FontSize="12px";
+this.FontWeight="normal";
+this.FontStyle="normal";
+this.Color="#000000";
+this.TitleLabel="Create Feedback Service Profile:";
+this.TitleFontFamily="Arial";
+this.TitleFontSize="14px";
+this.TitleFontWeight="bold";
+this.TitleFontStyle="normal";
+this.TitleFontVariant="small-caps";
+this.TitleColor="#000000";
+this.BackgroundColor="#ffffcc";
+this.SubmitButtonLabel="Submit";
+this.CancelButtonLabel="Cancel";
+this.ShadowColor="#000000";
+this.ShadowDistance=5;
+this.ShadowOpacity=100;
+this.BorderLeft="solid 2px #000000";
+this.BorderRight="solid 2px #000000";
+this.BorderTop="solid 2px #000000";
+this.BorderBottom="solid 2px #000000";
+this.RegistrationMessage="You must create a user profile to post comments to this help system. Please fill in the information below. An email will be sent to the address you provide. Please follow the instructions in the email to complete activation. Fields marked with an asterisk (*) are required.";
+this.EditProfileRegistrationMessage="Use this form to update your profile information. If you choose to update your email address, an email will be sent to the address you provide. Please follow the instructions in the email to complete activation.";
+this.RegistrationSubmit="Your information has been sent to MadCap Software. When the information has been processed, you will receive an email with a link to a verification page. Click this link, or copy and paste the link into your Web browser to complete the registration.";
+this.RegistrationSubmitNote="NOTE: Some service providers have email filtering software that may cause the notification email to be sent to your junk email folder. If you do not receive a notification email, please check this folder to see if it has been sent there.";
+this.MissingRequiredField="Please enter a value for: ";
+this.UpdateSuccess="Your profile was updated successfully!";}
+CMCRegisterUserDialog.prototype=new CMCDialog();
+CMCRegisterUserDialog.prototype.constructor=CMCRegisterUserDialog;
+CMCRegisterUserDialog.prototype.base=CMCDialog.prototype;
+CMCRegisterUserDialog.prototype.InnerHtml=""+
+"
"+
+"You must create a user profile to post comments to this help system. "+
+"Please fill in the information below. An email will be sent to the "+
+"address you provide. Please follow the instructions in the email to complete activation."+
+"Fields marked with an asterisk (*) are required."+
+"
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/AdapterYN_HWB.htm b/help/BasicStampHelp/Content/StartTopics/AdapterYN_HWB.htm
new file mode 100644
index 0000000..f573f6d
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/AdapterYN_HWB.htm
@@ -0,0 +1,56 @@
+
+
+
+ Using a USB to Serial Adapter?
+
+
+
+
+
+
+
Using a USB to Serial Adapter?
+
Will you be using your computer's USB port and a USB to Serial Adapter with your HomeWork Board?
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/AsciiPopup.htm b/help/BasicStampHelp/Content/StartTopics/AsciiPopup.htm
new file mode 100644
index 0000000..3be46bc
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/AsciiPopup.htm
@@ -0,0 +1,1075 @@
+
+
+
+ ASCII Chart
+
+
+
+
+
ASCII Chart
+
This chart includes the first 128 ASCII characters. Note that the control codes (lowest 32 ASCII characters) have no standardized screen symbols. The characters listed for them are just names used in referring to these codes. For example, to move the cursor to the beginning of the next line of a printer or terminal often requires sending line feed and carriage return codes. This common pair is referred to as "LF/CR."
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BOE-serial.htm b/help/BasicStampHelp/Content/StartTopics/BOE-serial.htm
new file mode 100644
index 0000000..2bf5775
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BOE-serial.htm
@@ -0,0 +1,103 @@
+
+
+
+ Board of Education - Serial
+
+
+
+
+
+
+
+
+
Board of Education - Serial
+
+
Take a look at your board to get familiar with its parts.
+
+
+
+
+
+
9V Battery Clip: You can use alkaline or rechargeable 9 volt batteries. The battery clip and barrel jack are intentionally positioned so you cannot use both at once.
+
+
Barrel Jack: This accepts a 2.1 mm center-positive barrel plug from a 6-9 V wall-mount supply or from a battery pack. You cannot use the barrel jack and a 9 volt battery at the same time.
+
+
Voltage regulator: Supplies regulated 5 V (up to 1 amp of current) for sockets and pins labeled Vdd. Vdd sockets are convenient for supplying 5 V to circuits you will build on the breadboard area.
+
+
Power Indicator LED: This LED will light up when power is supplied to your board and the power switch is in position 1 or 2.
+
+
Servo headers (X4 and X5) and Power Select Jumper: These each have two 3-pin connectors that bring power, ground, and I/O pin access together so you can easily plug in servos or other 3-pin devices. The power connection is pre-set to Vdd (+5 V) but you can set it to Vin (the board's supply voltage) by moving the shorting block on the jumper between the headers. Each 3-pin row is labeled with an I/O pin number above it. The 12, 13, 14, and 15 signal lines for the servo headers are also accessible as P12, P13, P14, and P15 I/O pin sockets on the X1 and X2 headers. This can be useful for building a servo signal indicator light on the breadboard as you may do in some Stamps in Class activities. For independent projects, keep these shared connections in mind, especially to avoid inadvertently connecting circuits with conflicting functions to the same I/O pin.
+
+
Power header (X3): The sockets labeled Vdd connect to +5 VDC, Vin connects directly to the power supplied to the board by the battery clip or barrel jack, and Vss connects to 0 V (ground).
+
+
Breadboard:The breadboard has metal clips that run underneath the white plastic board in a horizontal fashion. Each strip connects a 5-socket group, with two groups to each row, separated by a center trench. Wires or legs of components plugged into the same 5-socket group will be electrically connected. Components with many legs (such as pushbuttons or ICs), are placed in the middle of the board so that half of the legs are on the left side and half are on the right side of the trench. Note: Always disconnect power before building or modifying circuits!
+
+
I/O Pin Access Header (X2):The BASIC Stamp module's 16 I/O pins, labeled 0 to 15, are connected to this header. Its location adjacent to the breadboard makes it convenient for connecting circuits to I/O pins. Keep in mind that I/O pin access is also brought to the X4, X5, and X1 headers, so be careful not to build conflicting breadboard circuits if you are using these other headers as well.
+
+
AppMod header (X1):The AppMod header provides power, I/O pins, Vdd, Vin, and Vss access for any devices that are designed to use this 2x10 socket. Examples include the LCD Terminal AppMod (#29121), CMUcam (#30051), Easy Bluetooth Module (#30085), and Say It voice recognition module (#30080).
+
+
Reset Button: The reset button can be used to restart your BASIC Stamp without having to cycle the power. This saves wear-and-tear on the power switch for simple program restarts. Some advanced programming techniques use the reset button and the BASIC Stamp EEPROM program and data storage as a way to toggle between different program functions.
+
+
3-Position Power Switch: The leftmost position (0) is OFF – all power is disconnected. Always place the switch in this position when adding or changing components on the breadboard. The middle position (1) provides Vin (unregulated battery or power supply voltage) to the regulator, the BASIC Stamp socket, and to the connectors marked “Vin.” This switch position also makes Vdd (5 volts) available to Vdd sockets on the breadboard and AppMod connectors. The rightmost position (2) also provides power to the servo connectors X4 and X5. Especially if your program causes a robot with servos connected to X4/X5 to start moving immediately, you can keep the 3-position switch in position (1) while loading the program, then switch to position (2) when you are ready for the robot to start moving.
+
+
Socket for BASIC Stamp: This socket is compatible with all 24-pin BASIC Stamp modules. It connects the BASIC Stamp to the programming connector, power, the power indicator LED, reset button, and all I/O pin headers.
+
+
Serial Programming Connector: This is a female DB9 socket for programming and for two-way serial communication between the BASIC Stamp and your computer. You can connect directly to a serial port on your computer, or use a USB to Serial Adapter to connect to a USB port.
+
+
+
Important! Check the Revision Letter of your Board of Education
+
It’ll either be below the breadboard or in the upper-right corner, and might be Rev A, Rev B, Rev C, etc… Make a note of this revision because certain Stamps in Class activities will utilize different circuits, depending on which revision you use.
+
+
If you have a Board of Education - Serial Rev C, shown above, you don't need any extra instructions. Go ahead and click the NEXT arrow.
If you have a Board of Education - Serial Rev B, the label will be in the upper right corner on top of the board, just below and to the right of the X5 servo header. Read the Board of Education - Serial Rev B Special Instructions before continuing.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BOE-usb.htm b/help/BasicStampHelp/Content/StartTopics/BOE-usb.htm
new file mode 100644
index 0000000..794d0d3
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BOE-usb.htm
@@ -0,0 +1,84 @@
+
+
+
+ Board of Education - USB
+
+
+
+
+
+
+
+
Board of Education - USB
+
+
Take a look at your board to get familiar with its parts.
+
+
+
+
+
+
9V Battery Clip: You can use alkaline or rechargeable 9 volt batteries. The battery clip and barrel jack are intentionally positioned so you cannot use both at once.
+
+
Barrel Jack: This accepts a 2.1 mm center-positive barrel plug from a 6-9 V wall-mount supply or from a battery pack. You cannot use the barrel jack and a 9 volt battery at the same time.
+
+
Voltage regulator: Supplies regulated 5 V (up to 1 amp of current) for sockets and pins labeled Vdd. Vdd sockets are convenient for supplying 5 V to circuits you will build on the breadboard area.
+
+
Power Indicator LED: This LED will light up when power is supplied to your board and the power switch is in position 1 or 2.
+
+
Servo headers (X4 and X5) and Power Select Jumper: These each have two 3-pin connectors that bring power, ground, and I/O pin access together so you can easily plug in servos or other 3-pin devices. The power connection is pre-set to Vdd (+5 V) but you can set it to Vin (the board's supply voltage) by moving the shorting block on the jumper between the headers. Each 3-pin row is labeled with an I/O pin number above it. The 12, 13, 14, and 15 signal lines for the servo headers are also accessible as P12, P13, P14, and P15 I/O pin sockets on the X1 and X2 headers. This can be useful for building a servo signal indicator light on the breadboard as you may do in some Stamps in Class activities. For independent projects, keep these shared connections in mind, especially to avoid inadvertently connecting circuits with conflicting functions to the same I/O pin.
+
+
Power header (X3): The sockets labeled Vdd connect to +5 VDC, Vin connects directly to the power supplied to the board by the battery clip or barrel jack, and Vss connects to 0 V (ground).
+
+
Breadboard:The breadboard has metal clips that run underneath the white plastic board in a horizontal fashion. Each strip connects a 5-socket group, with two groups to each row, separated by a center trench. Wires or legs of components plugged into the same 5-socket group will be electrically connected. Components with many legs (such as pushbuttons or ICs), are placed in the middle of the board so that half of the legs are on the left side and half are on the right side of the trench. Note: Always disconnect power before building or modifying circuits!
+
+
I/O Pin Access Header (X2):The BASIC Stamp module's 16 I/O pins, labeled 0 to 15, are connected to this header. Its location adjacent to the breadboard makes it convenient for connecting circuits to I/O pins. Keep in mind that I/O pin access is also brought to the X4, X5, and X1 headers, so be careful not to build conflicting breadboard circuits if you are using these other headers as well.
+
+
AppMod header (X1):The AppMod header provides power, I/O pins, Vdd, Vin, and Vss access for any devices that are designed to use this 2x10 socket. Examples include the LCD Terminal AppMod (#29121), CMUcam (#30051), Easy Bluetooth Module (#30085), and Say It voice recognition module (#30080).
+
+
Reset Button: The reset button can be used to restart your BASIC Stamp without having to cycle the power. This saves wear-and-tear on the power switch for simple program restarts. Some advanced programming techniques use the reset button and the BASIC Stamp EEPROM program and data storage as a way to toggle between different program functions.
+
+
3-Position Power Switch: The leftmost position (0) is OFF – all power is disconnected. Always place the switch in this position when adding or changing components on the breadboard. The middle position (1) provides Vin (unregulated battery or power supply voltage) to the regulator, the BASIC Stamp socket, and to the connectors marked “Vin.” This switch position also makes Vdd (5 volts) available to Vdd sockets on the breadboard and AppMod connectors. The rightmost position (2) also provides power to the servo connectors X4 and X5. Especially if your program causes a robot with servos connected to X4/X5 to start moving immediately, you can keep the 3-position switch in position (1) while loading the program, then switch to position (2) when you are ready for the robot to start moving.
+
+
Socket for BASIC Stamp: This socket is compatible with all 24-pin BASIC Stamp modules. It connects the BASIC Stamp to the programming connector, power, the power indicator LED, reset button, and all I/O pin headers.
+
+
USB Programming Connector: This is a USB Mini B socket and USB to serial (RS-232) circuitry for programming and for two-way serial communication between the BASIC Stamp and your computer. The required USB drivers for Windows were included in the BASIC Stamp Editor software installer; see the USB Drivers page for more information.
+
+
+
BASIC Stamp Resets when Connecting USB
+
When you connect your BASIC Stamp to a PC using a USB-based development board or adapter, the PC's operating system typically resets the BASIC Stamp several times as it tries to determine if a new plug-and-play device was just connected.
+
Each time a BASIC Stamp is reset, all program variables are cleared, and the program starts from the beginning. For tips on writing programs that have variable values that you do not want to lose when you connect your board to the PC, see the article USB Resets BASIC Stamp.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BOEadapter-setup.htm b/help/BasicStampHelp/Content/StartTopics/BOEadapter-setup.htm
new file mode 100644
index 0000000..649aca2
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BOEadapter-setup.htm
@@ -0,0 +1,108 @@
+
+
+
+ Board of Education with USB to Serial Adapter - Setup
+
+
+
+
+
+
+
+
Board of Education with USB to Serial Adapter - Setup
+
+
DO NOT connect power to your board until instructed to do so!
+
+
Affixing the Rubber Feet
+
Your board should come with four adhesive rubber feet:
+
+
+
+
+
Remove each rubber foot from its adhesive, and affix it to the underside of your board. There are circles to show correct placement.
+
+
+
+
+
Making the Board Connections
+
+
Use the silkscreen pictures that show the three prominent chips on the BASIC Stamp to determine how to orient it before inserting it into its socket. There is also a small semi-circular notch at in the top-center of the BASIC Stamp module that indicates which way is “up.” Match this reference notch to the notch in the socket.
+
After correctly orienting the 24-pin BASIC Stamp module, gently insert it into its socket as shown at (1) in the picture below.
+
Make sure that each pin is seated in its corresponding socket hole, then apply firm downward pressure with your thumb. The module should sink about ¼ of an inch (~0.6 mm) into the socket, and only the flared portion of each BASIC Stamp leg should be visible above the socket.
+
Visually inspect the legs to make sure each pin is in its socket and that no pins are folded underneath the module.
+
Connect the larger "A" end of the USB cable to a USB 2.0 port on your computer.
USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.
+
USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
+
+
+
+
+
+
Connect the smaller "Mini B" end of the USB cable to the USB connector on the USB to Serial Adapter, as shown in (2).
+
Connect the male DB9 connector on the USB to Serial Adapter to the female DB9 socket on the board (3).
+
Connect one of the two power sources (see Power Supplies).
+
+
+
+
a 6 to 9 V wall-mount power supply with a 2.1 mm center positive barrel jack (4);
+
+
- OR -
+
+
a 9 V alkaline or rechargeable battery (5).
+
+
+
+
+
+
+
+
Set the 3 - position switch to Position 1 to turn on power to your board.
+
+
+
+
+
+
Tip: If you have a BASIC Stamp program running and want to take your board away from your computer, always disconnect and reconnect at the DB9 socket. Leave the USB to Serial Adapter connected to your computer. This will leave the virtual COM port open, allowing you to reconnect your board without the USB port resetting your BASIC Stamp. See the article USB Resets BASIC Stamp for more information.
+
You are ready to test your programming connection!
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BOEsetup.htm b/help/BasicStampHelp/Content/StartTopics/BOEsetup.htm
new file mode 100644
index 0000000..9196195
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BOEsetup.htm
@@ -0,0 +1,90 @@
+
+
+
+ Board of Education Serial - Setup
+
+
+
+
+
+
+
+
Board of Education Serial - Setup
+
+
DO NOT connect power to your board until instructed to do so!
+
+
Affixing the Rubber Feet
+
Your board should come with four adhesive rubber feet:
+
+
+
+
+
Remove each rubber foot from its adhesive, and affix it to the underside of your board. There are circles to show correct placement.
+
+
+
+
+
Making the Board Connections
+
+
Use the silkscreen pictures that show the three prominent chips on the BASIC Stamp to determine how to orient it before inserting it into its socket. There is also a small semi-circular notch at in the top-center of the BASIC Stamp module that indicates which way is “up.” Match this reference notch to the notch in the socket.
+
After correctly orienting the 24-pin BASIC Stamp module, gently insert it into its socket as shown at (1) in the picture below.
+
Make sure that each pin is seated in its corresponding socket hole, then apply firm downward pressure with your thumb. The module should sink about ¼ of an inch (~0.6 mm) into the socket, and only the flared portion of each BASIC Stamp leg should be visible above the socket.
+
Visually inspect the legs to make sure each pin is in its socket and that no pins are folded underneath the module.
+
Connect the female end of the serial cable to the serial port on your computer (it is a 9-pin male port).
+
Connect the male end of the serial cable to the DB9 connector on the board, as shown in (2).
+
Connect one of the two power sources (see Power Supplies).
+
+
+
+
a 6 to 9 V wall-mount power supply with a 2.1 mm center positive barrel jack (3);
+
+
- OR -
+
+
a 9 V alkaline or rechargeable battery (4).
+
+
+
+
+
+
+
Set the 3 - position switch to Position 1 to turn on power to your board.
+
+
+
+
+
+
You are ready to test your programming connection!
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BOEusb_setup.htm b/help/BasicStampHelp/Content/StartTopics/BOEusb_setup.htm
new file mode 100644
index 0000000..882068d
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BOEusb_setup.htm
@@ -0,0 +1,106 @@
+
+
+
+ Board of Education USB - Setup
+
+
+
+
+
+
+
+
Board of Education USB - Setup
+
+
DO NOT connect power to your board until instructed to do so!
+
+
Affixing the Rubber Feet
+
Your board should come with four adhesive rubber feet:
+
+
+
+
+
Remove each rubber foot from its adhesive, and affix it to the underside of your board. There are circles to show correct placement.
+
+
+
+
+
Making the Board Connections
+
+
Use the silkscreen pictures that show the three prominent chips on the BASIC Stamp to determine how to orient it before inserting it into its socket. There is also a small semi-circular notch at in the top-center of the BASIC Stamp module that indicates which way is “up.” Match this reference notch to the notch in the socket.
+
After correctly orienting the 24-pin BASIC Stamp module, gently insert it into its socket as shown at (1) in the picture below.
+
Make sure that each pin is seated in its corresponding socket hole, then apply firm downward pressure with your thumb. The module should sink about ¼ of an inch (~0.6 mm) into the socket, and only the flared portion of each BASIC Stamp leg should be visible above the socket.
+
Visually inspect the legs to make sure each pin is in its socket and that no pins are folded underneath the module.
+
Connect the larger "A" end of the USB cable to a USB 2.0 port on your computer.
USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.
+
USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
+
+
+
+
+
+
Connect the smaller "Mini B" end of the USB cable to the USB connector on the board, as shown in (2).
+
Connect one of the two power sources (see Power Supplies).
+
+
+
+
a 6 to 9 V wall-mount power supply with a 2.1 mm center positive barrel jack (3);
+
+
- OR -
+
+
a 9 V alkaline or rechargeable battery (4).
+
+
+
+
+
+
+
+
Set the 3 - position switch to Position 1 to turn on power to your board.
+
+
+
+
+
+
You are ready to test your programming connection!
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BoeSerRevApopup.htm b/help/BasicStampHelp/Content/StartTopics/BoeSerRevApopup.htm
new file mode 100644
index 0000000..3d7a876
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BoeSerRevApopup.htm
@@ -0,0 +1,18 @@
+
+
+
+ Board of Education - Serial Rev A Special Instructions
+
+
+
+
+
Board of Education - Serial Rev A Special Instructions
+
Servo Ports - There Are None!
+
The Board of Education Rev A does not have servo ports. However, 3-pin connections for servos and other devices can be built on the breadboard. For an example of connecting a standard servo to the Board of Education Rev A, see the instructions in the Servo Circuit Connections for Older Boards pdf at www.parallax.com/go/WAM. If you wish to supply a 3-pin device, such as a Parallax Continuous Rotation Servo, with a 6-volt power supply via a breadboard circuit, Parallax carries 4 AA cell battery holder with tinned leads (#753-00001) for this purpose.
+
3-Position Switch - There Isn’t One!
+
To disable power on the Board of Education Rev A, you must disconnect the power supply or battery at its connector.
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/BoeSerRevBpopup.htm b/help/BasicStampHelp/Content/StartTopics/BoeSerRevBpopup.htm
new file mode 100644
index 0000000..4574434
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/BoeSerRevBpopup.htm
@@ -0,0 +1,20 @@
+
+
+
+ Board of Education - Serial Rev B Special Instructions
+
+
+
+
+
Board of Education - Serial Rev B Special Instructions
+
Servo Ports - There is no Servo Power Selection Jumper!
+
The Board of Education Rev B has servo headers (labeled X4 and X5), but it does not have a Servo Power Selection Jumper. On this board, the X4 and X5 headers are permanently connected to Vin. When connecting servos or other devices to the X4 and X5 headers, be sure to use a power supply that does not exceed the voltage tolerance of the servo or device. For example, the Parallax Continuous Rotation Servo requires a 6 V (maximum) supply, so it should not be plugged into the servo headers if using a 9 V battery or a 7.5 V or 9 V wall supply, or the life of the servo could be shortened. A 4 AA cell battery pack with a compatible barrel jack connector is available from Parallax (#700-00038).
+
3-Position Switch - There Isn’t One!
+
To disable power on the Board of Education Rev B, you must disconnect the power supply or battery at its connector.
+
Vdd on AppMod Header - Limited Current Budget
+
Most of the connections labeled Vdd are supplied by the Board of Education Rev B’s 5 V, 1 A voltage regulator. However, the socket labeled Vdd on the X1 AppMod header is instead supplied by the small voltage regulator on the BASIC Stamp module. The BASIC Stamp module’s voltage regulator only has a 50 mA current budget for its processor, certain circuits built on the breadboard and connected to I/O pins, and any devices drawing current from its Vdd pin. The socket labeled Vdd on the X1 AppMod header draws current from the BASIC Stamp module’s Vdd pin, so an AppMod or other device that draws current from this pin has to stay within the 50 mA current budget, which in many applications may turn out to be only a few milliamps. Before using an AppMod with the Board of Education Rev B, verify that it gets its power from the AppMod Header’s Vin socket, and not Vdd.
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/First Program.htm b/help/BasicStampHelp/Content/StartTopics/First Program.htm
new file mode 100644
index 0000000..fe5ec66
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/First Program.htm
@@ -0,0 +1,88 @@
+
+
+
+ First Program
+
+
+
+
+
+
The first program you will write and test will tell the BASIC Stamp to send a message to your computer. The figure below shows how it sends a stream of ones and zeros to communicate the text characters displayed by your computer. These ones and zeros are called binary numbers. The BASIC Stamp Editor software has the ability to detect and display these messages as you will soon see.
+
+
+
+
First Program
+
In this Help tutorial, the program listings that you will type into the BASIC Stamp Editor and download to the BASIC Stamp module will be shown with a blue background like this:
+
Example Program: FirstProgram.bs2
' Stamps in Class - FirstProgram.bs2
+' BASIC Stamp sends message to Debug Terminal.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+DEBUG "Hello, it's me, your BASIC Stamp!"
+END
+
You will enter this program into the BASIC Stamp Editor. Some lines of the program are created automatically by clicking buttons on the toolbar. Other lines are made by typing them in from the keyboard.
+
+
Begin by clicking the BS2 icon (the green diagonal chip) on the toolbar. If you hold your cursor over this button, its flyover help description “Stamp Mode: BS2” will appear.
+
Next, click on the gear icon labeled “2.5.” It’s flyover help description is “PBASIC Language: 2.5”.
+
+
+
+
+
+
+
+
Tip: ALWAYS use these toolbar buttons to add these two lines as the beginning of every program! Compiler directives use braces { }. If you try to type in these parts of your program, you may accidentally use parentheses ( ) or square brackets [ ]. If you do this, your program will not work.
+
If you are using some other 24-pin BASIC Stamp model instead of a BS2, you can still follow the activities here and in any Stamps in Class text, but you will need to adjust all time-sensitive commands or they will not work properly. Read Adapt BS2 Code to Other Models for instructions. (It's under PBASIC Language Reference in the Table of Contents).
+
+
Type in the remaining lines of the program exactly as shown:
+
+
+
+
+
+
Save your work by clicking File and selecting Save.
+
+
+
+
Enter the name "FirstProgram" into the File name field near the bottom of the Save As window.
+
Click the Save button.
+
+
Tip: The next time you save, the BASIC Stamp Editor will automatically save to the same filename (FirstProgram.bs2) unless you tell it to save to a different filename by clicking File and selecting Save As (instead of just Save).
Click Run, and select Run from the menu that appears.
A Download Progress window will appear briefly as the program is transmitted from your computer to your BASIC Stamp module. The figure below shows the Debug Terminal that should appear when the download is complete. You can prove to yourself that this is a message from the BASIC Stamp by pressing and releasing the Reset button on your board. Every time you press and release it, the program will re-run, and you will see another copy of the message displayed in the Debug Terminal.
Press and release the Reset button. Did you see a second “Hello…” message appear in the Debug Terminal?
The BASIC Stamp Editor has shortcuts for most common tasks. For example, to run a program, you can press the ‘Ctrl’ and ‘R’ keys at the same time. You can also click the Run button. It’s the blue triangle that looks like a music player’s Play button. The flyover help (the Run hint) will appear if you point at the Run button with your mouse. You can get similar hints to find out what the other buttons do by pointing at them too.
How FirstProgram.bs2 Works
The first two lines in the example are called comments. A comment is a line of text that gets ignored by the BASIC Stamp Editor, because it’s meant for a human reading the program, not for the BASIC Stamp module. In PBASIC, everything to the right of an apostrophe is normally considered to be a comment by the BASIC Stamp Editor. The first comment tells which book the example program is from, and the program’s filename. The second comment contains a handy, one-line description that explains what the program does.
+' Stamps in Class - FirstProgram.bs2
+' BASIC Stamp sends message to Debug Terminal.
Although comments are ignored most of the time, the BASIC Stamp Editor does search through comments for special directives. Every program in this Getting Started section of help will use these two directives:
' {$STAMP BS2}
+' {$PBASIC 2.5}
The first directive is called the $STAMP Directive, and it tells the BASIC Stamp Editor that you will be downloading the program specifically to a BASIC Stamp 2 module. The second directive is called the $PBASIC directive, and it tells the BASIC Stamp Editor that you are using version 2.5 of the PBASIC programming language. These special comments are called compiler directives, and they are enclosed in braces { } not parentheses ( ). You should always use the toolbar icons to place these compiler directives in your program to avoid typing errors. Also, entering the compiler directives by hand may not activate the syntax highlighting in the BASIC Stamp Editor. That function is what causes various letters, characters and words in your program to appear in different colors and capitalization schemes. Syntax highlighting makes your programs easier to read, understand, and correct if there are any bugs in them.
A command is a word you can use to tell the BASIC Stamp do a certain job. The first of the two commands in this program is called the DEBUG command:
+DEBUG "Hello, it's me, your BASIC Stamp!"
This is the command that tells the BASIC Stamp to send a message to the PC using the serial cable.
The second command is the END command:
END
This command is handy because it puts the BASIC Stamp into low power mode when it’s done running the program. In low power mode, the BASIC Stamp waits for either the Reset button to be pressed (and released), or for a new program to be loaded into it by the BASIC Stamp Editor. If the Reset button on your board is pressed (or if you disconnect and reconnect your power supply), the BASIC Stamp will re-run the program you loaded into it. If a new program is loaded into it, the old one is erased, and the new program begins to run.
Your Turn – Delays with PAUSE, DEBUG Formatters, and Control Characters
In What’s a Microcontroller? and Robotics with the Boe-Bot, the first command you will likely see in the example programs that display messages in the Debug Terminal is a 1-second delay, typically with the command PAUSE 1000. The PAUSE command delays the program for a certain number of milliseconds. Milliseconds are thousandths of a second are typically abbreviated ms. So, PAUSE 1000 delays the program for 1000 thousandths of a second, which is one second.
Modify the program by inserting PAUSE 1000 immediately above the DEBUG command.
PAUSE 1000
Your code should then look like this:
' Stamps in Class - FirstProgram.bs2
+' BASIC Stamp sends message to Debug Terminal.
+
+' {$STAMP BS2}
+' {$PBASIC 2.5}
+
+
+PAUSE 1000
+DEBUG "Hello, it's me, your BASIC Stamp!"
+END
Run the modified program and verify that it delays for a second before displaying the Hello message.
For comparison, you can disable the PAUSE command by commenting it. In other words, add an apostrophe to its left so that it reads ' PAUSE 1000. By removing the apostrophe and re-running the program, you can then test how the program behaves without the PAUSE.
Try it.
Tip: Inserting a one second delay before the BASIC Stamp transmits messages to the Debug Terminal ensures that the Windows operating system cannot possibly mistake the BASIC Stamp for a plug-and play-serial device like a mouse or keyboard. This can happen if the BASIC Stamp is running a program that immediately transmits messages to the Debug Terminal when it gets connected to a USB port. It can also happen if the same program is running as the computer boots while it is connected to a serial or USB port. The PAUSE 1000 ensures that this case of "mistaken microcontroller identity" won't happen because it waits longer than the 0.7 second window that PCs give serial plug-and-play devices to identify themselves.
DEBUG Formatters and Control Characters
A DEBUG formatter is a code-word you can use to make the message the BASIC Stamp sends look a certain way in the Debug Terminal. DEC is an example of a formatter that makes the Debug Terminal display a decimal value. An example of a control character is CR, which is used to send a carriage return to the Debug Terminal. The text or numbers that come after a CR will appear on the line below characters that came before it. You can modify your program so that it contains more DEBUG commands along with some formatters and control characters. Here’s an example of how to do it:
Modify the comments at the beginning of the program so they read:
+' Stamps in Class - FirstProgramYourTurn.bs2
+' BASIC Stamp sends messages to Debug Terminal
Add these three lines between the first DEBUG command and the END command:
+DEBUG CR, "What's 7 X 11?"
+DEBUG CR, "The answer is: "
+DEBUG DEC 7 * 11
Save the changes you made by clicking File and selecting Save As. A good name would be FirstProgramYourTurn.bs2
Check your work against the example program shown here.
Run your modified program. You will have to either select Run from the Run menu again, or click the Run button.
Check your Debug Terminal - does it now look like this?
If not, correct your program and re-run it until you get the results you expect.
Tip: Sometimes the Debug Terminal gets hidden behind the BASIC Stamp Editor window. You can bring it back to the front by using the Run menu as shown, the Debug Terminal 1 shortcut button on the toolbar, or the F12 key on your keyboard.
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/HWB-setup.htm b/help/BasicStampHelp/Content/StartTopics/HWB-setup.htm
new file mode 100644
index 0000000..2eb71c3
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/HWB-setup.htm
@@ -0,0 +1,72 @@
+
+
+
+ HomeWork Board - Setup
+
+
+
+
+
+
+
+
HomeWork Board - Setup
+
+
DO NOT connect power to your board until instructed to do so!
+
+
Affixing the Rubber Feet
+
Your board should come with four adhesive rubber feet:
+
+
+
+
+
+
Remove each rubber foot from its adhesive, and affix it to the underside of your board near each corner. Make sure not to cover up the plated holes, you might need these holes later for mounting your board in a project box or on a robot.
+
+
+
+
+
Making the Board Connections
+
+
Connect the female end of the serial cable to the serial port on your computer (it is a 9-pin male port).
+
Connect the male end of the serial cable to the DB9 connector on the board, as shown in (1).
+
Connect a 9 V alkaline or rechargeable battery to the battery clip (2). (See Power Supplies for more about batteries and battery replacer devices.)
+
+
+
+
+
+
You are ready to test your programming connection!
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/HWB-usb.htm b/help/BasicStampHelp/Content/StartTopics/HWB-usb.htm
new file mode 100644
index 0000000..2ce1ca1
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/HWB-usb.htm
@@ -0,0 +1,72 @@
+
+
+
+ HomeWork Board - USB
+
+
+
+
+
+
+
HomeWork Board - USB
+
+
Take a look at your board to get familiar with its parts.
+
+
+
+
+
+
9V Battery Clip: You can use alkaline or rechargeable 9-volt batteries. Disconnect the battery to turn off power to your board.
+
+
USB Programming Connector: This is a USB Mini B socket and USB to serial (RS-232) circuitry for programming and for two-way serial communication between the BASIC Stamp and your computer. The required USB drivers for Windows were included in the BASIC Stamp Editor software installer; see the USB Drivers page for more information.
+
+
Voltage regulator: Supplies regulated 5 V, up to 500 milliamps with a 9 V battery. This supplies the BASIC Stamp and sockets labeled Vdd for circuits you will build on the breadboard area.
+
Power header (X3): The sockets labeled (+5)Vdd connect to +5 VDC, (+)Vin connects directly to the power supplied to the board by the battery clip (+9 VDC typical), and (-)Vss connects to 0 V (ground).
+
+
Breadboard:The breadboard has metal clips that run underneath the white plastic board in a horizontal fashion. Each strip connects a 5-socket group, with two groups to each row, separated by a center trench. Wires or legs of components plugged into the same 5-socket group will be electrically connected. Components with many legs (such as pushbuttons or ICs), are placed in the middle of the board so that half of the legs are on the left side and half are on the right side of the trench. Note: Always disconnect power before building or modifying circuits!
+
+
I/O Pin Access Header (X4):The BASIC Stamp module's 16 I/O pins, labeled 0 to 15, are connected to this header, so you can conveniently connect to your breadboard circuits. On this board, there are 220-ohm resistors placed between the header and the BASIC Stamp I/O pins to help prevent damage in case of a wiring mistake.
+
+
Reset Button: The reset button can be used to restart your BASIC Stamp without having to cycle the power. This saves wear-and-tear on the battery clip for simple program restarts. Some advanced programming techniques use the reset button and the BASIC Stamp EEPROM as a way to toggle between different program functions.
+
+
Running Indicator LED: This LED will light up when a BASIC Stamp program is running. It is not a power indicator LED.
+
+
BASIC Stamp 2 : The components of a BASIC Stamp 2 module are built directly onto the board. It connects the BASIC Stamp to the programming connector, power, the running indicator LED, reset button, and I/O pin header.
+
+
+
BASIC Stamp Resets when Connecting USB
+
When you connect your BASIC Stamp to a PC using a USB-based development board or adapter, the PC's operating system typically resets the BASIC Stamp several times as it tries to determine if a new plug-and-play device was just connected.
+
Each time a BASIC Stamp is reset, all program variables are cleared, and the program starts from the beginning. For tips on writing programs that have variable values that you do not want to lose when you connect your board to the PC, see the article USB Resets BASIC Stamp.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/HWB.htm b/help/BasicStampHelp/Content/StartTopics/HWB.htm
new file mode 100644
index 0000000..d5ca8bb
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/HWB.htm
@@ -0,0 +1,75 @@
+
+
+
+ HomeWork Board - Serial
+
+
+
+
+
+
+
HomeWork Board - Serial
+
+
Take a look at your board to get familiar with its parts.
+
+
+
+
+
+
9V Battery Clip: You can use alkaline or rechargeable 9-volt batteries. Disconnect the battery to turn off power to your board.
+
+
Serial Programming Connector: This is a female DB9 socket for programming and for two-way serial communication between the BASIC Stamp and your computer. You can connect directly to a serial port on your computer, or use a USB to Serial Adapter to connect to a USB port.
+
+
Voltage regulator: Supplies regulated 5 V, up to 500 milliamps with a 9 V battery. This supplies the BASIC Stamp and sockets labeled Vdd for circuits you will build on the breadboard area.
+
+
Power header (X3): The sockets labeled (+5)Vdd connect to +5 VDC, (+)Vin connects directly to the power supplied to the board by the battery clip (+9 VDC typical), and (-)Vss connects to 0 V (ground).
+
+
Breadboard:The breadboard has metal clips that run underneath the white plastic board in a horizontal fashion. Each strip connects a 5-socket group, with two groups to each row, separated by a center trench. Wires or legs of components plugged into the same 5-socket group will be electrically connected. Components with many legs (such as pushbuttons or ICs), are placed in the middle of the board so that half of the legs are on the left side and half are on the right side of the trench. Note: Always disconnect power before building or modifying circuits!
+
+
I/O Pin Access Header (X4):The BASIC Stamp module's 16 I/O pins, labeled 0 to 15, are connected to this header, so you can conveniently connect to your breadboard circuits. On this board, there are 220-ohm resistors placed between the header and the BASIC Stamp I/O pins to help prevent damage in case of a wiring mistake.
+
+
Reset Button: The reset button can be used to restart your BASIC Stamp without having to cycle the power. This saves wear-and-tear on the battery clip for simple program restarts. Some advanced programming techniques use the reset button and the BASIC Stamp EEPROM as a way to toggle between different program functions.
+
+
Running Indicator LED: This LED will light up when a BASIC Stamp program is running. It is not a power indicator LED.
+
+
BASIC Stamp 2 : The components of a BASIC Stamp 2 module are built directly onto the board. It connects the BASIC Stamp to the programming connector, power, the running indicator LED, reset button, and I/O pin header..
+
+
Important! Check the Revision Letter of your Serial HomeWork Board!
+
Look for the revision letter on your HomeWork Board:
+
+
If you have a Serial HomeWork Board - Rev C, D, or E, you don't need any extra instructions. Go ahead and click the NEXT arrow.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/HWB_RevBpopup.htm b/help/BasicStampHelp/Content/StartTopics/HWB_RevBpopup.htm
new file mode 100644
index 0000000..8bd0774
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/HWB_RevBpopup.htm
@@ -0,0 +1,16 @@
+
+
+
+ HomeWork Board Rev B Special Instructions
+
+
+
+
+
HomeWork Board Rev B Special Instructions
+
Vdd - Limited Current Budget
+
The BASIC Stamp HomeWork Board Rev B’s voltage regulator supplies current to the embedded BASIC Stamp, certain circuits built on the breadboard and connected to I/O pins, and any devices drawing current from the Vdd sockets. The current budget for the Board of Education Rev B board’s voltage regulator is 50 mA. Most devices featured in Stamps in Class texts only draw a few extra milliamps of current and will work fine when powered by the Board of Education Rev B board’s Vdd Pins. However, there are a few exceptions, including servos, pumps, and heating elements. These devices should not be connected to Vdd, or it could damage the board’s voltage regulator. Instead, these higher current devices should be connected to Vin. The voltage supplied to Vin should in turn be limited to a level that is compatible with the device (servo, pump, heating element).
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/HWBadapter_setup.htm b/help/BasicStampHelp/Content/StartTopics/HWBadapter_setup.htm
new file mode 100644
index 0000000..c494902
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/HWBadapter_setup.htm
@@ -0,0 +1,90 @@
+
+
+
+ HomeWork Board with USB to Serial Adapter - Setup
+
+
+
+
+
+
+
+
HomeWork Board with USB to Serial Adapter - Setup
+
+
DO NOT connect power to your board until instructed to do so!
+
+
Affixing the Rubber Feet
+
Your board should come with four adhesive rubber feet:
+
+
+
+
+
+
Remove each rubber foot from its adhesive, and affix it to the underside of your board near each corner. Make sure not to cover up the plated holes, you might need these holes later for mounting your board in a project box or on a robot.
+
+
+
+
+
Making the Board Connections
+
+
Connect the larger "A" end of the USB cable to a USB 2.0 port on your computer.
+
Connect the larger "A" end of the USB cable to a USB port on your computer.
USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.
+
USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
+
+
+
+
+
+
Connect the smaller "Mini B" end of the USB cable to the USB connector on the USB to Serial Adapter, as shown in (1).
+
Connect the male DB9 connector on the USB to Serial Adapter to the female DB9 socket on the board (2). N
+
Connect a 9 V alkaline or rechargeable battery to the battery clip (3). (See Power Supplies for more about batteries and battery replacer devices.)
+
+
+
+
+
+
Tip: If you have a BASIC Stamp program running and want to take your board away from your computer, always disconnect and reconnect at the DB9 socket. Leave the USB to Serial Adapter connected to your computer. This will leave the virtual COM port open, allowing you to reconnect your board without the USB port resetting your BASIC Stamp. See the article USB Resets BASIC Stamp for more information.
+
You are ready to test your programming connection!
USB 2.0 ports are recommended for BASIC Stamp boards. On some computers, the internal USB hub will freeze when disconnecting a USB 2.0 device from a USB 3.0 port. This may cause all USB ports on the computer to become unresponsive, requiring a reboot of the computer to remedy the situation. System updates from your computer manufacturer may correct the problem.
+
USB 3.0 ports can sometimes be identified by a blue tab inside the socket.
+
+
+
+
+
+
+
+
+
Connect the smaller "Mini B" end of the USB cable to the USB connector on the board, as shown in (1).
+
Connect a 9 V alkaline or rechargeable battery to the battery clip (2). (See Power Supplies for more about batteries and battery replacer devices.)
+
+
+
+
+
+
You are ready to test your programming connection!
In the First Program activity, you used the DEC formatter with the DEBUG command to display a decimal number in the Debug Terminal. But what happens if you don’t use the DEC formatter with a number? If you use the DEBUG command followed by a number with no formatter, the BASIC Stamp will read that number as an ASCII code.
+
Programming with ASCII Code
+
ASCII is short for American Standard Code for Information Interchange. Most microcontrollers and PC computers use this code to assign a number to each keyboard function. Some numbers correspond to keyboard actions, such as cursor up, cursor down, space, and delete. Other numbers correspond to printed characters and symbols. The numbers 32 through 126 correspond to those characters and symbols that the BASIC Stamp can display in the Debug Terminal. The following program will use ACSII code to display the words “BASIC Stamp 2” in the Debug Terminal.
+
Example Program – ASCIIName.bs2
+
+
Enter and run ASCIIName.bs2.
+
+
Tip: Remember to use the toolbar icons to place Compiler Directives into your programs! '{$STAMP BS2} - Use the diagonal green electronic chip icon. '{$PBASIC 2.5} - Use the gear icon labeled 2.5.
' Stamps in Class - ASCIIName.bs2
+' Use ASCII code in a DEBUG command to display the words BASIC Stamp 2.
+
+'{$STAMP BS2}
+'{$PBASIC 2.5}
+
+PAUSE 1000
+DEBUG 66,65,83,73,67,32,83,116,97,109,112,32,50
+
+END
+
How ASCIIName.bs2 Works
+
+
Each number in the DEBUG command corresponds to one ASCII code symbol that appeared in the Debug Terminal.
+
DEBUG 66,65,83,73,67,32,83,116,97,109,112,32,50
+
66 is the ASCII code for capital “B”, 65 is the code for capital “A” and so on. 32 is the code for a space between characters. Notice that each code number was separated with a comma. The commas allow the one instance of DEBUG to transmit each symbol as a separate value. This is much easier to type than 12 separate DEBUG commands.
+
Your Turn – Exploring ASCII Code
+
+
Save ASCIIName.bs2 as ASCIIRandom.bs2
+
Pick 12 random numbers between 32 and 126.
+
Replace the ASCII code numbers in the program with the numbers you chose.
+
Run your modified program to see what you get!
+
+
+
This Help file has an ASCII Chart(located in PBASIC Language Reference > ASCII Chart) with the numbers and their corresponding symbols. You can look up the corresponding code numbers to spell your own name.
The activities you just finished introduced two PBASIC commands: DEBUG and END. You can find out more about these commands and how they are used by looking them up. You can look up commands here in the BASIC Stamp Help or in the BASIC Stamp Manual.
+
+
Bookmark This Page First!
+
First, let's add this page to your "Favorites" list so you can find your way back here easily when you're done exploring.
+
+
+
Click on the Favorites icon on the BASIC Stamp Help toolbar.
+
+
+
+
+
Later, when you want to return to this page, you can click on the Favorites menu in the lower left of the window:
+
+
+
+
...and then click on "Looking Up Answers" in the Favorite Topics list to return to this page.
+
+
+
+
Exploring the Help Resources
+
There are many ways to find resources in the Help. If you want to know the syntax and usage details of a particular PBASIC command, you can click on "PBASIC Language Reference" in the Table of Contents to see the full list.
+
+
+
+
Next to each command is a set of icons representing which BASIC Stamp models support that command. All commands available to the BASIC Stamp 2 have this icon: . The syntax showing how to use the command is given to the right of the icons.
+
+
+
+
Clicking on a command will take you to a page full of information, and a link to example programs. Here is the DEBUG command's page:
+
+
+
+
You can also learn more about a command using the Search menu. If you enter a term in the field and hit the Search button, you will see a list of topics where the search term appears:
+
+
+
+
Clicking an item in the list will take you that page, and each instance of the search term on that page will be highlighted:
+
+
+
+
You can save the search string by clicking the magnifying glass icon, and then the search string will show up in your Favorites list:
+
+
+
+
+
+
Additional Resources
+
Some helpful books are included with the BASIC Stamp Editor software, as PDF files. You can find the Resources page link under Welcome in the Table of Contents. The Resources page contains links that will open PDF files in your computer's PDF viewer, if you have one.
+
+
+
+
+
Your Turn
+
+
Use the Help file's features to research the DEBUG and END commands.
+
If you have a PDF viewer, research DEBUG and END in the BASIC Stamp Manual file.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/Start.htm b/help/BasicStampHelp/Content/StartTopics/Start.htm
new file mode 100644
index 0000000..efe3564
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/Start.htm
@@ -0,0 +1,60 @@
+
+
+
+ Getting Started with Stamps in Class
+
+
+
+
+
+
You are here: Getting Started with Stamps in Class
+
+
Getting Started with Stamps in Class
+
This is the place to begin if you are setting up your BASIC Stamp 2 and Board of Education or BASIC Stamp HomeWork Board to prepare for the activities in any of our Stamps in Class tutorials, including What's a Microcontroller? and Robotics with the Boe-Bot.
+
The activities in this section of the Help file will guide you through the following tasks:
+
+
Identify what BASIC Stamp development board you are using.
+
Connect your BASIC Stamp development board to your computer.
+
Test the programming connection.
+
Write and test your first PBASIC program for your BASIC Stamp.
+
Write a PBASIC program that uses ASCII code.
+
Turn off the power to your BASIC Stamp development board when you are done.
+
+
You will navigate from one task to the next using the Next arrows. If you want to go back a step, use the Previous arrows. On each page, follow the instructions indicated by red checkmarks:
your BASIC Stamp on your development board (either built-in or inserted into its socket),
+
your development board connected to your computer,
+
power connected to your development board (and turned on if there is a switch).
+
+
+
If not, go back to "Identify your Board" with the PREVIOUS arrow, make those connections, then return here.
+
+
The Run/Identify Test
+
+
To make sure your BASIC Stamp module can communicate with your computer, click the Run menu, then select Identify.
+
+
+
+
+
+
Or, you can use the ID icon on the toolbar:
+
+
+
+
+
An identification window will appear similar to the one shown here. This example shows that a BASIC Stamp 2 has been detected on COM5.
+
+
+
+
+
Check the Identification window to make sure your BASIC Stamp module has been detected on one of the COM ports. If it has been detected, then you are ready to program your BASIC Stamp.
+
+
+
Click the NEXT arrow at the top or bottom of the page.
+
+
What if it didn't work?
+
If the Run -> Identify test DID NOT locate the BASIC Stamp on any COM port, you will need to go to the Troubleshooting section.
+
+
Bookmark This Page First!
+
First, let's add this page to your "Favorites" list so you can find your way back here easily when you're done exploring.
+
+
+
Click on the Favorites icon on the BASIC Stamp Help toolbar.
+
+
+
+
+
Later, when you want to return to this page, you can click on the Favorites menu in the lower left of the window:
+
+
+
+
...and then click on "Testing the Connection" in the Favorite Topics list to return to this page.
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Content/StartTopics/WhenDone.htm b/help/BasicStampHelp/Content/StartTopics/WhenDone.htm
new file mode 100644
index 0000000..fba44c8
--- /dev/null
+++ b/help/BasicStampHelp/Content/StartTopics/WhenDone.htm
@@ -0,0 +1,73 @@
+
+
+
+ When You Are Done
+
+
+
+
+
+
It’s important to disconnect the power from your BASIC Stamp and Board of Education (or HomeWork Board) whenever you leave it unattended or when you build or modify circuits on its breadboard. First, your batteries will last longer if the system is not drawing power when you’re not using it. Second, soon you will build circuits on the Board of Education or HomeWork Board prototyping area.
+
Caution! Circuit prototypes should never be left unattended with a battery or power supply connected. Always disconnect the power from your Board of Education or HomeWork Board before you walk away, even if you only plan on leaving it alone for a minute or two.
+
Disconnecting Power
+
For the Board of Education
+
With the Board of Education - Serial (Rev C), or Board of Education USB, disconnecting power is easy. Just move the 3-position switch to position-0 by pushing it to the left as shown below. (If you have an older Board of Education- Serial which does not have a 3-position switch, unplug the battery or power supply plug.)
+
+
+
+
+
+
+
+
Caution! Do not remove the BASIC Stamp module from its socket, unless it needs to be replaced with another module! Every time the BASIC Stamp is removed and re-inserted into the socket, you risk damaging it. You do not need to remove it for storage.
+
For the HomeWork Board
+
Disconnecting the BASIC Stamp HomeWork Board’s power is easy too. If you are using the BASIC Stamp HomeWork Board, disconnect the battery as shown below.
+
+
+
+
+
+
Your Turn
+
+
Disconnect the power to your board now.
+
If you are following the directions in a Stamps in Class text, you are ready to return to the text now.
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Skin/Toolbar.htm b/help/BasicStampHelp/Skin/Toolbar.htm
new file mode 100644
index 0000000..f4baf49
--- /dev/null
+++ b/help/BasicStampHelp/Skin/Toolbar.htm
@@ -0,0 +1,81 @@
+
+
+
+ Toolbar
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/help/BasicStampHelp/Skin/TopicComments.htm b/help/BasicStampHelp/Skin/TopicComments.htm
new file mode 100644
index 0000000..617f064
--- /dev/null
+++ b/help/BasicStampHelp/Skin/TopicComments.htm
@@ -0,0 +1,77 @@
+
+
+
+ Topic Comments
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/help/aef.html b/help/aef.html
new file mode 100644
index 0000000..dd745ef
--- /dev/null
+++ b/help/aef.html
@@ -0,0 +1,16 @@
+
Additional editor features
+
+
Additional elements which are supported by πBasic IDE but not supported by the Basic Stamp Editor®
+You don't need a Basic Stamp 1® to run a program (That's obvious - we're talking about an emulator).
+
+
You can automatically format your code (Options->Indent or CTRL+F)
+
+
+
You can extend the console of the standard run with a live-view of the EEPROM of the simulated controller (Options->Monitored Run or CTRL+M)
+
+
+
You can comment/uncomment a selection of the code (Options->Comment/Uncomment or CTRL+SHIFT+C/U)
+
+
+
You can use the content assistance (Options->Content Assist or CTRL+SPACE)
+
diff --git a/help/alf.html b/help/alf.html
new file mode 100644
index 0000000..5b7a6bf
--- /dev/null
+++ b/help/alf.html
@@ -0,0 +1,48 @@
+
Additional language features
+
+
Additional elements which are supported by πBasic but not supported by PBasic®
+
+
+
ACTIVATEINFO/DEACTIVATEINFO:
+
+
This command activates/deactivates the console output of additional information about the commands at runtime.
+
+
+
+
DEBUG EEPROM:
+
+
We added EEPROM as an additional argument to DEBUG (just like DEBUG CR or DEBUG CLS).
+
+
It's output is the composition of the EEPROM at runtime.
+
+
+
+
SYMBOL new = NEW 16:
+
+
We added the possibility of referencing new variables of a specified size (in bits).
+
+
It's not possible to reference variables with more than 16 bits.
+
+
+
+
SYSCLOCK
+
+
This is no command but a variable that contains the actual system time (in seconds).
+
It repeats at 0 after about 18 hours an 12 minutes.
+
+
+
+
BREAKPOINT
+
+
This command that loops the evaluation of the user-input until continue (ENTER).
+
+
It can evaluate all known commands of the piBasic Interpreter as to create the possibility
+
+
of simulating analogue input or debugging.
+
+
+
+
ASSERT expression
+
+
If you don't want to check for something by yourself, you can make the program stop if the asserted expression is false.
+
diff --git a/help/auth.html b/help/auth.html
new file mode 100644
index 0000000..93885d2
--- /dev/null
+++ b/help/auth.html
@@ -0,0 +1,4 @@
+
The authors
+
+
+
Elias Groll, Johanna Reichmann (2015)
diff --git a/help/ca.html b/help/ca.html
new file mode 100644
index 0000000..77e8d1f
--- /dev/null
+++ b/help/ca.html
@@ -0,0 +1,71 @@
+
How to use the content assistance
+
+
The content assistance can be activated by pressing CTRL+SPACE. Simply type the first letters of a keyword (command) and the content assistance will complete the statement.
+
+
The content assistance starts if you activate it at the beginning of a line, and if there are no other keywords that match your typing.
+
+
+
You can add, modify or remove keywords by editing the Content Assist Configuration (OPTIONS-> Content Assist Configuration).
+
+
+
+
All known keywords:
+
+
+
PAUSE
+
SOUND
+
SD
+
HIGH
+
LOW
+
OUTPUT
+
OP
+
PAUSE
+
PS
+
GOTO
+
JMP
+
IF
+
END
+
GOSUB
+
SUB
+
RETURN
+
FOR
+
LOOP
+
WHILE
+
DOWHILE
+
NEXT
+
DEBUG
+
DB
+
DG
+
SAY
+
BREAKPOINT
+
BP
+
SYMBOL
+
LOOKUP
+
LU
+
LD
+
LOOKDOWN
+
POT
+
PULSIN
+
PIN
+
POUT
+
PULSOUT
+
LET
+
=
+
INPUT
+
IP
+
ASSERT
+
CHECK
+
ACTIVATEINFO
+
AI
+
DI
+
DEACTIVATEINFO
+
BRANCH
+
NAP
+
SLEEP
+
EEPROM
+
RANDOM
+
READ
+
WRITE
+
TOGGLE
+
REVERSE
+
diff --git a/help/help.html b/help/help.html
new file mode 100644
index 0000000..ca53482
--- /dev/null
+++ b/help/help.html
@@ -0,0 +1,6 @@
+
How to start the help view
+
+
You can start the help view (Welcome-page) using Options->Help.
+
+
You can navigate the help view by clicking the links or clicking the "back"-button on the right-top of the view.
+
diff --git a/help/img/BP.png b/help/img/BP.png
new file mode 100644
index 0000000..4065e30
Binary files /dev/null and b/help/img/BP.png differ
diff --git a/help/img/assert.png b/help/img/assert.png
new file mode 100644
index 0000000..0fe6774
Binary files /dev/null and b/help/img/assert.png differ
diff --git a/help/img/ca.png b/help/img/ca.png
new file mode 100644
index 0000000..842569a
Binary files /dev/null and b/help/img/ca.png differ
diff --git a/help/img/cac.png b/help/img/cac.png
new file mode 100644
index 0000000..cd41339
Binary files /dev/null and b/help/img/cac.png differ
diff --git a/help/img/chaos.png b/help/img/chaos.png
new file mode 100644
index 0000000..315bad6
Binary files /dev/null and b/help/img/chaos.png differ
diff --git a/help/img/comment.png b/help/img/comment.png
new file mode 100644
index 0000000..fad725c
Binary files /dev/null and b/help/img/comment.png differ
diff --git a/help/img/debuge.png b/help/img/debuge.png
new file mode 100644
index 0000000..6dc3a7b
Binary files /dev/null and b/help/img/debuge.png differ
diff --git a/help/img/eeprom.png b/help/img/eeprom.png
new file mode 100644
index 0000000..59ff3a5
Binary files /dev/null and b/help/img/eeprom.png differ
diff --git a/help/img/format.png b/help/img/format.png
new file mode 100644
index 0000000..5f7a8a8
Binary files /dev/null and b/help/img/format.png differ
diff --git a/help/img/help.png b/help/img/help.png
new file mode 100644
index 0000000..c499003
Binary files /dev/null and b/help/img/help.png differ
diff --git a/help/img/indented.png b/help/img/indented.png
new file mode 100644
index 0000000..eec19b4
Binary files /dev/null and b/help/img/indented.png differ
diff --git a/help/img/info.png b/help/img/info.png
new file mode 100644
index 0000000..d7a3da0
Binary files /dev/null and b/help/img/info.png differ
diff --git a/help/img/jufo.jpg b/help/img/jufo.jpg
new file mode 100644
index 0000000..64c70b3
Binary files /dev/null and b/help/img/jufo.jpg differ
diff --git a/help/img/jufo_klein.png b/help/img/jufo_klein.png
new file mode 100644
index 0000000..7075d9b
Binary files /dev/null and b/help/img/jufo_klein.png differ
diff --git a/help/img/new.png b/help/img/new.png
new file mode 100644
index 0000000..2d68d38
Binary files /dev/null and b/help/img/new.png differ
diff --git a/help/img/open.png b/help/img/open.png
new file mode 100644
index 0000000..7c7a39d
Binary files /dev/null and b/help/img/open.png differ
diff --git a/help/img/rc.png b/help/img/rc.png
new file mode 100644
index 0000000..ea57742
Binary files /dev/null and b/help/img/rc.png differ
diff --git a/help/img/run.png b/help/img/run.png
new file mode 100644
index 0000000..b9e0846
Binary files /dev/null and b/help/img/run.png differ
diff --git a/help/img/splash.bmp b/help/img/splash.bmp
new file mode 100644
index 0000000..38b923e
Binary files /dev/null and b/help/img/splash.bmp differ
diff --git a/help/img/sysclock.png b/help/img/sysclock.png
new file mode 100644
index 0000000..2c4764c
Binary files /dev/null and b/help/img/sysclock.png differ
diff --git a/help/index.html b/help/index.html
new file mode 100644
index 0000000..2d3f40f
--- /dev/null
+++ b/help/index.html
@@ -0,0 +1,33 @@
+
Welcome to the πBasic Interpreter!
+
+
+
This software is an IDE for the πBasic Interpreter which can execute, debug and monitor the Basic Stamp 1® Basic language PBasic®.
\ No newline at end of file
diff --git a/help/keyb.html b/help/keyb.html
new file mode 100644
index 0000000..33e2f54
--- /dev/null
+++ b/help/keyb.html
@@ -0,0 +1,15 @@
+
List of key-bindings
+
+
The following list offers the key-bindings (shortcuts) of the πBasic Interpreter IDE
+
+
+
CTRL+O -> open a file (opens the File Explorer, then you have to open a file via double-click)
\ No newline at end of file
diff --git a/help/mig.html b/help/mig.html
new file mode 100644
index 0000000..ed0df95
--- /dev/null
+++ b/help/mig.html
@@ -0,0 +1,6 @@
+
How to migrate a program to the Basic Stamp 1®
+
To migrate a program which is written with this editor/IDE you have to:
+
+
remove/comment all the additional language features of the πBasic Interpreter that you have used in your program (SYSCLOCK, NEW 16, BREAKPOINT, ASSERT, DEBUG EEPROM, ACTIVATEINFO, DEACTIVATEINFO)
+
copy & paste the code or just open the file with your installation of the Basic Stamp Editor®
+
\ No newline at end of file
diff --git a/help/open.html b/help/open.html
new file mode 100644
index 0000000..4cfb652
--- /dev/null
+++ b/help/open.html
@@ -0,0 +1,14 @@
+
How to open, create or save a program
+
Open or create a program:
+
+
create a new file (File->New or CTRL-N)
+
open a file via FileBrowser ( File->Open.. or CTRL-O + double-click file)
+
+
+
Save a program:
+
+
save a file(File->Save or CTRL-S)
+
save all opened files (File->Save all.. or CTRL-SHIFT-S)
+
save as (File->Save as.. or CTRL+ALT+S11)
+
+
diff --git a/help/runp.html b/help/runp.html
new file mode 100644
index 0000000..5aadd4f
--- /dev/null
+++ b/help/runp.html
@@ -0,0 +1,9 @@
+
How to run a program
+
To run a program which is written with this Editor/IDE or the Basic Stamp Editor® you have to:
+
+
create a new file (File->New or CTRL-N) or open a file via FileBrowser ((File->Open.. or CTRL-O) + double-click file)
+
run it via standard run (Options->run or CTRL+R) or monitored run (Options->monitored run or CTRL+M)
+
+
You cannot run multiple programs at the same time.
The run configuration can be set by Options-> Run Configuration.
+
+
+
The debug color scheme can be changed (blue, white, balck) by Options-> Change Debug Scheme.
+
diff --git a/icons/128x128.gif b/icons/128x128.gif
new file mode 100644
index 0000000..2ae8794
Binary files /dev/null and b/icons/128x128.gif differ
diff --git a/icons/16x16.gif b/icons/16x16.gif
new file mode 100644
index 0000000..efd97d3
Binary files /dev/null and b/icons/16x16.gif differ
diff --git a/icons/16x16_32.bmp b/icons/16x16_32.bmp
new file mode 100644
index 0000000..5498517
Binary files /dev/null and b/icons/16x16_32.bmp differ
diff --git a/icons/16x16_8.bmp b/icons/16x16_8.bmp
new file mode 100644
index 0000000..4a672dc
Binary files /dev/null and b/icons/16x16_8.bmp differ
diff --git a/icons/256x256.gif b/icons/256x256.gif
new file mode 100644
index 0000000..126e4fc
Binary files /dev/null and b/icons/256x256.gif differ
diff --git a/icons/256x256_32.bmp b/icons/256x256_32.bmp
new file mode 100644
index 0000000..59418a4
Binary files /dev/null and b/icons/256x256_32.bmp differ
diff --git a/icons/32x32.gif b/icons/32x32.gif
new file mode 100644
index 0000000..d1215e7
Binary files /dev/null and b/icons/32x32.gif differ
diff --git a/icons/32x32_32.bmp b/icons/32x32_32.bmp
new file mode 100644
index 0000000..fe9dd16
Binary files /dev/null and b/icons/32x32_32.bmp differ
diff --git a/icons/32x32_8.bmp b/icons/32x32_8.bmp
new file mode 100644
index 0000000..b0f288f
Binary files /dev/null and b/icons/32x32_8.bmp differ
diff --git a/icons/48x48.gif b/icons/48x48.gif
new file mode 100644
index 0000000..425c8ec
Binary files /dev/null and b/icons/48x48.gif differ
diff --git a/icons/48x48_32.bmp b/icons/48x48_32.bmp
new file mode 100644
index 0000000..3d6bd2b
Binary files /dev/null and b/icons/48x48_32.bmp differ
diff --git a/icons/48x48_8.bmp b/icons/48x48_8.bmp
new file mode 100644
index 0000000..427bd14
Binary files /dev/null and b/icons/48x48_8.bmp differ
diff --git a/icons/64x64.gif b/icons/64x64.gif
new file mode 100644
index 0000000..e175380
Binary files /dev/null and b/icons/64x64.gif differ
diff --git a/icons/InputArrow.gif b/icons/InputArrow.gif
new file mode 100644
index 0000000..152a344
Binary files /dev/null and b/icons/InputArrow.gif differ
diff --git a/icons/InputArrowSmall.gif b/icons/InputArrowSmall.gif
new file mode 100644
index 0000000..d38a5ba
Binary files /dev/null and b/icons/InputArrowSmall.gif differ
diff --git a/icons/InputFilled.gif b/icons/InputFilled.gif
new file mode 100644
index 0000000..eb6c9f7
Binary files /dev/null and b/icons/InputFilled.gif differ
diff --git a/icons/InputFilledSmall.gif b/icons/InputFilledSmall.gif
new file mode 100644
index 0000000..68bc529
Binary files /dev/null and b/icons/InputFilledSmall.gif differ
diff --git a/icons/OutputArrow.gif b/icons/OutputArrow.gif
new file mode 100644
index 0000000..fd8839b
Binary files /dev/null and b/icons/OutputArrow.gif differ
diff --git a/icons/OutputArrowSmall.gif b/icons/OutputArrowSmall.gif
new file mode 100644
index 0000000..0ba00f1
Binary files /dev/null and b/icons/OutputArrowSmall.gif differ
diff --git a/icons/OutputFilled.gif b/icons/OutputFilled.gif
new file mode 100644
index 0000000..5f67724
Binary files /dev/null and b/icons/OutputFilled.gif differ
diff --git a/icons/OutputFilledSmall.gif b/icons/OutputFilledSmall.gif
new file mode 100644
index 0000000..bb78ca7
Binary files /dev/null and b/icons/OutputFilledSmall.gif differ
diff --git a/icons/bs1.gif b/icons/bs1.gif
new file mode 100644
index 0000000..7d1347b
Binary files /dev/null and b/icons/bs1.gif differ
diff --git a/icons/ca.gif b/icons/ca.gif
new file mode 100644
index 0000000..b24ce1e
Binary files /dev/null and b/icons/ca.gif differ
diff --git a/icons/comment.gif b/icons/comment.gif
new file mode 100644
index 0000000..0df4251
Binary files /dev/null and b/icons/comment.gif differ
diff --git a/icons/config.gif b/icons/config.gif
new file mode 100644
index 0000000..3115408
Binary files /dev/null and b/icons/config.gif differ
diff --git a/icons/console.gif b/icons/console.gif
new file mode 100644
index 0000000..9c0693e
Binary files /dev/null and b/icons/console.gif differ
diff --git a/icons/eeprom.gif b/icons/eeprom.gif
new file mode 100644
index 0000000..a4501d9
Binary files /dev/null and b/icons/eeprom.gif differ
diff --git a/icons/hardware.gif b/icons/hardware.gif
new file mode 100644
index 0000000..4a18c3a
Binary files /dev/null and b/icons/hardware.gif differ
diff --git a/icons/input.gif b/icons/input.gif
new file mode 100644
index 0000000..b9c91aa
Binary files /dev/null and b/icons/input.gif differ
diff --git a/icons/intent.gif b/icons/intent.gif
new file mode 100644
index 0000000..4e23e53
Binary files /dev/null and b/icons/intent.gif differ
diff --git a/icons/linuxico.xpm b/icons/linuxico.xpm
new file mode 100644
index 0000000..2ddef58
--- /dev/null
+++ b/icons/linuxico.xpm
@@ -0,0 +1,370 @@
+/* XPM */
+static char * C:\Users\Elias_2\Desktop\linuxico_xpm[] = {
+"256 258 109 2",
+" c #000000",
+". c #060606",
+"+ c #090909",
+"@ c #0D0D0D",
+"# c #111111",
+"$ c #191919",
+"% c #1C1C1C",
+"& c #202020",
+"* c #242424",
+"= c #262626",
+"- c #151515",
+"; c #020202",
+"> c #101010",
+", c #161616",
+"' c #1D1D1D",
+") c #292929",
+"! c #303030",
+"~ c #363636",
+"{ c #3C3C3C",
+"] c #404040",
+"^ c #232323",
+"/ c #030303",
+"( c #282828",
+"_ c #3A3A3A",
+": c #434343",
+"< c #4C4C4C",
+"[ c #555555",
+"} c #5A5A5A",
+"| c #313131",
+"1 c #050505",
+"2 c #333333",
+"3 c #4A4A4A",
+"4 c #565656",
+"5 c #626262",
+"6 c #6D6D6D",
+"7 c #737373",
+"8 c #3F3F3F",
+"9 c #6B6B6B",
+"0 c #7C7C7C",
+"a c #8D8D8D",
+"b c #9D9D9D",
+"c c #A5A5A5",
+"d c #5B5B5B",
+"e c #080808",
+"f c #8F8F8F",
+"g c #A3A3A3",
+"h c #B6B6B6",
+"i c #BFBFBF",
+"j c #696969",
+"k c #0A0A0A",
+"l c #B9B9B9",
+"m c #CECECE",
+"n c #D9D9D9",
+"o c #787878",
+"p c #0B0B0B",
+"q c #E6E6E6",
+"r c #F2F2F2",
+"s c #858585",
+"t c #0C0C0C",
+"u c #F9F9F9",
+"v c #F6F6F6",
+"w c #EEEEEE",
+"x c #E3E3E3",
+"y c #DFDFDF",
+"z c #DBDBDB",
+"A c #EAEAEA",
+"B c #FDFDFD",
+"C c #8C8C8C",
+"D c #EFEFEF",
+"E c #E9E9E9",
+"F c #E2E2E2",
+"G c #D6D6D6",
+"H c #CFCFCF",
+"I c #C9C9C9",
+"J c #C2C2C2",
+"K c #DCDCDC",
+"L c #FCFCFC",
+"M c #D7D7D7",
+"N c #C5C5C5",
+"O c #BCBCBC",
+"P c #B3B3B3",
+"Q c #AAAAAA",
+"R c #FAFAFA",
+"S c #CCCCCC",
+"T c #B5B5B5",
+"U c #A9A9A9",
+"V c #929292",
+"W c #C0C0C0",
+"X c #949494",
+"Y c #838383",
+"Z c #727272",
+"` c #A4A4A4",
+" . c #F7F7F7",
+".. c #707070",
+"+. c #5C5C5C",
+"@. c #494949",
+"#. c #969696",
+"$. c #F5F5F5",
+"%. c #464646",
+"&. c #878787",
+"*. c #F4F4F4",
+"=. c #7A7A7A",
+"-. c #F3F3F3",
+";. c #070707",
+">. c #4D4D4D",
+",. c #F8F8F8",
+"'. c #FEFEFE",
+"). c #B2B2B2",
+"!. c #010101",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" . + @ # $ % & * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * & $ - # @ . ; ",
+" + > , ' ) ! ~ { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" @ , & ( _ : < [ } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } [ < _ | ( & @ 1 ",
+" # ' ( 2 3 4 5 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" $ ) _ 3 9 0 a b c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c b a 9 d 3 _ $ e ",
+" % ! : 4 0 f g h i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i h g 0 j 4 : % k ",
+" & ~ < 5 a g l m n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n m l a o 5 < & p ",
+" * { [ 6 b h m q r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r q m b s 6 [ * t ",
+" = ] } 7 c i n r u v r w q x y z n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n z y x A w r u B r n c C 7 } = @ ",
+" = ] } 7 c i n r v D E F G H I J i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i J I H K F E v L r n c C 7 } = @ ",
+" = ] } 7 c i n r r E y M N O P Q c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c Q P O m M y r R r n c C 7 } = @ ",
+" = ] } 7 c i n r w F M S T U b V C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C V b U W S M w u r n c C 7 } = @ ",
+" = ] } 7 c i n r q G N T X Y Z 5 } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } 5 Z Y ` T N q .r n c C 7 } = @ ",
+" = ] } 7 c i n r x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] @.+...#.U O x $.r n c C 7 } = @ ",
+" = ] } 7 c i n r y I P b Z +.%.| = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = | %.+.&.b P y *.r n c C 7 } = @ ",
+" = ] } 7 c i n r z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ $ | @.=.V Q z -.r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" . ' ( 2 8 4 5 6 7 7 7 7 7 7 7 7 &.#.` ).m K A ,.A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 5 4 3 8 ( ' # . . # ' 2 8 3 4 6 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.,.A m W ).` &.=.7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" !./ 1 . ;.k p t @ @ @ @ @ @ @ @ | @.5 =.Q J z -.z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ p k e ;.1 / ; !. !.; / . ;.e k t @ @ @ @ @ @ @ @ $ | @.=.V Q z -.-.z Q V =.5 | $ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" . ' ( 2 8 4 5 6 7 7 7 7 7 7 7 7 &.#.` ).m K A ,.A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 5 4 3 8 ( ' # . . # ' 2 8 3 4 6 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.,.A m W ).` &.=.7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" !./ 1 . ;.k p t @ @ @ @ @ @ @ @ | @.5 =.Q J z -.z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ p k e ;.1 / ; !. !.; / . ;.e k t @ @ @ @ @ @ @ @ $ | @.=.V Q z -.-.z Q V =.5 | $ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" . ' ( 2 8 4 5 6 7 7 7 7 7 7 7 7 &.#.` ).m K A ,.A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 5 4 3 8 ( ' # . . # ' 2 8 3 4 6 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.,.A m W ).` &.=.7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" !./ 1 . ;.k p t @ @ @ @ @ @ @ @ | @.5 =.Q J z -.z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ p k e ;.1 / ; !. !.; / . ;.e k t @ @ @ @ @ @ @ @ $ | @.=.V Q z -.-.z Q V =.5 | $ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" . ' ( 2 8 4 5 6 7 7 7 7 7 7 7 7 &.#.` ).m K A ,.A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 5 4 3 8 ( ' # . . # ' 2 8 3 4 6 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.,.A m W ).` &.=.7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" !./ 1 . ;.k p t @ @ @ @ @ @ @ @ | @.5 =.Q J z -.z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ p k e ;.1 / ; !. !.; / . ;.e k t @ @ @ @ @ @ @ @ $ | @.=.V Q z -.-.z Q V =.5 | $ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" ; + @ # - % & * = = = = = = = = %.+.Z &.P I y *.y I P b Z +.%.| = = = = = = = = = = = = = = = = & % $ - @ + . ; ; . + # - $ % * = = = = = = = = | %.+.&.b P y *.*.y P b &.Z %.| = = = = = = = = * & $ - # @ . ; ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" e ) _ 3 d 0 a b c c c c c c c c P O N m y E r R r E y M N O P Q c c c c c c c c c c c c c c c c a 0 9 d _ ) $ e e $ ) 3 d 9 0 b c c c c c c c c Q P O m M y r R R r y M m N P Q c c c c c c c c b a 9 d 3 _ $ e ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" t { [ 6 s h m q r r r r r r r r *.$. .,.R L B '.B L R u .$.*.-.r r r r r r r r r r r r r r r r m h b s [ { * t t * { 6 s b h q r r r r r r r r -.*.$.,.u R B '.'.B R u ,. .*.-.r r r r r r r r q m b s 6 [ * t ",
+" p ~ < 5 o g l m n n n n n n n n y x q A r v u B u v r w q x y z n n n n n n n n n n n n n n n n l g a o < ~ & p p & ~ 5 o a g m n n n n n n n n z y x A w r u B B u r w A q y z n n n n n n n n m l a o 5 < & p ",
+" k ! : 4 j f g h i i i i i i i i I H G K E D v L v D E F G H I J i i i i i i i i i i i i i i i i g f 0 j : ! % k k % ! 4 j 0 f h i i i i i i i i J I H K F E v L L v E F K G I J i i i i i i i i h g 0 j 4 : % k ",
+" ;.^ | 8 >.j o s C C C C C C C C b U T W M F w u w F M S T U b V C C C C C C C C C C C C C C C C o j d >.| ^ - ;. ;.- ^ 8 >.d j s C C C C C C C C V b U W S M w u u w M S W T b V C C C C C C C C s o d >.8 | - ;. ",
+" . ' ( 2 8 4 5 6 7 7 7 7 7 7 7 7 &.#.` ).m K A ,.A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 5 4 3 8 ( ' # . . # ' 2 8 3 4 6 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.,.A m W ).` &.=.7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" 1 , & ( | : < [ } } } } } } } } Z Y X ` N G q .q G N T X Y Z 5 } } } } } } } } } } } } } } } } < : _ | & , @ 1 1 @ , ( | _ : [ } } } } } } } } 5 Z Y ` T N q . .q N T ` X Z 5 } } } } } } } } [ < _ | ( & @ 1 ",
+" / > , ' ^ ! ~ { ] ] ] ] ] ] ] ] +...Y #.O H x $.x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ~ ! ) ^ , > + / / + > ' ^ ) ! { ] ] ] ] ] ] ] ] @.+...#.U O x $.$.x O U #.Y +.@.] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" !./ 1 . ;.k p t @ @ @ @ @ @ @ @ | @.5 =.Q J z -.z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ p k e ;.1 / ; !. !.; / . ;.e k t @ @ @ @ @ @ @ @ $ | @.=.V Q z -.-.z Q V =.5 | $ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r n i c C } ] = @ @ = ] 7 C c n r r n c C 7 } = @ ",
+" = ] } 7 c i n r z J Q V 5 @.| $ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ $ | @.=.V Q z -.r n c C 7 } = @ ",
+" = ] } 7 c i n r y I P b Z +.%.| = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = | %.+.&.b P y *.r n c C 7 } = @ ",
+" = ] } 7 c i n r x H O U Y ..+.@.] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] @.+...#.U O x $.r n c C 7 } = @ ",
+" = ] } 7 c i n r A K m W ` #.&.=.7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 =.&.#.).W m A ,.r n c C 7 } = @ ",
+" = ] } 7 c i n r w F M S T U b V C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C V b U W S M w u r n c C 7 } = @ ",
+" = ] } 7 c i n r r E y M N O P Q c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c Q P O m M y r R r n c C 7 } = @ ",
+" = ] } 7 c i n r v D E F G H I J i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i J I H K F E v L r n c C 7 } = @ ",
+" = ] } 7 c i n r B L R u .$.*.-.r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r -.*.$.,.u R B '.r n c C 7 } = @ ",
+" * { [ 6 b h m q r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r q m b s 6 [ * t ",
+" & ~ < 5 a g l m n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n n m l a o 5 < & p ",
+" % ! : 4 0 f g h i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i i h g 0 j 4 : % k ",
+" - ^ | 8 d j o s C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C C s o d >.8 | - ;. ",
+" # ' ( 2 3 4 5 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 5 3 8 2 ( # . ",
+" @ , & ( _ : < [ } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } [ < _ | ( & @ 1 ",
+" + > , ' ) ! ~ { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] { ~ ) ^ ' , + / ",
+" ; / 1 . e k p t @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ t p e ;.. 1 ; !. ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" ",
+" "};
diff --git a/icons/macico.icns b/icons/macico.icns
new file mode 100644
index 0000000..1635749
Binary files /dev/null and b/icons/macico.icns differ
diff --git a/icons/monitored.gif b/icons/monitored.gif
new file mode 100644
index 0000000..7dd4ca9
Binary files /dev/null and b/icons/monitored.gif differ
diff --git a/icons/output.gif b/icons/output.gif
new file mode 100644
index 0000000..33137e5
Binary files /dev/null and b/icons/output.gif differ
diff --git a/icons/run.gif b/icons/run.gif
new file mode 100644
index 0000000..c10676b
Binary files /dev/null and b/icons/run.gif differ
diff --git a/icons/sample.gif b/icons/sample.gif
new file mode 100644
index 0000000..45517bc
Binary files /dev/null and b/icons/sample.gif differ
diff --git a/icons/status_black.gif b/icons/status_black.gif
new file mode 100644
index 0000000..12dc4e6
Binary files /dev/null and b/icons/status_black.gif differ
diff --git a/icons/status_blue.gif b/icons/status_blue.gif
new file mode 100644
index 0000000..9a9536f
Binary files /dev/null and b/icons/status_blue.gif differ
diff --git a/icons/status_green.gif b/icons/status_green.gif
new file mode 100644
index 0000000..9bd41e9
Binary files /dev/null and b/icons/status_green.gif differ
diff --git a/icons/status_red.gif b/icons/status_red.gif
new file mode 100644
index 0000000..36fa1aa
Binary files /dev/null and b/icons/status_red.gif differ
diff --git a/icons/status_white.gif b/icons/status_white.gif
new file mode 100644
index 0000000..40946c2
Binary files /dev/null and b/icons/status_white.gif differ
diff --git a/icons/status_yellow.gif b/icons/status_yellow.gif
new file mode 100644
index 0000000..b9cd7ea
Binary files /dev/null and b/icons/status_yellow.gif differ
diff --git a/icons/stop.gif b/icons/stop.gif
new file mode 100644
index 0000000..d002f35
Binary files /dev/null and b/icons/stop.gif differ
diff --git a/icons/uncomment.gif b/icons/uncomment.gif
new file mode 100644
index 0000000..ded8740
Binary files /dev/null and b/icons/uncomment.gif differ
diff --git a/icons/welcome.gif b/icons/welcome.gif
new file mode 100644
index 0000000..f2d47e5
Binary files /dev/null and b/icons/welcome.gif differ
diff --git a/pbi-product.product b/pbi-product.product
new file mode 100644
index 0000000..5135b54
--- /dev/null
+++ b/pbi-product.product
@@ -0,0 +1,176 @@
+
+
+
+
+
+
+
+
+
+
+ -consoleLog
+
+ -Dosgi.requiredJavaVersion=1.6 -XX:MaxPermSize=256m -Xms40m -Xmx512m
+
+ -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6
+
+
+
+ https://github.com/EliasGroll/pbi
+
+ The MIT License (MIT)
+
+Copyright (c) 2015 Elias Groll, Johanna Reichmann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugin.xml b/plugin.xml
new file mode 100644
index 0000000..be2d301
--- /dev/null
+++ b/plugin.xml
@@ -0,0 +1,417 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugin_customization.ini b/plugin_customization.ini
new file mode 100644
index 0000000..2d6ab60
--- /dev/null
+++ b/plugin_customization.ini
@@ -0,0 +1,2 @@
+org.eclipse.ui/KEY_CONFIGURATION_ID=pbibindingscheme
+org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP = false
diff --git a/splash.bmp b/splash.bmp
new file mode 100644
index 0000000..6af4177
Binary files /dev/null and b/splash.bmp differ
diff --git a/splash_old.bmp b/splash_old.bmp
new file mode 100644
index 0000000..2583022
Binary files /dev/null and b/splash_old.bmp differ
diff --git a/src/edu/fichte/pbi/ide/Activator.java b/src/edu/fichte/pbi/ide/Activator.java
new file mode 100644
index 0000000..bdfbd68
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/Activator.java
@@ -0,0 +1,64 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "edu.fichte.pbi.ide"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/Application.java b/src/edu/fichte/pbi/ide/Application.java
new file mode 100644
index 0000000..7e11719
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/Application.java
@@ -0,0 +1,50 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.equinox.app.IApplication;
+import org.eclipse.equinox.app.IApplicationContext;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+
+
+/**
+ * This class controls all aspects of the application's execution
+ */
+public class Application implements IApplication {
+
+ /* (non-Javadoc)
+ * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
+ */
+ @Override
+ public Object start(IApplicationContext context) throws Exception {
+ Display display = PlatformUI.createDisplay();
+ try {
+ int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
+ if (returnCode == PlatformUI.RETURN_RESTART)
+ return IApplication.EXIT_RESTART;
+ else
+ return IApplication.EXIT_OK;
+ } finally {
+ display.dispose();
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.equinox.app.IApplication#stop()
+ */
+ @Override
+ public void stop() {
+ if (!PlatformUI.isWorkbenchRunning())
+ return;
+ final IWorkbench workbench = PlatformUI.getWorkbench();
+ final Display display = workbench.getDisplay();
+ display.syncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (!display.isDisposed())
+ workbench.close();
+ }
+ });
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/ApplicationActionBarAdvisor.java b/src/edu/fichte/pbi/ide/ApplicationActionBarAdvisor.java
new file mode 100644
index 0000000..c4c93b0
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/ApplicationActionBarAdvisor.java
@@ -0,0 +1,85 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.jface.action.GroupMarker;
+import org.eclipse.jface.action.ICoolBarManager;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.jface.action.StatusLineContributionItem;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
+import org.eclipse.ui.application.ActionBarAdvisor;
+import org.eclipse.ui.application.IActionBarConfigurer;
+
+public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
+
+ public static final String MY_COLROW_TELLER = Activator.PLUGIN_ID
+ + ".colrowteller";
+ private IWorkbenchAction save;
+ private IWorkbenchAction saveAll;
+ private IWorkbenchAction saveAs;
+
+ // IWorkbenchAction newFile;
+
+ public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
+ super(configurer);
+ }
+
+ @Override
+ protected void makeActions(IWorkbenchWindow window) {
+ save = ActionFactory.SAVE.create(window);
+ saveAll = ActionFactory.SAVE_ALL.create(window);
+ saveAs = ActionFactory.SAVE_AS.create(window);
+ // newFile = ActionFactory.NEW.create(window);
+ }
+
+ @Override
+ protected void fillCoolBar(ICoolBarManager coolBar) {
+ ToolBarManager toolBarManager = new ToolBarManager();
+ toolBarManager.add(save);
+ toolBarManager.add(saveAs);
+ toolBarManager.add(saveAll);
+ // toolBarManager.add(newFile);
+ // for (IWizardDescriptor e : getAllWizards(WorkbenchPlugin.getDefault()
+ // .getNewWizardRegistry().getRootCategory().getCategories())) {
+ // System.out.println(e.toString());
+ //
+ // }
+ // AbstractExtensionWizardRegistry wizardRegistry =
+ // (AbstractExtensionWizardRegistry)WorkbenchPlugin.getDefault().getNewWizardRegistry();
+ //
+ // IWizardCategory[] categories =
+ // WorkbenchPlugin.getDefault().getNewWizardRegistry().getRootCategory().getCategories();
+ //
+ // for(IWizardDescriptor wizard : getAllWizards(categories)){
+ // WorkbenchWizardElement wizardElement = (WorkbenchWizardElement)
+ // wizard;
+ // wizardRegistry.removeExtension(wizardElement.getConfigurationElement().getDeclaringExtension(),
+ // new Object[]{wizardElement});
+ // }
+ coolBar.add(new GroupMarker("edu.fichte.pbi.ide.toolbar"));
+ coolBar.add(toolBarManager);
+ }
+
+ @Override
+ protected void fillMenuBar(IMenuManager menuBar) {
+ }
+
+ // private IWizardDescriptor[] getAllWizards(IWizardCategory[] categories) {
+ // List results = new ArrayList();
+ // for (IWizardCategory wizardCategory : categories) {
+ // results.addAll(Arrays.asList(wizardCategory.getWizards()));
+ // results.addAll(Arrays.asList(getAllWizards(wizardCategory
+ // .getCategories())));
+ // }
+ // return results.toArray(new IWizardDescriptor[0]);
+ // }
+
+ @Override
+ protected void fillStatusLine(IStatusLineManager statusLine) {
+ statusLine.add(new StatusLineContributionItem(MY_COLROW_TELLER, 10));
+ super.fillStatusLine(statusLine);
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/ApplicationWorkbenchAdvisor.java b/src/edu/fichte/pbi/ide/ApplicationWorkbenchAdvisor.java
new file mode 100644
index 0000000..2322067
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/ApplicationWorkbenchAdvisor.java
@@ -0,0 +1,21 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
+import org.eclipse.ui.application.WorkbenchAdvisor;
+import org.eclipse.ui.application.WorkbenchWindowAdvisor;
+
+
+public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
+
+ private static final String PERSPECTIVE_ID = "edu.fichte.pbi.ide.perspective"; //$NON-NLS-1$
+
+ @Override
+ public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
+ return new ApplicationWorkbenchWindowAdvisor(configurer);
+ }
+
+ @Override
+ public String getInitialWindowPerspectiveId() {
+ return PERSPECTIVE_ID;
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/ApplicationWorkbenchWindowAdvisor.java b/src/edu/fichte/pbi/ide/ApplicationWorkbenchWindowAdvisor.java
new file mode 100644
index 0000000..c7fc4d0
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/ApplicationWorkbenchWindowAdvisor.java
@@ -0,0 +1,84 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.e4.ui.model.application.ui.basic.MTrimBar;
+import org.eclipse.e4.ui.model.application.ui.basic.MTrimElement;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.application.ActionBarAdvisor;
+import org.eclipse.ui.application.IActionBarConfigurer;
+import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
+import org.eclipse.ui.application.WorkbenchWindowAdvisor;
+import org.eclipse.ui.internal.WorkbenchWindow;
+
+public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
+ private final IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
+
+ public ApplicationWorkbenchWindowAdvisor(
+ IWorkbenchWindowConfigurer configurer) {
+ super(configurer);
+ }
+
+ @Override
+ public ActionBarAdvisor createActionBarAdvisor(
+ IActionBarConfigurer configurer) {
+ return new ApplicationActionBarAdvisor(configurer);
+ }
+
+ @Override
+ public void preWindowOpen() {
+ Rectangle clientArea = Display.getCurrent().getClientArea();
+ configurer
+ .setInitialSize(new Point(clientArea.width, clientArea.height));
+ configurer.setShowCoolBar(false);
+ configurer.setShowStatusLine(true);
+ configurer.setTitle("PBasic IDE and Interpreter");
+ configurer.setShowPerspectiveBar(false);
+ }
+
+ @Override
+ public void postWindowOpen() {
+ hideQuickAccess();
+ }
+
+
+ private void hideQuickAccess() {
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ setQuickAccessVisible(window, false);
+
+ // final IHandlerService service = (IHandlerService)
+ // window.getService(IHandlerService.class);
+ // quickAccessHandlerActivation =
+ // service.activateHandler(QUICK_ACCESS_COMMAND_ID, new
+ // CustomQuickAccessHandler());
+ }
+
+ private void setQuickAccessVisible(IWorkbenchWindow window, boolean visible) {
+ if (window instanceof WorkbenchWindow) {
+ MTrimBar topTrim = ((WorkbenchWindow) window).getTopTrim();
+
+ for (MTrimElement element : topTrim.getChildren()) {
+ // System.out.println(element.getElementId());
+ if ("SearchField".equals(element.getElementId())) {
+ element.setVisible(false);
+ }
+ // if (QUICK_ACCESS_ELEMENT_ID.equals(element.getElementId())) {
+ // element.setVisible(visible);
+ // if (visible) {
+ // Composite control = (Composite) element.getWidget();
+ // control.getChildren()[0].addFocusListener(new
+ // QuickAccessFocusListener());
+ // }
+ // break;
+ // }
+ }
+ }
+ }
+ public IWorkbenchWindowConfigurer getConfigurer(){
+ return configurer;
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/Perspective.java b/src/edu/fichte/pbi/ide/Perspective.java
new file mode 100644
index 0000000..5134bfd
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/Perspective.java
@@ -0,0 +1,32 @@
+package edu.fichte.pbi.ide;
+
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
+import edu.fichte.pbi.ide.views.ConsoleView;
+import edu.fichte.pbi.ide.views.DebugView;
+import edu.fichte.pbi.ide.views.EEPROMView;
+import edu.fichte.pbi.ide.views.FileExplorer;
+import edu.fichte.pbi.ide.views.HelpView;
+import edu.fichte.pbi.ide.views.VariableView;
+
+public class Perspective implements IPerspectiveFactory {
+
+ @Override
+ public void createInitialLayout(IPageLayout layout) {
+ String editorAreaId = layout.getEditorArea();
+ layout.setEditorAreaVisible(false);
+ layout.addPlaceholder(FileExplorer.ID, IPageLayout.LEFT, 0.17f, editorAreaId);
+ layout.addView(HelpView.ID, IPageLayout.RIGHT, 0.7f, editorAreaId);
+ layout.setFixed(true);
+ layout.addPlaceholder(ConsoleView.ID, IPageLayout.BOTTOM, 0.54f,
+ editorAreaId);
+ layout.addPlaceholder(VariableView.ID, IPageLayout.RIGHT, 0.7f,
+ ConsoleView.ID);
+ layout.addPlaceholder(DebugView.ID, IPageLayout.RIGHT, 0.4f,
+ VariableView.ID);
+ layout.addPlaceholder(EEPROMView.ID, IPageLayout.RIGHT, 0.63f,
+ editorAreaId);
+
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/commands/CASettingsCommandHandler.java b/src/edu/fichte/pbi/ide/commands/CASettingsCommandHandler.java
new file mode 100644
index 0000000..16d18ca
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/CASettingsCommandHandler.java
@@ -0,0 +1,81 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.ide.editors.ConfigEditor;
+import edu.fichte.pbi.ide.editors.FileSystemFileEditorInput;
+import edu.fichte.pbi.ide.views.HelpView;
+
+public class CASettingsCommandHandler implements IHandler,IHandler2{
+ protected String filename = "ca.cfg";
+
+
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/" + filename);
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ if (!file.canRead()) {
+ // must copy the html from the bundle .jar to the data file location
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+ if (file.isFile()) {
+ FileSystemFileEditorInput fileSystemFileEditorInput = new FileSystemFileEditorInput(
+ file);
+ try {
+ window.getActivePage().openEditor(fileSystemFileEditorInput,
+ ConfigEditor.ID);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ } else {
+ System.out.println("something went wrong");
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/commands/CommentCommandHandler.java b/src/edu/fichte/pbi/ide/commands/CommentCommandHandler.java
new file mode 100644
index 0000000..2cad933
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/CommentCommandHandler.java
@@ -0,0 +1,88 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+
+public class CommentCommandHandler implements IHandler, IHandler2 {
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ StyledText text = pbi.getText();
+ Point selectionRange = text.getSelection();
+ int from = selectionRange.x;
+ int to = selectionRange.y;
+ String selection = text.getText().substring(from, to);
+ Scanner scanner = new Scanner(selection);
+ // List lines = new LinkedList<>();
+ // boolean uncomment = true;
+ String replacement = "";
+
+ while (scanner.hasNextLine()) {
+ String actual = scanner.nextLine();
+ replacement += (actual.startsWith("'") ? "" : "'") + actual
+ + (scanner.hasNextLine() ? "\n" : "");
+ // uncomment &= s.startsWith("'");
+ // lines.add(s);
+ }
+ // for (String actual : lines) {
+ // replacement += (uncomment ? actual.substring(1) : "'" + actual)
+ // + "\n";
+ // }
+ text.setText(text.getText().replaceAll(selection, replacement));
+ scanner.close();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/ContentAssistCommandHandler.java b/src/edu/fichte/pbi/ide/commands/ContentAssistCommandHandler.java
new file mode 100644
index 0000000..8089fd7
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/ContentAssistCommandHandler.java
@@ -0,0 +1,170 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.ide.editors.ConfigEditor;
+import edu.fichte.pbi.ide.editors.PBIEditor;
+import edu.fichte.pbi.ide.views.ConsoleView;
+import edu.fichte.pbi.ide.views.HelpView;
+
+public class ContentAssistCommandHandler implements IHandler, IHandler2 {
+
+ private static Map commands = null;
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ StyledText editor = pbi.getText();
+ Point selectionRange = editor.getSelection();
+ String text = editor.getText();
+ int from;
+ int to = selectionRange.y;
+ for (from = to - 1; from > 0; from--) {
+ if (text.charAt(from) == ' ')
+ return null;
+ if (text.charAt(from) == '\n')
+ break;
+ }
+ try {
+ String content = text.substring(from, to).trim();
+ content = content.toUpperCase();
+ execute: {
+ boolean defined = false;
+ String result = null;
+ if (commands == null || ConfigEditor.hasChanged) {
+ initCommands(event);
+ }
+ for (String cmd : commands.keySet()) {
+ cmd = cmd.toUpperCase();
+ if (cmd.startsWith(content) && !defined) {
+ defined = true;
+ result = cmd;
+ } else if (cmd.startsWith(content) && defined) {
+ break execute;
+ }
+ }
+ String replacement = commands.get(result);
+ if (replacement != null) {
+ String left = text.substring(0, from + 1);
+ String right = text.substring(from + content.length()
+ + 1);
+ String newText = left + replacement + right;
+ editor.setText(newText);
+ to = from + replacement.length() + 1;
+ editor.setSelection(new Point(to, to));
+ }
+ }
+ } catch (ArrayIndexOutOfBoundsException e) {
+ e.printStackTrace();
+ }
+
+ }
+ return null;
+ }
+
+ public static void initCommands(ExecutionEvent event) {
+ commands = new HashMap<>();
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/ca.cfg");
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ if (!file.canRead()) {
+ // must copy the html from the bundle .jar to the data file location
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+
+ Scanner scanner = null;
+ try {
+ scanner = new Scanner(file);
+ String line;
+ while (scanner.hasNextLine()) {
+ line = scanner.nextLine().trim();
+ if (line.startsWith("##") || line.isEmpty()) {
+ continue;
+ } else if (line.contains("->")) {
+ String[] split = line.split("->");
+ if (split.length != 2) {
+ scanner.close();
+
+ throw new IllegalArgumentException();
+ }
+ commands.put(split[0].trim(),
+ split[1].trim().replace("/CR", "\n"));
+ } else {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+ }
+ scanner.close();
+ } catch (FileNotFoundException | IllegalArgumentException e) {
+ e.printStackTrace();
+ try {
+ ((ConsoleView) window.getActivePage().showView(ConsoleView.ID))
+ .print("[Error, content assist]Couldn't read the configuration file\n");
+ } catch (PartInitException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ }
+
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/DebugSchemeCommandHandler.java b/src/edu/fichte/pbi/ide/commands/DebugSchemeCommandHandler.java
new file mode 100644
index 0000000..6806c71
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/DebugSchemeCommandHandler.java
@@ -0,0 +1,108 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.ide.views.ConsoleView;
+import edu.fichte.pbi.ide.views.HelpView;
+
+public class DebugSchemeCommandHandler implements IHandler, IHandler2 {
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ try {
+ final ConsoleView console = (ConsoleView) window.getActivePage()
+ .showView(ConsoleView.ID);
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/color.cfg");
+ if (!file.canRead()) {
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+ String s = "";
+ Scanner scanner = new Scanner(file);
+ while (scanner.hasNextLine()) {
+ String line = scanner.nextLine();
+ if (line.startsWith("##") || line.isEmpty())
+ continue;
+ if (line.contains("console scheme")) {
+ String[] split = line.split("=");
+ if (split.length != 2) {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+ split[1] = split[1].trim().equals("blue") ? " white"
+ : split[1].trim().equals("white") ? " black"
+ : split[1].trim().equals("black") ? "blue"
+ : null;
+ split[1] = split[1] == null ? "blue" : split[1];
+ line = split[0] + "=" + split[1];
+ }
+ s += line + "\n";
+ }
+ scanner.close();
+ try {
+ FileOutputStream out = new FileOutputStream(file);
+ out.write(s.getBytes());
+ out.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ console.setScheme();
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/commands/ExportCommandHandler.java b/src/edu/fichte/pbi/ide/commands/ExportCommandHandler.java
new file mode 100644
index 0000000..459ca59
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/ExportCommandHandler.java
@@ -0,0 +1,93 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.util.LinkedList;
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+import edu.fichte.pbi.ide.views.ConsoleView;
+
+public class ExportCommandHandler implements IHandler, IHandler2 {
+
+ java.util.List deprecated = new LinkedList();
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ }
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ Scanner scanner = new Scanner(pbi.text.getText());
+ String result = "";
+ int curLineNr = 1;
+ while (scanner.hasNextLine()) {
+ String curLine = scanner.nextLine();
+ if (curLine.contains("EEPROM") && curLine.contains("DEBUG")
+ || curLine.contains("BREAKPOINT")
+ || curLine.contains("ASSERT")
+ || curLine.contains("ACTIVATEINFO")
+ || curLine.contains("DEACTIVATEINFO")) {
+ curLine = "'" + curLine.trim();
+ } else if (curLine.contains("NEW")
+ || curLine.contains("SYSCLOCK")) {
+ deprecated.add(curLineNr);
+ }
+ result += curLine + "\n";
+ curLineNr++;
+ }
+ scanner.close();
+ pbi.text.setText(result);
+ IWorkbenchWindow window = HandlerUtil
+ .getActiveWorkbenchWindow(event);
+ try {
+ final ConsoleView console = (ConsoleView) window
+ .getActivePage().showView(ConsoleView.ID);
+ for (Integer lineNr : deprecated) {
+ console.print("[Warn, line " + lineNr + "]You have to remove the referenced object and all it's assignments to export");
+ }
+ } catch (PartInitException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/HelpCommandHandler.java b/src/edu/fichte/pbi/ide/commands/HelpCommandHandler.java
new file mode 100644
index 0000000..c4ceb19
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/HelpCommandHandler.java
@@ -0,0 +1,60 @@
+package edu.fichte.pbi.ide.commands;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.views.HelpView;
+
+public class HelpCommandHandler implements IHandler, IHandler2{
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchWindow window = HandlerUtil
+ .getActiveWorkbenchWindow(event);
+ try {
+ @SuppressWarnings("unused")
+ final HelpView help = (HelpView) window
+ .getActivePage().showView(HelpView.ID);
+ } catch (PartInitException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/IntentCommandHandler.java b/src/edu/fichte/pbi/ide/commands/IntentCommandHandler.java
new file mode 100644
index 0000000..dd3c3c1
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/IntentCommandHandler.java
@@ -0,0 +1,98 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+
+public class IntentCommandHandler implements IHandler, IHandler2 {
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ String intent = autoIntent(pbi.text.getText()); // TODO Zugriff
+ // sch�ner machen
+ pbi.text.setText(intent);
+
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor;
+ }
+
+ @Override
+ public boolean isHandled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ private static String autoIntent(String text) {
+ String retVal = "";
+ Scanner scanner = new Scanner(text);
+ int intent = 0;
+ while (scanner.hasNextLine()) {
+ String line = scanner.nextLine().trim();
+ String space = "";
+ if (!line.startsWith("'")) {
+ intentation: {
+ int endLineComment = line.lastIndexOf("'");
+ if (line.substring(
+ 0,
+ endLineComment == -1 ? line.length()
+ : endLineComment).trim().endsWith(":"))
+ break intentation;
+ for (int i = 0; i < intent; i++)
+ space += " ";
+ if (line.startsWith("FOR"))
+ intent += 2;
+ else if (line.startsWith("NEXT"))
+ intent -= 2;
+ if (intent < 0)
+ intent = 0;
+ }
+ }
+ retVal += space + line + "\n";
+ }
+ scanner.close();
+ return retVal;
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/MonitoredRunCommandHandler.java b/src/edu/fichte/pbi/ide/commands/MonitoredRunCommandHandler.java
new file mode 100644
index 0000000..63a1adf
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/MonitoredRunCommandHandler.java
@@ -0,0 +1,113 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.HandlerEvent;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+import edu.fichte.pbi.ide.views.ConsoleView;
+import edu.fichte.pbi.ide.views.DebugView;
+import edu.fichte.pbi.ide.views.EEPROMView;
+import edu.fichte.pbi.ide.views.IRunStateListener;
+import edu.fichte.pbi.ide.views.VariableView;
+
+public class MonitoredRunCommandHandler implements IHandler, IHandler2 {
+ private List listeners = new ArrayList();
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ this.listeners.add(handlerListener);
+ }
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ private void fireEnabledStateChanged() {
+ for (IHandlerListener iHandlerListener : listeners) {
+ iHandlerListener.handlerChanged(new HandlerEvent(this, true, true));
+ }
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ final File file = pbi.getFile();
+ IWorkbenchWindow window = HandlerUtil
+ .getActiveWorkbenchWindow(event);
+ final Display display = window.getShell().getDisplay();
+
+ try {
+// IViewPart view = window.getActivePage().findView(HelpView.ID);
+// if (view != null) {
+// window.getActivePage().hideView(view);
+// }
+ final VariableView varView = (VariableView) window
+ .getActivePage().showView(VariableView.ID);
+ final ConsoleView console = (ConsoleView) window
+ .getActivePage().showView(ConsoleView.ID);
+ final EEPROMView eeprom = (EEPROMView) window.getActivePage()
+ .showView(EEPROMView.ID);
+ final DebugView debugView = (DebugView) window
+ .getActivePage().showView(DebugView.ID);
+ console.run(file, eeprom, debugView, varView,
+ new IRunStateListener() {
+ @Override
+ public void runStateChanged(boolean isRunning) {
+ RunCommandHandler.somethingIsRunning = isRunning;
+ display.asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ fireEnabledStateChanged();
+ }
+ });
+ }
+ });
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return RunCommandHandler.enabled();
+ }
+
+ @Override
+ public boolean isHandled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/NewFileCommandHandler.java b/src/edu/fichte/pbi/ide/commands/NewFileCommandHandler.java
new file mode 100644
index 0000000..16e6ba9
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/NewFileCommandHandler.java
@@ -0,0 +1,86 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.FileSystemFileEditorInput;
+import edu.fichte.pbi.ide.editors.PBIEditor;
+
+public class NewFileCommandHandler implements IHandler {
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ FileDialog fileDialog = new FileDialog(window.getShell(), SWT.SAVE);
+ fileDialog.setFileName("new.bs1");
+ fileDialog.setFilterExtensions(new String[] { "*.bs1" });
+ // fileDialog.setFileName(fileInput.getName());
+ // fileDialog.setFilterPath(fileInput.getFile().getParent());
+ String newFile = fileDialog.open();
+ File file = new File(newFile);
+ if (!file.exists()) {
+ try {
+ file.createNewFile();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ FileSystemFileEditorInput fileSystemFileEditorInput = new FileSystemFileEditorInput(
+ file);
+ try {
+ PBIEditor editor = (PBIEditor) window.getActivePage().openEditor(fileSystemFileEditorInput,
+ PBIEditor.ID);
+ if(editor.text.getText().isEmpty()){
+ editor.text.setText("' {$STAMP BS1}");
+ }
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+
+ // setInput(fileSystemFileEditorInput);
+ // doSave(null);
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/OpenCommandHandler.java b/src/edu/fichte/pbi/ide/commands/OpenCommandHandler.java
new file mode 100644
index 0000000..957ce07
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/OpenCommandHandler.java
@@ -0,0 +1,66 @@
+package edu.fichte.pbi.ide.commands;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.views.FileExplorer;
+
+public class OpenCommandHandler implements IHandler, IHandler2 {
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ try {
+ @SuppressWarnings("unused")
+ final FileExplorer fe = (FileExplorer) window.getActivePage()
+ .showView(FileExplorer.ID);
+ } catch (PartInitException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/RunCommandHandler.java b/src/edu/fichte/pbi/ide/commands/RunCommandHandler.java
new file mode 100644
index 0000000..6b61737
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/RunCommandHandler.java
@@ -0,0 +1,111 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.HandlerEvent;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+import edu.fichte.pbi.ide.views.ConsoleView;
+import edu.fichte.pbi.ide.views.DebugView;
+import edu.fichte.pbi.ide.views.IRunStateListener;
+
+public class RunCommandHandler implements IHandler, IHandler2 {
+
+ private List listeners = new ArrayList();
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ this.listeners.add(handlerListener);
+ }
+
+ private void fireEnabledStateChanged(){
+ for (IHandlerListener IHandlerListener : listeners) {
+ IHandlerListener.handlerChanged(new HandlerEvent(this, true, true));
+ }
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public static boolean somethingIsRunning = false;
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ if(somethingIsRunning) return null;
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ final File file = pbi.getFile();
+ IWorkbenchWindow window = HandlerUtil
+ .getActiveWorkbenchWindow(event);
+ final Display display = window.getShell().getDisplay();
+ try {
+ final ConsoleView console = (ConsoleView) window
+ .getActivePage().showView(ConsoleView.ID);
+ final DebugView debugView = (DebugView) window
+ .getActivePage().showView(DebugView.ID);
+ console.run(file,null,debugView,null, new IRunStateListener(){
+ @Override
+ public void runStateChanged(boolean isRunning) {
+ // TODO das enabling unenabling funktioniert nicht richtig
+ somethingIsRunning = isRunning;
+ display.asyncExec(new Runnable(){
+
+ @Override
+ public void run() {
+ fireEnabledStateChanged();
+ }});
+ }
+ });
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ } finally {
+
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return enabled();
+ }
+
+ public static boolean enabled(){
+ return (PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor) && !somethingIsRunning;
+ }
+
+ @Override
+ public boolean isHandled() {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ listeners.remove(handlerListener);
+ }
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/SettingsCommandHandler.java b/src/edu/fichte/pbi/ide/commands/SettingsCommandHandler.java
new file mode 100644
index 0000000..08b4d14
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/SettingsCommandHandler.java
@@ -0,0 +1,85 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.io.File;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.ide.editors.ConfigEditor;
+import edu.fichte.pbi.ide.editors.FileSystemFileEditorInput;
+import edu.fichte.pbi.ide.views.HelpView;
+
+public class SettingsCommandHandler implements IHandler, IHandler2 {
+
+ protected String filename;;
+
+ public SettingsCommandHandler() {
+ filename = "set.cfg";
+ }
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/" + filename);
+ IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
+ if (!file.canRead()) {
+ // must copy the html from the bundle .jar to the data file location
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+ if (file.isFile()) {
+ FileSystemFileEditorInput fileSystemFileEditorInput = new FileSystemFileEditorInput(
+ file);
+ try {
+ window.getActivePage().openEditor(fileSystemFileEditorInput,
+ ConfigEditor.ID);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ } else {
+ System.out.println("something went wrong");
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/commands/UncommentCommandHandler.java b/src/edu/fichte/pbi/ide/commands/UncommentCommandHandler.java
new file mode 100644
index 0000000..b98c814
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commands/UncommentCommandHandler.java
@@ -0,0 +1,86 @@
+package edu.fichte.pbi.ide.commands;
+
+import java.util.Scanner;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.IHandler;
+import org.eclipse.core.commands.IHandler2;
+import org.eclipse.core.commands.IHandlerListener;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+
+import edu.fichte.pbi.ide.editors.PBIEditor;
+
+public class UncommentCommandHandler implements IHandler, IHandler2 {
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
+
+ if (activeEditor instanceof PBIEditor) {
+ PBIEditor pbi = (PBIEditor) activeEditor;
+ StyledText text = pbi.getText();
+ Point selectionRange = text.getSelection();
+ int from = selectionRange.x;
+ int to = selectionRange.y;
+ String selection = text.getText().substring(from, to);
+ Scanner scanner = new Scanner(selection);
+ // List lines = new LinkedList<>();
+ // boolean uncomment = true;
+ String replacement = "";
+
+ while (scanner.hasNextLine()) {
+ String actual = scanner.nextLine();
+ replacement += (actual.startsWith("'") ? actual.substring(1) : actual) + (scanner.hasNextLine() ? "\n" : "");
+ // uncomment &= s.startsWith("'");
+ // lines.add(s);
+ }
+ // for (String actual : lines) {
+ // replacement += (uncomment ? actual.substring(1) : "'" + actual)
+ // + "\n";
+ // }
+ text.setText(text.getText().replaceAll(selection, replacement));
+ scanner.close();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor() instanceof PBIEditor;
+ }
+
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void setEnabled(Object evaluationContext) {
+ // TODO Auto-generated method stub
+
+ }
+}
diff --git a/src/edu/fichte/pbi/ide/commonsstolen/FileUtils.java b/src/edu/fichte/pbi/ide/commonsstolen/FileUtils.java
new file mode 100644
index 0000000..98003d1
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/commonsstolen/FileUtils.java
@@ -0,0 +1,23 @@
+package edu.fichte.pbi.ide.commonsstolen;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.StringWriter;
+
+public class FileUtils {
+
+ public static String readFileToString(File file) throws IOException {
+ char[] buf = new char[10000];
+ int c = 0;
+ BufferedReader reader = new BufferedReader(new FileReader(file));
+ StringWriter stringWriter = new StringWriter();
+ while(-1!=(c=reader.read(buf))){
+ stringWriter.write(buf,0,c);
+ }
+ reader.close();
+ return stringWriter.toString();
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/editors/ConfigEditor.java b/src/edu/fichte/pbi/ide/editors/ConfigEditor.java
new file mode 100644
index 0000000..5e1a6c9
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/editors/ConfigEditor.java
@@ -0,0 +1,134 @@
+package edu.fichte.pbi.ide.editors;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.EditorPart;
+
+import edu.fichte.pbi.ide.commonsstolen.FileUtils;
+
+public class ConfigEditor extends EditorPart {
+
+ public static final String ID = "edu.fichte.pbi.ide.cfgeditor";
+ public Text text;
+ private IEditorInput input;
+ private boolean dirty = false;
+ private FileSystemFileEditorInput fileInput;
+ public static boolean hasChanged = false;
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ String content = text.getText();
+ File file = fileInput.getFile();
+ try {
+ FileOutputStream out = new FileOutputStream(file);
+ out.write(content.getBytes());
+ out.close();
+ beClean();
+ hasChanged = true;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+
+ @Override
+ public boolean isSaveOnCloseNeeded() {
+ return true;
+ }
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ this.input = input;
+ setSite(site);
+ setInput(input);
+ setTitle(input.getName());
+ }
+
+ private void beDirty() {
+ dirty = true;
+ firePropertyChange(PROP_DIRTY);
+ }
+
+ private void beClean() {
+ dirty = false;
+ firePropertyChange(PROP_DIRTY);
+ }
+
+ @Override
+ public boolean isDirty() {
+ return dirty;
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
+
+ @Override
+ protected void setInput(IEditorInput input) {
+ super.setInput(input);
+ this.input = input;
+ this.fileInput = (FileSystemFileEditorInput) input;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ parent = new Composite(parent, 0);
+ parent.setLayout(new FillLayout());
+
+ text = new Text(parent, SWT.MULTI | SWT.V_SCROLL);
+ readFileContentToEditor();
+ text.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ beDirty();
+ }
+ });
+ }
+
+ private void readFileContentToEditor() {
+ if (input instanceof FileSystemFileEditorInput) {
+ fileInput = (FileSystemFileEditorInput) input;
+ File file = fileInput.getFile();
+ try {
+ text.setText(FileUtils.readFileToString(file));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ @Override
+ public void setFocus() {
+ text.setFocus();
+ }
+
+ public File getFile() {
+ return fileInput.getFile();
+ }
+
+
+
+ @Override
+ public void doSaveAs() {
+ // TODO Auto-generated method stub
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/edu/fichte/pbi/ide/editors/FileSystemFileEditorInput.java b/src/edu/fichte/pbi/ide/editors/FileSystemFileEditorInput.java
new file mode 100644
index 0000000..92ae764
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/editors/FileSystemFileEditorInput.java
@@ -0,0 +1,78 @@
+package edu.fichte.pbi.ide.editors;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IPersistableElement;
+
+public class FileSystemFileEditorInput implements IEditorInput {
+
+ private File file;
+
+ public FileSystemFileEditorInput(File file) {
+ this.file = file;
+ }
+
+ public Object getAdapter(Class adapter) {
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
+
+ @Override
+ public boolean exists() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return file.getName();
+ }
+
+ @Override
+ public IPersistableElement getPersistable() {
+ return null;
+ }
+
+ @Override
+ public String getToolTipText() {
+ return file.getAbsolutePath();
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((file == null) ? 0 : file.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ FileSystemFileEditorInput other = (FileSystemFileEditorInput) obj;
+ if (file == null) {
+ if (other.file != null)
+ return false;
+ } else if (!file.equals(other.file))
+ return false;
+ return true;
+ }
+
+ public File getFile() {
+ return file;
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/editors/PBIEditor.java b/src/edu/fichte/pbi/ide/editors/PBIEditor.java
new file mode 100644
index 0000000..e055c68
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/editors/PBIEditor.java
@@ -0,0 +1,349 @@
+package edu.fichte.pbi.ide.editors;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.action.StatusLineContributionItem;
+import org.eclipse.jface.action.StatusLineManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.internal.WorkbenchWindow;
+import org.eclipse.ui.part.EditorPart;
+
+import edu.fichte.pbi.ide.ApplicationActionBarAdvisor;
+import edu.fichte.pbi.ide.commonsstolen.FileUtils;
+import edu.fichte.pbi.prgm.parse.Lexer;
+import etinyplugins.commons.swt.UndoRedoImpl;
+
+@SuppressWarnings("restriction")
+public class PBIEditor extends EditorPart {
+
+ public static final String ID = "edu.fichte.pbi.ide.pbieditor";
+ public StyledText text;
+ private IEditorInput input;
+ private boolean dirty = false;
+ private FileSystemFileEditorInput fileInput;
+ private StatusLineContributionItem statusLine;
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ String content = text.getText();
+ File file = fileInput.getFile();
+ try {
+ FileOutputStream out = new FileOutputStream(file);
+ out.write(content.getBytes());
+ out.close();
+ beClean();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void doSaveAs() {
+ FileDialog fileDialog = new FileDialog(getSite().getShell(), SWT.SAVE);
+ fileDialog.setFileName(fileInput.getName());
+ fileDialog.setFilterPath(fileInput.getFile().getParent());
+ String newFile = fileDialog.open();
+ File file = new File(newFile);
+ if (!file.exists()) {
+ try {
+ file.createNewFile();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ FileSystemFileEditorInput fileSystemFileEditorInput = new FileSystemFileEditorInput(
+ file);
+ setInput(fileSystemFileEditorInput);
+ doSave(null);
+ }
+
+ @Override
+ public boolean isSaveOnCloseNeeded() {
+ return true;
+ }
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ this.input = input;
+ setSite(site);
+ setInput(input);
+ setPartName(input.getName());
+ }
+
+ private void beDirty() {
+ dirty = true;
+ firePropertyChange(PROP_DIRTY);
+ }
+
+ private void beClean() {
+ dirty = false;
+ firePropertyChange(PROP_DIRTY);
+ }
+
+ @Override
+ public boolean isDirty() {
+ return dirty;
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return true;
+ }
+
+ @Override
+ protected void setInput(IEditorInput input) {
+ super.setInput(input);
+ this.input = input;
+ this.fileInput = (FileSystemFileEditorInput) input;
+ }
+
+ public StyledText getText() {
+ return text;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ parent = new Composite(parent, 0);
+ parent.setLayout(new FillLayout());
+
+ text = new StyledText(parent, SWT.MULTI | SWT.V_SCROLL);
+ text.setAlwaysShowScrollBars(true);
+ new UndoRedoImpl(text);
+
+ addCurrentPositionTelling();
+
+ readFileContentToEditor();
+ text.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ beDirty();
+ reformat();
+ }
+
+ });
+
+ // Status Zeilenzugriff merken
+ StatusLineManager statusLineManager = ((WorkbenchWindow) getSite()
+ .getWorkbenchWindow()).getStatusLineManager();
+ statusLine = (StatusLineContributionItem) statusLineManager
+ .find(ApplicationActionBarAdvisor.MY_COLROW_TELLER);
+ }
+
+ private void addCurrentPositionTelling() {
+ text.addKeyListener(new KeyListener() {
+
+ @Override
+ public void keyPressed(KeyEvent arg0) {
+ updatePositionDisplay();
+ }
+
+ @Override
+ public void keyReleased(KeyEvent arg0) {
+ updatePositionDisplay();
+ }
+ });
+
+ text.addMouseListener(new MouseListener() {
+
+ @Override
+ public void mouseUp(MouseEvent arg0) {
+ updatePositionDisplay();
+ }
+
+ @Override
+ public void mouseDown(MouseEvent arg0) {
+ updatePositionDisplay();
+ }
+
+ @Override
+ public void mouseDoubleClick(MouseEvent arg0) {
+ updatePositionDisplay();
+ }
+ });
+ }
+
+ private void updatePositionDisplay() {
+ int caretOffset = text.getCaretOffset();
+ int lineNo = 1;
+ int charNo = 1;
+ String content = text.getText();
+ for (int n = 0; n < caretOffset; n++) {
+ char currentChar = content.charAt(n);
+ if (currentChar == '\n') {
+ lineNo++;
+ charNo = 1;
+ } else if (currentChar == '\r') {
+ } else {
+ charNo++;
+ }
+ }
+ String position = lineNo + "/" + charNo;
+ statusLine.setText(position);
+ }
+
+ private void reformat() {
+ // StyleRange styleRange = new StyleRange();
+ // styleRange.start = 0;
+ // styleRange.length = 10;
+ // styleRange.fontStyle = SWT.BOLD;
+ // styleRange.foreground = Display.getCurrent().getSystemColor(
+ // SWT.COLOR_BLUE);
+ for (StyleRange styleRange : sytaxHighlighting()) {
+ text.setStyleRange(styleRange);
+ }
+
+ }
+
+ private List sytaxHighlighting() {
+ String text = this.text.getText();
+ String tmp = "";
+ List knowCommands = new LinkedList<>();
+ for (String cmd : Lexer.KNOWN_COMMANDS) {
+ knowCommands.add(cmd);
+ }
+ knowCommands.add("TO");
+ knowCommands.add("THEN");
+ knowCommands.add("STEP");
+ List retVal = new LinkedList();
+ StyleRange allBlack = new StyleRange();
+ allBlack.start = 0;
+ allBlack.length = text.length();
+ allBlack.foreground = Display.getCurrent().getSystemColor(
+ SWT.COLOR_BLACK);
+ retVal.add(allBlack);
+ global: for (int i = 0; i < text.length(); i++) {
+ char actual = text.charAt(i);
+ if (actual == ' ' || actual == '\n' || actual == ',') {
+ tmp = "";
+ continue;
+ }
+ if (actual == '=' || actual == '/' || actual == '*'
+ || actual == '+' || actual == '-' || actual == '^'
+ || actual == '|' || actual == '&' || actual == '>'
+ || actual == '<') {
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = i;
+ styleRange.length = 1;
+ styleRange.fontStyle = SWT.BOLD;
+ styleRange.foreground = Display.getCurrent().getSystemColor(
+ SWT.COLOR_DARK_RED);
+ retVal.add(styleRange);
+ tmp = "";
+ continue;
+ }
+ if (actual == '\'') {
+ for (int k = i + 1; k < text.length(); k++) {
+ if (text.charAt(k) == '\n' || k == text.length() - 1) {
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = i;
+ styleRange.length = k == text.length() - 1 ? k - i + 1
+ : k - i;
+ styleRange.foreground = Display.getCurrent()
+ .getSystemColor(SWT.COLOR_DARK_GREEN);
+ retVal.add(styleRange);
+ tmp = "";
+ i = k;
+ continue global;
+ }
+ }
+ }
+ if (actual == '\"') {
+ for (int k = i + 1; k < text.length(); k++) {
+ if (text.charAt(k) == '\"') {
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = i;
+ styleRange.length = k - i + 1;
+ styleRange.foreground = Display.getCurrent()
+ .getSystemColor(SWT.COLOR_DARK_YELLOW);
+ retVal.add(styleRange);
+ tmp = "";
+ i = k;
+ continue global;
+ }
+ }
+ }
+ tmp += text.charAt(i);
+ for (String cmd : knowCommands) {
+ if (tmp.equals(cmd)) {
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = (i + 1) - cmd.length();
+ styleRange.length = cmd.length();
+ styleRange.fontStyle = SWT.BOLD;
+ styleRange.foreground = Display.getCurrent()
+ .getSystemColor(SWT.COLOR_BLUE);
+ retVal.add(styleRange);
+ tmp = "";
+ break;
+ }
+ }
+ char prev = (i == 0 ? ' ' : text.charAt(i - 1));
+ if (((actual > 47 && actual < 58))
+ && (prev == ' ' || prev == '\n' || prev == ',' || prev == '(') || prev == '=' || prev == '/' || prev == '*'
+ || prev == '+' || prev == '-' || prev == '^'
+ || prev == '|' || prev == '&' || prev == '>'
+ || prev == '<') {
+ for (int k = i; k < text.length(); k++) {
+ char c = text.charAt(k);
+ if (c < 48 || c > 57) {
+ StyleRange styleRange = new StyleRange();
+ styleRange.start = i;
+ styleRange.length = k - i;
+ styleRange.foreground = Display.getCurrent()
+ .getSystemColor(SWT.COLOR_DARK_YELLOW);
+ retVal.add(styleRange);
+ tmp = "";
+ i = k;
+ continue global;
+ }
+ }
+ }
+ }
+ return retVal;
+
+ }
+
+ private void readFileContentToEditor() {
+ if (input instanceof FileSystemFileEditorInput) {
+ fileInput = (FileSystemFileEditorInput) input;
+ File file = fileInput.getFile();
+ try {
+ text.setText(FileUtils.readFileToString(file));
+ reformat();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void setFocus() {
+ text.setFocus();
+ }
+
+ public File getFile() {
+ return fileInput.getFile();
+ }
+
+}
+
diff --git a/src/edu/fichte/pbi/ide/views/ConsoleView.java b/src/edu/fichte/pbi/ide/views/ConsoleView.java
new file mode 100644
index 0000000..a911d12
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/views/ConsoleView.java
@@ -0,0 +1,375 @@
+package edu.fichte.pbi.ide.views;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.Scanner;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.events.TraverseEvent;
+import org.eclipse.swt.events.TraverseListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.part.ViewPart;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.run.PluginRunner;
+import edu.fichte.pbi.run.app.IConsole;
+import edu.fichte.pbi.vm.IRunWatcher;
+import edu.fichte.pbi.vm.Settings;
+import edu.fichte.pbi.vm.storage.IEEPROMMonitor;
+
+public class ConsoleView extends ViewPart implements IConsole {
+ public static final String ID = "edu.fichte.pbi.ide.consoleView";
+ public StyledText text;
+ private StyledText inputText;
+
+
+ @Override
+ public void createPartControl(Composite parent) {
+ parent = new Composite(parent, SWT.NULL);
+ parent.setLayout(new GridLayout(1, false));
+ Label debugLabel = new Label(parent, SWT.HORIZONTAL);
+ debugLabel.setText("Console");
+ text = new StyledText(parent, SWT.VERTICAL | SWT.HORIZONTAL | SWT.MULTI);
+ text.setAlwaysShowScrollBars(false);
+ text.setEditable(false);
+ Label inputLabel = new Label(parent, SWT.HORIZONTAL);
+ inputLabel.setText("Input");
+ GridData textGridData = new GridData();
+ textGridData.horizontalAlignment = GridData.FILL;
+ textGridData.verticalAlignment = GridData.FILL;
+ textGridData.grabExcessHorizontalSpace = true;
+ textGridData.grabExcessVerticalSpace = true;
+ text.setLayoutData(textGridData);
+ setScheme();
+ inputText = new StyledText(parent, SWT.SINGLE);
+
+ GridData inputTextGridData = new GridData();
+ inputTextGridData.horizontalAlignment = GridData.FILL;
+ inputTextGridData.verticalAlignment = GridData.FILL;
+ inputText.setLayoutData(inputTextGridData);
+ inputText.setEditable(false);
+ inputText.addTraverseListener(new TraverseListener() {
+
+ @Override
+ public void keyTraversed(TraverseEvent e) {
+ if (e.keyCode == 13) {
+ if (runnerLock != null) {
+ inputText.setEditable(false);
+ readlineText = inputText.getText();
+ inputText.setText("");
+
+ String formerText = text.getText();
+// int formerLength = formerText.length();
+ String textAdditionWithNewLines = "\r\n" + readlineText
+ + "\r\n";
+ String newText = formerText + textAdditionWithNewLines;
+ text.setText(newText);
+ synchronized (runnerLock) {
+ runnerLock.notifyAll();
+ }
+ }
+ }
+ }
+ });
+
+ createPartMenu();
+ }
+
+ private void stopCurrentExecution() {
+ if (isRunning()) {
+// runner.stop();
+ runner = null;
+ if (runStateListener != null) {
+ runStateListener.runStateChanged(false);
+ }
+ }
+ }
+
+ public boolean isRunning() {
+ return runner != null && runner.isAlive();
+ }
+
+ private void createPartMenu() {
+ Action stopAction = new Action("Stop") {
+ @Override
+ public void run() {
+ // Kill the runner
+ stopCurrentExecution();
+ text.setText(text.getText()+"\n[STOP]");
+
+ //now lock the debugview => notify it to lock itself
+ System.out.println("Locking Pins...");
+ ((DebugView) getViewSite().getPage().findView(DebugView.ID)).lockPinState();
+ }
+ };
+ getViewSite().getActionBars().getToolBarManager().add(stopAction);
+ }
+
+ @Override
+ public void setFocus() {
+
+ }
+
+ private Thread runner;
+ private Object runnerLock;
+ private String readlineText;
+ private IRunStateListener runStateListener;
+
+ public void run(final File file, final IEEPROMMonitor monitor,
+ final IRunWatcher runWatcher,
+ final VariableView varView,
+ final IRunStateListener runStateListener) {
+ if (runner != null && runner.isAlive()) {
+ runner.interrupt();
+ }
+ clearConsole();
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ try {
+ runStateListener.runStateChanged(true);
+ PluginRunner pluginRunner = new PluginRunner();
+ pluginRunner.run(file, ConsoleView.this, monitor,
+ runWatcher,getSettings(), varView);
+ runStateListener.runStateChanged(false);
+ } catch (Throwable e) {
+ e.printStackTrace();
+ runStateListener.runStateChanged(false);
+ }
+ }
+ };
+ runner = new Thread(runnable);
+ int priority = Thread.currentThread().getPriority() - 2;
+ priority = Math.max(Thread.MIN_PRIORITY, priority);
+ runnerLock = new Object();
+ ((DebugView) getViewSite().getPage().findView(DebugView.ID)).unlockPinState();
+ runner.setPriority(priority);
+ runner.start();
+ }
+
+ private Settings getSettings() {
+
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/set.cfg");
+ if (!file.canRead()) {
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+ boolean emulate4Mhz = true, activateinfo = false, printInternComposition = false, nowarn = false;
+ try {
+ Scanner scanner = new Scanner(file);
+ String line = "";
+ while (scanner.hasNextLine()) {
+ line = scanner.nextLine().trim();
+ if (line.startsWith("##") || line.isEmpty())
+ continue;
+ if (line.startsWith("emulate 4Mhz")) {
+ emulate4Mhz = evaluateBooleanExpression(line);
+ } else if (line.startsWith("activate info")) {
+ activateinfo = evaluateBooleanExpression(line);
+ } else if (line.startsWith("print intern composition")) {
+ printInternComposition = evaluateBooleanExpression(line);
+ } else if (line.startsWith("ignore warnings")) {
+ nowarn = evaluateBooleanExpression(line);
+ } else {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+
+ }
+ scanner.close();
+ } catch (FileNotFoundException | IllegalArgumentException e) {
+ e.printStackTrace();
+ err("[Error, run configurations]Couldn't read the configuration file -> using standard cfg\n");
+ }
+ return new Settings(activateinfo, emulate4Mhz, printInternComposition,
+ nowarn);
+ }
+
+ public void setScheme() {
+
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+ File file = new File(targetRoot, "config/color.cfg");
+ if (!file.canRead()) {
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
+ targetRoot);
+ }
+ try {
+ Scanner scanner = new Scanner(file);
+ String line = "";
+ while (scanner.hasNextLine()) {
+ line = scanner.nextLine().trim();
+ if (line.startsWith("##") || line.isEmpty())
+ continue;
+ if (line.startsWith("console scheme")) {
+ String[] split = line.split("=");
+ if (split.length != 2) {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+ if (split[1].trim().equals("blue")) {
+ text.setBackground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_DARK_BLUE));
+ text.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_WHITE));
+ } else if (split[1].trim().equals("black")) {
+ text.setBackground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_BLACK));
+ text.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_WHITE));
+
+ } else if (split[1].trim().equals("white")) {
+ text.setBackground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_WHITE));
+ text.setForeground(Display.getCurrent().getSystemColor(
+ SWT.COLOR_BLACK));
+
+ } else {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+
+ } else {
+ scanner.close();
+ throw new IllegalArgumentException();
+ }
+
+ }
+ scanner.close();
+ } catch (FileNotFoundException | IllegalArgumentException e) {
+ e.printStackTrace();
+ err("[Error, run configurations]Couldn't read the configuration file -> using standard cfg\n");
+ }
+ }
+
+ private boolean evaluateBooleanExpression(String s) {
+ String[] split = s.split("=");
+ if (split.length != 2) {
+ throw new IllegalArgumentException();
+ }
+ return split[1].trim().equals("true");
+ }
+
+ @Override
+ public void printLn(final String line) {
+ print("\n" + line);
+ }
+
+ @Override
+ public void print(final String s) {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+
+ text.setText(text.getText() + s);
+ text.setTopIndex(text.getLineCount() - 1);
+ }
+ });
+ }
+
+ @Override
+ public String readLn() {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ ConsoleView.this.focusOnInput();
+ }
+ });
+
+ synchronized (runnerLock) {
+ try {
+ runnerLock.wait();
+ } catch (InterruptedException ie) {
+ // do nothing here, we have been killed.
+ }
+ }
+ return readlineText;
+ }
+
+ protected void focusOnInput() {
+ inputText.setEditable(true);
+ inputText.forceFocus();
+ }
+
+ @Override
+ public void clearConsole() {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ text.setText("");
+ text.setTopIndex(text.getLineCount() - 1);
+ }
+ });
+
+ }
+
+ @Override
+ public void err(final String err) {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+// StyleRange styleRange = new StyleRange();
+// styleRange.start = text.getText().length();
+// styleRange.length = err.length();
+// styleRange.fontStyle = SWT.BOLD;
+// styleRange.foreground = Display.getCurrent().getSystemColor(
+// SWT.COLOR_RED);
+ text.setText(text.getText() + err + "\n");
+ text.setTopIndex(text.getLineCount() - 1);
+// text.setStyleRange(styleRange);
+ }
+ });
+ }
+
+ @Override
+ public void warn(final String warn) {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+// StyleRange styleRange = new StyleRange();
+// styleRange.start = text.getText().length();
+// styleRange.length = warn.length();
+// styleRange.fontStyle = SWT.BOLD;
+// styleRange.foreground = Display.getCurrent().getSystemColor(
+// SWT.COLOR_RED);
+ text.setText(text.getText() + warn + "\n");
+ text.setTopIndex(text.getLineCount() - 1);
+// text.setStyleRange(styleRange);
+ }
+ });
+ }
+
+ @Override
+ public void info(final String info) {
+ getSite().getShell().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+// StyleRange styleRange = new StyleRange();
+// styleRange.start = text.getText().length();
+// styleRange.length = info.length();
+// styleRange.fontStyle = SWT.BOLD;
+// styleRange.foreground = Display.getCurrent().getSystemColor(
+// SWT.COLOR_RED);
+ text.setText(text.getText() + info + "\n");
+ text.setTopIndex(text.getLineCount() - 1);
+// text.setStyleRange(styleRange);
+ }
+ });
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/views/DebugView.java b/src/edu/fichte/pbi/ide/views/DebugView.java
new file mode 100644
index 0000000..cdf34be
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/views/DebugView.java
@@ -0,0 +1,322 @@
+package edu.fichte.pbi.ide.views;
+
+import java.io.File;
+
+import org.eclipse.swt.custom.CLabel;
+import org.eclipse.swt.custom.StackLayout;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.part.ViewPart;
+import org.osgi.framework.Bundle;
+
+import edu.fichte.pbi.ide.Activator;
+import edu.fichte.pbi.util.CallbackVariableListener;
+import edu.fichte.pbi.vm.IRunWatcher;
+import edu.fichte.pbi.vm.Machine;
+import edu.fichte.pbi.vm.var.IVariable;
+
+public class DebugView extends ViewPart implements IRunWatcher {
+
+ public static String ID = "edu.fichte.pbi.ide.debugView";
+
+ private Machine machine;
+
+ //GUI elements
+ private Label[] label = new Label[8];
+ private CLabel[] labelInOut = new CLabel[8];
+ private CLabel[] labelHighLow = new CLabel[8];
+ private Button[] buttonHighLow = new Button[8];
+ private Composite[] widgetPin = new Composite[8];
+ private StackLayout[] stackLayout = new StackLayout[8];
+
+ //load icons
+ private Image imageHigh = loadIcon("status_red.gif");
+ private Image imageLow = loadIcon("status_black.gif");
+
+ private Image imageInput = loadIcon("InputArrowSmall.gif");
+ private Image imageOutput = loadIcon("OutputArrowSmall.gif");
+
+
+
+ @Override
+ public void createPartControl(Composite parent) {
+ //create layout Parent with GridLayout
+ Composite layoutParent = new Composite(parent, 0);
+ layoutParent.setLayout(new GridLayout(3, true));
+
+ //create Labels
+ Label pin = new Label(layoutParent, 0);
+ pin.setText("PIN");
+ Label io = new Label(layoutParent, 0);
+ io.setText("I/O");
+ Label hl = new Label(layoutParent, 0);
+ hl.setText("High/Low");
+
+ for (int i = widgetPin.length - 1; i >= 0; i--) {
+ //first column: Pin Label
+ label[i] = new Label(layoutParent, 0);
+ label[i].setText("P" + String.valueOf(i));
+
+ //second column: Pin direction (Input/Output)
+ labelInOut[i] = new CLabel(layoutParent, 0);
+ labelInOut[i].setText("Input");
+ labelInOut[i].setImage(imageInput);
+ //default is input, see:
+ //(http://www.parallax.com/go/PBASICHelp/Content\
+ ///LanguageTopics/Commands/INPUT.htm -> Explanation)
+
+ //third column: Pin state (High/Low)
+ //changes between CLabel and Button, depending on if an
+ //input is accepted or not (uses StackLayout for that)
+ stackLayout[i] = new StackLayout();
+ //create new composite in which stackLayout is active
+ widgetPin[i] = new Composite(layoutParent, 0);
+ widgetPin[i].setLayout(stackLayout[i]);
+ //create first "page" of stackLayout: label (if pin is output)
+ labelHighLow[i] = new CLabel(widgetPin[i], 0);
+ labelHighLow[i].setText("Low");
+ labelHighLow[i].setImage(imageLow);
+ labelHighLow[i].pack();
+ //create second "page" of stackLayout: button (if pin is input)
+ buttonHighLow[i] = new Button(widgetPin[i], 0);
+ buttonHighLow[i].setText("Low");
+ buttonHighLow[i].setImage(imageLow);
+ buttonHighLow[i].pack();
+ //show second "page" first as pin is initialized as input pin
+ stackLayout[i].topControl = buttonHighLow[i];
+ //actions listeners are defined outside of the loop
+ }
+ //action listeners as you are not allowed to use
+ //non-final variables in an inner class
+ buttonHighLow[0].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(0);
+ }
+ });
+ buttonHighLow[1].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(1);
+ }
+ });
+ buttonHighLow[2].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(2);
+ }
+ });
+ buttonHighLow[3].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(3);
+ }
+ });
+ buttonHighLow[4].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(4);
+ }
+ });
+ buttonHighLow[5].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(5);
+ }
+ });
+ buttonHighLow[6].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(6);
+ }
+ });
+ buttonHighLow[7].addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent arg0) {
+ toggleVariable(7);
+ }
+ });
+ }
+
+ @Override
+ public void setFocus() {
+
+ }
+
+ private void toggleVariable(int varNum) {
+ IVariable variable = machine.parseIVariable("PIN" + varNum);
+ long value = variable.getValue();
+ if (value == 0) {
+ value = 1;
+ } else {
+ value = 0;
+ }
+ variable.setValue(value);
+ }
+
+ public void setMachine(Machine machine) {
+ this.machine = machine;
+
+ IVariable[] listener = new IVariable[labelHighLow.length];
+ for (int i = 0; i < labelHighLow.length; i++) {
+ listener[i] = this.machine.parseIVariable("PIN" + String.valueOf(i));
+ listener[i].setVariableListener(
+ new CallbackVariableListener(
+ new PinCommObject(labelHighLow[i], buttonHighLow[i])) {
+
+ @Override
+ public void variableChanged(IVariable variable) {
+ final long value = variable.getValue();
+ final boolean[] newState = new boolean[1];
+ if (value == 1) {
+ newState[0] = true;
+ }
+ getSite().getShell().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ PinCommObject obj = (PinCommObject) callback;
+ if (newState[0]) {
+ obj.label.setText("High");
+ obj.label.setImage(imageHigh);
+ obj.button.setText("High");
+ obj.button.setImage(imageHigh);
+ } else {
+ obj.label.setText("Low");
+ obj.label.setImage(imageLow);
+ obj.button.setText("Low");
+ obj.button.setImage(imageLow);
+ }
+ }
+
+ });
+ }
+ });
+ }
+
+ IVariable[] dirListener = new IVariable[labelInOut.length];
+ for (int i = 0; i < labelInOut.length; i++) {
+ dirListener[i] = this.machine.parseIVariable("DIR"
+ + String.valueOf(i));
+ dirListener[i].setVariableListener(
+ new CallbackVariableListener(
+ new DirCommObject(
+ labelInOut[i],
+ labelHighLow[i],
+ buttonHighLow[i],
+ stackLayout[i],
+ widgetPin[i])) {
+
+ @Override
+ public void variableChanged(IVariable variable) {
+ final long value = variable.getValue();
+ final boolean[] newState = new boolean[1];
+ if (value == 1) {
+ newState[0] = true;
+ }
+ getSite().getShell().getDisplay().syncExec(
+ new Runnable() {
+ @Override
+ public void run() {
+ DirCommObject obj = (DirCommObject) callback;
+ if (newState[0]) {
+ obj.labelDir.setText("Output");
+ obj.labelDir.pack();
+ obj.labelDir.setImage(imageOutput);
+ obj.labelState.setVisible(true);
+ obj.buttonState.setVisible(false);
+ obj.stackLayout.topControl = obj.labelState;
+ } else {
+ obj.labelDir.setText("Input");
+ obj.labelDir.pack();
+ obj.labelDir.setImage(imageInput);
+ obj.labelState.setVisible(false);
+ obj.buttonState.setVisible(true);
+ obj.stackLayout.topControl = obj.buttonState;
+ }
+ obj.widgetPin.layout();
+ }
+
+ });
+ }
+ });
+ }
+ }
+
+ private static Image loadIcon(String iconFilename) {
+ Bundle bundle = Activator.getDefault().getBundle();
+ File targetRoot = bundle.getDataFile("");
+
+ File file = new File(targetRoot, "icons/" + iconFilename);
+ if (!file.canRead()) {
+ HelpView.copyPathFromBundleToFSRecursive(bundle, "icons",
+ targetRoot);
+ }
+ return new Image(Display.getCurrent(), file.getAbsolutePath());
+ }
+
+ public void lockPinState() {
+ for (int i = 0; i < buttonHighLow.length; i++) {
+ buttonHighLow[i].setEnabled(false);
+ }
+ }
+
+ public void unlockPinState() {
+ for (int i = 0; i < buttonHighLow.length; i++) {
+ buttonHighLow[i].setEnabled(true);
+ }
+ }
+
+ private class PinCommObject {
+
+ protected CLabel label;
+
+ protected Button button;
+
+ private PinCommObject(CLabel label, Button button) {
+ this.label = label;
+ this.button = button;
+ }
+ }
+
+ private class DirCommObject {
+
+ protected CLabel labelDir;
+
+ protected CLabel labelState;
+
+ protected Button buttonState;
+
+ protected StackLayout stackLayout;
+
+ protected Composite widgetPin;
+
+ private DirCommObject(
+ CLabel labelDir,
+ CLabel labelState,
+ Button buttonState,
+ StackLayout stackLayout,
+ Composite widgetPin) {
+ this.labelDir = labelDir;
+ this.labelState = labelState;
+ this.buttonState = buttonState;
+ this.stackLayout = stackLayout;
+ this.widgetPin = widgetPin;
+ }
+
+ }
+
+}
diff --git a/src/edu/fichte/pbi/ide/views/EEPROMView.java b/src/edu/fichte/pbi/ide/views/EEPROMView.java
new file mode 100644
index 0000000..1cf1550
--- /dev/null
+++ b/src/edu/fichte/pbi/ide/views/EEPROMView.java
@@ -0,0 +1,167 @@
+package edu.fichte.pbi.ide.views;
+
+import java.util.ArrayList;
+
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.part.ViewPart;
+
+import edu.fichte.pbi.vm.storage.EEPROM;
+import edu.fichte.pbi.vm.storage.IEEPROMMonitor;
+
+public class EEPROMView extends ViewPart implements IEEPROMMonitor {
+
+ public static final String ID = "edu.fichte.pbi.ide.eepromView";
+
+ private Label selected;
+ private Label previous;
+
+ Label address;
+ Label charValue;
+ Label binaryValue;
+ Label decimalValue;
+ ArrayList