slides14-basic

Download Report

Transcript slides14-basic

BasicStamp II Language
(Quick) Tutorial
Lexical Aspects
• Line oriented language (one stmt per line)
– Multiple statements separated by “:”
– Lines limited to 256 chars, extended with trailing “_”
– Each line may have a label at start (“label:”)
• Comments start with single quote “'” (to EOL)
• Identifiers like other languages
– Including underscore
– Not case sensitive
Lexical Aspects
• Literals
– Decimal
– Hex
– Binary
– Chars
– Strings
123
$FF
%10101110
“A”
“string”
• Only useful in parameters to certain built in
statements
• Means: “s”, “t”, “r”, “i”, “n”, “g”
Variables
• Flat global name space
• Variable declaration:
<name> var <type>
<type>: bit nib byte word
• 1, 4, 8, 16 bits values
• E.g., counter var byte
• Arrays
<name> var <type>(<size>)
e.g., table var byte(5)
(nib=nibble=4 bits)
Variables (cont.)
• Aliases (two names for the same variable)
<name1> var <name2>
<name1> var <name2>.<part>
<part>: bit0 bit1 bit2 … bit15
highbit lowbit
nib0 … nib3 highnib lownib
byte0 byte1 highbyte lowbyte
– Example: LED_pin var outs.bit5
Constants
• Declaration
<name> con <constant expr>
– Limits on <constant expr>
– Evaluated left to right, no parens
Example: sw_time con 41 + 1
Expressions
• 8 and 16 bit unsigned integers
• Operators:
+-*/ << >> &|^~ (all as in C or Java)
**
top 16 bits of multiplication
*/
mult top 8 as in, low 8 as fraction
//
remainder (mod)
• Evaluated left-to-right (wrong precedence!)
• Parens allowed to change order of eval
More Operators
• ABS
absolute value
• MIN, MAX
min and max “(5 MIN 3)”
• SQR
integer square root
• SIN, COS
sine & cosine
– Input:
0..255 for 0..360deg
– Output: –127…127
More Operators
• DCD
w/ 1 bit set
“decode” – creates bit mask
(DCD 2) == %00000100
• NCD
“encode” – find highest bit set
(NCD %01001000) == 7
(NCD %00000000) == 0
• REV
[bits numbered 0..7]
[bits numbered 1..8 (!)]
reverse some low order bits
(%10101000 REV 4) == %10100001
Comparison and Logical
Operators
• The usual comparison operators
= <> < > <=
>=
• Logical operators:
not and or xor
• Zero is false, non-zero is true
Assignment & Conditionals
<name> = <expr>
<name>(<expr>) = <expr>
<name>.<part> = <expr>
If <expr> Then <label>
Control Statements
For <var> = <expr> To <expr> Step <val>
<stmt-list>
Next
Note: always executes at least once through loop!
Goto <label>
Branch <expr>, [<label>, …]
– Labels numbered from 0
– If index is larger than label set no jump is made
Control Statements (cont.)
Gosub <label>
– call basic subroutine at label (ending at return)
– no parameters
Return
– return from most recently called subroutine
Control Statements (cont.)
End
– stop execution and enter low power mode
– I/O pins retain state
Stop
– stop execution but don’t enter low power mode
– I/O pins retain state
• Control starts at the first statement in your code
• It is possible to “run off the bottom” of your
program (apparently starts back at the top??)
Placing Data in EEPROM
Memory
• Non-volatile memory
– keeps values w/o power
• Data <const>, <const>, …
• <constname> Data <const>, <const>, …
– Fill EEPROM with values
• Optionally defining constant to starting address
– Values are placed at program download time
not run-time
Placing Data in EEPROM
Memory
Read <addr>, <var>
Write <addr>, <val>
– Read / write a value from / to given EEPROM
address
Sleeping and Low Power Mode
• PIC has low power mode (draws ~1A)
– Typical low power strategy: sleep most of
the time
Sleep <seconds>
Nap <code>
– Timing is not extremely accurate
0
1
2
3
4
5
6
7
NAP Codes
18msec
36msec
72msec
144msec
288msec
576msec
1.152sec
2.304sec
Accurate Delays (Full Power)
Pause <msec>
– Do nothing for given number of milliseconds
– Example: pause 500 ‘ ½ second delay
Misc. Statements
Lookup <index>,[<const>, …], <var>
– Table lookup for 8 or 16 bit values
– Constant from Nth position (from 0) goes in
<var>
– Strings count as multiple single character
entries
– Out of range index causes no action
Misc. Statements
Lookdown <val> [<const>, …], <var>
–
–
–
–
Search for a value in an 8-bit constant table
Strings equivalent to list of single characters
Var gets index of matching value (0 based indexing)
If not found then no action taken
Lookdown <val> <compop> [<const>, …], <var>
– First that given comparison succeeds
– = <> < > <= >=
Random <var>
– Generate 16-bit random number using var as seed (and
result)
I/O Related Statements
• Both low level , simple functions
– Input, Output, High, Low
• And high level, complex functions
– I2Cin, SerIn, etc.
Statements for Low Level I/O
Input <pin>, Output <pin>
– Establish direction of single pin
Reverse <pin>
– Reverse direction of a single pin
High <pin>, Low <pin>
– Implies output (most I/O commands imply input/output)
• Same as “Output <pin> : <pin> = <val>”
Toggle <pin>
– Invert value of pin
<var> = <pin>
– To read input value
Additional I/O
Button <pin>, <down>, <delay>, <rate>, <bvar>, <action>, <label>
– Wait for debounced & repeated button
press/release on pin
– Have a look at the manual…
Additional I/O
Pulsein <pin>, <state>, <var>
– Measure width of high/low pulse on pin
– <state> = 0 low pulse, = 1 high pulse
– Returns in units of 2sec (0 for too long / never)
Pulseout <pin>, <time>
– Emit measured pulse in units of 2sec
– High/low depends on prior state (toggles pin twice)
Count <pin>, <time>, <var>
– Count pulses occurring within given time (in msec)
Analog I/O
• RCTime <pin>, <state>, <var>
– Measure time pin stays in current state
• 2sec units
– Typical use charge pin then measure time it
takes RC circuit to drain
• See example from last slides
Analog and Audio I/O
• PWM <pin>, <duty>, <time>
– Pulse width modulation output on pin
– PWM signal is used to efficiently drive e.g., DC
motor at fractional speed
– High only some percentage (duty cycle)
• <duty> 0 = 0% on, 255 = 100% on
– Delivers % of full power
• note: not clean square wave
– <time> in msec units
Analog and Audio I/O
• FreqOut <pin>, <on_msec>, <freq1>
• FreqOut <pin>, <on_msec>, <freq1>, <freq2>
– Output sine wave(s) at given frequency
– Use filter capacitors for reasonable sound
Analog and Audio I/O
• DTMFOut <pin>, [ <v1>, <v2>, …]
• DTMFOut <pin>, <onms>, <offms>, [ <v1>, <v2>, …]
– Output telephone touch tones (DTMF)
• Generated with FreqOut
• Needs low pass filter (freqout)
– Values 0..15
• 10 is *
• 11 is #
• 12..15 are defined, but not on the phone
Serial I/O
Shiftin
<datapin>, <clkpin>, <mode>, [ <var>, <var>\<bits>, … ]
Shiftout <datapin>, <clkpin>, <mode>, [ <var>,
<var>\<bits>, … ]
Serin <pin>, <mode>, [ <item>, …]
Serout <pin>, <mode>, <item>, …
– items can be qualified with formatting information
• e.g. “dec” for ascii decimal encoding
– Also can do flow control and timeouts (see manual)
Debug <item>, <item>, …
About Serial Output
• RS232C is standard for serial communications
• EIA “recommended standard” from the early 60s
– Designed for modems
• Uses odd voltages (from modern perspective)
• Logical 1 (mark) –15..-3v
• Logical 0 (space) 3..15v
• Stamps can put out 0 and +5v
…. so we have a problem
Level conversion for RS232
• Maxim makes a single chip (powered by only 5v)
– Built into BS II (used for Debug only)
• Can buy HW that fits inside connector case ($15)
• http://www.sxlist.com/techref/io/serial/RCL1.htm
Or you can cheat for about $.04
• It turns out that most PC serial ports have a wide
margin of things they will accept
– If you invert the signal (1 = 0v; 0 = +5v) it turns out that
most PC serial ports will accept it as RS232!
– Special modes for Serin (e.g., N9600) to do this
• PICs have over/under voltage protection on pins
– Negative voltage clamped and read as logic 0
– Voltage > +5V also clamped and read as 1
– Because of details, need current limiting resistors in
series
Serial “cheater” cable
• Has worked on all (both) PCs I’ve tried
• Failed on 1 Mac I tried
Debugging Strategies
• When programming you don’t really spend
your time/effort writing code, you spend it
debugging the code when you get it wrong
(which is pretty much always)…
• Embedded systems are particularly hard
– Is it hardware or software?
– Impoverished debug environment
• Few tools
• Low visibility
– Timing may be an issue
Software Debugging in PBP
• Have the equivalent of “printf” (debug)
– If you have the code space
– And you are not timing dependent
• Can get small serial driven LCD displays
• Can also do things like flash LED on Pin
– E.g., unique patterns indicating that certain
pieces of code are being executed
Hardware debugging
• “Preemptive debugging” (AKA testing)
• Seriously test your circuits before you use them
– Start with ensuring power doesn’t conduct to ground
– Check that connections actually conduct
– Check that adjacent soldered holes aren’t shorted
• Multimeter for basic continuity checks
– Double check that you have connected everything
– Double check that you have connected it right
• Polarity, etc.
– Check that you have power (battery ok)
Hardware debugging
• Logic probe
– Very useful to checking that basic signals you
expect are showing up on the pin you expect
– Clipped to power and
ground, “needle” touches
point to probe
– Indicates 0/1
– Also shows fast pulses
long enough to see
Hardware Debugging
• Oscilloscope
– Shows graph of actual voltages over time
Hardware Debugging
• Can scale time (horiz) or voltage (vert)
• Can typically trigger
– Start graph at point of some event
– E.g., first rise
• Graph allows time
measurements
– E.g., see at right that
pulse lasts just under
1msec
• Some allow dual trace
– Allows comparisons