diff options
author | Marti Bolivar <mbolivar@mit.edu> | 2010-10-25 21:15:28 -0400 |
---|---|---|
committer | Marti Bolivar <mbolivar@mit.edu> | 2010-11-17 12:44:28 -0500 |
commit | 95783b750fda95f5f4c1fac00ab24da03b31b517 (patch) | |
tree | 2b0bf89c101aa58af5796fbe76c7ec98eebbb0a5 /docs | |
parent | 3a9a119e9a8ce72c0e1b8fa4d3904bdf84ce355c (diff) | |
download | librambutan-95783b750fda95f5f4c1fac00ab24da03b31b517.tar.gz librambutan-95783b750fda95f5f4c1fac00ab24da03b31b517.zip |
arduino language reference nearing completion, properly CC-BY-SA 3.0 attributed
Diffstat (limited to 'docs')
98 files changed, 3059 insertions, 3165 deletions
@@ -1,91 +0,0 @@ -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/analogreference.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/analogwrite.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bit.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitclear.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitread.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitset.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitshift.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitwiseand.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitwisecompound.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitwisexornot.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bitwrite.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/boolean.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/booleanvariables.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/braces.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/break.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/byte.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/bytecast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/changes.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/char.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/charcast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/comments.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/comparison.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/const.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/constants.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/constrain.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/continue.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/cos.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/define.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/delay.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/delaymicroseconds.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/detachinterrupt.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/digitalread.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/digitalwrite.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/double.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/dowhile.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/else.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/float.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/floatcast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/for.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/fpconstants.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/goto.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/highbyte.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/if.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/include.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/increment.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/incrementcompound.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/int.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/intcast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/integerconstants.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/interrupts.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/long.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/longcast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/loop.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/lowbyte.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/map.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/max.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/micros.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/millis.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/min.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/modulo.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/nointerrupts.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/notone.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/pointer.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/pow.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/pulsein.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/random.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/randomseed.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/return.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/scope.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/semicolon.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/serial.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/setup.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/shiftout.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/sin.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/sizeof.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/sqrt.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/static.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/string.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/stringobject.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/switchcase.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/tan.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/tone.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/unsignedchar.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/unsignedint.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/unsignedlong.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/void.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/volatile.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/while.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/word.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arduino/wordcast.rst:: WARNING: document isn't included in any toctree -/Users/mbolivar/hack/leaf/libmaple/docs/source/arm-gcc.rst:: WARNING: document isn't included in any toctree diff --git a/docs/Doxyfile b/docs/Doxyfile index 4016c05..88b8764 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -1369,7 +1369,7 @@ INCLUDE_FILE_PATTERNS = # undefined via #undef or recursively expanded use the := operator # instead of the = operator. -PREDEFINED = +PREDEFINED = __cplusplus # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. diff --git a/docs/source/adc.rst b/docs/source/adc.rst index c088652..6bbbac2 100644 --- a/docs/source/adc.rst +++ b/docs/source/adc.rst @@ -59,7 +59,11 @@ range; opamps and other powered components can also be used. Function Reference ------------------ -TODO function reference (figure out Doxygen first) +.. doxygenfunction:: analogRead + +.. doxygenfunction:: pinMode + +.. doxygenenum:: WiringPinMode .. _adc-recommended-reading: diff --git a/docs/source/arduino/abs.rst b/docs/source/arduino/abs.rst index 5d699ae..ed7296a 100644 --- a/docs/source/arduino/abs.rst +++ b/docs/source/arduino/abs.rst @@ -11,7 +11,7 @@ Description Parameters ---------- -**x**: the number +**x**: the number. Returns ------- @@ -24,10 +24,16 @@ Warning ------- Because of the way ``abs()`` is implemented, avoid using other -functions or causing side effects inside the brackets, as it may lead -to incorrect results :: +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: abs(a++); // avoid this - yields incorrect results - - a++; // use this instead - - abs(a); // keep other math outside the function + + abs(a); // use this instead - + a++; // keep other operations outside abs() + + +Arduino Compatibility +--------------------- + +Maple's implementation of ``abs()`` is compatible with Arduino. diff --git a/docs/source/arduino/analogread.rst b/docs/source/arduino/analogread.rst index d0fa5a1..9577c62 100644 --- a/docs/source/arduino/analogread.rst +++ b/docs/source/arduino/analogread.rst @@ -5,15 +5,18 @@ analogRead() ============ +Used to perform ADC conversion. -Signature ---------- +.. contents:: Contents + :local: -``int analogRead(int pin);`` +Library Documentation +--------------------- +.. doxygenfunction:: analogRead -Description ------------ +Discussion +---------- Reads the value from the specified analog pin. The Maple board contains a 16-channel, 12-bit analog to digital converter. This means @@ -24,36 +27,26 @@ interfere with getting full accuracy and precision. For more information, see :ref:`adc`. Before calling analogRead() on a pin, that pin must first be -configured for analog input, using :ref:`arduino-pinMode`. - -The input range and resolution can be changed using -:ref:`arduino-analogReference`. +configured for analog input, using :ref:`arduino-pinMode` (you only +have to do this once, so it's usually done in :ref:`arduino-setup`\ ). It takes about 0.8 microseconds (.0000008 seconds) to read an analog input, so the maximum sample rate using this function is approximately -1.3 million samples per second [#fsamp]_. +1.3 million samples per second\ [#fsamp]_. -Parameters ----------- +Parameter Discussion +-------------------- -**pin** +The pin parameter is the number of the analog input pin to read from. +Header pins on the Maple with ADC functionality (marked as "AIN" on +the silkscreen) are: - The number of the analog input pin to read from. Header pins on the - Maple with ADC functionality (marked as "AIN" on the silkscreen) - are: - - 0, 1, 2, 3, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 27, 28 - - Note that pins 3, 27, and 28 are not marked AIN on the silkscreen - for Maple revisions through Rev 5, however, they **do work** as - analog input pins. - -Returns -------- - -Converted input voltage as an ``int``, with value 0 to 4095, inclusive. + 0, 1, 2, 3, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 27, 28 +Note that pins 3, 27, and 28 are not marked AIN on the silkscreen +for Maple revisions through Rev 5, however, they **do work** as +analog input pins. Note ---- @@ -61,7 +54,7 @@ Note If the analog input pin is not connected to anything, the value returned by analogRead() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to -the board, etc.). +the board, etc.) in a seemingly random way. Example @@ -70,43 +63,65 @@ Example :: - int analogPin = 3; // potentiometer wiper (middle terminal) connected to analog pin 3 - // outside leads to ground and +3.3V + int analogPin = 3; // potentiometer wiper (middle terminal) connected + // to analog pin 3. outside leads to ground and +3.3V int val = 0; // variable to store the value read void setup() { - pinMode(analogPin, INPUT_ANALOG); - SerialUSB.begin(); + pinMode(analogPin, INPUT_ANALOG); // set up pin for analog input + SerialUSB.begin(); // set up usb virtual COM port } void loop() { val = analogRead(analogPin); // read the input pin - SerialUSB.println(val); // debug value + SerialUSB.println(val); // print the value, for debugging with + // a serial monitor } -Arduino Compatibility Note --------------------------- +Arduino Compatibility +--------------------- The Arduino board contains a 6 channel (8 channels on the Mini and -Nano, 16 on the Mega), 10-bit analog to digital converter. This means -that it will map input voltages between 0 and 5 volts into integer -values between 0 and 1023. This yields a resolution between readings -of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. On the -Arduino, the input range and resolution can be changed using their -implementation of `analogReference() -<http://arduino.cc/en/Reference/AnalogReference>`_\ . - -On the Arduino, it takes about 100 microseconds (0.0001 s) to read an -analog input, so the maximum reading rate is about 10,000 times a -second. +Nano, 16 on the Mega), 10-bit analog to digital converter with an +input voltage range of 0V--5V. This means that it will map input +voltages between 0 and 5 volts (which is **larger** than Maple's range +of 0V-3.3V) into integer values between 0 and 1023 (which is +**smaller** than the Maple's range of 0--4095). + +This yields a theoretical resolution between readings of: 5 volts / +1024 units or .0049 volts (4.9 mV) per unit on Arduino boards, which +is larger, and thus less precise, than Maple's 0.0008 volts (0.8 mV). + +If your program expects Arduino-style 10-bit ADC, you can :ref:`right +shift <arduino-bitshift>` the value of a Maple readout by 2, like so:: + + // right shift means that the result will be between 0 and 1023; + // be aware that you're losing a lot of precision if you do this + int adc_reading = analogRead(pin) >> 2; + +On the Arduino, the input range and resolution can be changed using +their implementation of `analogReference() +<http://arduino.cc/en/Reference/AnalogReference>`_\ . Because of the +way its hardware (as of Rev 5) was designed, it's not possible to +implement analogReference on the Maple, so this function doesn't +exist. If your inputs lie in a different voltage range than 0V--3.3V, +you'll need to bring them into that range before using analogRead. +Some basic tools to accomplish this are `resistor dividers +<http://en.wikipedia.org/wiki/Voltage_divider>`_ and `Zener diodes +<http://en.wikipedia.org/wiki/Voltage_source#Zener_voltage_source>`_\ +. However, opamps and other powered components can also be used if +greater precision is required. + +Finally, On the Arduino, it takes significantly longer to read analog +input: about 100 microseconds (0.0001 s), so the maximum reading rate +is 10,000 times a second. See also -------- - :ref:`ADC note <adc>` -- :ref:`analogReference <arduino-analogreference>` - `(Arduino) Tutorial: Analog Input Pins <http://arduino.cc/en/Tutorial/AnalogInputPins>`_ diff --git a/docs/source/arduino/analogreference.rst b/docs/source/arduino/analogreference.rst deleted file mode 100644 index 9a25169..0000000 --- a/docs/source/arduino/analogreference.rst +++ /dev/null @@ -1,66 +0,0 @@ -.. _arduino-analogreference: - -analogReference(type) -===================== - -Description ------------ - -Configures the reference voltage used for analog input (i.e. the -value used as the top of the input range). The options are: - - - - -- DEFAULT: the default analog reference of 5 volts (on 5V Arduino - boards) or 3.3 volts (on 3.3V Arduino boards) -- INTERNAL: an built-in reference, equal to 1.1 volts on the - ATmega168 or ATmega328 and 2.56 volts on the ATmega8. -- EXTERNAL: the voltage applied to the AREF pin is used as the - reference. - - - -Parameters ----------- - -type: which type of reference to use (DEFAULT, INTERNAL, or -EXTERNAL). - - - -Returns -------- - -None. - - - -Warning -------- - -**If you're using an external reference voltage (applied to the AREF pin), you must set the analog reference to EXTERNAL before calling analogRead().** -Otherwise, you will short together the active reference voltage -(internally generated) and the AREF pin, possibly damaging the -microcontroller on your Arduino board. - - - -Alternatively, you can connect the external reference voltage to -the AREF pin through a 5K resistor, allowing you to switch between -external and internal reference voltages. Note that the resistor -will alter the voltage that gets used as the reference because -there is an internal 32K resistor on the AREF pin. The two act as a -voltage divider, so, for example, 2.5V applied through the resistor -will yield 2.5 \* 32 / (32 + 5) = ~2.2V at the AREF pin. - - - -See also --------- - - -- `Description of the analog input pins <http://arduino.cc/en/Tutorial/AnalogInputPins>`_ -- `analogRead <http://arduino.cc/en/Reference/AnalogRead>`_\ () - - diff --git a/docs/source/arduino/analogwrite.rst b/docs/source/arduino/analogwrite.rst index 64ecd5b..d04f485 100644 --- a/docs/source/arduino/analogwrite.rst +++ b/docs/source/arduino/analogwrite.rst @@ -1,116 +1,161 @@ +.. highlight:: cpp + .. _arduino-analogwrite: analogWrite() ============= -TODO - -In libmaple, analogWrite is just a convenience alias for -:ref:`pwmWrite`. This is because PWM is not true analog output (i.e., -is not the output of a DAC), so the name was badly-chosen; however, -for the sake of compatibility, the alias was provided. - -.. doxygenfunction:: pwmWrite - -Description ------------ - -Writes an analog value -(`PWM wave <http://arduino.cc/en/Tutorial/PWM>`_) to a pin. Can be -used to light a LED at varying brightnesses or drive a motor at -various speeds. After a call to **analogWrite()**, the pin will -generate a steady square wave of the specified duty cycle until the -next call to **analogWrite()** (or a call to **digitalRead()** or -**digitalWrite()** on the same pin). The frequency of the PWM -signal is approximately 490 Hz. - - - -On most Arduino boards (those with the ATmega168 or ATmega328), -this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino -Mega, it works on pins 2 through 13. Older Arduino boards with an -ATmega8 only support analogWrite() on pins 9, 10, and 11. You do -not need to call pinMode() to set the pin as an output before -calling analogWrite(). - - - -The *analogWrite* function has nothing whatsoever to do with the -analog pins or the *analogRead* function. - - - -Syntax ------- - -analogWrite(pin, value) - - - -Parameters ----------- - -pin: the pin to write to. - - - -value: the duty cycle: between 0 (always off) and 255 (always on). - - - -Returns -------- +.. note:: + + On the Maple, calling analogWrite() is the same as calling + :ref:`wirish-pwmwrite`\ ; see that function's documentation for more + information. + + This is because PWM is not true analog output (i.e., is not the + output of a `DAC + <http://en.wikipedia.org/wiki/Digital-to-analog_converter>`_\ ), so + the function is badly named. For instance, **analogWrite() has + absolutely nothing to do with** :ref:`arduino-analogread`\ , which + is potentially confusing. + + The alias of analogWrite() to pwmWrite() is provided (sigh) for the + sake of compatibility with Arduino, but we recommend using + :ref:`wirish-pwmwrite` when writing new software, for clarity. + +.. contents:: Contents + :local: + +Arduino Compatibility +--------------------- + +There are a few important differences between Arduino's `analogWrite() +<http://arduino.cc/en/Reference/AnalogWrite>`_ and Maple's +:ref:`wirish-pwmwrite` that you should keep in mind. In each case, we +have some recommendations you can use to help converting from Arduino +to Maple. + +Difference 1: Duty cycle range is different +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The first and most important difference is that the largest possible +value for the duty cycle is much bigger on the Maple. Using Arduino's +analogWrite(), the duty cycle ranges between 0--255 (always off -- +always on)\ [#fbytemax]_\ . Using Maple's pwmWrite(), the duty cycle +ranges from 0--65,535 by default\ [#fuint16max]_\ . + +This is a good thing! The greater range of values on the Maple gives +you much more precise control over the duty cycle of your PWM output. + +If you're porting code from the Arduino and want a quick-and-dirty +fix, one solution is to :ref:`map <arduino-map>` the argument to +analogWrite into the right range:: + + // Arduino code: + analogWrite(pin, duty); + + // Becomes Maple code: + analogWrite(pin, map(duty, 0, 255, 0, 65535)); + +This will convert values in the range 0-255 to values in the range +0--65,635, which is the correct default range for all of the timers +which control PWM output. See the :ref:`timers reference <timers>` +for more information. + +Another fix is to consult the :ref:`pin mapping mega table +<pin-mapping-mega table>` to find the timer which controls PWM on the +pin you're using, then set that Timer's overflow to 255. Subsequent +calls to analogWrite() should work as on the Arduino (with the same +loss of precision). Note, however, that that affects the overflow for +the **entire timer**, so other code relying on that timer (such as any +:ref:`interrupts <arduino-attachinterrupt>` the timer controls) will +likely need to be modified as well. + +Difference 2: You must use pinMode() to set up PWM +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The second difference is that on the Maple, you **must** set up the pin +for PWM output using :ref:`arduino-pinmode`\ , with argument ``PWM``. +This should just be one extra line of code in your +:ref:`arduino-setup` function. Example:: + + void setup() { + // set up pin 9 for PWM + pinMode(9, PWM); + } -nothing +This also means that you can't later call :ref:`arduino-digitalread` +or :ref:`arduino-digitalwrite` on that pin (unless some time in +between, you use pinMode() to reconfigure that pin for ``INPUT`` or +``OUTPUT``; see the :ref:`arduino-pinmode` page for more information). +Difference 3: No PWM on pin 10 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, +9, 11, 12, and 14, or twelve pins in total. That is at least as +*many* PWM pins as any Arduino board, but there are differences in +*which* pins support it. -Notes and Known Issues ----------------------- +* On **most Arduino boards** (those with the ATmega168 or ATmega328; + this includes the **Arduino Uno**), this function works on pins 3, + 5, 6, 9, 10, and 11, or six pins total. Note that these boards + support PWM on pin 10, while Maple does not. -The PWM outputs generated on pins 5 and 6 will have -higher-than-expected duty cycles. This is because of interactions -with the millis() and delay() functions, which share the same -internal timer used to generate those PWM outputs. This will be -noticed mostly on low duty-cycle settings (e.g 0 - 10) and may -result in a value of 0 not fully turning off the output on pins 5 -and 6. +* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins + total. Note that this board supports PWM on pins 4, 10, and 13, + while the Maple does not. Maple supports PWM on pins 0, 1, and 14, + which the Mega does not, making the total number of pins supporting + PWM equal on these boards. +* **Older Arduino boards** with an ATmega8 only support analogWrite() on + pins 9, 10, and 11. Maple does not support PWM on pin 10. +In all cases, Arduino boards support PWM on pin 10, unlike Maple. We +did our best to make PWM as pin-compatible as possible; however, +circuit layout constraints prevented us from achieving perfect +compatibility. -Example -------- +The "safest" pins to use for PWM output are pins 9 and 11. These pins +work on any Arduino board and on Maple. The "safe" pins, which work +on most recent Arduino boards, the Arduino Mega and the Maple, are +pins 3, 5, 6, 9, and 11. Thus, if you want your project to be as +portable as possible between Maple and Arduino, we recommend using the +"safest" pins first, then the "safe" pins, as necessary. -Sets the output to the LED proportional to the value read from the -potentiometer. +Difference 4: PWM frequency +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The frequency of the PWM signal (i.e., the frequency of a complete +on/off cycle) on the Arduino is approximately 490 Hz. +On the Maple, the frequency is configurable, defaulting to about 1100 +Hz, or 1.1 KHz. This is because the PWM frequency is the frequency of +the timer which controls PWM output on the particular pin (\ +:ref:`the PWM tutorial has the details <pwm>`\ ). -:: +If your application absolutely requires Arduino's PWM frequency (it +probably doesn't), then the steps are: - - int ledPin = 9; // LED connected to digital pin 9 - int analogPin = 3; // potentiometer connected to analog pin 3 - int val = 0; // variable to store the read value - - void setup() - { - pinMode(ledPin, OUTPUT); // sets the pin as output - } - - void loop() - { - val = analogRead(analogPin); // read the input pin - analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 - } +1. Figure out which timer controls PWM output on your pin (\ :ref:`this table <pwm-timer-table>` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. +2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. +Be aware that this will change the period for the **entire timer**\ , +and will affect anything else in your program that depends on that +timer. One example is :ref:`interrupts <timers-attachinterrupt>`\ . +You've been :ref:`warned <timers-pwm-conflicts>`\ . See also -------- +- :ref:`Maple PWM tutorial <pwm>` -- `analogRead <http://arduino.cc/en/Reference/AnalogRead>`_\ () -- `Tutorial: PWM <http://arduino.cc/en/Tutorial/PWM>`_ +.. rubric:: Footnotes +.. [#fbytemax] This is because the value for the duty cycle on Arduino + must fit in 1 byte of memory, and an unsigned (i.e., nonnegative) + integer with size 1 byte can hold the values between 0 and 255. +.. [#fuint16max] This is because the value for the duty cycle on the + Maple uses 2 bytes of memory, and an unsigned (i.e., nonnegative) + integer with size 2 bytes can hold the values between 0 and 65,535. diff --git a/docs/source/arduino/arithmetic.rst b/docs/source/arduino/arithmetic.rst index cbe3059..8fb9771 100644 --- a/docs/source/arduino/arithmetic.rst +++ b/docs/source/arduino/arithmetic.rst @@ -5,6 +5,9 @@ Addition, Subtraction, Multiplication, & Division ================================================= +.. contents:: Contents + :local: + Description ----------- @@ -17,17 +20,20 @@ This also means that the operation can overflow if the result is larger than that which can be stored in the data type (e.g. adding 1 to an :ref:`arduino-int` with the value 2147483647 gives -2147483648). If the operands are of different types, the "larger" -type is used for the calculation. - -(The specifics of these rules are beyond the scope of this -documentation; for more information, see `The C++ Programming Language -<http://www2.research.att.com/~bs/3rd.html>`_\ , by Bjarne -Stroustroup, Appendix C, especially §§C.4-C.6, or `this WikiBooks -entry on C++ type conversion -<http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Variables/Type_Casting#Automatic_type_conversion>`_\ -. For more information on how computers represent integers, see the -Wikipedia page on `two's complement -<http://en.wikipedia.org/wiki/Two's_complement>`_\ ). +type is used for the calculation. + +.. _arduino-arithmetic-typeconversion: + +.. note:: The specifics of these rules are beyond the scope of this + documentation; for more information, see `The C++ Programming + Language <http://www2.research.att.com/~bs/3rd.html>`_\ , by Bjarne + Stroustroup, Appendix C, especially §§C.4-C.6, or `this WikiBooks + entry on C++ type conversion + <http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Variables/Type_Casting#Automatic_type_conversion>`_. + +.. note:: For more information on how computers represent integers, + see the Wikipedia page on `two's complement + <http://en.wikipedia.org/wiki/Two's_complement>`_. If one of the numbers (operands) are of the type **float** or of type **double**, floating point math will be used for the @@ -55,30 +61,18 @@ Syntax result = value1 / value2; -Parameters: ------------ +Parameters +---------- **value1**: any numeric variable or constant **value2**: any numeric variable or constant +Programming Tips +---------------- -Arduino Compatibility Note --------------------------- - -Since the STM32 processor on the Maple is a 32-bit machine, the int -type overflows at a much higher value on Maple than on Arduino. In -particular, on Maple, ints do not overflow (become negative) until -they reach 2,147,483,648; on the Arduino, they overflow at 32,767. -Because of this, programs running on Maple are much less likely to run -into overflow issues. - - -Programming Tips: ------------------ - -- Know that :ref:`integer constants <arduino-integerconstants>` - default to :ref:`int <arduino-Int>`, so some constant calculations +- Know that :ref:`integer constants <arduino-constants-integers>` + default to :ref:`int <arduino-int>`, so some constant calculations may overflow (e.g., 200000 * 5000000 will yield a negative result). - Choose variable sizes that are large enough to hold the largest @@ -93,12 +87,40 @@ Programming Tips: (the STM32 has no floating point hardware, so all floating point calculations have to be done in software). -- Use the cast operator e.g. (int)myFloat to convert one variable type +- Use cast operator, e.g. ``(int)myFloat`` to convert one variable type to another on the fly. +Arduino Compatibility +--------------------- + +Since the STM32 processor on the Maple is a 32-bit machine, the int +type overflows at a much higher value on Maple than on Arduino. In +particular, on Maple, ints do not overflow (become negative) until +they reach 2,147,483,648; on the Arduino, they overflow at 32,767. +Because of this, programs running on Maple are much less likely to run +into overflow issues. The following table summarizes the sizes and +ranges of integer datatypes on the Maple (the ranges of long long +types are approximate): + +.. _arduino-arithmetic-int-sizes: + +.. csv-table:: + :header: Datatype, Unsigned range, Signed range, Size (bytes) + :widths: 8, 12, 17, 8 + + ``char``, 0 --- 255, -128 --- 127, 1 + ``short``, "0 --- 65,535", "-32,768 --- 32,767", 2 + ``int``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long long``, "0 --- 1.8*10\ :sup:`19`\ " (approx.), "-9.2*10\ :sup:`18` --- 9.2*10\ :sup:`18` (approx.)", 8 + See Also -------- -- `libmaple_types.h <http://github.com/leaflabs/libmaple/blob/master/libmaple/libmaple_types.h>`_ +- The individual sizes (in bits) of various available types are + defined in `libmaple_types.h + <http://github.com/leaflabs/libmaple/blob/master/libmaple/libmaple_types.h>`_\ + . +- :ref:`sizeof <arduino-sizeof>`\ () diff --git a/docs/source/arduino/arithmeticcompound.rst b/docs/source/arduino/arithmeticcompound.rst new file mode 100644 index 0000000..a2c5b89 --- /dev/null +++ b/docs/source/arduino/arithmeticcompound.rst @@ -0,0 +1,43 @@ +.. highlight:: cpp + +.. _arduino-arithmeticcompound: + +Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) +=============================================================== + +Description +----------- + +Perform a mathematical operation on a variable with another constant +or variable. These operators are just a convenient shorthand:: + + x += y; // equivalent to the expression x = x + y; + x -= y; // equivalent to the expression x = x - y; + x *= y; // equivalent to the expression x = x * y; + x /= y; // equivalent to the expression x = x / y; + +Here is an example:: + + int x = 2; + int y = 10; + + x += 4; // x now contains 6 + x -= 3; // x now contains 3 + x *= y; // x now contains 30 + x /= 2; // x now contains 15 + x += max(20, 6); // x now contains 35 + x -= sq(5); // x now contains 15 + +Parameters +---------- + +**x**: a numeric variable + +**y**: a numeric variable, number constant, or any other expression +that evaluates to a number (e.g. call to a function that returns a +number). + +See Also +-------- + +- :ref:`Arithmetic operators <arduino-arithmetic>` diff --git a/docs/source/arduino/array.rst b/docs/source/arduino/array.rst index f6bc141..92f3091 100644 --- a/docs/source/arduino/array.rst +++ b/docs/source/arduino/array.rst @@ -10,6 +10,8 @@ number. Arrays in the C++ programming language, in which the Maple is programmed, can be complicated, but using simple arrays is relatively straightforward. +.. contents:: Contents + :local: Creating (Declaring) an Array ----------------------------- @@ -69,15 +71,15 @@ access is within legal bounds of the array size that you have declared. -To assign a value to an array: ------------------------------- +To assign a value to an array +----------------------------- :: mySensVals[0] = 10; -To retrieve a value from an array: ----------------------------------- +To retrieve a value from an array +--------------------------------- :: @@ -106,6 +108,10 @@ Arduino `Knight Rider example <http://www.arduino.cc/en/Tutorial/KnightRider>`_\ (which will run unmodified on the Maple). +Arduino Compatibility +--------------------- + +Arrays on Maple are identical those on Arduino. See also -------- diff --git a/docs/source/arduino/assignment.rst b/docs/source/arduino/assignment.rst index 1c790bb..21e90e9 100644 --- a/docs/source/arduino/assignment.rst +++ b/docs/source/arduino/assignment.rst @@ -8,7 +8,6 @@ Stores the value to the right of the equal sign in the variable to the left of the equal sign. - The single equal sign in the C++ programming language is called the assignment operator. It has a different meaning than in algebra class, where it indicated an equation or equality. The assignment @@ -36,13 +35,17 @@ needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect. - - Don't confuse the assignment operator [ = ] (single equal sign) with the comparison operator [ == ] (double equal signs), which evaluates whether two expressions are equal. +Arduino Compatibility +--------------------- + +Assignments on the Maple are identical to those on Arduino. + + See Also -------- diff --git a/docs/source/arduino/attachinterrupt.rst b/docs/source/arduino/attachinterrupt.rst index 189141b..cb11327 100644 --- a/docs/source/arduino/attachinterrupt.rst +++ b/docs/source/arduino/attachinterrupt.rst @@ -2,8 +2,18 @@ .. _arduino-attachinterrupt: -attachInterrupt(interrupt, function, mode) -========================================== +attachInterrupt() +================= + +Used to specify a function to call when an external interrupt (like an +GPIO changing from LOW to HIGH, a button getting pressed, etc.) +occurs. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- .. doxygenfunction:: attachInterrupt @@ -14,17 +24,15 @@ attachInterrupt(interrupt, function, mode) Discussion ---------- -Specifies a function to call when an external interrupt occurs. -Replaces any previous function that was attached to the interrupt. -For more information on external interrupts on the Maple +Because the function will run in interrupt context, inside of it, +:ref:`arduino-delay` won't work, and the value returned by +:ref:`arduino-millis` will not increment. Serial data received while +in the function may be lost. You should declare as ``volatile`` any +global variables that you modify within the attached function. -Note ----- - -Inside the attached function, delay() won't work, and the value -returned by millis() will not increment. Serial data received while in -the function may be lost. You should declare as volatile any variables -that you modify within the attached function. +There are a few constraints you should be aware of if you're using +more than one interrupt at a time; the :ref:`external-interrupts` page +has the details. Using Interrupts @@ -33,8 +41,7 @@ Using Interrupts Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. A good task for using an interrupt might be reading a rotary encoder, -monitoring user input. - +or monitoring user input. If you wanted to insure that a program always caught the pulses @@ -49,45 +56,44 @@ situations, using an interrupt can free the microcontroller to get some other work done while not missing the doorbell. - Example ------- :: int maple_led_pin = 13; - volatile int state = LOW; - - void setup() - { + volatile int state = LOW; // must declare volatile, since it's + // modified within the blink handler + + void setup() { pinMode(maple_led_pin, OUTPUT); attachInterrupt(0, blink, CHANGE); } - - void loop() - { + + void loop() { digitalWrite(maple_led_pin, state); } - - void blink() - { + + void blink() { state = !state; } -Arduino Compatibility Note --------------------------- +Arduino Compatibility +--------------------- Most Arduino boards have two external interrupts: numbers 0 (on digital pin 2) and 1 (on digital pin 3). The Arduino Mega has an additional four: numbers 2 (pin 21), 3 (pin 20), 4 (pin 19), and 5 -(pin 18). +(pin 18). On the Maple, you don't have to remember which interrupt +number goes with which pin -- just tell ``attachInterrupt()`` the pin +you want. See also -------- -- `detachInterrupt <http://arduino.cc/en/Reference/DetachInterrupt>`_ - +- :ref:`detachInterrupt <arduino-detachinterrupt>` +- :ref:`external-interrupts` diff --git a/docs/source/arduino/bit.rst b/docs/source/arduino/bit.rst index f8241a5..b74ad3d 100644 --- a/docs/source/arduino/bit.rst +++ b/docs/source/arduino/bit.rst @@ -6,37 +6,40 @@ bit() Description ----------- -Computes the value of the specified bit (bit 0 is 1, bit 1 is 2, -bit 2 is 4, etc.). - +(Macro) Computes the value of an (unsigned) integer with the specified +bit set (``bit(0)`` is 1, ``bit(1)`` is 2, ``bit(2)`` is 4, then 8, +16, 32, etc.). Syntax ------ -bit(n) - +``bit(n)`` Parameters ---------- -n: the bit whose value to compute +* **n** the bit to set. + +Value +----- +The value of an integer with the given bit set. -Returns -------- -the value of the bit +Arduino Compatibility +--------------------- +The Maple implementation of bit is compatible with Arduino. See also -------- -- `bitRead <http://arduino.cc/en/Reference/BitRead>`_\ () -- `bitWrite <http://arduino.cc/en/Reference/BitWrite>`_\ () -- `bitSet <http://arduino.cc/en/Reference/BitSet>`_\ () -- `bitClear <http://arduino.cc/en/Reference/BitClear>`_\ () +- :ref:`arduino-bitread` +- :ref:`arduino-bitwrite` +- :ref:`arduino-bitset` +- :ref:`arduino-bitclear` diff --git a/docs/source/arduino/bitclear.rst b/docs/source/arduino/bitclear.rst index e86dbc5..8a46877 100644 --- a/docs/source/arduino/bitclear.rst +++ b/docs/source/arduino/bitclear.rst @@ -6,43 +6,39 @@ bitClear() Description ----------- -Clears (writes a 0 to) a bit of a numeric variable. - - +(Macro) Clears (writes a 0 to) a bit of a numeric variable. Syntax ------ -bitClear(x, n) - +``bitClear(x, n)`` Parameters ---------- -x: the numeric variable whose bit to clear - - - -n: which bit to clear, starting at 0 for the least-significant -(rightmost) bit +* **x** the numeric variable whose bit to clear +* **n** which bit to clear, starting at 0 for the least-significant + (rightmost) bit Returns ------- -none +None. +Arduino Compatibility +--------------------- -See also --------- - +This implementation is compatible with that of Arduino. -- `bit <http://arduino.cc/en/Reference/Bit>`_\ () -- `bitRead <http://arduino.cc/en/Reference/BitRead>`_\ () -- `bitWrite <http://arduino.cc/en/Reference/BitWrite>`_\ () -- `bitSet <http://arduino.cc/en/Reference/BitSet>`_\ () +See also +-------- +- :ref:`bit <arduino-bit>`\ () +- :ref:`bitRead <arduino-bitread>`\ () +- :ref:`bitWrite <arduino-bitwrite>`\ () +- :ref:`bitSet <arduino-bitset>`\ () diff --git a/docs/source/arduino/bitread.rst b/docs/source/arduino/bitread.rst index 3d0b1a4..c3a79c4 100644 --- a/docs/source/arduino/bitread.rst +++ b/docs/source/arduino/bitread.rst @@ -6,43 +6,41 @@ bitRead() Description ----------- -Reads a bit of a number. - +(Macro) Gets the value of a bit in a number. Syntax ------ -bitRead(x, n) - +``bitRead(x, n)`` Parameters ---------- -x: the number from which to read - +* **x** the number from which to read the bit. +* **n** which bit to read, starting at 0 for the least-significant + (rightmost) bit -n: which bit to read, starting at 0 for the least-significant -(rightmost) bit +Value +----- +The value of the bit (0 or 1). -Returns -------- -the value of the bit (0 or 1). +Arduino Compatibility +--------------------- +The Maple implementation of ``bitRead`` is compatible with Arduino. See also -------- -- `bit <http://arduino.cc/en/Reference/Bit>`_\ () -- `bitWrite <http://arduino.cc/en/Reference/BitWrite>`_\ () -- `bitSet <http://arduino.cc/en/Reference/BitSet>`_\ () -- `bitClear <http://arduino.cc/en/Reference/BitClear>`_\ () - - +- :ref:`arduino-bit` +- :ref:`arduino-bitwrite` +- :ref:`arduino-bitset` +- :ref:`arduino-bitclear` diff --git a/docs/source/arduino/bitset.rst b/docs/source/arduino/bitset.rst index 882ec92..adf637a 100644 --- a/docs/source/arduino/bitset.rst +++ b/docs/source/arduino/bitset.rst @@ -6,42 +6,41 @@ bitSet() Description ----------- -Sets (writes a 1 to) a bit of a numeric variable. - +(Macro) Sets (writes a 1 to) a bit of a numeric variable. Syntax ------ -bitSet(x, n) - +``bitSet(x, n)`` Parameters ---------- -x: the numeric variable whose bit to set +* **x** the numeric variable whose bit to set +* **n** which bit to set, starting at 0 for the least-significant + (rightmost) bit -n: which bit to set, starting at 0 for the least-significant -(rightmost) bit +Value +----- +None. -Returns -------- +Arduino Compatibility +--------------------- -none +The Maple implementation of bitSet is compatible with Arduino. - -See also +See Also -------- - -- `bit <http://arduino.cc/en/Reference/Bit>`_\ () -- `bitRead <http://arduino.cc/en/Reference/BitRead>`_\ () -- `bitWrite <http://arduino.cc/en/Reference/BitWrite>`_\ () -- `bitClear <http://arduino.cc/en/Reference/BitClear>`_\ () +- :ref:`arduino-bit` +- :ref:`arduino-bitread` +- :ref:`arduino-bitwrite` +- :ref:`arduino-bitclear` diff --git a/docs/source/arduino/bitshift.rst b/docs/source/arduino/bitshift.rst index f59b489..d849f2a 100644 --- a/docs/source/arduino/bitshift.rst +++ b/docs/source/arduino/bitshift.rst @@ -1,74 +1,76 @@ +.. highlight:: cpp + .. _arduino-bitshift: -bitshift left (<<), bitshift right (>>) -======================================= +Bit shift left (``<<``), bit shift right (``>>``) +================================================= Description ----------- -From *The Bitmath Tutorial* in The Playground - +(Adapted from `The Bit Math Tutorial +<http://www.arduino.cc/playground/Code/BitMath>`_ in `The Arduino +Playground <http://www.arduino.cc/playground/Main/HomePage>`_\ ) There are two bit shift operators in C++: the left shift operator -<< and the right shift operator >>. These operators cause the bits -in the left operand to be shifted left or right by the number of +``<<`` and the right shift operator ``>>``. These operators cause the +bits in the left operand to be shifted left or right by the number of positions specified by the right operand. -More on bitwise math may be found -`here. <http://www.arduino.cc/playground/Code/BitMath>`_ +More information on bitwise math can be obtained in the Wikipedia +article on `bitwise operations +<http://en.wikipedia.org/wiki/Bitwise_operation>`_\ , especially the +section on shifts in `C, C++, and Java +<http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_C.2C_C.2B.2B.2C_C.23_and_Java>`_\ . Syntax ------ -variable << number\_of\_bits - - - -variable >> number\_of\_bits +``some_int << number_of_bits`` +``some_int >> number_of_bits`` Parameters ---------- -variable - (byte, int, long) number\_of\_bits integer <= 32 +* **some_int** An integer value or variable. + +* **number_of_bits** integer whose value is at most ``8 * + sizeof(variable)`` (so ``number_of_bits`` can be at most 32 for + ``int`` values, at most ``8`` for ``char`` values, etc.; the various + integer sizes are summarized :ref:`in this table + <arduino-arithmetic-int-sizes>`\ ). Example: -------- -:: - - int a = 5; // binary: 0000000000000101 - int b = a << 3; // binary: 0000000000101000, or 40 in decimal - int c = b >> 3; // binary: 0000000000000101, or back to 5 like we started with - - - -When you shift a value x by y bits (x << y), the leftmost y bits in -x are lost, literally shifted out of existence: - +Here are some examples of bit shifting, with the binary representation of the number in comments:: + int a = 5; // binary: 101 + int b = a << 3; // binary: 101000, or 40 in decimal + int c = b >> 3; // binary: 101, or back to 5 like we started with -:: - int a = 5; // binary: 0000000000000101 - int b = a << 14; // binary: 0100000000000000 - the first 1 in 101 was discarded +When you left shift a value x by y bits (x << y), the leftmost y bits +in x are lost, literally shifted out of existence. We'll do this +example with ``char`` values (which are integers in the range 0-255, +and take up 8 bits of memory):: + char a = 5; // binary (all 8 bits): 00000101 + char b = a << 7; // binary: 10000000 - the first 1 in 101 was discarded -If you are certain that none of the ones in a value are being -shifted into oblivion, a simple way to think of the left-shift -operator is that it multiplies the left operand by 2 raised to the -right operand power. For example, to generate powers of 2, the -following expressions can be employed: - - - -:: +If you are certain that none of the ones in a value are being shifted +into oblivion, a simple way to think of the left-shift operator is +that it multiplies the left operand by 2 raised to the right operand +power (in math notation, ``x << y`` equals x * 2\ :sup:`y`\ , as long +as none of the bits of x get shifted out). For example, to generate +powers of 2, the following expressions can be employed:: 1 << 0 == 1 1 << 1 == 2 @@ -80,48 +82,64 @@ following expressions can be employed: 1 << 10 == 1024 ... +.. _arduino-bitshift-signbit-gotcha: +When you shift x right by y bits (``x >> y``), and the highest bit in +x is a 1, the behavior depends on the exact data type of x. If x is of +type ``int``, the highest bit is special, and determines whether x is +negative or not; the details are too complicated to explain here, but +they are thoroughly explained in the Wikipedia article on `two's +complement arithmetic +<http://en.wikipedia.org/wiki/Two%27s_complement>`_\ , which the +system most computers use to store integers. In that case, the sign +bit is copied into lower bits, for esoteric historical reasons:: -When you shift x right by y bits (x >> y), and the highest bit in x -is a 1, the behavior depends on the exact data type of x. If x is -of type int, the highest bit is the sign bit, determining whether x -is negative or not, as we have discussed above. In that case, the -sign bit is copied into lower bits, for esoteric historical -reasons: - - - -:: + int x = -16; // binary (all 32 bits): 11111111111111111111111111110000 + int y = x >> 3; // binary: 11111111111111111111111111111110 - int x = -16; // binary: 1111111111110000 - int y = x >> 3; // binary: 1111111111111110 +This behavior, called "sign extension", is often not what you +want. You probably wish zeros to be shifted in from the left. It +turns out that the right shift rules are different for ``unsigned +int`` values, so you can use a type cast to suppress ones being copied +from the left:: -This behavior, called sign extension, is often not the behavior you -want. Instead, you may wish zeros to be shifted in from the left. -It turns out that the right shift rules are different for unsigned -int expressions, so you can use a typecast to suppress ones being -copied from the left: + int x = -16; // binary: 11111111111111111111111111110000 + int y = (unsigned int)x >> 3; // binary: 00011111111111111111111111111110 -:: - - int x = -16; // binary: 1111111111110000 - int y = (unsigned int)x >> 3; // binary: 0001111111111110 +If you are careful to avoid sign extension, you can use the +right-shift operator, ``>>``, as a way to divide by powers of 2. For +example:: + int x = 1000; + int y = x >> 3; // integer division of 1000 by 8, causing y = 125. -If you are careful to avoid sign extension, you can use the -right-shift operator >> as a way to divide by powers of 2. For -example: +Arduino Compatibility +--------------------- +Since it's part of the C++ language, bit shifting on the Maple is +compatible with the Arduino; however, you should keep in mind that the +Maple has bigger integer types (as in, more bits) than the Arduino. +Since the STM32 is a 32-bit processor, the ``int`` type takes up 32 +bits instead of 16, like on Arduino's 16-bit microcontroller. This +means that you can shift left, like ``x << y``, with bigger values of +``y`` on the Maple before ones in ``x`` start to get shifted out. -:: - - int x = 1000; - int y = x >> 3; // integer division of 1000 by 8, causing y = 125. +To calculate the number of bits of an integer type on the Maple, +multiply its size in bytes (see :ref:`this table +<arduino-arithmetic-int-sizes>` for these) by 8, since there are 8 +bits in 1 byte. For example, a ``short`` takes up 2 bytes of memory, +or 2 * 8 = 16 bits. +See Also +-------- +- :ref:`arduino-bit` +- :ref:`arduino-bitread` +- :ref:`arduino-bitwrite` +- :ref:`arduino-bitclear` diff --git a/docs/source/arduino/bitwiseand.rst b/docs/source/arduino/bitwiseand.rst deleted file mode 100644 index 8d4eb3f..0000000 --- a/docs/source/arduino/bitwiseand.rst +++ /dev/null @@ -1,230 +0,0 @@ -.. _arduino-bitwiseand: - -Bitwise AND (&), Bitwise OR (\|), Bitwise XOR (^) -================================================= - -Bitwise AND (&) ---------------- - -The bitwise operators perform their calculations at the bit level -of variables. They help solve a wide range of common programming -problems. Much of the material below is from an excellent tutorial -on bitwise math wihch may be found -`here. <http://www.arduino.cc/playground/Code/BitMath>`_ - - - -Description and Syntax ----------------------- - -Below are descriptions and syntax for all of the operators. Further -details may be found in the referenced tutorial. - - - -Bitwise AND (&) ---------------- - -The bitwise AND operator in C++ is a single ampersand, &, used -between two other integer expressions. Bitwise AND operates on each -bit position of the surrounding expressions independently, -according to this rule: if both input bits are 1, the resulting -output is 1, otherwise the output is 0. Another way of expressing -this is: - - - -:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 0 0 1 (operand1 & operand2) - returned result - - - -In Arduino, the type int is a 16-bit value, so using & between two -int expressions causes 16 simultaneous AND operations to occur. In -a code fragment like: - - - -:: - - int a = 92; // in binary: 0000000001011100 - int b = 101; // in binary: 0000000001100101 - int c = a & b; // result: 0000000001000100, or 68 in decimal. - - - -Each of the 16 bits in a and b are processed by using the bitwise -AND, and all 16 resulting bits are stored in c, resulting in the -value 01000100 in binary, which is 68 in decimal. - - - -One of the most common uses of bitwise AND is to select a -particular bit (or bits) from an integer value, often called -masking. See below for an example - - - -Bitwise OR (\|) ---------------- - -The bitwise OR operator in C++ is the vertical bar symbol, \|. Like -the & operator, \| operates independently each bit in its two -surrounding integer expressions, but what it does is different (of -course). The bitwise OR of two bits is 1 if either or both of the -input bits is 1, otherwise it is 0. In other words: - - - -:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) - returned result - - - -Here is an example of the bitwise OR used in a snippet of C++ -code: - - - -:: - - int a = 92; // in binary: 0000000001011100 - int b = 101; // in binary: 0000000001100101 - int c = a | b; // result: 0000000001111101, or 125 in decimal. - - - -Example Program ---------------- - -A common job for the bitwise AND and OR operators is what -programmers call Read-Modify-Write on a port. On microcontrollers, -a port is an 8 bit number that represents something about the -condition of the pins. Writing to a port controls all of the pins -at once. - - - -PORTD is a built-in constant that refers to the output states of -digital pins 0,1,2,3,4,5,6,7. If there is 1 in an bit position, -then that pin is HIGH. (The pins already need to be set to outputs -with the pinMode() command.) So if we write ``PORTD = B00110001;`` -we have made pins 2,3 & 7 HIGH. One slight hitch here is that we -*may* also have changeed the state of Pins 0 & 1, which are used by -the Arduino for serial communications so we may have interfered -with serial communication. - - - -:: - - Our algorithm for the program is: - - -- Get PORTD and clear out only the bits corresponding to the pins - we wish to control (with bitwise AND). -- Combine the modified PORTD value with the new value for the pins - under control (with biwise OR). - - - -:: - - int i; // counter variable - int j; - - void setup(){ - DDRD = DDRD | B11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx) - // same as pinMode(pin, OUTPUT) for pins 2 to 7 - Serial.begin(9600); - } - - void loop(){ - for (i=0; i<64; i++){ - - PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx) - j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1 - PORTD = PORTD | j; // combine the port information with the new information for LED pins - Serial.println(PORTD, BIN); // debug to show masking - delay(100); - } - } - - - -Bitwise XOR (^) ---------------- - -There is a somewhat unusual operator in C++ called bitwise -EXCLUSIVE OR, also known as bitwise XOR. (In English this is -usually pronounced "eks-or".) The bitwise XOR operator is written -using the caret symbol ^. This operator is very similar to the -bitwise OR operator \|, only it evaluates to 0 for a given bit -position when both of the input bits for that position are 1: - - - -:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 0 (operand1 ^ operand2) - returned result - - - -Another way to look at bitwise XOR is that each bit in the result -is a 1 if the input bits are different, or 0 if they are the same. - - - -Here is a simple code example: - - - -:: - - int x = 12; // binary: 1100 - int y = 10; // binary: 1010 - int z = x ^ y; // binary: 0110, or decimal 6 - - - -The ^ operator is often used to toggle (i.e. change from 0 to 1, or -1 to 0) some of the bits in an integer expression. In a bitwise OR -operation if there is a 1 in the mask bit, that bit is inverted; if -there is a 0, the bit is not inverted and stays the same. Below is -a program to blink digital pin 5. - - - -:: - - // Blink_Pin_5 - // demo for Exclusive OR - void setup(){ - DDRD = DDRD | B00100000; // set digital pin five as OUTPUT - Serial.begin(9600); - } - - void loop(){ - PORTD = PORTD ^ B00100000; // invert bit 5 (digital pin 5), leave others untouched - delay(100); - } - - - -See Also - - -- `&& <http://arduino.cc/en/Reference/Boolean>`_ (Boolean AND) -- `\|\| <http://arduino.cc/en/Reference/Boolean>`_ (Boolean OR) - diff --git a/docs/source/arduino/bitwisecompound.rst b/docs/source/arduino/bitwisecompound.rst index c3c808f..d460dc8 100644 --- a/docs/source/arduino/bitwisecompound.rst +++ b/docs/source/arduino/bitwisecompound.rst @@ -1,227 +1,228 @@ +.. highlight:: cpp + .. _arduino-bitwisecompound: -compound bitwise AND (&=), compound bitwise OR (\|=) -==================================================== +Compound bitwise and (&=), or (\|=), XOR (^=) +============================================= The compound bitwise operators perform their calculations at the bit level of variables. They are often used to clear and set specific bits of a variable. +See the :ref:`bitwise math tutorial <arduino-bitwisemath>` for more +information on bitwise operators. +.. contents:: Contents + :local: -See the -`bitwise AND (&) <http://arduino.cc/en/Reference/BitwiseAnd>`_ and -`bitwise OR (\|) <http://arduino.cc/en/Reference/BitwiseAnd>`_ -operators for the details of their operation, and also the -`Bitmath Tutorial <http://www.arduino.cc/playground/Code/BitMath>`_ -for more information on bitwise operators. - - - -compound bitwise AND (&=) -========================= - -Description ------------ - -The compound bitwise AND operator (&=) is often used with a -variable and a constant to force particular bits in a variable to -the LOW state (to 0). This is often referred to in programming -guides as "clearing" or "resetting" bits. - - +.. _arduino-bitwisecompound-and: -Syntax: -------- +Compound bitwise AND (&=) +------------------------- -:: +The compound bitwise AND operator ``&=`` is often used with a variable +and a constant to force particular bits in a variable to be zero. This +is often referred to in programming guides as "clearing" or +"resetting" bits. In a program, writing the line ``x &= y;`` is +equivalent to writing ``x = x & y;``. That is, the value of ``x`` +after the line will be equal to its old value bitwise ANDed with the +value of ``y``:: - x &= y; // equivalent to x = x & y; + x &= y; // equivalent to x = x & y; +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any :ref:`integer value +<arduino-constants-integers>` (like ``3`` or ``0x20``) for ``y``. - -Parameters ----------- - -x: a char, int or long variable -y: an integer constant or char, int, or long - - - -Example: --------- - -First, a review of the Bitwise AND (&) operator - -:: +Before doing an example of ``&=``, let's first review the Bitwise AND +(``&``) operator:: 0 0 1 1 operand1 0 1 0 1 operand2 ---------- - 0 0 0 1 (operand1 & operand2) - returned result - - - -Bits that are "bitwise ANDed" with 0 are cleared to 0 so, if myByte -is a byte variable, -``myByte & B00000000 = 0;`` - - - -Bits that are "bitwise ANDed" with 1 are unchanged so, -``myByte & B11111111 = myByte;`` + 0 0 0 1 (operand1 & operand2) = result +As shown above, bits that are "bitwise ANDed" with 0 become 0, while +bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` +is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & +B11111111`` equals ``b``. +.. _arduino-bitwisecompound-binconst: -Note: because we are dealing with bits in a bitwise operator - it -is convenient to use the binary formatter with -`constants. <http://arduino.cc/en/Reference/IntegerConstants>`_ The -numbers are still the same value in other representations, they are -just not as easy to understand. Also, B00000000 is shown for -clarity, but zero in any number format is zero (hmmm something -philosophical there?) +.. note:: The above uses :ref:`binary constants + <arduino-constants-integers-bin>`\ . The numbers are still the same + value in other representations, they just might not be as easy to + understand. + Normally, in C and C++ code, :ref:`hexadecimal + <arduino-constants-integers-hex>` or :ref:`octal + <arduino-constants-integers-oct>` are used when we're interested in + an integer's bits, rather than its value as a number. + While hexadecimal and octal literals might be harder to understand + at first, you should really take the time to learn them. They're + part of C, C++, and many other programming languages, while binary + constants are available only for compatibility with Arduino. -Consequently - to clear (set to zero) bits 0 & 1 of a variable, -while leaving the rest of the variable unchanged, use the compound -bitwise AND operator (&=) with the constant B11111100 + Also, ``B00000000`` is shown for clarity, but zero in any number + format is zero. -:: +So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while +leaving the rest of the variable's bits unchanged, use the compound +bitwise AND operator ``&=`` with the constant ``B11111100`` +(hexadecimal ``0xFC``\ ):: - 1 0 1 0 1 0 1 0 variable + 1 0 1 0 1 0 1 0 variable 1 1 1 1 1 1 0 0 mask ---------------------- 1 0 1 0 1 0 0 0 - - variable unchanged - bits cleared - - -Here is the same representation with the variable's bits replaced -with the symbol x - + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared -:: +Here is the same representation with the variable's bits replaced +with the symbol ``x``\ :: x x x x x x x x variable 1 1 1 1 1 1 0 0 mask ---------------------- x x x x x x 0 0 - - variable unchanged - bits cleared - - -So if: + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared -:: - myByte = 10101010; - - myByte &= B1111100 == B10101000; +So, using a byte variable ``b``\ , if we say:: + b = B10101010; // B10101010 == 0xAA + b &= B11111100; // B11111100 == 0xFC +then we will have :: -compound bitwise OR (\|=) -========================= + b == B10101000; // B10101000 == 0xA8 -Description ------------ +.. _arduino-bitwisecompound-or: -The compound bitwise OR operator (\|=) is often used with a -variable and a constant to "set" (set to 1) particular bits in a -variable. +Compound bitwise OR (\|=) +------------------------- +The compound bitwise OR operator ``|=`` is often used with a variable +and a constant to "set" (set to 1) particular bits in a variable. In +a program, writing the line ``x |= y;`` is equivalent to writing ``x = +x | y;``. That is, the value of ``x`` after the line will be equal to +its old value bitwise ORed with the value of ``y``:: + x |= y; // equivalent to x = x | y; -Syntax: -------- +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`compound bitwise AND +<arduino-bitwisecompound-and>`\ , ``&=``). -:: +Before doing an example of ``|=``, let's first review the Bitwise OR +(``|``) operator:: - x |= y; // equivalent to x = x | y; + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result +Bits that are "bitwise ORed" with 0 are unchanged, while bits that are +"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` +variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` +equals ``B11111111`` (here we've used binary constants; see the +:ref:`note <arduino-bitwisecompound-binconst>` above). +So, to set bits 0 and 1 of a one-byte variable, while leaving the rest +of the variable unchanged, use the compound bitwise OR operator +(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: -Parameters ----------- + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set -x: a char, int or long variable -y: an integer constant or char, int, or long +Here is the same representation with the variable's bits replaced with +the symbol ``x``:: + x x x x x x x x variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + x x x x x x 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set +So, using a byte variable ``b``, if we say:: -Example: --------- + b = B10101010; // B10101010 == 0xAA + b |= B00000011; // B00000011 == 0x3 -First, a review of the Bitwise OR (\|) operator +then we will have :: -:: + b == B10101011; // B10101011 == 0xAB - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) - returned result +.. _arduino-bitwisecompound-xor: -Bits that are "bitwise ORed" with 0 are unchanged, so if myByte is -a byte variable, -myByte \| B00000000 = myByte; +Compound bitwise XOR (\^=) +-------------------------- +The compound bitwise XOR operator ``^=`` is used with a variable and a +constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a +variable. In a program, writing the line ``x ^= y;`` is equivalent to +writing ``x = x ^ y;``. That is, the value of ``x`` after the line +will be equal to its old value bitwise XORed with the value of ``y``:: + x ^= y; // equivalent to x = x ^ y; -Bits that are "bitwise ORed" with 1 are set to 1 so: -myByte & B11111111 = B11111111; +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`&= +<arduino-bitwisecompound-and>` and :ref:`\|= +<arduino-bitwisecompound-or>`; in fact, these three operators all +work the same in this way). +Before doing an example of ``^=``, let's first review the Bitwise +XOR operator, ``^``:: + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result -Consequently - to set bits 0 & 1 of a variable, while leaving the -rest of the variable unchanged, use the compound bitwise AND -operator (&=) with the constant B00000011 +One way to look at bitwise XOR is that each bit in the result is a 1 +if the input bits are different, or 0 if they are the same. Another +way to think about it is that the result bit will be 1 when *exactly* +one (no more, no less) of the input bits is 1; otherwise, it will be +zero. This means that if you XOR a bit with 1, it will change (or +toggle) its value, while if you XOR a bit with 0, it stays the same. -:: +So, to toggle bits 0 and 1 of a one-byte variable, while leaving the +rest of the variable unchanged, use the compound bitwise XOR operator +``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see +:ref:`note <arduino-bitwisecompound-binconst>` above):: 1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask ---------------------- 1 0 1 0 1 0 1 1 - - variable unchanged - bits set - + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged toggled -Here is the same representation with the variables bits replaced -with the symbol x +So, using a byte variable ``b``, if we say:: + b = B10101010; // B10101010 == 0xAA + b ^= B00000011; // B00000011 == 0x3 +then we will have :: -:: - - x x x x x x x x variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - x x x x x x 1 1 - - variable unchanged - bits set - -So if: - -:: - - myByte = B10101010; - - myByte |= B00000011 == B10101011; - - + b == B10101001; // B10101001 == 0xA9 See Also +-------- - -- `& <http://arduino.cc/en/Reference/BitwiseAnd>`_ (bitwise AND) -- `\| <http://arduino.cc/en/Reference/BitwiseAnd>`_ (bitwise OR) -- `&& <http://arduino.cc/en/Reference/Boolean>`_ (Boolean AND) -- `\|\| <http://arduino.cc/en/Reference/Boolean>`_ (Boolean OR) - - +- :ref:`Boolean operations <arduino-boolean>` (``&&``, ``||``) +- :ref:`Bitwise operators <arduino-bitwisemath>` (``&``, ``|``, ``^``, ``~``) diff --git a/docs/source/arduino/bitwisemath.rst b/docs/source/arduino/bitwisemath.rst new file mode 100644 index 0000000..3f102eb --- /dev/null +++ b/docs/source/arduino/bitwisemath.rst @@ -0,0 +1,183 @@ +.. highlight:: cpp + +.. _arduino-bitwisemath: + +Bitwise AND (&), OR (\|), XOR (^), NOT (~) +========================================== + +The bitwise operators perform their calculations at the bit level of +variables. They help solve a wide range of common programming +problems. + +Much of the material here is adapted for Maple from an (Arduino) +`tutorial on bitwise math +<http://www.arduino.cc/playground/Code/BitMath>`_\ . Another great +resource is the Wikipedia article on `bitwise operations +<http://en.wikipedia.org/wiki/Bitwise_operation>`_\ . + +Below are descriptions and syntax for all of the operators. + +.. contents:: Contents + :local: + +.. _arduino-bitwisemath-and: + +Bitwise AND (&) +--------------- + +The bitwise AND operator in C++ is a single ampersand, ``&``, used +between two other integer expressions. Bitwise AND operates on each +bit position of the surrounding expressions independently, according +to this rule: if both input bits are 1, the resulting output is 1, +otherwise the output is 0. Another way of expressing this is:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + + +On the Maple, the type ``int`` is a 32-bit value, so using ``&`` +between two ``int`` expressions causes 32 simultaneous AND operations +to occur. In a code fragment like:: + + int a = 92; // in binary: 00000000000000000000000001011100 + int b = 101; // in binary: 00000000000000000000000001100101 + int c = a & b; // result: 00000000000000000000000001000100, + // (or 68 in decimal). + + +Each of the 32 bits in ``a`` and ``b`` are processed using bitwise +AND, and all 32 resulting bits are stored in ``c``, resulting in the +value 1000100 in binary, which is 68 in decimal. + + +.. _arduino-bitwisemath-or: + +Bitwise OR (\|) +--------------- + +The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like +the ``&`` operator, ``|`` operates independently on each bit in its +two surrounding integer expressions, but what it does is +different. The bitwise OR of two bits is 1 if either or both of the +input bits is 1, otherwise it is 0. For example:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Here is an example of bitwise OR used in a snippet of C++ code (using +``char``, which takes up 8 bits of memory, instead of ``int``, which +uses 32):: + + char a = 92; // in binary: 01011100 + char b = 101; // in binary: 01100101 + char c = a | b; // result: 01111101, or 125 in decimal. + +.. _arduino-bitwisemath-xor: + +Bitwise XOR (^) +--------------- + +There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE +OR, also known as bitwise XOR. (In English, this is usually pronounced +"zor" or "ex-or"). The bitwise XOR operator is written using the caret +symbol, ``^``. This operator is very similar to the bitwise OR +operator ``|``, except it evaluates to 0 for a given bit position when +both of the input bits for that position are 1:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + + +Another way to look at bitwise XOR is that each bit in the result +is a 1 if the input bits are different, or 0 if they are the same. + +Here is a simple example:: + + int x = 12; // binary (ignoring extra bits): 1100 + int y = 10; // binary: 1010 + int z = x ^ y; // binary: 0110, or decimal 6 + + + +The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 +to 0) some of the bits in an integer expression. In a bitwise OR +operation if there is a 1 in the mask bit, that bit is inverted; if +there is a 0, the bit is not inverted and stays the same. Below is a +program to blink digital pin 13 (the LED pin on Maple):: + + // Blink Maple LED pin + + int led_pin = 13; + int toggle = 0; + + // demo for Exclusive OR + void setup(){ + pinMode(led_pin, OUTPUT); + } + + void loop(){ + toggle = toggle ^ 1; + digitalWrite(led_pin, toggle); + delay(100); + } + +.. _arduino-bitwisemath-not: + +Bitwise NOT (~) +--------------- + +The bitwise NOT operator in C++ is the tilde character ``~``. Unlike +``&`` and ``|``, the bitwise NOT operator is applied to a single +operand to its right. Bitwise NOT changes each bit to its opposite: 0 +becomes 1, and 1 becomes 0. For example:: + + 0 1 operand1 + ---- + 1 0 ~operand1 = result + +Another example:: + + char a = 103; // binary: 01100111 + char b = ~a; // binary: 10011000 = -104 + +You might be surprised to see a negative number like -104 as the +result of this operation. This is because the highest bit in an int +variable is the so-called "sign bit". If the highest bit is 1, the +number is interpreted as negative. This encoding of positive and +negative numbers is referred to as *two's complement*. For more +information, see the Wikipedia article on `two's +complement. <http://en.wikipedia.org/wiki/Twos_complement>`_ + +As an aside, it is interesting to note that (under two's complement +arithmetic) for any integer ``x``, ``~x`` is the same as ``-x-1``. + +At times, the sign bit in a signed integer expression can cause +some unwanted surprises. + + +Uses +---- + +One of the most common uses of bitwise operations is to select or +manipulate a particular bit (or bits) from an integer value, often +called `bit masking +<http://en.wikipedia.org/wiki/Mask_%28computing%29>`_\ . See the +linked Wikipedia article for more information and examples. + +If you really want to see bit-twiddling techniques in their full +glory, you could do much worse than to get yourself a copy of +`Hacker's Delight <http://www.hackersdelight.org/>`_\ . + + +See Also +-------- + +- :ref:`Boolean operations <arduino-boolean>` (``&&``, ``||``) +- :ref:`Compound bitwise operations <arduino-bitwisecompound>` (``&=``, + ``|=``, ``^=``). diff --git a/docs/source/arduino/bitwisexornot.rst b/docs/source/arduino/bitwisexornot.rst deleted file mode 100644 index 25389cb..0000000 --- a/docs/source/arduino/bitwisexornot.rst +++ /dev/null @@ -1,51 +0,0 @@ -.. _arduino-bitwisexornot: - -Bitwise NOT (~) -=============== - -The bitwise NOT operator in C++ is the tilde character ~. Unlike & -and \|, the bitwise NOT operator is applied to a single operand to -its right. Bitwise NOT changes each bit to its opposite: 0 becomes -1, and 1 becomes 0. For example: - - - -:: - - 0 1 operand1 - - - -:: - - ---------- - 1 0 ~ operand1 - - - -:: - - int a = 103; // binary: 0000000001100111 - int b = ~a; // binary: 1111111110011000 = -104 - - - -You might be surprised to see a negative number like -104 as the -result of this operation. This is because the highest bit in an int -variable is the so-called sign bit. If the highest bit is 1, the -number is interpreted as negative. This encoding of positive and -negative numbers is referred to as two's complement. For more -information, see the Wikipedia article on -`two's complement. <http://en.wikipedia.org/wiki/Twos_complement>`_ - - - -As an aside, it is interesting to note that for any integer x, ~x -is the same as -x-1. - - - -At times, the sign bit in a signed integer expression can cause -some unwanted surprises. - - diff --git a/docs/source/arduino/bitwrite.rst b/docs/source/arduino/bitwrite.rst index 5d95506..b35a54f 100644 --- a/docs/source/arduino/bitwrite.rst +++ b/docs/source/arduino/bitwrite.rst @@ -1,52 +1,37 @@ .. _arduino-bitwrite: -bitWrite() -========== +bitWrite(x, n, b) +================= Description ----------- -Writes a bit of a numeric variable. - - - -Syntax ------- - -bitWrite(x, n, b) - - +(Macro) Writes a bit of a numeric variable. Parameters ---------- -x: the numeric variable to which to write - - - -n: which bit of the number to write, starting at 0 for the -least-significant (rightmost) bit - - - -b: the value to write to the bit (0 or 1) +**x**: the numeric variable whose bit to write. +**n**: which bit of the number to write, starting at 0 for the +least-significant (rightmost) bit. +**b**: the value to write to the bit (0 or 1). Returns ------- -none +Nothing. +Arduino Compatibility +--------------------- +Maple's version of ``bitWrite()`` is compatible with Arduino. See also -------- - -- `bit <http://arduino.cc/en/Reference/Bit>`_\ () -- `bitRead <http://arduino.cc/en/Reference/BitRead>`_\ () -- `bitSet <http://arduino.cc/en/Reference/BitSet>`_\ () -- `bitClear <http://arduino.cc/en/Reference/BitClear>`_\ () - - +- :ref:`bit() <arduino-bit>` +- :ref:`bitRead() <arduino-bitRead>` +- :ref:`bitSet() <arduino-bitSet>` +- :ref:`bitClear() <arduino-bitClear>` diff --git a/docs/source/arduino/boolean.rst b/docs/source/arduino/boolean.rst index f109bdb..a724c20 100644 --- a/docs/source/arduino/boolean.rst +++ b/docs/source/arduino/boolean.rst @@ -1,94 +1,86 @@ +.. highlight:: cpp + .. _arduino-boolean: Boolean Operators ================= -These can be used inside the condition of an -`if <http://arduino.cc/en/Reference/If>`_ statement. +These can be used inside the condition of an :ref:`if <arduino-if>` +statement. +.. contents:: Contents + :local: +.. _arduino-boolean-and: && (logical and) -~~~~~~~~~~~~~~~~ - -True only if both operands are true, e.g. +---------------- -:: +True only if both operands are true. For example:: - if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches + if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches // ... - } + } + +is true only if both inputs are high. Another example:: -is true only if both inputs are high. + if (a >= 10 && a <= 20){} // true if a is between 10 and 20 +**Be careful** not to say ``10 <= a <= 20``! This won't work the way +you want. You have to separately test whether ``a`` is at least 10 +using ``a >= 10``, then test whether ``a`` is at most 20 using ``a <= +20``, then combine the results using ``&&``. -\|\| (logical or) -~~~~~~~~~~~~~~~~~ +.. _arduino-boolean-or: -True if either operand is true, e.g. +\|\| (logical or) +----------------- -:: +True if either operand is true. For example:: if (x > 0 || y > 0) { // ... - } + } -is true if either x or y is greater than 0. +is true if either ``x`` or ``y`` is greater than 0. +! (logical not) +--------------- -! (not) -~~~~~~~ +True if the operand is false. For example:: -True if the operand is false, e.g. - -:: - - if (!x) { + if (!x) { // ... - } - -is true if x is false (i.e. if x equals 0). - - - -Warning -------- + } -Make sure you don't mistake the boolean AND operator, && (double -ampersand) for the bitwise AND operator & (single ampersand). They -are entirely different beasts. +is true if ``x`` is false (i.e. if ``x`` equals zero). +Some Advice +----------- +.. warning:: -Similarly, do not confuse the boolean \|\| (double pipe) operator -with the bitwise OR operator \| (single pipe). + Make sure you don't mistake the boolean AND operator ``&&`` + (double ampersand) for the :ref:`bitwise AND operator + <arduino-bitwisemath-and>` ``&`` (single ampersand). They are + entirely different beasts. + Similarly, do not confuse the boolean OR operator ``||`` (double + pipe) with the :ref:`bitwise OR operator <arduino-bitwisemath-or>` + ``|`` (single pipe). + The :ref:`bitwise NOT operator <arduino-bitwisemath-not>` ``~`` + (tilde) looks much different than the boolean not operator ``!`` + (exclamation point, or "bang", as some programmers say), but you + still have to be sure which one you want. -The bitwise not ~ (tilde) looks much different than the boolean not -! (exclamation point or "bang" as the programmers say) but you -still have to be sure which one you want where. - - -Examples --------- - -:: - - if (a >= 10 && a <= 20){} // true if a is between 10 and 20 - - - -See also +See Also -------- - -- `& <http://arduino.cc/en/Reference/BitwiseAnd>`_ (bitwise AND) -- `\| <http://arduino.cc/en/Reference/BitwiseAnd>`_ (bitwise OR) -- `~ <http://arduino.cc/en/Reference/BitwiseXorNot>`_ (bitwise NOT -- `if <http://arduino.cc/en/Reference/If>`_ - - +- :ref:`Bitwise operators <arduino-bitwisemath>` (``&``, ``|``, ``^``, ``~``) +- :ref:`Compound bitwise operators <arduino-bitwisecompound>` (``&=``, + ``|=``, ``^=``). +- :ref:`if statement <arduino-if>` diff --git a/docs/source/arduino/booleanvariables.rst b/docs/source/arduino/booleanvariables.rst index 3bbe72a..772db0f 100644 --- a/docs/source/arduino/booleanvariables.rst +++ b/docs/source/arduino/booleanvariables.rst @@ -1,53 +1,52 @@ +.. highlight:: cpp + .. _arduino-booleanvariables: -boolean -======= +Booleans +======== -A **boolean** holds one of two values, -`true <http://arduino.cc/en/Reference/Constants>`_ or -`false <http://arduino.cc/en/Reference/Constants>`_. (Each boolean -variable occupies one byte of memory.) +A **boolean** holds one of two values, :ref:`true +<arduino-constants-true>` or :ref:`false <arduino-constants-false>`. +On a Maple, each boolean variable occupies one byte of memory, and has +type ``bool``. +.. warning:: + On an Arduino, the type ``boolean`` is also provided. While the + Maple also has this type for compatibility, **its use is strongly + discouraged**. The ``bool`` type is a standard part of C++, while + ``boolean`` is a non-standard extension that serves no purpose. Example ------- :: - int LEDpin = 5; // LED on pin 5 - int switchPin = 13; // momentary switch on 13, other side connected to ground - - boolean running = false; - - void setup() - { - pinMode(LEDpin, OUTPUT); + int ledPin = 13; // LED on pin 13 + int switchPin = 12; // momentary switch on 12, other side connected to ground + + // running is a boolean variable: + bool running = false; + + void setup() { + pinMode(ledPin, OUTPUT); pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); // turn on pullup resistor } - - void loop() - { - if (digitalRead(switchPin) == LOW) - { // switch is pressed - pullup keeps pin high normally + + void loop() { + if (digitalRead(switchPin) == LOW) { + // switch is pressed - pullup keeps pin high normally delay(100); // delay to debounce switch running = !running; // toggle running variable - digitalWrite(LEDpin, running) // indicate via LED + digitalWrite(ledPin, running) // indicate via LED } } - - - - - See also -------- -- `constants <http://arduino.cc/en/Reference/Constants>`_ -- `boolean operators <http://arduino.cc/en/Reference/Boolean>`_ -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ - - +- :ref:`Boolean constants <arduino-constants-bool>` +- :ref:`Boolean operators <arduino-boolean>` +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/braces.rst b/docs/source/arduino/braces.rst index c7bd148..1ae34e8 100644 --- a/docs/source/arduino/braces.rst +++ b/docs/source/arduino/braces.rst @@ -1,113 +1,94 @@ +.. highlight:: cpp + .. _arduino-braces: -{} Curly Braces -=============== +Curly Braces ({}) +================= -Curly braces (also referred to as just "braces" or as "curly -brackets") are a major part of the C programming language. They are -used in several different constructs, outlined below, and this can -sometimes be confusing for beginners. +.. contents:: Contents + :local: +Introduction +------------ +Curly braces (also referred to as just "braces" or as "curly +brackets") are a major part of the C and C++ programming +languages. They are used in several different constructs, outlined +below, and this can sometimes be confusing for beginners. -An opening curly brace "{" must always be followed by a closing -curly brace "}". This is a condition that is often referred to as -the braces being balanced. The Arduino IDE (integrated development +An opening curly brace, ``{`` must always be followed by a closing +curly brace ``}``. This is a condition that is often referred to as +the braces being *balanced*. The Maple IDE (integrated development environment) includes a convenient feature to check the balance of -curly braces. Just select a brace, or even click the insertion -point immediately following a brace, and its logical companion will -be highlighted. - - - -At present this feature is slightly buggy as the IDE will often -find (incorrectly) a brace in text that has been "commented out." - - - -Beginning programmers, and programmers coming to C from the BASIC -language often find using braces confusing or daunting. After all, -the same curly braces replace the RETURN statement in a subroutine -(function), the ENDIF statement in a conditional and the NEXT -statement in a FOR loop. - +curly braces. Just select a brace, or even click the insertion point +immediately following a brace, and its companion will be highlighted\ +[#fbug]_\ . +Beginning programmers, and programmers coming to C++ from languages +without braces, often find using them confusing or daunting. Because the use of the curly brace is so varied, it is good programming practice to type the closing brace immediately after typing the opening brace when inserting a construct which requires -curly braces. Then insert some carriage returns between your braces -and begin inserting statements. Your braces, and your attitude, -will never become unbalanced. - - +curly braces. Then insert some blank lines between your braces and +begin inserting statements. Your braces, and your attitude, will never +become unbalanced. Unbalanced braces can often lead to cryptic, impenetrable compiler errors that can sometimes be hard to track down in a large program. -Because of their varied usages, braces are also incredibly -important to the syntax of a program and moving a brace one or two -lines will often dramatically affect the meaning of a program. +Because of their varied usages, braces are also incredibly important +to the syntax of a program and moving a brace one or two lines will +usually dramatically affect the meaning of a program. +The main uses of curly braces +----------------------------- +**Functions**:: -**The main uses of curly braces** ---------------------------------- - -Functions ---------- - -:: - - void myfunction(datatype argument){ - statements(s) + // a function body needs braces around it + void myfunction(datatype argument) { + // ... function body goes in here ... } +**Loops** (see the :ref:`while <arduino-while>`\ , :ref:`for +<arduino-for>`\ , and :ref:`do/while <arduino-dowhile>` loop reference +pages for more information):: + // you should put braces around the body of a loop: -Loops ------ - -:: - - while (boolean expression) - { - statement(s) + while (boolean expression) { + // code inside the loop goes here } - do - { - statement(s) - } while (boolean expression); - - for (initialisation; termination condition; incrementing expr) - { - statement(s) + for (initialisation; termination condition; incrementing expr) { + // code inside the loop goes here } + do { + // code inside the loop goes here + } while (boolean expression); -Conditional statements ----------------------- - - +**Conditional statements** (see the :ref:`if statement <arduino-if>` +reference page for more information):: -:: + // you should put braces around the body of an "if", "else if", + // or "else": - if (boolean expression) - { - statement(s) + if (boolean expression) { + // code inside the "if" } - - else if (boolean expression) - { - statement(s) + else if (boolean expression) { + // code inside the "else if" } - else - { - statement(s) + else { + // code inside the "else" } +.. rubric:: Footnotes +.. TODO remove this once IDE 0.1.0 released -`Reference Home <http://arduino.cc/en/Reference/HomePage>`_ - +.. [#fbug] At present this feature is slightly buggy as the IDE will + often find (incorrectly) a brace in text that has been commented + out. diff --git a/docs/source/arduino/break.rst b/docs/source/arduino/break.rst index d951c52..57009c1 100644 --- a/docs/source/arduino/break.rst +++ b/docs/source/arduino/break.rst @@ -1,12 +1,14 @@ +.. highlight:: cpp + .. _arduino-break: break ===== -**break** is used to exit from a **do**, **for**, or **while** -loop, bypassing the normal loop condition. It is also used to exit -from a **switch** statement. - +``break`` is used to exit from a :ref:`while <arduino-while>`\ , +:ref:`for <arduino-for>`\ , or :ref:`do/while <arduino-dowhile>` loop, +bypassing the normal loop condition. It is also used to exit from a +:ref:`switch <arduino-switchcase>` statement. Example @@ -20,6 +22,8 @@ Example sens = analogRead(sensorPin); if (sens > threshold){ // bail out on sensor detect x = 0; + // this line of code means that we'll immediately exit + // from the "for" loop: break; } delay(50); diff --git a/docs/source/arduino/byte.rst b/docs/source/arduino/byte.rst index 5e94bd4..0b21b31 100644 --- a/docs/source/arduino/byte.rst +++ b/docs/source/arduino/byte.rst @@ -1,13 +1,20 @@ +.. highlight:: cpp + .. _arduino-byte: byte ==== -Description ------------ +The ``byte`` type stores a 1-byte (8-bit) unsigned integer number, +from 0 to 255. -A byte stores an 8-bit unsigned number, from 0 to 255. +.. warning:: + The ``byte`` type is provided for compatibility with Arduino. + However, it is a non-standard extension. The standard C++ type for + storing an 8-bit unsigned integer is ``unsigned char``; we + recommend using that instead. (Your code will still work on an + Arduino). Example @@ -15,15 +22,10 @@ Example :: - byte b = B10010; // "B" is the binary formatter (B10010 = 18 decimal) - - + byte b = 134; -See also +See Also -------- - -- `word <http://arduino.cc/en/Reference/Word>`_ -- `byte <http://arduino.cc/en/Reference/ByteCast>`_\ () -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ - +- :ref:`byte() <arduino-bytecast>` (casting a value to a byte) +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/bytecast.rst b/docs/source/arduino/bytecast.rst index 71ab4aa..bf85a35 100644 --- a/docs/source/arduino/bytecast.rst +++ b/docs/source/arduino/bytecast.rst @@ -1,41 +1,50 @@ +.. highlight:: cpp + .. _arduino-bytecast: -byte() -====== +byte() (cast) +============= Description ----------- -Converts a value to the -`byte <http://arduino.cc/en/Reference/Byte>`_ data type. +Converts a value to the :ref:`byte <arduino-byte>` data type. + +.. warning:: + Casting to the byte type is provided for compatibility with + Arduino. However, ``byte`` is a non-standard type. The standard + C++ type for storing an 8-bit unsigned integer is ``unsigned + char``, and we recommend using that instead. + In order to cast a variable ``x`` to an ``unsigned char``, the + following syntax can be used:: + + (unsigned char)(x); Syntax ------ -byte(x) - +``byte(x)`` Parameters ---------- -x: a value of any type - +**x**: a value of any integer type Returns ------- -byte - +The value, converted to a ``byte``. Note, however, that if the value +is larger than the maximum value you can store in a byte (255), then +the results might be strange and unexpected. -See also +See Also -------- - -- `byte <http://arduino.cc/en/Reference/Byte>`_ +- :ref:`arduino-byte` diff --git a/docs/source/arduino/cc-attribution.txt b/docs/source/arduino/cc-attribution.txt new file mode 100644 index 0000000..e662eeb --- /dev/null +++ b/docs/source/arduino/cc-attribution.txt @@ -0,0 +1,9 @@ +.. Included in all this directory's files in order to satisfy the +.. Arduino CC Attribution-ShareAlike 3.0 License + +.. admonition:: License + + This documentation page was adapted from the `Arduino Reference + Documentation <http://arduino.cc/en/Reference/HomePage>`_\ , which + is released under a `Creative Commons Attribution-ShareAlike 3.0 + License <http://creativecommons.org/licenses/by-sa/3.0/>`_. diff --git a/docs/source/arduino/changes.rst b/docs/source/arduino/changes.rst deleted file mode 100644 index 75cd65d..0000000 --- a/docs/source/arduino/changes.rst +++ /dev/null @@ -1,93 +0,0 @@ -.. _arduino-changes: - -Changes -======= - -This page lists major changes to the Arduino core, libraries, and -environment. For details, see the -`release notes <http://arduino.cc/en/Main/ReleaseNotes>`_. - - - -Changes in Arduino 0017 -~~~~~~~~~~~~~~~~~~~~~~~ - - -- **Environment**: The code base for the Arduino development - environment was largely re-written to bring it back into sync with - Processing (1.0.3). The main differences include support for - multiple sketch windows open simultaneously and a dedicated window - for the serial monitor. - - -- **Icons**: The icons and about images were updated. - - -- **Arduino.app**: The Mac OS X version of Arduino is now a .app - file packaged in a .dmg. - - -- **Libraries**: Support was added for third-party libraries in - the *SKETCHBOOK*/libraries directory. This allows user-installed - libraries to persist across upgrades of the Arduino software. - - -- **Servo**: The servo library was rewritten to allow support for - up to 12 servos (on any pins) and up to 48 on the Mega. - - -- **LiquidCrystal**: The begin(), cursor(), noCursor(), blink(), - noBlink(), display(), noDisplay(), scrollDisplayLeft(), - scrollDisplayRight(), autoscroll(), noAutoscroll(), leftToRight(), - rightToLeft(), and createChar() functions were added. - - - -Changes in Arduino 0016 -~~~~~~~~~~~~~~~~~~~~~~~ - - -- New functions for writing a string, write(str), or buffer, - write(buf, len), were added to the Print, Serial, and Ethernet - library Client and Server classes. - - - -Changes in Arduino 0015 -~~~~~~~~~~~~~~~~~~~~~~~ - - -- Support for the Arduino Mega. - - - -Changes in Arduino 0013 -~~~~~~~~~~~~~~~~~~~~~~~ - - -- Support for printing floats was added to the Print, Serial, and - Ethernet library Client and Server classes. - - -- The word type and word(), bitRead(), bitWrite(), bitSet(), - bitClear(), bit(), lowByte(), and highByte() functions were added. - - - -Changes in Arduino 0012 -~~~~~~~~~~~~~~~~~~~~~~~ - - -- Added the Firmata library, which provides a standard protocol - for serial communication. - - -- Added Ethernet library. - - -- Added Servo library. - - -- Added LiquidCrystal library. - - diff --git a/docs/source/arduino/char.rst b/docs/source/arduino/char.rst index e783ed6..53dd060 100644 --- a/docs/source/arduino/char.rst +++ b/docs/source/arduino/char.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-char: char @@ -6,28 +8,25 @@ char Description ----------- -A data type that takes up 1 byte of memory that stores a character -value. Character literals are written in single quotes, like this: -'A' (for multiple characters - strings - use double quotes: -"ABC"). - - +The ``char`` type stores a 1-byte character value (or integer with +value from -128 to 127). Character literals are written in single +quotes, like this: ``'A'`` (for multiple characters - strings - use +double quotes: ``"ABC"``). -Characters are stored as numbers however. You can see the specific -encoding in the -`ASCII chart <http://arduino.cc/en/Reference/ASCIIchart>`_. This -means that it is possible to do arithmetic on characters, in which -the ASCII value of the character is used (e.g. 'A' + 1 has the -value 66, since the ASCII value of the capital letter A is 65). See -`Serial.println <http://arduino.cc/en/Serial/Println>`_ reference -for more on how characters are translated to numbers. +Just like everything else on a computer, characters are stored as +numbers. You can see the specific encoding in the `ASCII chart +<http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters>`_\ +. This means that it is possible to do arithmetic on characters, in +which the ASCII value of the character is used (e.g. ``'A' + 1`` has the +decimal value 66, since the ASCII value of the capital letter A in +decimal is 65). See the :ref:`Serial.println() +<arduino-serial-println>` documentation for more information about how +characters are converted into numbers. - -The char datatype is a signed type, meaning that it encodes numbers -from -128 to 127. For an unsigned, one-byte (8 bit) data type, use -the *byte* data type. - +The ``char`` datatype is a signed type, meaning that it encodes +numbers from -128 to 127. For an unsigned type, which stores values +from 0 to 255, just use the type ``unsigned char`` (two words). Example @@ -35,17 +34,16 @@ Example :: - char myChar = 'A'; - char myChar = 65; // both are equivalent - + // the following two lines are equivalent: + char c = 'A'; + char c = 65; See also -------- -- `byte <http://arduino.cc/en/Reference/Byte>`_ -- `int <http://arduino.cc/en/Reference/Int>`_ -- `array <http://arduino.cc/en/Reference/Array>`_ -- `Serial.println <http://arduino.cc/en/Serial/Println>`_ +- :ref:`arduino-int` +- :ref:`arduino-array` (a string is just an array of ``char``\ s) +- :ref:`Serial.println() <arduino-serial-println>` diff --git a/docs/source/arduino/charcast.rst b/docs/source/arduino/charcast.rst index daa7c92..d8184c1 100644 --- a/docs/source/arduino/charcast.rst +++ b/docs/source/arduino/charcast.rst @@ -1,41 +1,36 @@ +.. highlight:: cpp + .. _arduino-charcast: -char() -====== +char() (cast) +============= Description ----------- -Converts a value to the -`char <http://arduino.cc/en/Reference/Char>`_ data type. - - +Converts a value to the :ref:`char <arduino-char>` data type. Syntax ------ -char(x) - +``char(x)`` Parameters ---------- -x: a value of any type - +**x**: a value of any type Returns ------- -char +The value, converted to a ``char``. Note, however, that if the value +is outside the range of a ``char`` (-128 to 127), then the results +might be strange and unexpected. - -See also +See Also -------- - -- `char <http://arduino.cc/en/Reference/Char>`_ - - +- :ref:`char <arduino-char>` diff --git a/docs/source/arduino/comments.rst b/docs/source/arduino/comments.rst index 189ead5..3aeb37f 100644 --- a/docs/source/arduino/comments.rst +++ b/docs/source/arduino/comments.rst @@ -1,45 +1,60 @@ +.. highlight:: cpp + .. _arduino-comments: Comments ======== -Comments are lines in the program that are used to inform yourself -or others about the way the program works. They are ignored by the -compiler, and not exported to the processor, so they don't take up -any space on the Atmega chip. - - +Comments are lines in the program that are used to inform yourself or +others about the way the program works. They are ignored by the +compiler, and not exported to the processor, so they don't take up any +space in RAM or Flash. -Comments only purpose are to help you understand (or remember) how -your program works or to inform others how your program works. -There are two different ways of marking a line as a comment: +One use for comments is to help you understand (or remember) how your +program works, or to inform others how your program works. There are +two different ways of making comments. +**Single line comment**: Anything following two slashes, ``//``, until +the end of the line, is a comment:: + x = 5; // the rest of this line is a comment -Example -------- - -:: - - x = 5; // This is a single line comment. Anything after the slashes is a comment - // to the end of the line +**Multi-line comment**: Anything in between a pair of ``/*`` and ``*/`` +is a comment:: - /* this is multiline comment - use it to comment out whole blocks of code + /* <-- a slash-star begins a multi-line comment + + all of this in the multi-line comment - you can use it to comment + out whole blocks of code - if (gwb == 0){ // single line comment is OK inside a multiline comment - x = 3; /* but not another multiline comment - this is invalid */ + if (gwb == 0){ // single line comment is OK inside a multi-line comment + x = 3; } - // don't forget the "closing" comment - they have to be balanced! + + // don't forget the "closing" star-slash - they have to be balanced: */ +Note that it's okay to use single-line comments within a multi-line +comment, but you can't use multi-line comments within a multi-line +comment. Here's an example:: + + /* ok, i started a multi-line comment + + x = 3; /* this next star-slash ENDS the multi-line comment: */ + + x = 4; // this line is outside of the multi-line comment + + // next line is also outside of the comment, and causes a compile error: + */ +Programming Tip +--------------- -**Tip** -When experimenting with code, "commenting out" parts of your -program is a convenient way to remove lines that may be buggy. This -leaves the lines in the code, but turns them into comments, so the -compiler just ignores them. This can be especially useful when -trying to locate a problem, or when a program refuses to compile -and the compiler error is cryptic or unhelpful. +When experimenting with code, "commenting out" parts of your program +is a convenient way to remove lines that may be buggy. This leaves +the lines in the code, but turns them into comments, so the compiler +just ignores them. This can be especially useful when trying to locate +a problem, or when a program refuses to compile and the compiler error +is cryptic or unhelpful. diff --git a/docs/source/arduino/comparison.rst b/docs/source/arduino/comparison.rst index b87e05b..85c2118 100644 --- a/docs/source/arduino/comparison.rst +++ b/docs/source/arduino/comparison.rst @@ -1,54 +1,84 @@ +.. highlight:: cpp + .. _arduino-comparison: -Arduino/Processing Language Comparison -====================================== +Comparison Operators +==================== + +The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and +``>=`` are used to compare two numbers. They are :ref:`true +<arduino-constants-true>` when the comparison is true, and :ref:`false +<arduino-constants-false>` otherwise. They are based on the symbols +=, ≠, <, >, ≤, and ≥ from mathematics. + +Here are some examples, with their meaning in comments:: + + // "eq" is true when x is equal to y + bool eq = (x == y); + + // "neq" is true when x is different than y + bool neq = (x != y); + + // "lt" is true when x is less than, but NOT equal to, y + bool lt = (x < y); + + // "gt" is true when x is greater than, but NOT equal to, y + bool gt = (x > y); + + // "lte" is true when x is less than or equal to y + bool lte = (x <= y); + + // "gte" is true when x is greater than or equal to y + bool gte = (x >= y); -The Arduino language (based on Wiring) is implemented in C/C++, and -therefore has some differences from the Processing language, which -is based on Java. +The parentheses are optional; they are present only for clarity. For +example, the following two lines are the same:: + bool eq = x == y; + bool eq = (x == y); -Arrays -~~~~~~ +Uses +---- -*Arduino* -*Processing* -int bar[8]; -bar[0] = 1; -int[] bar = new int[8]; -bar[0] = 1; -int foo[] = { 0, 1, 2 }; -int foo[] = { 0, 1, 2 }; -*or* -int[] foo = { 0, 1, 2 }; +Comparison operators, along with :ref:`boolean operators +<arduino-boolean>`, are useful inside the conditionals of :ref:`if +<arduino-if>` statements. Here's one example:: + if (x < 50) { + // only execute these lines if x is less than 50 + SerialUSB.println("delaying:"); + SerialUSB.println(x); + delay(x); + } -Loops -~~~~~ +.. warning:: + Beware of accidentally using the single equal sign (``=``) when you + meant to test if two numbers are equal (``==``). This is a common + mistake inside of ``if`` statement conditionals, e.g.:: -*Arduino* -*Processing* -int i; -for (i = 0; i < 5; i++) { ... } -for (int i = 0; i < 5; i++) { ... } + // DON'T MAKE THIS MISTAKE + if (x = 10) { + // body + } + The single equal sign is the assignment operator, and sets x to 10 + (puts the value 10 into the variable x). Instead use the double equal + sign (e.g. ``if (x == 10)``), which is the comparison operator, and + tests *whether* x is equal to 10 or not. The latter statement is only + true if x equals 10, but the former statement will always be true. -Printing -~~~~~~~~ + This is because C evaluates the statement ``if (x=10)`` as follows: 10 + is assigned to x (remember that the single equal sign is the + :ref:`assignment operator <arduino-assignment>`), so x now + contains 10. Then the 'if' conditional evaluates 10, which evaluates + to :ref:`true <arduino-constants-true>`, since any non-zero number + evaluates to ``true``. -*Arduino* -*Processing* -Serial.println("hello world"); -println("hello world"); -int i = 5; -Serial.println(i); -int i = 5; -println(i); -int i = 5; -Serial.print("i = "); -Serial.print(i); -Serial.println(); -int i = 5; -println("i = " + i); + Consequently, the conditional of an ``if`` statement like ``if (x = + 10) {...}`` will always evaluate to ``true``, and the variable x + will be set to 10, which is probably not what you meant. + (This sometimes has uses, though, so just because an assignment + appears within a conditional doesn't mean it's automatically wrong. + Be careful to know what you mean.) diff --git a/docs/source/arduino/const.rst b/docs/source/arduino/const.rst index 295b817..4a45387 100644 --- a/docs/source/arduino/const.rst +++ b/docs/source/arduino/const.rst @@ -1,37 +1,35 @@ +.. highlight:: cpp + .. _arduino-const: -const keyword +const Keyword ============= -The **const** keyword stands for constant. It is a variable +The ``const`` keyword stands for "constant". It is a variable *qualifier* that modifies the behavior of the variable, making a -variable "*read-only*". This means that the variable can be used -just as any other variable of its type, but its value cannot be -changed. You will get a compiler error if you try to assign a value -to a **const** variable. - - - -Constants defined with the *const* keyword obey the rules of -*`variable scoping <http://arduino.cc/en/Reference/Scope>`_* that -govern other variables. This, and the pitfalls of using*#define*, -makes the *const* keyword a superior method for defining constants -and is preferred over using -*`#define <http://arduino.cc/en/Reference/Define>`_*. - +variable "*read-only*". This means that the variable can be used just +as any other variable of its type, but its value cannot be +changed. You will get a compiler error if you try to assign a value to +a ``const`` variable. +Constants defined with the ``const`` keyword obey the same rules of +:ref:`variable scoping <arduino-scope>` that govern other +variables. This, and the pitfalls of using :ref:`#define +<arduino-define>`, often makes using the ``const`` keyword a superior +method for defining constants than ``#define``. Example ------- :: + // this defines a variable called "pi", which cannot be changed: const float pi = 3.14; float x; // .... - x = pi * 2; // it's fine to use const's in math + x = pi * 2; // it's fine to find the value of a const variable pi = 7; // illegal - you can't write to (modify) a constant @@ -39,17 +37,13 @@ Example **#define** or **const** ------------------------ -You can use either **const** or **#define** for creating numeric or -string constants. For -`arrays <http://arduino.cc/en/Reference/Array>`_, you will need to -use **const**. In general *const* is preferred over *#define* for -defining constants. - - - -See also: - +You can use either ``const`` or ``#define`` for creating numeric or +string constants. For :ref:`arrays <arduino-array>`\ , you will need +to use ``const``. In general, ``const`` is preferred over ``#define`` +for defining constants. -- `#define <http://arduino.cc/en/Reference/Define>`_ -- `volatile <http://arduino.cc/en/Reference/Volatile>`_ +See Also +-------- +- :ref:`#define <arduino-define>` +- :ref:`volatile <arduino-volatile>` diff --git a/docs/source/arduino/constants.rst b/docs/source/arduino/constants.rst index 49f3933..b082774 100644 --- a/docs/source/arduino/constants.rst +++ b/docs/source/arduino/constants.rst @@ -7,26 +7,29 @@ Constants are predefined variables in the Arduino language. They are used to make the programs easier to read. We classify constants in groups. +.. contents:: Contents + :local: +.. _arduino-constants-bool: -Defining Logical Levels, true and false (Boolean Constants) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Boolean Constants +----------------- There are two constants used to represent truth and falsity in the Arduino language: **true**, and **false**. - +.. _arduino-constants-false: false ------ +^^^^^ false is the easier of the two to define. false is defined as 0 (zero). - +.. _arduino-constants-true: true ----- +^^^^ true is often said to be defined as 1, which is correct, but true has a wider definition. Any integer which is *non-zero* is TRUE, in @@ -34,19 +37,17 @@ a Boolean sense. So -1, 2 and -200 are all defined as true, too, in a Boolean sense. - Note that the *true* and *false* constants are typed in lowercase unlike HIGH, LOW, INPUT, & OUTPUT. - Defining Pin Levels, HIGH and LOW -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +--------------------------------- When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: **HIGH** and **LOW**. - +.. _arduino-constants-high: **HIGH** @@ -73,7 +74,7 @@ with digitalWrite, the pin is at 5 volts. In this state it can series resistor to ground, or to another pin configured as an output, and set to LOW. - +.. _arduino-constants-low: **LOW** @@ -96,7 +97,7 @@ output, and set to HIGH. Defining Digital Pins, INPUT and OUTPUT -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +--------------------------------------- Digital pins can be used either as **INPUT** or **OUTPUT**. Changing a pin from INPUT TO OUTPUT with pinMode() drastically @@ -105,7 +106,7 @@ changes the electrical behavior of the pin. Pins Configured as Inputs -------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^ Arduino (Atmega) pins configured as **INPUT** with pinMode() are said to be in a high-impedance state. One way of explaining this is @@ -117,7 +118,7 @@ reading a sensor, but not powering an LED. Pins Configured as Outputs --------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^ Pins configured as **OUTPUT** with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial @@ -131,6 +132,158 @@ of current provided by an Atmega pin is also not enough to power most relays or motors, and some interface circuitry will be required. +.. _arduino-fpconstants: + +Floating-Point Constants +------------------------ + +Similar to integer constants, floating point constants are used to +make code more readable. Floating point constants are swapped at +compile time for the value to which the expression evaluates. + + + +Examples: + + + +``n = .005;`` + + + +Floating point constants can also be expressed in a variety of +scientific notation. 'E' and 'e' are both accepted as valid +exponent indicators. + + + +:: + + + floating-point evaluates to: also evaluates to: + constant + + 10.0 10 + 2.34E5 2.34 * 10^5 234000 + 67e-12 67.0 * 10^-12 .000000000067 + +.. _arduino-constants-integers: + +Integer Constants +----------------- + +Integer constants are numbers used directly in a sketch, like +``123``. By default, these numbers are treated as +`int <http://arduino.cc/en/Reference/Int>`_'s but you can change +this with the U and L modifiers (see below). + + + +Normally, integer constants are treated as base 10 (decimal) +integers, but special notation (formatters) may be used to enter +numbers in other bases. + + + +:: + + Base Example Formatter Comment + + 10 (decimal) 123 none + + 2 (binary) B1111011 leading 'B' only works with 8 bit values (0 to 255) + characters 0-1 valid + + 8 (octal) 0173 leading "0" characters 0-7 valid + + 16 (hexadecimal) 0x7B leading "0x" characters 0-9, A-F, a-f valid + +.. _arduino-constants-integers-dec: + +**Decimal** is base 10. This is the common-sense math with which +you are acquainted. Constants without other prefixes are assumed to +be in decimal format. + + + +Example: +:: + + 101 // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) + +.. _arduino-constants-integers-bin: + +**Binary** is base two. Only characters 0 and 1 are valid. + + + +Example: +:: + + B101 // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) + +The binary formatter only works on bytes (8 bits) between 0 (B0) +and 255 (B11111111). If it is convenient to input an int (16 bits) +in binary form you can do it a two-step procedure such as: + + + +:: + + myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte + +.. _arduino-constants-integers-oct: + +**Octal** is base eight. Only characters 0 through 7 are valid. Octal +values are indicated by the prefix "0". + +Example: + +:: + + 0101 // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) + +Warning +It is possible to generate a hard-to-find bug by (unintentionally) +including a leading zero before a constant and having the compiler +unintentionally interpret your constant as octal. + +.. _arduino-constants-integers-hex: + +**Hexadecimal (or hex)** is base sixteen. Valid characters are 0 +through 9 and letters A through F; A has the value 10, B is 11, up +to F, which is 15. Hex values are indicated by the prefix "0x". +Note that A-F may be syted in upper or lower case (a-f). + + + +Example: + +:: + + 0x101 // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) + +.. _arduino-constants-integers-u-l: + +U & L formatters +^^^^^^^^^^^^^^^^ + +By default, an integer constant is treated as an +`int <http://arduino.cc/en/Reference/Int>`_ with the attendant +limitations in values. To specify an integer constant with another +data type, follow it with: + + + + +- a 'u' or 'U' to force the constant into an unsigned data format. + Example: ``33u`` +- a 'l' or 'L' to force the constant into a long data format. + Example: ``100000L`` +- a 'ul' or 'UL' to force the constant into an unsigned long + constant. Example: ``32767ul`` + + See also @@ -140,5 +293,9 @@ See also - `pinMode() <http://arduino.cc/en/Reference/PinMode>`_ - `Integer Constants <http://arduino.cc/en/Reference/IntegerConstants>`_ - `boolean variables <http://arduino.cc/en/Reference/BooleanVariables>`_ - - +- `#define <http://arduino.cc/en/Reference/Define>`_ +- `byte <http://arduino.cc/en/Reference/Byte>`_ +- `int <http://arduino.cc/en/Reference/Int>`_ +- `unsigned int <http://arduino.cc/en/Reference/UnsignedInt>`_ +- `long <http://arduino.cc/en/Reference/Long>`_ +- `unsigned long <http://arduino.cc/en/Reference/UnsignedLong>`_ diff --git a/docs/source/arduino/constrain.rst b/docs/source/arduino/constrain.rst index 2769219..eb06122 100644 --- a/docs/source/arduino/constrain.rst +++ b/docs/source/arduino/constrain.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-constrain: constrain(x, a, b) @@ -6,55 +8,55 @@ constrain(x, a, b) Description ----------- -Constrains a number to be within a range. - +(Macro) Constrains a number to be within a range. Parameters ---------- -x: the number to constrain, all data types - - - -a: the lower end of the range, all data types - - - -b: the upper end of the range, all data types +**x**: the number to constrain +**a**: the lower end of the range +**b**: the upper end of the range Returns ------- **x**: if **x** is between **a** and **b** - - **a**: if **x** is less than **a** - - **b**: if **x** is greater than **b** - - Example ------- :: + // limits range of sensor values to between 10 and 150: sensVal = constrain(sensVal, 10, 150); - // limits range of sensor values to between 10 and 150 +Warning +------- -See also --------- +Because of the way ``constrain()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + constrain(x,a++,b); // avoid this - yields incorrect results + + constrain(x,a,b); // use this instead- + a++; // keep other math outside constrain() +Arduino Compatibility +--------------------- -- `min <http://arduino.cc/en/Reference/Min>`_\ () -- `max <http://arduino.cc/en/Reference/Max>`_\ () +Maple's implementation of ``constrain()`` is compatible with Arduino. +See also +-------- +- :ref:`min() <arduino-min>` +- :ref:`max() <arduino-max>` diff --git a/docs/source/arduino/continue.rst b/docs/source/arduino/continue.rst index 66c7e60..42d7825 100644 --- a/docs/source/arduino/continue.rst +++ b/docs/source/arduino/continue.rst @@ -1,13 +1,15 @@ +.. highlight:: cpp + .. _arduino-continue: continue ======== -The continue statement skips the rest of the current iteration of a -loop (**do**, **for**, or **while**). It continues by checking the -conditional expression of the loop, and proceeding with any -subsequent iterations. - +The ``continue`` keyword skips the rest of the current iteration of a +:ref:`while <arduino-while>`\ , :ref:`for <arduino-for>`\ , or +:ref:`do/while <arduino-dowhile>` loop. It continues by checking the +conditional expression of the loop, and proceeding with any subsequent +iterations. Example @@ -19,11 +21,11 @@ Example for (x = 0; x < 255; x ++) { if (x > 40 && x < 120){ // create jump in values - continue; + continue; // skips the next two lines and goes to the + // beginning of the loop, with the next value of x } digitalWrite(PWMpin, x); delay(50); } - diff --git a/docs/source/arduino/cos.rst b/docs/source/arduino/cos.rst index 7fed4bb..6b1406a 100644 --- a/docs/source/arduino/cos.rst +++ b/docs/source/arduino/cos.rst @@ -3,31 +3,28 @@ cos(rad) ======== -Description ------------ +Calculate the cosine of an angle (in radians). -Calculates the cos of an angle (in radians). The result will be -between -1 and 1. +Library Documentation +--------------------- -Parameters ----------- +.. doxygenfunction:: cos -rad: the angle in radians (*float*) +Arduino Compatibility +--------------------- +The Maple ``cos()`` implementation is compatible with Arduino. -Returns -------- - -The cos of the angle ("double") - - +Note that the Maple implementation comes from `newlib +<http://sourceware.org/newlib/>`_\ , while Arduino's is that of +`avr-libc <http://avr-libc.nongnu.org/>`_\ . See also -------- -- `sin <http://arduino.cc/en/Reference/Sin>`_\ () -- `tan <http://arduino.cc/en/Reference/Tan>`_\ () -- `float <http://arduino.cc/en/Reference/Float>`_ -- `double <http://arduino.cc/en/Reference/Double>`_ +- :ref:`sin() <arduino-sin>` +- :ref:`tan() <arduino-tan>` +- :ref:`float <arduino-float>` +- :ref:`double <arduino-double>` diff --git a/docs/source/arduino/define.rst b/docs/source/arduino/define.rst index 6190cb9..e718775 100644 --- a/docs/source/arduino/define.rst +++ b/docs/source/arduino/define.rst @@ -1,83 +1,53 @@ -.. _arduino-define: - -Define -====== - -``#define`` is a useful C component that allows the programmer to -give a name to a constant value before the program is compiled. -Defined constants in arduino don't take up any program memory space -on the chip. The compiler will replace references to these -constants with the defined value at compile time. - - - -This can have some unwanted side effects though, if for example, a -constant name that had been #defined is included in some other -constant or variable name. In that case the text would be replaced -by the #defined number (or text). - - - -In general, the *`const <http://arduino.cc/en/Reference/Const>`_* -keyword is preferred for defining constants and should be used -instead of #define. +.. highlight:: cpp +.. _arduino-define: +#define +======= -Arduino defines have the same syntax as C defines: +``#define`` is a useful C and C++ feature that allows the programmer +to give a name to a constant value before the program is compiled. +The compiler will replace references to these constants with the +defined value at compile time. +This can have some unwanted side effects. In general, the :ref:`const +<arduino-const>` keyword is preferred for defining constants. Syntax ------ -``#define constantName value`` +The following line would define the name ``MY_CONSTANT`` to have value +``value``:: + + #define MY_CONSTANT value +Note that the ``#`` is necessary. It is usually good style for the +name to be capitalized, although this is not required. +There is no semicolon after the #define statement. If you include one, +the compiler will likely throw cryptic errors in unrelated places. +That is, **don't do this**:: -Note that the # is necessary. + // DON'T DO THIS! THE SEMICOLON SHOULDN'T BE THERE! + #define NAME value; +Similarly, including an equal sign after the ``#define`` line will +also generate a cryptic compiler error further down the page. That +is, **don't do this, either**:: + // DON'T DO THIS, EITHER! THE EQUALS SIGN SHOULDN'T BE THERE! + #define NAME = value Example ------- :: - #define ledPin 3 - // The compiler will replace any mention of ledPin with the value 3 at compile time. - - - -Tip ---- - -There is no semicolon after the #define statement. If you include -one, the compiler will throw cryptic errors further down the page. - - - -:: - - #define ledPin 3; // this is an error - - - -Similarly, including an equal sign after the #define statement will -also generate a cryptic compiler error further down the page. - - - -:: - - #define ledPin = 3 // this is also an error - - - -See ---- - - -- `const <http://arduino.cc/en/Reference/Const>`_ -- `Constants <http://arduino.cc/en/Reference/IntegerConstants>`_ + #define LED_PIN 13 + // The compiler will replace any mention of LED_PIN with + // the value 3 at compile time. +See Also +-------- +- :ref:`const <arduino-const>` diff --git a/docs/source/arduino/delay.rst b/docs/source/arduino/delay.rst index 973c75b..644e8c4 100644 --- a/docs/source/arduino/delay.rst +++ b/docs/source/arduino/delay.rst @@ -1,35 +1,40 @@ +.. highlight:: cpp + .. _arduino-delay: delay() ======= -Description ------------ - -Pauses the program for the amount of time (in miliseconds) -specified as parameter. (There are 1000 milliseconds in a second.) - - - -Syntax ------- +Pauses the program for at least a given number of milliseconds. (There +are 1000 milliseconds in a second.) -delay(ms) +Library Documentation +--------------------- +.. doxygenfunction:: delay -Parameters +Discussion ---------- -ms: the number of milliseconds to pause (*unsigned long*) - - - -Returns -------- - -nothing - +While it is easy to create a blinking LED with the ``delay()`` +function, and many sketches use short delays for such tasks as switch +debouncing, the use of ``delay()`` in a sketch has significant +drawbacks. No other reading of sensors, mathematical calculations, or +pin manipulation can go on during the delay function, so in effect, it +brings most other activity to a halt. For alternative approaches to +controlling timing see the :ref:`millis() <arduino-millis>` function +and the "Blink Without Delay" sketch cited :ref:`below +<arduino-delay-seealso>`\ . More knowledgeable programmers usually +avoid the use of ``delay()`` for timing of events longer than tens of +milliseconds, unless the sketch is very simple. + +Certain things *do* go on while the ``delay()`` function is +controlling the STM32 chip, however, because the delay function does +not disable interrupts. Serial communication that appears at the RX +pin is recorded, PWM (see :ref:`pwmWrite() <wirish-pwmwrite>`\ ) +values and pin states are maintained, and :ref:`interrupts +<arduino-attachinterrupt>` will work as they should. Example @@ -37,58 +42,26 @@ Example :: - int ledPin = 13; // LED connected to digital pin 13 + int ledPin = 13; // LED connected to pin 13 - void setup() - { + void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } - void loop() - { + void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second } - - -Caveat ------- - -While it is easy to create a blinking LED with the delay() -function, and many sketches use short delays for such tasks as -switch debouncing, the use of delay() in a sketch has significant -drawbacks. No other reading of sensors, mathematical calculations, -or pin manipulation can go on during the delay function, so in -effect, it brings most other activity to a halt. For alternative -approaches to controlling timing see the -`millis() <http://arduino.cc/en/Reference/Millis>`_ function and -the sketch sited below. More knowledgeable programmers usually -avoid the use of delay() for timing of events longer than 10's of -milliseconds unless the Arduino sketch is very simple. - - - -Certain things *do* go on while the delay() function is controlling -the Atmega chip however, because the delay function does not -disable interrupts. Serial communication that appears at the RX pin -is recorded, PWM -(`analogWrite <http://arduino.cc/en/Reference/AnalogWrite>`_) -values and pin states are maintained, and -`interrupts <http://arduino.cc/en/Reference/AttachInterrupt>`_ will -work as they should. - - +.. _arduino-delay-seealso: See also -------- -- `millis <http://arduino.cc/en/Reference/Millis>`_\ () -- `micros <http://arduino.cc/en/Reference/Micros>`_\ () -- `delayMicroseconds <http://arduino.cc/en/Reference/DelayMicroseconds>`_\ () -- `Blink Without Delay <http://arduino.cc/en/Tutorial/BlinkWithoutDelay>`_ - example - +- :ref:`millis() <arduino-millis>` +- :ref:`micros() <arduino-micros>` +- :ref:`delayMicroseconds() <arduino-delayMicroseconds>` +- (Arduino) `Blink Without Delay <http://arduino.cc/en/Tutorial/BlinkWithoutDelay>`_ example (works unmodified on Maple) diff --git a/docs/source/arduino/delaymicroseconds.rst b/docs/source/arduino/delaymicroseconds.rst index 0feaba7..2c7cde6 100644 --- a/docs/source/arduino/delaymicroseconds.rst +++ b/docs/source/arduino/delaymicroseconds.rst @@ -1,60 +1,34 @@ +.. highlight:: cpp + .. _arduino-delaymicroseconds: delayMicroseconds() =================== -Description ------------ - Pauses the program for the amount of time (in microseconds) specified as parameter. There are a thousand microseconds in a millisecond, and a million microseconds in a second. +Library Documentation +--------------------- - -Currently, the largest value that will produce an accurate delay is -16383. This could change in future Arduino releases. For delays -longer than a few thousand microseconds, you should use delay() -instead. - - - -Syntax ------- - -delayMicroseconds(us) - - - -Parameters ----------- - -us: the number of microseconds to pause (*unsigned int*) - - - -Returns -------- - -None - +.. doxygenfunction:: delayMicroseconds Example ------- -:: - +The following example configures pin number 8 to work as an output +pin, and sends a train of pulses with a period of roughly 100 +microseconds:: - int outPin = 8; // digital pin 8 + int outPin = 8; - void setup() - { + void setup() { pinMode(outPin, OUTPUT); // sets the digital pin as output } - void loop() - { + void loop() { digitalWrite(outPin, HIGH); // sets the pin on delayMicroseconds(50); // pauses for 50 microseconds digitalWrite(outPin, LOW); // sets the pin off @@ -62,32 +36,27 @@ Example } - -configures pin number 8 to work as an output pin. It sends a train -of pulses with 100 microseconds period. - - - Caveats and Known Issues ------------------------ -This function works very accurately in the range 3 microseconds and -up. We cannot assure that delayMicroseconds will perform precisely -for smaller delay-times. - +The longest time ``delayMicroseconds()`` can delay is bounded by its +argument type and the STM32 clock rate to be (2^32 - 1) / 12 +microseconds, or less than 6 minutes. For longer pauses, use of +:ref:`arduino-delay` is possible. +Arduino Compatibility +--------------------- -As of Arduino 0018, delayMicroseconds() no longer disables -interrupts. +While we have made every effort we could to ensure that the timing of +delayMicroseconds is as accurate as possible, we cannot guarantee it +will behave as the Arduino implementation down to the microsecond, +especially for smaller values of ``us``. - - -See also +See Also -------- - -- `millis <http://arduino.cc/en/Reference/Millis>`_\ () -- `micros <http://arduino.cc/en/Reference/Micros>`_\ () -- `delay <http://arduino.cc/en/Reference/Delay>`_\ () +- :ref:`millis <arduino-millis>` +- :ref:`micros <arduino-micros>` +- :ref:`delay <arduino-delay>` diff --git a/docs/source/arduino/detachinterrupt.rst b/docs/source/arduino/detachinterrupt.rst index f0342df..f770de1 100644 --- a/docs/source/arduino/detachinterrupt.rst +++ b/docs/source/arduino/detachinterrupt.rst @@ -1,26 +1,34 @@ .. _arduino-detachinterrupt: -detachInterrupt(interrupt) -========================== +detachInterrupt() +================= -Description ------------ +Used to disable an interrupt specified with +:ref:`arduino-attachinterrupt`\ . -Turns off the given interrupt. +Library Documentation +--------------------- +.. doxygenfunction:: detachInterrupt -Parameters ----------- +Arduino Compatibility +--------------------- -interrupt: the number of interrupt to disable (0 or 1). +There is one important difference between the Maple version of +detachInterrupt and the Arduino version. On the Maple, the argument +to ``detachInterrupt()`` is the *pin* on which the interrupt is +attached, while on the Arduino, the argument is the *interrupt +number*, which is different from the pin the interrupt is enabled on. +If you're calling this function, you've already called +:ref:`arduino-attachinterrupt` to set up your interrupt handler, so +just call ``detachInterrupt()`` with the same pin argument you gave to +``attachInterrupt()``. - -See also +See Also -------- - -- `attachInterrupt <http://arduino.cc/en/Reference/AttachInterrupt>`_\ () +- :ref:`attachInterrupt() <arduino-attachInterrupt>` diff --git a/docs/source/arduino/digitalread.rst b/docs/source/arduino/digitalread.rst index ec64fb0..86e52d8 100644 --- a/docs/source/arduino/digitalread.rst +++ b/docs/source/arduino/digitalread.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-digitalread: digitalRead() @@ -6,81 +8,51 @@ digitalRead() Description ----------- -Reads the value from a specified digital pin, either -`HIGH <http://arduino.cc/en/Reference/Constants>`_ or -`LOW <http://arduino.cc/en/Reference/Constants>`_. - - - -Syntax ------- - -digitalRead(pin) +Reads the value from a specified digital pin, either :ref:`HIGH +<arduino-constants-high>` or :ref:`LOW <arduino-constants-low>`. +Library Documentation +--------------------- -Parameters ----------- - -pin: the number of the digital pin you want to read (*int*) - - - -Returns -------- - -`HIGH <http://arduino.cc/en/Reference/Constants>`_ or -`LOW <http://arduino.cc/en/Reference/Constants>`_ - +.. doxygenfunction:: digitalRead Example ------- -:: +The following example turns the LED on when the button is pressed:: - - int ledPin = 13; // LED connected to digital pin 13 - int inPin = 7; // pushbutton connected to digital pin 7 - int val = 0; // variable to store the read value + int ledPin = 13; // LED connected to Maple pin 13 + int buttonPin = 38; // BUT connected to Maple pin 38 - void setup() - { - pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output - pinMode(inPin, INPUT); // sets the digital pin 7 as input + void setup() { + pinMode(ledPin, OUTPUT); + pinMode(buttonPin, INPUT); } - void loop() - { - val = digitalRead(inPin); // read the input pin - digitalWrite(ledPin, val); // sets the LED to the button's value + void loop() { + int val = digitalRead(buttonPin); // reads the input pin + digitalWrite(ledPin, val); } - - -Sets pin 13 to the same value as the pin 7, which is an input. - - - Note ---- -If the pin isn't connected to anything, digitalRead() can return -either HIGH or LOW (and this can change randomly). - - +If the pin isn't connected to anything, ``digitalRead()`` can return +either HIGH or LOW (and this can change in a way that seems random). -The analog input pins can be used as digital pins, referred to as -A0, A1, etc. +Arduino Compatibility +--------------------- +The Maple version of ``digitalRead()`` is compatible with Arduino. -See also +See Also -------- +- :ref:`pinMode <arduino-pinMode>` +- :ref:`digitalWrite <arduino-digitalWrite>` -- `pinMode <http://arduino.cc/en/Reference/PinMode>`_\ () -- `digitalWrite <http://arduino.cc/en/Reference/DigitalWrite>`_\ () -- `Tutorial: Digital Pins <http://arduino.cc/en/Tutorial/DigitalPins>`_ diff --git a/docs/source/arduino/double.rst b/docs/source/arduino/double.rst index 4e7f20c..658af12 100644 --- a/docs/source/arduino/double.rst +++ b/docs/source/arduino/double.rst @@ -3,30 +3,44 @@ double ====== -Desciption ----------- +Description +----------- -Double precision floating point number. Occupies 4 bytes. +Double precision floating point number. Occupies 8 bytes. +Floating point numbers are not exact, and may yield strange results +when compared. For example ``6.0 / 3.0`` may not equal ``2.0``. You +should instead check that the absolute value of the difference between +the numbers is less than some small number. +Floating point math is also much slower than integer math in +performing calculations, so should be avoided if, for example, a loop +has to run at top speed for a critical timing function. Programmers +often go to some lengths to convert floating point calculations to +integer math to increase speed. -The double implementation on the Arduino is currently exactly the -same as the float, with no gain in precision. +For more information about floating point math, see the `Wikipedia +article <http://en.wikipedia.org/wiki/Floating_point>`_\ . +Floating-point numbers represent numbers with "decimal point", unlike +integral types, which always represent whole numbers. Floating-point +numbers are often used to approximate analog and continuous values +because they have greater resolution than integers. +The double implementation on the Maple uses twice the number of bytes +as a :ref:`float <arduino-float>`, with the corresponding gains in +precision. Tip --- Users who borrow code from other sources that includes double variables may wish to examine the code to see if the implied -precision is different from that actually achieved on the Arduino. +precision is different from that actually achieved on the Maple. +See Also +-------- -See: ----- - - -- `float <http://arduino.cc/en/Reference/Float>`_ +- :ref:`float <arduino-float>` diff --git a/docs/source/arduino/dowhile.rst b/docs/source/arduino/dowhile.rst index 48fe75b..697e4b7 100644 --- a/docs/source/arduino/dowhile.rst +++ b/docs/source/arduino/dowhile.rst @@ -1,33 +1,24 @@ -.. _arduino-dowhile: - -do - while -========== +.. highlight:: cpp -The **do** loop works in the same manner as the **while** loop, -with the exception that the condition is tested at the end of the -loop, so the **do** loop will *always* run at least once. +.. _arduino-dowhile: +do/while Loop +============= +A ``do`` loop works in the same manner as a :ref:`while +<arduino-while>` loop, with the exception that the condition is tested +at the end of the loop, so the ``do`` loop will *always* run at least +once. -:: +This is the basic syntax:: - do - { + do { // statement block } while (test condition); +Example:: - -Example -------- - -:: - - do - { + do { delay(50); // wait for sensors to stabilize x = readSensors(); // check the sensors - } while (x < 100); - - diff --git a/docs/source/arduino/else.rst b/docs/source/arduino/else.rst index f278a0d..e94bb25 100644 --- a/docs/source/arduino/else.rst +++ b/docs/source/arduino/else.rst @@ -1,73 +1,51 @@ -.. _arduino-else: - -if / else -========= - -**if/else** allows greater control over the flow of code than the -basic **if** statement, by allowing multiple tests to be grouped -together. For example, an analog input could be tested and one -action taken if the input was less than 500, and another action -taken if the input was 500 or greater. The code would look like -this: +.. highlight:: cpp +.. _arduino-else: +if/else +======= -:: +``if``/\ ``else`` allows greater control over the flow of code than +the basic :ref:`if <arduino-if>` statement, by allowing multiple tests +to be grouped together. For example, an :ref:`analog input +<arduino-analogread>` could be tested, with one action taken if the +input was less than 500, and another action taken if the input was 500 +or greater. The code would look like this:: - if (pinFiveInput < 500) - { + if (pinFiveInput < 500) { // action A - } - else - { + } else { // action B } - - -**else** can proceed another **if** test, so that multiple, -mutually exclusive tests can be run at the same time. - - +``else`` can precede another ``if`` test, so that multiple, mutually +exclusive tests can be run at the same time. Each test will proceed to the next one until a true test is -encountered. When a true test is found, its associated block of -code is run, and the program then skips to the line following the -entire if/else construction. If no test proves to be true, the -default **else** block is executed, if one is present, and sets the -default behavior. +encountered. When a true test is found, its associated block of code +is run, and the program then skips to the line following the entire +if/else construction. If no test proves to be true, the default +``else`` block is executed, if one is present, and sets the default +behavior. +Note that an ``else if`` block may be used with or without a +terminating ``else`` block, and vice-versa. An unlimited number of +such ``else if`` branches is allowed. Here is a code example:: -Note that an **else if** block may be used with or without a -terminating **else** block and vice versa. An unlimited number of -such **else if** branches is allowed. - - - -:: - - if (pinFiveInput < 500) - { + if (pinFiveInput < 500) { // do Thing A - } - else if (pinFiveInput >= 1000) - { + } else if (pinFiveInput >= 1000) { // do Thing B - } - else - { + } else { // do Thing C } -Another way to express branching, mutually exclusive tests, is with -the `switch case <http://arduino.cc/en/Reference/SwitchCase>`_ -statement. - - - -See also: ---------- +Another way to express branching, mutually exclusive tests, is with a +:ref:`switch/case <arduino-switchcase>` statement. -`switch case <http://arduino.cc/en/Reference/SwitchCase>`_ +See Also +-------- +- :ref:`if <arduino-if>` +- :ref:`switch/case <arduino-switchcase>` diff --git a/docs/source/arduino/float.rst b/docs/source/arduino/float.rst index 2f83a67..683f32d 100644 --- a/docs/source/arduino/float.rst +++ b/docs/source/arduino/float.rst @@ -1,88 +1,55 @@ +.. highlight:: cpp + .. _arduino-float: float ===== +.. TODO move all the useful examples over to arduino/double.rst. We +.. want to discourage using floats, since most of the common cmath +.. functions are only declared with doubles. + Description ----------- -Datatype for floating-point numbers, a number that has a decimal -point. Floating-point numbers are often used to approximate analog -and continuous values because they have greater resolution than -integers. Floating-point numbers can be as large as 3.4028235E+38 -and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) -of information. - - - -Floats have only 6-7 decimal digits of precision. That means the -total number of digits, not the number to the right of the decimal -point. Unlike other platforms, where you can get more precision by -using a double (e.g. up to 15 digits), on the Arduino, double is -the same size as float. - - +Single-precision floating point number. ``float`` values can be as +large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored +as 32 bits (4 bytes) of information. -Floating point numbers are not exact, and may yield strange results -when compared. For example ``6.0 / 3.0`` may not equal ``2.0``. You -should instead check that the absolute value of the difference -between the numbers is less than some small number. +``float``\ s have only 6-7 decimal digits of precision. That means the total +number of digits, not the number to the right of the decimal point. +You can get more precision by using a :ref:`double <arduino-double>` +(which has a precision of about 16 decimal digits). - - -Floating point math is also much slower than integer math in -performing calculations, so should be avoided if, for example, a -loop has to run at top speed for a critical timing function. -Programmers often go to some lengths to convert floating point -calculations to integer math to increase speed. - - - -Examples --------- - -:: +The following example declares a ``float`` value named ``myfloat``:: float myfloat; - float sensorCalbrate = 1.117; - +This example declares a ``float`` value named ``sensorCalibrate``, +with value 1.117:: -Syntax ------- + float sensorCalibrate = 1.117; -:: +The general syntax for declaring a float named ``var`` with value +``val`` is:: float var = val; - - - -- var - your float variable name -- val - the value you assign to that variable - - - -Example Code ------------- - -:: +Here is a more extended example involving a :ref:`float cast +<arduino-floatcast>`:: int x; int y; float z; x = 1; - y = x / 2; // y now contains 0, ints can't hold fractions - z = (float)x / 2.0; // z now contains .5 (you have to use 2.0, not 2) - - + y = x / 2; // y now contains 0, ints can't hold fractions + z = float(x) / 2; // z now contains .5 See Also -------- - -- `int <http://arduino.cc/en/Reference/Int>`_ -- `double <http://arduino.cc/en/Reference/Double>`_ -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ +- :ref:`int <arduino-int>` +- :ref:`double <arduino-double>` +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/floatcast.rst b/docs/source/arduino/floatcast.rst index 6b85727..773bfe9 100644 --- a/docs/source/arduino/floatcast.rst +++ b/docs/source/arduino/floatcast.rst @@ -1,51 +1,26 @@ +.. highlight:: cpp + .. _arduino-floatcast: -float() -======= +float() (cast) +============== Description ----------- -Converts a value to the -`float <http://arduino.cc/en/Reference/Float>`_ data type. - - - -Syntax ------- - -float(x) - - - -Parameters ----------- - -x: a value of any type - +Converts a value to the :ref:`float <arduino-float>` data type. Here +is an example:: + int x = 2; + float f = float(x); // f now holds "2.0", a floating point value -Returns -------- +The value ``x`` can be of any type. However, if ``x`` is not a number +(like an ``int`` or ``long``), you will get strange results. -float +See the :ref:`float <arduino-float>` reference for details about the +precision and limitations of ``float`` values on the Maple. - - -Notes ------ - -See the reference for -`float <http://arduino.cc/en/Reference/Float>`_ for details about -the precision and limitations of floating point numbers on -Arduino. - - - -See also +See Also -------- - -- `float <http://arduino.cc/en/Reference/Float>`_ - - +- :ref:`float <arduino-float>` diff --git a/docs/source/arduino/for.rst b/docs/source/arduino/for.rst index b7e2e95..cc18722 100644 --- a/docs/source/arduino/for.rst +++ b/docs/source/arduino/for.rst @@ -1,117 +1,139 @@ -.. _arduino-for: - -for statements -============== - -Desciption ----------- - -The **for** statement is used to repeat a block of statements -enclosed in curly braces. An increment counter is usually used to -increment and terminate the loop. The **for** statement is useful -for any repetitive operation, and is often used in combination with -arrays to operate on collections of data/pins. - - - -There are three parts to the **for** loop header: - - - -``<strong>for</strong> (<strong>initialization</strong>;<strong> condition</strong>;<strong> increment</strong>) {`` +.. highlight:: cpp +.. _arduino-for: +for Loops +========= -``//statement(s);`` - - - -``}`` - -|image0| - +.. contents:: Contents + :local: -The **initialization** happens first and exactly once. Each time -through the loop, the **condition** is tested; if it's true, the -statement block, and the **increment** is executed, then the -**condition** is tested again. When the **condition** becomes -false, the loop ends. +Description +----------- +A ``for`` loop is used to repeat a block of statements enclosed in +curly braces. ``for`` loops are useful for performing repetitive +operations, and are often used in combination with :ref:`arrays +<arduino-array>` to operate on collections of data or multiple +:ref:`pins <gpio>`. A ``for`` loop is composed of two parts: first, a +*header*, which sets up the for loop, and then a *body*, which is made +up of lines of code enclosed in curly braces. + +There are three parts to the ``for`` loop header: an *initialization* +expression, *loop condition* expression, and a *post-loop* +expression. The general syntax looks like this:: + + for (initialization; condition; post-loop) { + // all of these lines inside the curly braces are part + // of the loop body. + statement 1; + statement 2; + ... + } +(Note that there is no semicolon after the post-loop). The +initialization happens first and exactly once, before the loop begins. +Each time through the loop, the condition is tested. The condition is +a :ref:`boolean arduino-boolean` expression. If it is true, then the +list of statements inside the curly braces are executed. Next, the +post-loop is executed. The loop then begins again by evaluating the +condition again, entering the loop body if it is true. This proceeds +until the condition becomes false. -Example -------- +Examples +-------- -:: +Here's an example:: // Dim an LED using a PWM pin - int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10 - - void setup() - { - // no setup needed - } - - void loop() - { - for (int i=0; i <= 255; i++){ - analogWrite(PWMpin, i); - delay(10); - } + int pwmPin = 9; // LED in series with 470 ohm resistor on pin 9 + + void setup() { + pinMode(pwmPin, PWM); } + void loop() { + for (int i=0; i <= 65535; i++) { + pwmWrite(pwmPin, i); + delay(1); + } + } +There is a ``for`` loop In the :ref:`loop() <arduino-loop>` function +of the above example. This loop starts by declaring an ``int`` +variable named ``i``, whose value starts out at zero. The loop +proceeds by checking if ``i`` is less than or equal to 65535. Since +``i`` is zero, this is true, and so the calls to :ref:`pwmWrite() +<wirish-pwmwrite>` and :ref:`arduino-delay` happen next. At this +point, the post-loop expression ``i++`` is evaluated, which +:ref:`increments <arduino-increment>` ``i``, so that ``i`` becomes +one. That concludes the first time through the loop. Each "time +through the loop" is referred to as an *iteration*. + +The loop then jumps back to the beginning, checking the condition as +the beginning of its second iteration (initialization is skipped, +since this only happens once, before the first iteration). One is +less than 65535, so the loop statements are executed again. This +proceeds over and over until the iteration when ``i`` finally +reaches 65536. At that point, the condition is no longer true, so the +loop stops executing, and the ``loop()`` function returns. + +Here's another example, using a ``for`` loop to brighten and fade an +LED (see the :ref:`pwmWrite() <wirish-pwmwrite>` reference for more +information):: + + int pwmPin = 9; // hook up the LED to pin 9 + void loop() { + int x = 1; + for (int i = 0; i >= 0; i += x) { + analogWrite(pwmPin, i); // controls the brightness of the LED + if (i == 65535) { + x = -1; // switch direction, so i starts decreasing + } + delay(1); + } + } Coding Tips ----------- -The C **for** loop is much more flexible than **for** loops found -in some other computer languages, including BASIC. Any or all of -the three header elements may be omitted, although the semicolons -are required. Also the statements for initialization, condition, -and increment can be any valid C statements with unrelated -variables, and use any C datatypes including floats. These types of -unusual **for** statements may provide solutions to some rare +The C ``for`` loop is more flexible than ``for`` loops found in some +other computer languages, including BASIC. Any or all of the three +header elements may be left blank, although the semicolons are +required. Also the statements for initialization, condition, and +post-loop can be any valid C statements, and use any C datatypes, +including :ref:`floating point numbers <arduino-double>`. These types +of unusual ``for`` loops sometimes provide solutions to less-common programming problems. +For example, using a multiplication in the post-loop line will +generate a `geometric progression +<http://en.wikipedia.org/wiki/Geometric_progression>`_:: - -For example, using a multiplication in the increment line will -generate a logarithmic progression: - -:: - - for(int x = 2; x < 100; x = x * 1.5){ - println(x); + for(int x = 1; x <= 100; x = x * 2) { + SerialUSB.println(x); } +This loop prints out the numbers 1, 2, 4, 8, ..., 64. Check +your understanding of ``for`` loops by answering the following two +questions (answers are in footnote [#fanswers]_\ ): -Generates: 2,3,4,6,9,13,19,28,42,63,94 - - - -Another example, fade an LED up and down with one **for** loop: - - - -:: - - void loop() - { - int x = 1; - for (int i = 0; i > -1; i = i + x){ - analogWrite(PWMpin, i); - if (i = 255) x = -1; // switch direction at peak - delay(10); - } - } - +1. How many iterations occur before the loop finishes? +2. Why does it stop at 64? See also -------- +- :ref:`while <arduino-while>` loops +- :ref:`do <arduino-dowhile>` loops + +.. rubric:: Footnotes -- `while <http://arduino.cc/en/Reference/While>`_ +.. [#fanswers] + 1. Seven. + 2. After the seventh iteration, the post-loop causes ``x`` to + equal 128. This is larger than 100, so the loop condition is + false, and the loop stops. diff --git a/docs/source/arduino/fpconstants.rst b/docs/source/arduino/fpconstants.rst deleted file mode 100644 index 284342b..0000000 --- a/docs/source/arduino/fpconstants.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. _arduino-fpconstants: - -floating point constants -======================== - -Similar to integer constants, floating point constants are used to -make code more readable. Floating point constants are swapped at -compile time for the value to which the expression evaluates. - - - -Examples: - - - -``n = .005;`` - - - -Floating point constants can also be expressed in a variety of -scientific notation. 'E' and 'e' are both accepted as valid -exponent indicators. - - - -:: - - - floating-point evaluates to: also evaluates to: - constant - - 10.0 10 - 2.34E5 2.34 * 10^5 234000 - 67e-12 67.0 * 10^-12 .000000000067 - - diff --git a/docs/source/arduino/goto.rst b/docs/source/arduino/goto.rst index 1fcceb7..b19d424 100644 --- a/docs/source/arduino/goto.rst +++ b/docs/source/arduino/goto.rst @@ -1,55 +1,127 @@ -.. _arduino-goto: - -goto -==== - -Transfers program flow to a labeled point in the program - - - -Syntax ------- - -label: - - - -goto label; // sends program flow to the label - - +.. highlight:: cpp -Tip ---- - -The use of *goto* is discouraged in C programming, and some authors -of C programming books claim that the *goto* statement is never -necessary, but used judiciously, it can simplify certain programs. -The reason that many programmers frown upon the use of *goto* is -that with the unrestrained use of *goto* statements, it is easy to -create a program with undefined program flow, which can never be -debugged. - - - -With that said, there are instances where a goto statement can come -in handy, and simplify coding. One of these situations is to break -out of deeply nested *for* loops, or *if* logic blocks, on a -certain condition. +.. _arduino-goto: +Labels and goto +=============== + +A *label* gives a name to a line of code within a function. You can +label a line by writing a name for it, then a colon (``:``), before +the line starts. The ``goto`` keyword allows program flow to transfer +to a labeled line from anywhere within the same function. + +.. warning:: The use of ``goto`` is discouraged in C and C++ + programming. It is *never necessary* to use ``goto`` to write a + program. + + Unless you know what you're doing, using ``goto`` tends to + encourage code which is harder to debug and understand than + programs without ``goto`` that do the same thing. That said, + however, it's sometimes useful; :ref:`see below <goto-when-to-use>` + for a concrete example. + +Using Labels and goto +--------------------- + +Labels and ``goto`` are probably best explained through example. +Let's start with an example of how to label lines. The first line +(``int x = analogRead(some_pin);``) in the :ref:`loop <arduino-loop>` +function below has label ``readpin``. The third line (``delay(x);``) +has label ``startdelay``. The second line (``SerialUSB.println(x);``) +does not have a label:: + + void loop() { + readpin: + int x = analogRead(some_pin); + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +Anything which can be a :ref:`variable <arduino-variables>` name can +be a label. + +Let's say that we wanted to print ``x`` only if it was very large, say +at least 2000. We might want to do this just so anybody watching on a +:ref:`serial monitor <ide-serial-monitor>` would know they were in for +a longer wait than usual. We can accomplish this through the use of a +``goto`` statement that skips the printing if ``x`` is less than +2000:: + + void loop() { + readpin: + int x = analogRead(some_pin); + if (x < 2000) { + goto startdelay; + } + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +In this modified program, whenever ``x`` is less than 2000, the body +of the :ref:`if <arduino-if>` statement in the second line is +executed. The ``goto`` statement inside the ``if`` body skips +straight to the line labeled ``startdelay``, passing over the line +doing the printing. + +A ``goto`` does not have to "move forwards"; it can go "backwards", +too. For example, the following program prints "5" forever (why?):: + + void loop() { + printfive: + SerialUSB.println(5); + goto printfive; + SerialUSB.println(6); + } +.. _goto-when-to-use: -Example -------- +When to Use goto +---------------- -:: +As mentioned above, use of ``goto`` is `generally discouraged +<http://en.wikipedia.org/wiki/Goto#Criticism_and_decline>`_. However, +when used with care, ``goto`` can simplify certain programs. One +important use case for ``goto`` is breaking out of deeply nested +:ref:`for <arduino-for>` loops or :ref:`if <arduino-if>` logic blocks. +Here's an example:: - for(byte r = 0; r < 255; r++){ - for(byte g = 255; g > -1; g--){ - for(byte b = 0; b < 255; b++){ - if (analogRead(0) > 250){ goto bailout;} + for(int r = 0; r < 255; r++) { + for(int g = 255; g > -1; g--) { + for(int b = 0; b < 255; b++) { + if (analogRead(0) > 250) { + goto bailout; + } // more statements ... } + // innermost loop ends here } } bailout: + // more code here + +In the above example, whenever the :ref:`analog reading +<arduino-analogread>` on pin 0 was greater than 250, the program would +jump to the line labeled ``bailout``, exiting all three loops at once. + +While there is already a :ref:`break <arduino-break>` keyword for +breaking out of a loop, it will only break out of the *innermost* +loop. So, if instead of saying "``goto bailout;``", there was a +"``break;``" instead, the program would only exit from the loop with +header "``for(int b = 0; b < 255; b++)``". The program would continue +at the line which reads "``// innermost loop ends here``", which is +clearly undesirable if you wanted to leave all three loops at once. + +More examples of when ``goto`` is a good choice are given in Donald +Knuth's paper, "Structured Programming with go to Statements"; see +below for a link. + +See Also +-------- + +- Dijkstra, Edsger W. `Go To Statement Considered Harmful <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.92.4846&rep=rep1&type=pdf>`_ (PDF) +- Knuth, Donald. `Structured Programming with go to Statements <http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf>`_ (PDF) diff --git a/docs/source/arduino/highbyte.rst b/docs/source/arduino/highbyte.rst index dc6a1d6..0682391 100644 --- a/docs/source/arduino/highbyte.rst +++ b/docs/source/arduino/highbyte.rst @@ -1,42 +1,50 @@ .. _arduino-highbyte: -highByte() -========== - -Description ------------ - -Extracts the high-order (leftmost) byte of a word (or the second -lowest byte of a larger data type). - - +highByte(x) +=========== -Syntax ------- +.. warning:: This macro is provided for compatibility with Arduino + only. It returns the second-least significant byte in an integral + value. It makes sense to call this the "high" byte on a 16-bit + microcontroller like the Atmel chips on Arduinos, but it makes no + sense at all on a 32-bit microcontroller like the STM32s in the + Maple line. -highByte(x) + In short: we provide this so that existing Arduino code works as + expected, but **strongly discourage its use** in new programs. +Description +----------- +(Macro) Extracts the second lowest byte of an integral data type. Parameters ---------- -x: a value of any type +**x**: a value of any integral type. +Returns +------- +Second lowest byte in **x**. -Returns +Example ------- -byte +:: + + int x = 0xDEADBEEF; + SerialUSB.println(x, HEX); // prints "BE" +Arduino Compatibility +--------------------- +The Maple version of ``highByte()`` is compatible with Arduino. -See also +See Also -------- +- :ref:`lowByte() <arduino-lowbyte>` -- `lowByte <http://arduino.cc/en/Reference/LowByte>`_\ () -- `word <http://arduino.cc/en/Reference/WordCast>`_\ () diff --git a/docs/source/arduino/if.rst b/docs/source/arduino/if.rst index d75f6d3..00f1a4d 100644 --- a/docs/source/arduino/if.rst +++ b/docs/source/arduino/if.rst @@ -1,95 +1,78 @@ -.. _arduino-if: +.. highlight:: cpp -if (conditional) and ==, !=, <, > (comparison operators) -======================================================== +.. _arduino-if: -**``if``**, which is used in conjunction with a comparison -operator, tests whether a certain condition has been reached, such -as an input being above a certain number. The format for an if test -is: +if Statements +============= +An ``if`` statement is used to execute code when certain conditions +are met. The general syntax for an ``if`` statement is:: + if (condition) { + body + } -:: +An ``if`` statement first tests whether its *condition* is true (such +as an input being above a certain number). If the condition is true, +the ``if`` statement executes its *body*, which is made up of lines of +code inside :ref:`curly braces <arduino-braces>`. If the condition is +false, the body is not executed. Here's a more concrete example:: - if (someVariable > 50) - { + if (someVariable > 50) { // do something here } +The program tests to see if ``someVariable`` is greater than 50. If it +is, the program executes every line in the curly braces (which in the +above example does nothing, since the body is just the :ref:`comment +<arduino-comments>` line "``// do something here``"). +Put another way, if the statement in parentheses is true, the +statements inside the braces are run. If not, the program skips over +the code. -The program tests to see if someVariable is greater than 50. If it -is, the program takes a particular action. Put another way, if the -statement in parentheses is true, the statements inside the -brackets are run. If not, the program skips over the code. +An ``if`` statement's condition (which is inside the parentheses after +``if``) often uses one or more :ref:`boolean <arduino-boolean>` or +:ref:`comparison <arduino-comparison>` operators. +Writing the if Body +------------------- +The brackets may be omitted after an ``if`` statement's +conditional. If this is done, the next line (which ends in a +semicolon) becomes the only line in the body. The following three +``if`` statements all do the same thing:: -The brackets may be omitted after an *if* statement. If this is -done, the next line (defined by the semicolon) becomes the only -conditional statement. + if (x > 120) digitalWrite(ledPin, HIGH); -:: - - - if (x > 120) digitalWrite(LEDpin, HIGH); - if (x > 120) - digitalWrite(LEDpin, HIGH); - - if (x > 120){ digitalWrite(LEDpin, HIGH); } - - if (x > 120){ - digitalWrite(LEDpin1, HIGH); - digitalWrite(LEDpin2, HIGH); - } // all are correct - - - -The statements being evaluated inside the parentheses require the -use of one or more operators: - - + digitalWrite(ledPin, HIGH); -Comparison Operators: -~~~~~~~~~~~~~~~~~~~~~ + if (x > 120) { + digitalWrite(ledPin, HIGH); + } -:: +However, the following two examples are different:: - x == y (x is equal to y) - x != y (x is not equal to y) - x < y (x is less than y) - x > y (x is greater than y) - x <= y (x is less than or equal to y) - x >= y (x is greater than or equal to y) + // example 1: two lines of code in the if body + if (x > 120) { + digitalWrite(ledPin1, HIGH); + digitalWrite(ledPin2, HIGH); + } + // example 2: one line of code in the if body, and + // another line of code after the if statement + if (x > 120) + digitalWrite(ledPin1, HIGH); // this is in the if body + digitalWrite(ledPin2, HIGH); // this is NOT in the if body +In the first example, since the body is enclosed in curly braces, both +lines are included. In the second example, since the curly braces are +missing, only the first line is in the ``if`` body. -Warning: +See Also -------- -Beware of accidentally using the single equal sign -(e.g.``if (x = 10)`` ). The single equal sign is the assignment -operator, and sets x to 10 (puts the value 10 into the variable x). -Instead use the double equal sign (e.g.``if (x == 10)``), which is -the comparison operator, and tests *whether* x is equal to 10 or -not. The latter statement is only true if x equals 10, but the -former statement will always be true. - - - -This is because C evaluates the statement ``if (x=10)`` as follows: -10 is assigned to x (remember that the single equal sign is the -`assignment operator <http://arduino.cc/en/Reference/Assignment>`_), -so x now contains 10. Then the 'if' conditional evaluates 10, which -always evaluates to TRUE, since any non-zero number evaluates to -TRUE. Consequently, ``if (x = 10)`` will always evaluate to TRUE, -which is not the desired result when using an 'if' statement. -Additionally, the variable x will be set to 10, which is also not a -desired action. - - - -**if** can also be part of a branching control structure using the -`if...else <http://arduino.cc/en/Reference/Else>`_] construction. +- :ref:`boolean operators <arduino-boolean>` +- :ref:`comparison operators <arduino-comparison>` +- :ref:`else <arduino-else>` diff --git a/docs/source/arduino/include.rst b/docs/source/arduino/include.rst index 6d53801..da124e5 100644 --- a/docs/source/arduino/include.rst +++ b/docs/source/arduino/include.rst @@ -1,42 +1,68 @@ +.. highlight:: cpp + .. _arduino-include: #include ======== -**#include** is used to include outside libraries in your sketch. +``#include`` is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C -libraries (groups of pre-made functions), and also libraries -written especially for Arduino. - - - -The main reference page for AVR C libraries (AVR is a reference to -the Atmel chips on which the Arduino is based) is -`here. <http://www.nongnu.org/avr-libc/user-manual/modules.html>`_ - - - -Note that **#include**, similar to **#define**, has no semicolon -terminator, and the compiler will yield cryptic error messages if -you add one. - - +libraries (groups of pre-made functions and data types), and also +libraries written especially for Maple. Example ------- -This example includes a library that is used to put data into the -program space *flash* instead of *ram*. This saves the ram space -for dynamic memory needs and makes large lookup tables more -practical. - - - -:: - - #include <avr/pgmspace.h> - - prog_uint16_t myConstants[] PROGMEM = {0, 21140, 702 , 9128, 0, 25764, 8456, - 0,0,0,0,0,0,0,0,29810,8968,29762,29762,4500}; - +This example (from the `Arduino LiquidCrystal Tutorial +<http://arduino.cc/en/Tutorial/LiquidCrystal>`_) includes a library +that is used to control :ref:`LCD displays <liquid-crystal>`:: + + // include the library code: + #include <LiquidCrystal.h> + + // initialize the library with the numbers of the interface pins + LiquidCrystal lcd(12, 11, 5, 4, 3, 2); + + void setup() { + // set up the LCD's number of columns and rows: + lcd.begin(16, 2); + // Print a message to the LCD. + lcd.print("hello, world!"); + } + + void loop() { + // set the cursor to column 0, line 1 + // (note: line 1 is the second row, since counting begins with 0): + lcd.setCursor(0, 1); + // print the number of seconds since reset: + lcd.print(millis()/1000); + } + +Note that a ``#include`` line, like :ref:`#define <arduino-define>`, +has **no semicolon**. The compiler will print strange error messages +if you add one. + +C Standard Library +------------------ + +The standard C library that comes with Maple is called `newlib +<http://sourceware.org/newlib/>`_. Its main sources of documentation +are its `main reference <http://sourceware.org/newlib/libc.html>`_ +page and its `math functions +<http://sourceware.org/newlib/libm.html>`_ reference page. Here's an +example that imports the math.h library in order to take the `cube +root <http://en.wikipedia.org/wiki/Cube_root>`_ of a number:: + + #include <math.h> + + void setup() { + // no setup necessary + } + + void loop() { + // "cbrt" stands for "cube root" + double cubeRootOf3 = cbrt(3.0); + // prints a number that is approximately the cube root of 3: + SerialUSB.println(cubeRootOf3); + } diff --git a/docs/source/arduino/increment.rst b/docs/source/arduino/increment.rst index f9e87c9..ea9cb88 100644 --- a/docs/source/arduino/increment.rst +++ b/docs/source/arduino/increment.rst @@ -1,58 +1,41 @@ -.. _arduino-increment: +.. highlight:: cpp -++ (increment) / -- (decrement) -=============================== +.. _arduino-increment: -Description ------------ +Increment (``++``) and Decrement (``--``) +========================================= -Increment or decrement a variable +These operators increment (add one to) or decrement (subtract one +from) a variable. If they come before the variable, they return its +new value; otherwise, they return its old value. +Some quick examples:: + x++; // adds one to x, and returns the old value of x + ++x; // adds one to x, and returns the new value of x -Syntax ------- + x--; // decrement x by one and returns the old value of x + --x; // decrement x by one and returns the new value of x -:: +A more extended example:: - x++; // increment x by one and returns the old value of x - ++x; // increment x by one and returns the new value of x - - x-- ; // decrement x by one and returns the old value of x - --x ; // decrement x by one and returns the new value of x + x = 2; + y = ++x; // x now contains 3, y contains 3 + y = x--; // x contains 2 again, y still contains 3 +.. warning:: Be careful! You cannot put a space in between the two + ``+`` or ``-`` signs. This example is broken:: + // this line won't compile (notice the extra space): + int y = x+ +; Parameters ---------- -x: an integer or long (possibly unsigned) - - - -Returns -------- - -The original or newly incremented / decremented value of the -variable. - - - -Examples --------- - -:: - - x = 2; - y = ++x; // x now contains 3, y contains 3 - y = x--; // x contains 2 again, y still contains 3 - - +**x**: an integer value (like an ``int``, ``long``, ``unsigned int``, +etc.). See also -------- -`+= <http://arduino.cc/en/Reference/Arithmetic>`_ -`-= <http://arduino.cc/en/Reference/Arithmetic>`_ - - +- :ref:`Compound arithmetic operators <arduino-arithmeticcompound>` diff --git a/docs/source/arduino/incrementcompound.rst b/docs/source/arduino/incrementcompound.rst deleted file mode 100644 index 0005fbc..0000000 --- a/docs/source/arduino/incrementcompound.rst +++ /dev/null @@ -1,49 +0,0 @@ -.. _arduino-incrementcompound: - -+= , -= , \*= , /= -================== - -Description ------------ - -Perform a mathematical operation on a variable with another -constant or variable. The += (et al) operators are just a -convenient shorthand for the expanded syntax, listed below. - - - -Syntax ------- - -:: - - x += y; // equivalent to the expression x = x + y; - x -= y; // equivalent to the expression x = x - y; - x *= y; // equivalent to the expression x = x * y; - x /= y; // equivalent to the expression x = x / y; - - - -Parameters ----------- - -x: any variable type - - - -y: any variable type or constant - - - -Examples --------- - -:: - - x = 2; - x += 4; // x now contains 6 - x -= 3; // x now contains 3 - x *= 10; // x now contains 30 - x /= 2; // x now contains 15 - - diff --git a/docs/source/arduino/int.rst b/docs/source/arduino/int.rst index 2bb3bef..4bb876c 100644 --- a/docs/source/arduino/int.rst +++ b/docs/source/arduino/int.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-int: int @@ -6,79 +8,60 @@ int Description ----------- -Integers are your primary datatype for number storage, and store a -2 byte value. This yields a range of -32,768 to 32,767 (minimum -value of -2^15 and a maximum value of (2^15) - 1). - - - -Int's store negative numbers with a technique called -`2's complement math. <http://en.wikipedia.org/wiki/2's_complement>`_ -The highest bit, sometimes refered to as the "sign" bit, flags the -number as a negative number. The rest of the bits are inverted and -1 is added. - - - -The Arduino takes care of dealing with negative numbers for you, so -that arithmetic operations work transparently in the expected -manner. There can be an unexpected complication in dealing with the -`bitshift right operator (>>) <http://arduino.cc/en/Reference/Bitshift>`_ -however. - - - -Example -------- - -:: +The ``int`` data type represents integers. Integers are your primary +data type for number storage, and store a 4 byte value. This yields a +range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a +maximum value of (2^31) - 1; that's about negative 2 billion to +positive 2 billion). - int ledPin = 13; +An ``int`` stores a negative number with a technique called `two's +complement math +<http://en.wikipedia.org/wiki/Two%27s_complement#Explanation>`_\ . +The highest bit in an ``int``, sometimes refered to as the "sign" bit, +flags the number as a negative number. (See the linked article on +two's complement for more information). +The Maple takes care of dealing with negative numbers for you, so that +arithmetic operations work mostly as you'd expect. There can be an +:ref:`unexpected complication <arduino-bitshift-signbit-gotcha>` in +dealing with the :ref:`bitshift right operator (>>) +<arduino-bitshift>`, however. +Here is an example of declaring an ``int`` variable named ``ledPin``, +then giving it value 13:: -Syntax ------- + int ledPin = 13; -:: +The general syntax for declaring an ``int`` variable named ``var``, +then giving it value ``val``, looks like:: - int var = val; + int var = val; +.. _arduino-int-overflow: +Integer Overflow +---------------- +When ``int`` variables leave the range specified above, they "roll +over" in the other direction. It's like in the game *Pac-Man* -- when +Pac-Man goes past the right edge of the screen, he reappears on the +left, and when he goes past the left side of the screen, he reappears +on the right. Here are some examples:: -- var - your int variable name -- val - the value you assign to that variable - - - -Coding Tip ----------- - -When variables are made to exceed their maximum capacity they "roll -over" back to their minimum capacitiy, note that this happens in -both directions. - - - -:: - - int x - x = -32,768; - x = x - 1; // x now contains 32,767 - rolls over in neg. direction - - x = 32,767; - x = x + 1; // x now contains -32,768 - rolls over - + int x; + x = -2,147,483,648; + x--; // x now contains 2,147,483,647; rolled over "left to right" + x = 2,147,483,647; + x++; // x now contains -2,147,483,648; rolled over "right to left" See Also -------- - -- `byte <http://arduino.cc/en/Reference/Byte>`_ -- `unsigned int <http://arduino.cc/en/Reference/UnsignedInt>`_ -- `long <http://arduino.cc/en/Reference/Long>`_ -- `unsigned long <http://arduino.cc/en/Reference/UnsignedLong>`_ -- `Integer Constants <http://arduino.cc/en/Reference/IntegerConstants>`_ -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ +- :ref:`unsigned int <arduino-unsignedint>` +- :ref:`char <arduino-char>` +- :ref:`unsigned char <arduino-unsignedchar>` +- :ref:`long <arduino-long>` +- :ref:`unsigned long <arduino-unsignedlong>` +- :ref:`Integer Constants <arduino-constants-integers>` +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/intcast.rst b/docs/source/arduino/intcast.rst index d6bcca4..4db65d2 100644 --- a/docs/source/arduino/intcast.rst +++ b/docs/source/arduino/intcast.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-intcast: int() @@ -6,36 +8,22 @@ int() Description ----------- -Converts a value to the `int <http://arduino.cc/en/Reference/Int>`_ -data type. - - - -Syntax ------- - -int(x) - - +Converts a value to the :ref:`int <arduino-int>` data type. Here is +an example:: -Parameters ----------- + double d = 2.5; + int i = int(d); // i holds "2", an int value -x: a value of any type +The value inside of the parentheses (``int(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. +See the :ref:`int <arduino-int>` reference for details about the +precision and limitations of ``int`` variables on the Maple. - -Returns -------- - -int - - - -See also +See Also -------- - -- `int <http://arduino.cc/en/Reference/Int>`_ +- :ref:`int <arduino-int>` diff --git a/docs/source/arduino/integerconstants.rst b/docs/source/arduino/integerconstants.rst deleted file mode 100644 index d60ed24..0000000 --- a/docs/source/arduino/integerconstants.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. _arduino-integerconstants: - -Integer Constants -================= - -Integer constants are numbers used directly in a sketch, like -``123``. By default, these numbers are treated as -`int <http://arduino.cc/en/Reference/Int>`_'s but you can change -this with the U and L modifiers (see below). - - - -Normally, integer constants are treated as base 10 (decimal) -integers, but special notation (formatters) may be used to enter -numbers in other bases. - - - -:: - - Base Example Formatter Comment - - 10 (decimal) 123 none - - 2 (binary) B1111011 leading 'B' only works with 8 bit values (0 to 255) - characters 0-1 valid - - 8 (octal) 0173 leading "0" characters 0-7 valid - - 16 (hexadecimal) 0x7B leading "0x" characters 0-9, A-F, a-f valid - - - -**Decimal** is base 10. This is the common-sense math with which -you are acquainted. Constants without other prefixes are assumed to -be in decimal format. - - - -Example: -:: - - 101 // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) - -**Binary** is base two. Only characters 0 and 1 are valid. - - - -Example: -:: - - B101 // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) - -The binary formatter only works on bytes (8 bits) between 0 (B0) -and 255 (B11111111). If it is convenient to input an int (16 bits) -in binary form you can do it a two-step procedure such as: - - - -:: - - myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte - - - -**Octal** is base eight. Only characters 0 through 7 are valid. -Octal values are indicated by the prefix "0" - - - -Example: - -:: - - 0101 // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) - -Warning -It is possible to generate a hard-to-find bug by (unintentionally) -including a leading zero before a constant and having the compiler -unintentionally interpret your constant as octal. -**Hexadecimal (or hex)** is base sixteen. Valid characters are 0 -through 9 and letters A through F; A has the value 10, B is 11, up -to F, which is 15. Hex values are indicated by the prefix "0x". -Note that A-F may be syted in upper or lower case (a-f). - - - -Example: - -:: - - 0x101 // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) - - - -U & L formatters ----------------- - -By default, an integer constant is treated as an -`int <http://arduino.cc/en/Reference/Int>`_ with the attendant -limitations in values. To specify an integer constant with another -data type, follow it with: - - - - -- a 'u' or 'U' to force the constant into an unsigned data format. - Example: ``33u`` -- a 'l' or 'L' to force the constant into a long data format. - Example: ``100000L`` -- a 'ul' or 'UL' to force the constant into an unsigned long - constant. Example: ``32767ul`` - - - - - -See also --------- - - -- `constants <http://arduino.cc/en/Reference/Constants>`_ -- `#define <http://arduino.cc/en/Reference/Define>`_ -- `byte <http://arduino.cc/en/Reference/Byte>`_ -- `int <http://arduino.cc/en/Reference/Int>`_ -- `unsigned int <http://arduino.cc/en/Reference/UnsignedInt>`_ -- `long <http://arduino.cc/en/Reference/Long>`_ -- `unsigned long <http://arduino.cc/en/Reference/UnsignedLong>`_ - - diff --git a/docs/source/arduino/long.rst b/docs/source/arduino/long.rst index 3d59896..6d20111 100644 --- a/docs/source/arduino/long.rst +++ b/docs/source/arduino/long.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-long: long @@ -6,45 +8,45 @@ long Description ----------- -Long variables are extended size variables for number storage, and -store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647. - - - -Example -------- - - - -:: +The ``long`` data type stores extended size integer values. You can +use a ``long`` when your values are too large to fit into an :ref:`int +<arduino-int>`. A ``long`` occupies 8 bytes of memory. This yields a +range of approximately -9.2×10^18 to 9.2×10^18 (that's 9.2 billion +billion, or about 92 million times the number of stars in the Milky +Way galaxy). The exact range of a ``long`` on the Maple is from +-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, or -2^63 to +(2^63-1). - long speedOfLight = 186000L; // see Integer Constants for explanation of the 'L' +Here's an example of declaring a long (see :ref:`integer constants +<arduino-constants-u-l>` for explanation of the 'L'):: + // Speed of light in nanometers per second (approximate). + long c = 299792458000000000L; +The general syntax for declaring an ``long`` variable named ``var``, +then giving it value ``val``, looks like:: -Syntax ------- + long var = val; -:: - - long var = val; - - - - -- var - the long variable name -- val - the value assigned to the variable +This is identical to the ``int`` syntax, with ``long`` replacing +``int``. +Note that ``long`` values will still :ref:`overflow +<arduino-int-overflow>`, just like ``int`` values, but their much +larger range makes this less likely to happen. +The downside to using a ``long`` instead of an ``int`` (besides the +extra storage) is that :ref:`arithmetic <arduino-arithmetic>` +operations on ``long``\ s will take longer than on ``int``\ s. See Also -------- - -- `byte <http://arduino.cc/en/Reference/Byte>`_ -- `int <http://arduino.cc/en/Reference/Int>`_ -- `unsigned int <http://arduino.cc/en/Reference/UnsignedInt>`_ -- `unsigned long <http://arduino.cc/en/Reference/UnsignedLong>`_ -- `Integer Constants <http://arduino.cc/en/Reference/IntegerConstants>`_ -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ +- :ref:`char <arduino-char>` +- :ref:`unsigned char <arduino-unsignedchar>` +- :ref:`int <arduino-int>` +- :ref:`unsigned int <arduino-unsignedint>` +- :ref:`unsigned long <arduino-unsignedlong>` +- :ref:`Integer Constants <arduino-constants-integers>` +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/longcast.rst b/docs/source/arduino/longcast.rst index 9f31443..ed23821 100644 --- a/docs/source/arduino/longcast.rst +++ b/docs/source/arduino/longcast.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-longcast: long() @@ -6,36 +8,20 @@ long() Description ----------- -Converts a value to the -`long <http://arduino.cc/en/Reference/Long>`_ data type. - - - -Syntax ------- - -long(x) - - - -Parameters ----------- +Converts a value to the :ref:`long <arduino-long>` data type. Here is +an example:: -x: a value of any type + double d = 2.5; + long i = long(d); // i holds "2L", an long value +The value inside of the parentheses (``long(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. +See the :ref:`long <arduino-long>` reference for details about the +precision and limitations of ``long`` variables on the Maple. -Returns -------- - -long - - - -See also +See Also -------- - -- `long <http://arduino.cc/en/Reference/Long>`_ - - +- :ref:`long <arduino-long>` diff --git a/docs/source/arduino/loop.rst b/docs/source/arduino/loop.rst index 165b7b0..b558edf 100644 --- a/docs/source/arduino/loop.rst +++ b/docs/source/arduino/loop.rst @@ -1,39 +1,42 @@ +.. highlight:: cpp + .. _arduino-loop: loop() ====== -After creating a setup() function, which initializes and sets the -initial values, the loop() function does precisely what its name -suggests, and loops consecutively, allowing your program to change -and respond. Use it to actively control the Arduino board. - - +After creating a :ref:`setup() <arduino-setup>` function, which +initializes your sketch, the ``loop()`` function gets called +repeatedly, allowing your program to change and respond. Use it to +actively control your Maple board. Example -~~~~~~~ +------- :: - - int buttonPin = 3; - + + int buttonPin = 38; + // setup initializes serial and the button pin - void setup() - { - beginSerial(9600); + void setup() { + SerialUSB.begin(); pinMode(buttonPin, INPUT); } - - // loop checks the button pin each time, - // and will send serial if it is pressed - void loop() - { - if (digitalRead(buttonPin) == HIGH) - serialWrite('H'); - else - serialWrite('L'); - + + // loop() checks the button pin each time it executes, + // and will print 'H' if it is pressed, 'L' otherwise + void loop() { + if (digitalRead(buttonPin) == HIGH) { + SerialUSB.println('H'); + } else { + SerialUSB.println('L'); + } + delay(1000); } +See Also +-------- + +- :ref:`setup() <arduino-setup>` diff --git a/docs/source/arduino/max.rst b/docs/source/arduino/max.rst index 375625c..1e2c619 100644 --- a/docs/source/arduino/max.rst +++ b/docs/source/arduino/max.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-max: max(x, y) @@ -6,19 +8,16 @@ max(x, y) Description ----------- -Calculates the maximum of two numbers. +(Macro) Calculates the maximum of two numbers. Parameters ---------- -x: the first number, any data type - - - -y: the second number, any data type +**x**: the first number; may be any number or numeric expression. +**y**: the second number; may be any number or numeric expression. Returns @@ -26,8 +25,6 @@ Returns The larger of the two parameter values. - - Example ------- @@ -36,36 +33,28 @@ Example sensVal = max(senVal, 20); // assigns sensVal to the larger of sensVal or 20 // (effectively ensuring that it is at least 20) -Note ----- - -Perhaps counter-intuitively, max() is often used to constrain the -lower end of a variable's range, while min() is used to constrain -the upper end of the range. - - +.. note:: Perhaps counter-intuitively, max() is often used to + constrain the lower end of a variable's range, while :ref:`min() + <arduino-min>` is used to constrain the upper end of the range. Warning ------- -Because of the way the max() function is implemented, avoid using -other functions inside the brackets, it may lead to incorrect -results - - - -:: +Because of the way ``max()`` is implemented, avoid using other +functions inside the parentheses. It may lead to incorrect results:: max(a--, 0); // avoid this - yields incorrect results - + a--; // use this instead - - max(a, 0); // keep other math outside the function + max(a, 0); // keep other operations outside max() +Arduino Compatibility +--------------------- +The Maple version of ``max()`` is compatible with Arduino. -See also +See Also -------- - -- `min <http://arduino.cc/en/Reference/Min>`_\ () -- `constrain <http://arduino.cc/en/Reference/Constrain>`_\ () +- :ref:`min() <arduino-min>` +- :ref:`constrain() <arduino-constrain>` diff --git a/docs/source/arduino/min.rst b/docs/source/arduino/min.rst index fdd7a5f..0ac018c 100644 --- a/docs/source/arduino/min.rst +++ b/docs/source/arduino/min.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-min: min(x, y) @@ -6,19 +8,16 @@ min(x, y) Description ----------- -Calculates the minimum of two numbers. +(Macro) Calculates the minimum of two numbers. Parameters ---------- -x: the first number, any data type - - - -y: the second number, any data type +**x**: the first number; may be any number or numeric expression. +**y**: the second number; may be any number or numeric expression. Returns @@ -27,45 +26,38 @@ Returns The smaller of the two numbers. - -Examples --------- +Example +------- :: sensVal = min(sensVal, 100); // assigns sensVal to the smaller of sensVal or 100 // ensuring that it never gets above 100. -Note ----- - -Perhaps counter-intuitively, max() is often used to constrain the -lower end of a variable's range, while min() is used to constrain -the upper end of the range. +.. note:: Perhaps counter-intuitively, max() is often used to + constrain the lower end of a variable's range, while min() is used + to constrain the upper end of the range. Warning ------- -Because of the way the min() function is implemented, avoid using -other functions inside the brackets, it may lead to incorrect -results - - - -:: +Because of the way ``min()`` is implemented, avoid using other +functions inside the parentheses. It may lead to incorrect results:: min(a++, 100); // avoid this - yields incorrect results - - a++; - min(a, 100); // use this instead - keep other math outside the function + a++; // use this instead - + min(a, 100); // keep other operations outside min() +Arduino Compatibility +--------------------- -See also --------- +The Maple version of ``min()`` is compatible with Arduino. +See Also +-------- -- `max <http://arduino.cc/en/Reference/Max>`_\ () -- `constrain <http://arduino.cc/en/Reference/Constrain>`_\ () +- :ref:`max() <arduino-max>` +- :ref:`constrain() <arduino-constrain>` diff --git a/docs/source/arduino/modulo.rst b/docs/source/arduino/modulo.rst index 195d15b..64a546d 100644 --- a/docs/source/arduino/modulo.rst +++ b/docs/source/arduino/modulo.rst @@ -1,3 +1,5 @@ +.. highlight:: cpp + .. _arduino-modulo: % (modulo) @@ -6,79 +8,67 @@ Description ----------- -Calculates the remainder when one integer is divided by another. It -is useful for keeping a variable within a particular range (e.g. -the size of an array). - - +Calculates the `remainder <http://en.wikipedia.org/wiki/Remainder>`_ +when one integer is divided by another. It is useful for keeping a +variable within a particular range (e.g. the size of an array). Syntax ------ -result = dividend % divisor +:: + + result = dividend % divisor Parameters ---------- -dividend: the number to be divided - - - -divisor: the number to divide by - +**dividend**: the number to be divided +**divisor**: the number to divide by Returns ------- -the remainder - - +The remainder of **dividend**\ /\ **divisor**\ . Examples -------- :: + int x; x = 7 % 5; // x now contains 2 x = 9 % 5; // x now contains 4 x = 5 % 5; // x now contains 0 x = 4 % 5; // x now contains 4 - - -Example Code ------------- - :: /* update one value in an array each time through a loop */ - + int values[10]; int i = 0; - - void setup() {} - - void loop() - { - values[i] = analogRead(0); - i = (i + 1) % 10; // modulo operator rolls over variable - } + void setup() { + // no setup necessary + } + void loop() { + values[i] = analogRead(0); + i = (i + 1) % 10; // modulo operator makes sure i stays between 0 and 9 + } Tip --- -The modulo operator does not work on floats. - +The modulo operator does not work on floats. For that, you can use +the C standard library function `fmod() +<http://sourceware.org/newlib/libm.html#fmod>`_. -See also +See Also -------- - -- `division <http://arduino.cc/en/Reference/Arithmetic>`_ - +- :ref:`Arithmetic <arduino-arithmetic>` diff --git a/docs/source/arduino/pinmode.rst b/docs/source/arduino/pinmode.rst index 34c7998..b34bb31 100644 --- a/docs/source/arduino/pinmode.rst +++ b/docs/source/arduino/pinmode.rst @@ -5,6 +5,12 @@ pinMode() ========= +.. contents:: Contents + :local: + +Library Documentation +--------------------- + .. doxygenfunction:: pinMode .. doxygenenum:: WiringPinMode @@ -13,7 +19,7 @@ Discussion ---------- pinMode() is usually called within :ref:`arduino-setup` in order to -configure a pin for a certain usage (although it may be called from +configure a pin for a certain usage (although it may be called anywhere). @@ -40,8 +46,8 @@ Example -Arduino Compatibility Note --------------------------- +Arduino Compatibility +--------------------- The libmaple implementation of pinMode() supports OUTPUT and INPUT modes with a meaning identical to that of the Arduino function. @@ -64,4 +70,4 @@ See also - :ref:`arduino-digitalwrite` - :ref:`arduino-digitalread` - Maple :ref:`GPIO <gpio>` reference page -- Arduino `pinMode() <http://www.arduino.cc/en/Reference/PinMode>`_ reference + diff --git a/docs/source/arduino/pointer.rst b/docs/source/arduino/pointer.rst index 4e4b9e5..b9bbc48 100644 --- a/docs/source/arduino/pointer.rst +++ b/docs/source/arduino/pointer.rst @@ -1,10 +1,8 @@ .. _arduino-pointer: -The pointer operators -===================== +The pointer operators: & (reference) and \* (dereference) +========================================================= -& (reference) and \* (dereference) -================================== Pointers are one of the more complicated subjects for beginners in learning C, and it is possible to write the vast majority of @@ -13,4 +11,15 @@ manipulating certain data structures, the use of pointers can simplify the code, and and knowledge of manipulating pointers is handy to have in one's toolkit. +Introducing pointers is somewhat outside the scope of this +documentation. However, a good `pointer tutorial +<http://www.cplusplus.com/doc/tutorial/pointers/>`_ is available. +Also see the `Wikipedia article on pointers +<http://en.wikipedia.org/wiki/Pointer_%28computing%29>`_, especially +the section on `pointers in C +<http://en.wikipedia.org/wiki/Pointer_%28computing%29#C_pointers>`_. +See Also +======== + +- http://xkcd.com/138/ diff --git a/docs/source/arduino/pow.rst b/docs/source/arduino/pow.rst index 3a09481..66e67d7 100644 --- a/docs/source/arduino/pow.rst +++ b/docs/source/arduino/pow.rst @@ -3,45 +3,24 @@ pow(base, exponent) =================== -Description ------------ - -Calculates the value of a number raised to a power. Pow() can be -used to raise a number to a fractional power. This is useful for -generating exponential mapping of values or curves. - - - -Parameters ----------- - -base: the number (*float*) - - - -exponent: the power to which the base is raised (*float*) - - - -Returns -------- - -The result of the exponentiation (*double*) +Calculates the value of a number raised to a power. +Library Documentation +--------------------- +.. doxygenfunction:: pow Example ------- -See the `fscale <http://arduino.cc/playground/Main/Fscale>`_ -function in the code library. - +``pow()`` can be used to raise a number to a fractional power. This +is useful for e.g. generating exponential mapping of values or +curves. See the `fscale <http://arduino.cc/playground/main/fscale>`_ +function in the Arduino playground for more on this. - -See also +See Also -------- - -- `sqrt <http://arduino.cc/en/Reference/Sqrt>`_\ () -- `float <http://arduino.cc/en/Reference/Float>`_ -- `double <http://arduino.cc/en/Reference/Double>`_ +- :ref:`sqrt() <arduino-sqrt>` +- :ref:`float <arduino-float>` +- :ref:`double <arduino-double>` diff --git a/docs/source/arduino/return.rst b/docs/source/arduino/return.rst index ae3b37d..9774320 100644 --- a/docs/source/arduino/return.rst +++ b/docs/source/arduino/return.rst @@ -1,69 +1,58 @@ +.. highlight:: cpp + .. _arduino-return: return ====== -Terminate a function and return a value from a function to the -calling function, if desired. - - +(Keyword) Terminates a function and return a value from a function to +the calling function, if the function has non-``void`` return type. Syntax: ------- -return; - - - -return value; // both forms are valid - - - -Parameters ----------- +:: -value: any variable or constant type + // from within a "void" function: + return; + // from within a non-"void" function: + return value; +In the second case, ``value`` should have a type which is the same as +the return type of the function, or be convertible to it (like an +``int`` to a ``long``, etc.; see :ref:`this note +<arduino-arithmetic-typeconversion>` for some references). Examples: --------- -A function to compare a sensor input to a threshold - -:: +A function to compare a sensor input to a threshold:: - int checkSensor(){ + // converts analog readings between 0 and 400 to 0, and 400 up to 1. + int checkSensor() { if (analogRead(0) > 400) { return 1; - else{ + else { return 0; } } +An early ``return`` is also useful when testing a section of code +without having to "comment out" large sections of possibly buggy code, +like so:: + void loop() { -The return keyword is handy to test a section of code without -having to "comment out" large sections of possibly buggy code. - - + // brilliant code idea to test here -:: + return; - void loop(){ - - // brilliant code idea to test here - - return; - - // the rest of a dysfunctional sketch here - // this code will never be executed + // the rest of a dysfunctional sketch here + // this code will never be executed } - - -See also +See Also -------- -`comments <http://arduino.cc/en/Reference/Comments>`_ - +- :ref:`comments <arduino-comments>` diff --git a/docs/source/arduino/scope.rst b/docs/source/arduino/scope.rst index bb56246..0e793ec 100644 --- a/docs/source/arduino/scope.rst +++ b/docs/source/arduino/scope.rst @@ -1,56 +1,59 @@ +.. highlight:: cpp + .. _arduino-scope: Variable Scope ============== -Variables in the C programming language, which Arduino uses, have a -property called *scope*. This is in contrast to languages such as -BASIC where every variable is a *global* variable. - - - -A global variable is one that can be *seen* by every function in a -program. Local variables are only visible to the function in which -they are declared. In the Arduino environment, any variable -declared outside of a function (e.g. setup(), loop(), etc. ), is a -global variable. - +Variables in the C++ programming language, which Maple uses (all of +your sketches are C++ programs in disguise), have a property called +*scope*. This is in contrast to languages such as BASIC where every +variable is a *global* variable. +A global variable is one that can be "seen" by every function in a +program. Local variables are only usable within the function in which +they are declared. In the :ref:`Maple IDE <ide>`, any variable +declared outside of a function (like :ref:`setup() <arduino-setup>`, +:ref:`loop() <arduino-loop>`, etc.), is a global variable. When programs start to get larger and more complex, local variables -are a useful way to insure that only one function has access to its -own variables. This prevents programming errors when one function +are a useful way to ensure that a function has exclusive access to its +own variables. This prevents programming errors when one function inadvertently modifies variables used by another function. +It is also sometimes useful to declare and initialize a variable +inside a :ref:`for <arduino-for>` loop. This creates a variable that +can only be accessed from inside the loop body. - -It is also sometimes handy to declare and initialize a variable -inside a *for* loop. This creates a variable that can only be -accessed from inside the for-loop brackets. - - +Scope in C++ is actually a fairly complex topic. More information is +available in the `C++ programming Wikibook +<http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Scope>`_. Example: -------- :: - int gPWMval; // any function will see this variable - - void setup() - { + int globalVar; // any function will see this variable + + void setup() { // ... } - - void loop() - { + + void loop() { int i; // "i" is only "visible" inside of "loop" float f; // "f" is only "visible" inside of "loop" // ... - + for (int j = 0; j <100; j++){ - // variable j can only be accessed inside the for-loop brackets + // variable j can only be accessed inside the for-loop brackets + i = j * j; } - + i = globalVar; // globalVar can be accessed from anywhere, including loop() } +See Also +-------- + +- `C++ programming Wikibook <http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Scope>`_. +- Wikipedia article on `scope <http://en.wikipedia.org/wiki/Scope_%28programming%29>`_ diff --git a/docs/source/arduino/semicolon.rst b/docs/source/arduino/semicolon.rst index b3cc8c4..3230819 100644 --- a/docs/source/arduino/semicolon.rst +++ b/docs/source/arduino/semicolon.rst @@ -1,16 +1,11 @@ -.. _arduino-semicolon: - -; semicolon -=========== - -Used to end a statement. - +.. highlight:: cpp +.. _arduino-semicolon: -Example -~~~~~~~ +Semicolon (;) +============= -:: +Used to end a line of code. Example:: int a = 13; diff --git a/docs/source/arduino/serial.rst b/docs/source/arduino/serial.rst index 31ce06c..abba049 100644 --- a/docs/source/arduino/serial.rst +++ b/docs/source/arduino/serial.rst @@ -43,6 +43,9 @@ Functions - `read <http://arduino.cc/en/Serial/Read>`_\ () - `flush <http://arduino.cc/en/Serial/Flush>`_\ () - `print <http://arduino.cc/en/Serial/Print>`_\ () + +.. _arduino-serial-println: + - `println <http://arduino.cc/en/Serial/Println>`_\ () - `write <http://arduino.cc/en/Serial/Write>`_\ () diff --git a/docs/source/arduino/sin.rst b/docs/source/arduino/sin.rst index 3a06a8f..4eb2e1f 100644 --- a/docs/source/arduino/sin.rst +++ b/docs/source/arduino/sin.rst @@ -1,35 +1,25 @@ .. _arduino-sin: -sin(rad) -======== +sin() +===== -Description ------------ +Calculates the `sine <http://en.wikipedia.org/wiki/Sine>`_ of an angle +(in radians). -Calculates the sine of an angle (in radians). The result will be -between -1 and 1. +Library Documentation +--------------------- +.. doxygenfunction:: sin +Arduino Compatibility +--------------------- -Parameters ----------- +The Maple versino of ``sin()`` is compatible with Arduino. -rad: the angle in radians (*float*) - - - -Returns -------- - -the sine of the angle (*double*) - - - -See also +See Also -------- - -- `cos <http://arduino.cc/en/Reference/Cos>`_\ () -- `tan <http://arduino.cc/en/Reference/Tan>`_\ () -- `float <http://arduino.cc/en/Reference/Float>`_ -- `double <http://arduino.cc/en/Reference/Double>`_ +- :ref:`cos <arduino-cos>` +- :ref:`tan <arduino-tan>` +- :ref:`float <arduino-float>` +- :ref:`double <arduino-double>` diff --git a/docs/source/arduino/sizeof.rst b/docs/source/arduino/sizeof.rst index a95dfbf..104c183 100644 --- a/docs/source/arduino/sizeof.rst +++ b/docs/source/arduino/sizeof.rst @@ -1,71 +1,62 @@ -.. _arduino-sizeof: - -sizeof -====== - -Description ------------ - -The sizeof operator returns the number of bytes in a variable type, -or the number of bytes occupied by an array. +.. highlight:: cpp +.. _arduino-sizeof: +sizeof() +======== Syntax ------ -sizeof(variable) - - +:: -Parameters ----------- + sizeof(type) + sizeof(var) -variable: any variable type or array (e.g. int, float, byte) +Description +----------- -Example code ------------- +The ``sizeof`` operator returns the number of bytes needed to store a +value of a given type. This can be an ordinary numeric type, like +``int``. It can be something more complicated, like a ``struct`` or +``union``. If the argument to ``sizeof`` is an array, it returns the +total number of bytes occupied by the array. -The sizeof operator is useful for dealing with arrays (such as -strings) where it is convenient to be able to change the size of -the array without breaking other parts of the program. +Examplec +-------- +The ``sizeof`` operator is useful for dealing with arrays (such as +strings) where it is convenient to be able to change the size of the +array without breaking other parts of the program. This program prints out a text string one character at a time. Try -changing the text phrase. - - - -:: +changing the text phrase:: char myStr[] = "this is a test"; int i; - - void setup(){ + + void setup() { Serial.begin(9600); } - - void loop() { - for (i = 0; i < sizeof(myStr) - 1; i++){ + + void loop() { + for (i = 0; i < sizeof(myStr) - 1; i++) { Serial.print(i, DEC); Serial.print(" = "); Serial.println(myStr[i], BYTE); } } - - -Note that sizeof returns the total number of bytes. So for larger -variable types such as ints, the for loop would look something like -this. - -:: +Note that ``sizeof`` returns the total number of bytes; this is equal +to the number of ``char``\ s only because the C++ standard guarantees +that ``sizeof(char) == 1``. So for larger variable types such as +``int``, the :ref:`for loop <arduino-for>` would look something like +this:: for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { // do something with myInts[i] } - diff --git a/docs/source/arduino/sq.rst b/docs/source/arduino/sq.rst new file mode 100644 index 0000000..2b6b1fe --- /dev/null +++ b/docs/source/arduino/sq.rst @@ -0,0 +1,39 @@ +.. highlight:: cpp + +.. _arduino-sq: + +sq(a) +===== + +Description +----------- + +(Macro) computes the square of a number. + +Parameters +---------- + +**a**: the number. + +Returns +------- + +**a** squared (**a** × **a**). + +Warning +------- + +Because of the way ``sq()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + b = sq(a++); // avoid this - yields incorrect results + + b = sq(a); // use this instead - + a++; // keep other operations outside sq() + + +Arduino Compatibility +--------------------- + +Maple's implementation of ``sq()`` is compatible with Arduino. diff --git a/docs/source/arduino/sqrt.rst b/docs/source/arduino/sqrt.rst index 5b8a73e..4263345 100644 --- a/docs/source/arduino/sqrt.rst +++ b/docs/source/arduino/sqrt.rst @@ -1,33 +1,22 @@ .. _arduino-sqrt: -sqrt(x) -======= - -Description ------------ +sqrt() +====== Calculates the square root of a number. +Library Documentation +--------------------- +.. doxygenfunction:: sqrt -Parameters ----------- - -x: the number, any data type - - - -Returns -------- +Arduino Compatibility +--------------------- -double, the number's square root. +The Maple versino of ``sqrt()`` is compatible with Arduino. - - -See also +See Also -------- - -- `pow <http://arduino.cc/en/Reference/Pow>`_\ () -- `sq <http://arduino.cc/en/Reference/Sq>`_\ () - +- :ref:`pow <arduino-pow>` +- :ref:`sq <arduino-sq>` diff --git a/docs/source/arduino/static.rst b/docs/source/arduino/static.rst index 1c0340e..b292891 100644 --- a/docs/source/arduino/static.rst +++ b/docs/source/arduino/static.rst @@ -1,71 +1,54 @@ +.. highlight:: cpp + .. _arduino-static: Static ====== -The static keyword is used to create variables that are visible to -only one function. However unlike local variables that get created -and destroyed every time a function is called, static variables -persist beyond the function call, preserving their data between -function calls. - - +The ``static`` keyword can be used to create variables that are +visible to only one function. However, unlike local variables that get +created and destroyed every time a function is called, ``static`` +variables persist beyond the function call, preserving their data +between function calls. -Variables declared as static will only be created and initialized +Variables declared as ``static`` will only be created and initialized the first time a function is called. - +.. note:: This is only one use of the ``static`` keyword in C++. It + has some other important uses that are outside the scope of this + documentation; consult a reliable C++ reference for details. Example ------- -:: +One use case for ``static`` variables is implementing counters that +last longer than the functions which need them, but shouldn't be +shared to other functions. Here's an example:: - - - /* RandomWalk - * Paul Badger 2007 - * RandomWalk wanders up and down randomly between two - * endpoints. The maximum move in one loop is governed by - * the parameter "stepsize". - * A static variable is moved up and down a random amount. - * This technique is also known as "pink noise" and "drunken walk". - */ - - #define randomWalkLowRange -20 - #define randomWalkHighRange 20 - int stepsize; - - int thisTime; - int total; - - void setup() - { - Serial.begin(9600); + void setup() { + SerialUSB.begin(); } - - void loop() - { // tetst randomWalk function - stepsize = 5; - thisTime = randomWalk(stepsize); - Serial.println(thisTime); - delay(10); + + void loop() { + int reading; + if (timeToReadSensors()) { + reading = readSensors(); + } + // do something with reading } - - int randomWalk(int moveSize){ - static int place; // variable to store value in random walk - declared static so that it stores - // values in between function calls, but no other functions can change its value - - place = place + (random(-moveSize, moveSize + 1)); - - if (place < randomWalkLowRange){ // check lower and upper limits - place = place + (randomWalkLowRange - place); // reflect number back in positive direction - } - else if(place > randomWalkHighRange){ - place = place - (place - randomWalkHighRange); // reflect number back in negative direction - } - - return place; + + int readSensors() { + static int numSensorReadings = 0; + numSensorReadings++; + if (numSensorReadings % 100 == 0) { + SerialUSB.print("just got to another 100 sensor readings"); + } + return analogRead(...); } - +In this example, the static variable ``numSensorReadings`` is +initialized to zero the first time ``readSensors()`` is called, and +then incremented, so it starts out at one. Subsequent calls to +``readSensors()`` won't reset ``numSensorReadings`` to zero, because +it was declared ``static``. Thus, ``numSensorReadings`` is a count of +the number of times that ``readSensors()`` has been called. diff --git a/docs/source/arduino/string.rst b/docs/source/arduino/string.rst index b841728..8db400a 100644 --- a/docs/source/arduino/string.rst +++ b/docs/source/arduino/string.rst @@ -1,158 +1,128 @@ +.. highlight:: cpp + .. _arduino-string: -string -====== +Strings +======= Description ----------- -Text strings can be represented in two ways. you can use the String -data type, which is part of the core as of version 0019, or you can -make a string out of an array of type char and null-terminate it. -This page described the latter method. For more details on the -String object, which gives you more functionality at the cost of -more memory, see the -`String object <http://arduino.cc/en/Reference/StringObject>`_ -page. +Text strings can be represented in two ways. You can + +1. Use the :ref:`String <arduino-stringclass>` data type, which is +part of the core as of version 0.0.9, or +2. You can make a string out of an array of type :ref:`char +<arduino-char>` and null-terminate it. +This page describes the second method. Examples -------- -All of the following are valid declarations for strings. - -:: - - char Str1[15]; - char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'}; - char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'}; - char Str4[ ] = "arduino"; - char Str5[8] = "arduino"; - char Str6[15] = "arduino"; - - - -**Possibilities for declaring strings** - - +All of the following are valid declarations for strings:: + char str1[15]; + char str2[6] = {'m', 'a', 'p', 'l', 'e'}; + char str3[6] = {'m', 'a', 'p', 'l', 'e', '\0'}; + char str4[ ] = "maple"; + char str5[6] = "maple"; + char str6[15] = "maple"; -- Declare an array of chars without initializing it as in Str1 -- Declare an array of chars (with one extra char) and the compiler - will add the required null character, as in Str2 -- Explicitly add the null character, Str3 -- Initialize with a string constant in quotation marks; the - compiler will size the array to fit the string constant and a - terminating null character, Str4 -- Initialize the array with an explicit size and string constant, - Str5 -- Initialize the array, leaving extra space for a larger string, - Str6 +As you can see, there are several methods available for declaring and +initializing strings: +- Declare an array of ``char`` without initializing it, as with ``str1``. +- Declare an array of ``char`` (with one extra ``char``) and the + compiler will add the required null character, as with ``str2``. -**Null termination** +- Explicitly add the null character (``'\0'``), as with ``str3``. +- Initialize with a string constant in quotation marks (``"..."``); + the compiler will size the array to fit the string constant and a + terminating null character (``str4``). +- Initialize the array with an explicit size and string constant, + (``str5``). -Generally, strings are terminated with a null character (ASCII code -0). This allows functions (like Serial.print()) to tell where the -end of a string is. Otherwise, they would continue reading -subsequent bytes of memory that aren't actually part of the -string. +- Initialize the array, leaving extra space for a larger string + (``str6``). +Null Termination +---------------- +Generally, strings are terminated with a null character (`ASCII +<http://en.wikipedia.org/wiki/ASCII>`_ code 0). This allows functions +(like ``SerialUSB.print()``) to tell where the end of a string is. +Otherwise, they would continue reading subsequent bytes of memory that +aren't actually part of the string. -This means that your string needs to have space for one more -character than the text you want it to contain. That is why Str2 -and Str5 need to be eight characters, even though "arduino" is only -seven - the last position is automatically filled with a null -character. Str4 will be automatically sized to eight characters, -one for the extra null. In Str3, we've explicitly included the null -character (written '\\0') ourselves. - - +This means that your string needs to have space for one more character +than the text you want it to contain. That is why ``str2`` and +``str5`` need to be six characters, even though "maple" is only five +-- the last position is automatically filled with a NULL +character. ``str4`` will be automatically sized to six characters, one +for the extra null. In the case of ``str3``, we've explicitly included +the null character (written ``'\0'``) ourselves. Note that it's possible to have a string without a final null -character (e.g. if you had specified the length of Str2 as seven -instead of eight). This will break most functions that use strings, -so you shouldn't do it intentionally. If you notice something -behaving strangely (operating on characters not in the string), -however, this could be the problem. - - - -**Single quotes or double quotes?** - - - -Strings are always defined inside double quotes ("Abc") and -characters are always defined inside single quotes('A'). +character (e.g. if you had specified the length of ``str2`` as five +instead of six). This will break most functions that use strings, so +you shouldn't do it intentionally. If you notice something behaving +strangely (operating on characters not in the string), however, this +could be the problem. +Single quotes or double quotes? +------------------------------- +Strings are always defined inside double quotes (``"Abc"``) and +characters are always defined inside single quotes (``'A'``). -**Wrapping long strings** +Wrapping long strings +--------------------- - - -You can wrap long strings like this: - -:: +You can wrap long strings like this:: char myString[] = "This is the first line" - " this is the second line" - " etcetera"; - - - -**Arrays of strings** - + " this is the second line" + " etcetera"; +Arrays of Strings +----------------- It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is in actually an example of a two-dimensional array. - - -In the code below, the asterisk after the datatype char "char\*" +In the code below, the asterisk after the datatype char ``char *`` indicates that this is an array of "pointers". All array names are actually pointers, so this is required to make an array of arrays. Pointers are one of the more esoteric parts of C for beginners to -understand, but it isn't necessary to understand pointers in detail -to use them effectively here. - - - -Example -------- +understand, but it isn't necessary to understand pointers in detail to +use them effectively here:: -:: + char* myStrings[] = {"This is string 1", "This is string 2", + "This is string 3", "This is string 4", + "This is string 5", "This is string 6"}; - - char* myStrings[]={"This is string 1", "This is string 2", "This is string 3", - "This is string 4", "This is string 5","This is string 6"}; - - void setup(){ - Serial.begin(9600); - } - - void loop(){ - for (int i = 0; i < 6; i++){ - Serial.println(myStrings[i]); - delay(500); - } + void setup() { + SerialUSB.begin(); } + void loop() { + for (int i = 0; i < 6; i++) { + SerialUSB.println(myStrings[i]); + delay(500); + } + } See Also -------- - -- `array <http://arduino.cc/en/Reference/Array>`_ -- `PROGMEM <http://arduino.cc/en/Reference/PROGMEM>`_ -- `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ - +- :ref:`array <arduino-array>` +- :ref:`__attribute__ <arm-gcc-attribute-flash>` +- :ref:`Variables <arduino-variables>` diff --git a/docs/source/arduino/stringclass.rst b/docs/source/arduino/stringclass.rst new file mode 100644 index 0000000..0c9c61d --- /dev/null +++ b/docs/source/arduino/stringclass.rst @@ -0,0 +1,6 @@ +.. _arduino-stringclass: + +String Class +============ + +Stub. diff --git a/docs/source/arduino/switchcase.rst b/docs/source/arduino/switchcase.rst index 28791eb..1634de1 100644 --- a/docs/source/arduino/switchcase.rst +++ b/docs/source/arduino/switchcase.rst @@ -3,71 +3,72 @@ switch / case statements ======================== -Like **if** statements, **switch...case** controls the flow of -programs by allowing programmers to specify different code that -should be executed in various conditions. In particular, a switch -statement compares the value of a variable to the values specified -in case statements. When a case statement is found whose value -matches that of the variable, the code in that case statement is -run. - - - -The **break** keyword exits the switch statement, and is typically -used at the end of each case. Without a break statement, the switch -statement will continue executing the following expressions -("falling-through") until a break, or the end of the switch -statement is reached. - - - -Example -~~~~~~~ - -:: - - switch (var) { - case 1: - //do something when var equals 1 - break; - case 2: - //do something when var equals 2 - break; - default: - // if nothing else matches, do the default - // default is optional - } - - +Like :ref:`if/else <arduino-else>` blocks, A ``switch`` statement +controls program flow by allowing you to specify different code that +should be executed under various cases. Syntax -~~~~~~ +------ :: switch (var) { - case label: + case val1: // statements break; - case label: + case val2: // statements break; - default: + ... + default: // statements } +Where ``var`` is a variable whose value to investigate, and the +``val1``, ``val2`` after each ``case`` are constant values that +``var`` might be. +Description +----------- -Parameters -~~~~~~~~~~ +A ``switch`` statement compares the value of a variable to the values +specified in ``case`` statements. When a ``case`` statement is found +whose value matches that of the variable, the code in that case +statement is run. -var: the variable whose value to compare to the various cases +The ``break`` keyword exits the switch statement, and is typically +used at the end of each ``case``. Without a ``break``, the ``switch`` +statement will continue executing the following ``case`` expressions +("falling-through") until a ``break`` (or the end of the switch +statement) is reached. +Writing ``default:`` instead of a ``case`` statement allows you to +specify what to do if none of the ``case`` statements matches. Having +a ``default:`` is optional (you can leave it out), but if you have +one, it must appear after all of the ``case`` statements, as shown +above. +``switch`` statements are often used with an ``enum`` value as the +variable to compare. In this case, you can write down all of the +values the ``enum`` takes as ``case`` statements, and be sure you've +covered all the possibilities. -label: a value to compare the variable to +Example +------- +:: + switch (var) { + case 1: + //do something when var equals 1 + break; + case 2: + //do something when var equals 2 + break; + default: + // if nothing else matches, do the default + // default is optional + } See also: --------- diff --git a/docs/source/arduino/variables.rst b/docs/source/arduino/variables.rst new file mode 100644 index 0000000..d79f28b --- /dev/null +++ b/docs/source/arduino/variables.rst @@ -0,0 +1,188 @@ +.. highlight:: cpp + +.. _arduino-variables: + +Variables +--------- + +A variable is a way of naming and storing a value for later use by +the program, such as data from a sensor or an intermediate value +used in a calculation. + + + +Declaring Variables +^^^^^^^^^^^^^^^^^^^ + +Before they are used, all variables have to be declared. Declaring +a variable means defining its type, and optionally, setting an +initial value (initializing the variable). Variables do not have to +be initialized (assigned a value) when they are declared, but it is +often useful. + + + +:: + + int inputVariable1; + int inputVariable2 = 0; // both are correct + + + +Programmers should consider the size of the numbers they wish to +store in choosing variable types. Variables will +`roll over <#VariableRollover>`_ when the value stored exceeds the +space assigned to store it. See below for an example. + + + +Variable Scope +^^^^^^^^^^^^^^ + +Another important choice that programmers face is where to declare +variables. The specific place that variables are declared +influences how various functions in a program will *see* the +variable. This is called variable +`scope <http://arduino.cc/en/Reference/Scope>`_. + + + +Initializing Variables +^^^^^^^^^^^^^^^^^^^^^^ + +Variables may be *initialized* (assigned a starting value) when +they are declared or not. It is always good programming practice +however to double check that a variable has valid data in it, +before it is accessed for some other purpose. + + + +Example: + +:: + + int calibrationVal = 17; // declare calibrationVal and set initial value + + + +Variable Rollover +^^^^^^^^^^^^^^^^^ + +When variables are made to exceed their maximum capacity they "roll +over" back to their minimum capacity, note that this happens in +both directions. + + + +:: + + int x + x = -32,768; + x = x - 1; // x now contains 32,767 - rolls over in neg. direction + + + +:: + + x = 32,767; + x = x + 1; // x now contains -32,768 - rolls over + + + +Using Variables +^^^^^^^^^^^^^^^ + +Once variables have been declared, they are used by setting the +variable equal to the value one wishes to store with the +`assignment operator <http://arduino.cc/en/Reference/Assignment>`_ +(single equal sign). The assignment operator tells the program to +put whatever is on the right side of the equal sign into the +variable on the left side. + + + +:: + + inputVariable1 = 7; // sets the variable named inputVariable1 to 7 + inputVariable2 = analogRead(2); // sets the variable named inputVariable2 to the + // (digitized) input voltage read from analog pin #2 + + + +Examples +^^^^^^^^ + +:: + + int lightSensVal; + char currentLetter; + unsigned long speedOfLight = 186000UL; + char errorMessage = {"choose another option"}; // see string + + + +Once a variable has been set (assigned a value), you can test its +value to see if it meets certain conditions, or you can use its +value directly. For instance, the following code tests whether the +inputVariable2 is less than 100, then sets a delay based on +inputVariable2 which is a minimum of 100: + + + +:: + + if (inputVariable2 < 100) + { + inputVariable2 = 100; + } + + delay(inputVariable2); + + + +This example shows all three useful operations with variables. It +tests the variable ( ``if (inputVariable2 < 100)`` ), it sets the +variable if it passes the test ( ``inputVariable2 = 100`` ), and it +uses the value of the variable as an input parameter to the delay() +function (``delay(inputVariable2)`` ) + + + +**Style Note:** You should give your variables descriptive names, +so as to make your code more readable. Variable names like +**tiltSensor** or **pushButton** help you (and anyone else reading +your code) understand what the variable represents. Variable names +like **var** or **value**, on the other hand, do little to make +your code readable. + + + +You can name a variable any word that is not already one of the +`keywords <http://arduino.cc/en/Reference/Keywords?action=edit>`_`? <http://arduino.cc/en/Reference/Keywords?action=edit>`_ +in Arduino. Avoid beginning variable names with numeral +characters. + + + +Some variable types +^^^^^^^^^^^^^^^^^^^ + + +- `char <http://arduino.cc/en/Reference/Char>`_ +- `byte <http://arduino.cc/en/Reference/Byte>`_ +- `int <http://arduino.cc/en/Reference/Int>`_ +- `unsigned int <http://arduino.cc/en/Reference/UnsignedInt>`_ +- `long <http://arduino.cc/en/Reference/Long>`_ +- `unsigned long <http://arduino.cc/en/Reference/UnsignedLong>`_ +- `float <http://arduino.cc/en/Reference/Float>`_ +- `double <http://arduino.cc/en/Reference/Double>`_ + + + +Variable Scope +^^^^^^^^^^^^^^ + + +- `Variable Scope <http://arduino.cc/en/Reference/scope>`_ + + diff --git a/docs/source/arduino/while.rst b/docs/source/arduino/while.rst index 5155f09..9ec9f78 100644 --- a/docs/source/arduino/while.rst +++ b/docs/source/arduino/while.rst @@ -1,6 +1,6 @@ .. _arduino-while: -while loops +while Loops =========== Description diff --git a/docs/source/arm-gcc.rst b/docs/source/arm-gcc.rst index 21379db..8435a1f 100644 --- a/docs/source/arm-gcc.rst +++ b/docs/source/arm-gcc.rst @@ -1,13 +1,34 @@ .. _arm-gcc: -.. _arm-gcc-attribute-flash: ============ GCC on ARM ============ +This document provides an introduction to using +:command:`arm-none-eabi-gcc`\ , the `CodeSourcery +<http://codesourcery.com>`_ version of the GNU `GCC +<http://gcc.gnu.org/>`_ compilers used to compile programs for the +Maple. + Stub. -Include special things, differences with AVR-GCC, using -``__attribute__`` to stick things in flash, etc. + +.. _arm-gcc-avr-gcc-diff: + + +Differences with AVR-GCC +------------------------ + +people coming from arduino and other Atmel AVR powered microcontroller +platforms are likely to be used to AVR-GCC. our compiler is +different. explain why (stub). + + +.. _arm-gcc-attribute-flash: + +Tips and Tricks +--------------- + +* you can use ``__attribute__`` to stick things in flash (stub) diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index fea1f35..032b20b 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -4,6 +4,8 @@ Maple Bootloader ================== +.. TODO: [Stub] add a section on flashing your own bootloader + The firmware which allows the Maple to be reprogrammed via a USB connection. Every Maple board comes programmed with this by default, and it is not overwritten by regular programs (it lives lower in the @@ -21,10 +23,10 @@ Flash memory and only runs when the chip is reset). Bootloader Schemes Explained! ----------------------------- -Maple Rev 3 (the version currently shipping) represents a drastic -remake of the core library as well as the upload process. Some of -these changes are aesthetic, refactoring and reorganization. Some are -performance minded. The changes to the bootloader, however, were +Maple Rev 3 and Rev 5 (the version currently shipping) represents a +drastic remake of the core library as well as the upload process. Some +of these changes are aesthetic, refactoring and reorganization. Some +are performance minded. The changes to the bootloader, however, were implemented to solve some really gritty cross platform issues. Before delving in to how the Rev 1 bootloader worked and how the Rev 3 bootloader works now, lets look at the features common to both of them diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index 8872a1b..cf4c2b3 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -75,7 +75,7 @@ The incompatible hardware differences are: Software Language/Library Changes --------------------------------- -With :ref:`one notable exception <language-no-word>`, the entire +With :ref:`a few exceptions <language-missing-features>`, the entire Arduino language is supported. However, there are some subtle differences, most of which are improvements: diff --git a/docs/source/conf.py b/docs/source/conf.py index e1aa3a4..288efad 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -59,7 +59,7 @@ copyright = u'2010, LeafLabs, LLC' # The short X.Y version. version = '0.0' # The full version, including alpha/beta/rc tags. -release = '0.0.7' +release = '0.0.9' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/docs/source/foo.rst b/docs/source/foo.rst index 769e666..5631922 100644 --- a/docs/source/foo.rst +++ b/docs/source/foo.rst @@ -6,8 +6,10 @@ This is the index of the imported Arduino docs. +Finished: + .. toctree:: - :maxdepth: 2 + :maxdepth: 1 abs() <arduino/abs> analogRead() <arduino/analogread> @@ -16,99 +18,104 @@ This is the index of the imported Arduino docs. Arrays <arduino/array> Assignment <arduino/assignment> attachInterrupt() <arduino/attachinterrupt> - bit <arduino/bit> + bit() <arduino/bit> + bitClear() <arduino/bitclear> + bitRead() <arduino/bitread> + bitSet() <arduino/bitset> + arduino/bitshift + arduino/analogwrite + arduino/bitwisemath + arduino/bitwisecompound + bitWrite() <arduino/bitwrite> + arduino/boolean + arduino/booleanvariables + arduino/braces + arduino/break + arduino/byte + arduino/bytecast + arduino/char + arduino/charcast + arduino/comments + arduino/const + constrain() <arduino/constrain> + arduino/continue + cos() <arduino/cos> + #define <arduino/define> + arduino/delay + arduino/delaymicroseconds + arduino/detachinterrupt + arduino/digitalread + arduino/double + arduino/dowhile + arduino/else + arduino/float + arduino/floatcast + arduino/for + arduino/goto + arduino/highbyte + arduino/if + arduino/comparison + arduino/include + arduino/increment + arduino/arithmeticcompound + arduino/int + arduino/intcast + arduino/long + arduino/longcast + arduino/loop + arduino/max + arduino/min + arduino/modulo + arduino/pointer + arduino/pow + arduino/return + arduino/scope + arduino/semicolon + arduino/sin + arduino/sizeof + arduino/sqrt + arduino/sq + arduino/static + arduino/string + +Unfinished; straightforward to convert: + +.. toctree:: + :maxdepth: 1 -.. bitclear <arduino-bitclear> -.. bitread <arduino-bitread> -.. bitset <arduino-bitset> -.. bitshift <arduino-bitshift> -.. bitwiseand <arduino-bitwiseand> -.. bitwisecompound <arduino-bitwisecompound> -.. bitwisexornot <arduino-bitwisexornot> -.. bitwrite <arduino-bitwrite> -.. boolean <arduino-boolean> -.. booleanvariables <arduino-booleanvariables> -.. braces <arduino-braces> -.. break <arduino-break> -.. byte <arduino-byte> -.. bytecast <arduino-bytecast> -.. changes <arduino-changes> -.. char <arduino-char> -.. charcast <arduino-charcast> -.. comments <arduino-comments> -.. comparison <arduino-comparison> -.. const <arduino-const> -.. constants <arduino-constants> -.. constrain <arduino-constrain> -.. continue <arduino-continue> -.. cos <arduino-cos> -.. define <arduino-define> -.. delay <arduino-delay> -.. delaymicroseconds <arduino-delaymicroseconds> -.. detachinterrupt <arduino-detachinterrupt> -.. digitalread <arduino-digitalread> -.. digitalwrite <arduino-digitalwrite> -.. double <arduino-double> -.. dowhile <arduino-dowhile> -.. else <arduino-else> -.. float <arduino-float> -.. floatcast <arduino-floatcast> -.. for <arduino-for> -.. fpconstants <arduino-fpconstants> -.. goto <arduino-goto> -.. highbyte <arduino-highbyte> -.. homepage <arduino-homepage> -.. if <arduino-if> -.. include <arduino-include> -.. increment <arduino-increment> -.. incrementcompound <arduino-incrementcompound> -.. int <arduino-int> -.. intcast <arduino-intcast> -.. integerconstants <arduino-integerconstants> -.. interrupts <arduino-interrupts> -.. libraries <arduino-libraries> -.. long <arduino-long> -.. longcast <arduino-longcast> -.. loop <arduino-loop> -.. lowbyte <arduino-lowbyte> -.. map <arduino-map> -.. max <arduino-max> -.. micros <arduino-micros> -.. millis <arduino-millis> -.. min <arduino-min> -.. modulo <arduino-modulo> -.. nointerrupts <arduino-nointerrupts> -.. notone <arduino-notone> -.. pointer <arduino-pointer> -.. pow <arduino-pow> -.. pulsein <arduino-pulsein> -.. random <arduino-random> -.. randomseed <arduino-randomseed> -.. return <arduino-return> -.. scope <arduino-scope> -.. semicolon <arduino-semicolon> -.. serial <arduino-serial> -.. setup <arduino-setup> -.. shiftout <arduino-shiftout> -.. sin <arduino-sin> -.. sizeof <arduino-sizeof> -.. sqrt <arduino-sqrt> -.. static <arduino-static> -.. string <arduino-string> -.. stringobject <arduino-stringobject> -.. switchcase <arduino-switchcase> -.. tan <arduino-tan> -.. tone <arduino-tone> -.. unsignedchar <arduino-unsignedchar> -.. unsignedint <arduino-unsignedint> -.. unsignedlong <arduino-unsignedlong> -.. void <arduino-void> -.. volatile <arduino-volatile> -.. while <arduino-while> -.. word <arduino-word> -.. wordcast <arduino-wordcast> + arduino/switchcase + arduino/tan + arduino/unsignedchar + arduino/unsignedint + arduino/unsignedlong + arduino/variables + arduino/void + arduino/volatile + arduino/while -.. TODO later +Unfinished, requires libmaple/Arduino knowledge: + +.. toctree:: + :maxdepth: 1 -.. analogreference() <arduino/analogreference> -.. analogWrite() <arduino/analogwrite> + arduino/word + arduino/wordcast + arduino/constants + arduino/digitalwrite + arduino/notone + arduino/serial + arduino/interrupts + analogWrite() <arduino/analogwrite> + arduino/nointerrupts + arduino/pulsein + arduino/stringobject + arduino/tone + arduino/random + arduino/randomseed + arduino/setup + arduino/map + arduino/shiftout + arduino/micros + arduino/millis + arduino/lowbyte + arduino/stringclass diff --git a/docs/source/gpio.rst b/docs/source/gpio.rst index 7a9031a..ee2b6eb 100644 --- a/docs/source/gpio.rst +++ b/docs/source/gpio.rst @@ -1,8 +1,7 @@ .. _gpio: -====== - GPIO -====== +GPIO +==== The Maple features 38 ready-to-use general purpose input/output (GPIO) pins for digital input/output, numbered D0 through D37. These numbers @@ -80,7 +79,7 @@ above). GPIO Modes ---------- -.. doxygenenum:: WiringMode +.. doxygenenum:: WiringPinMode Function Reference ------------------ diff --git a/docs/source/ide.rst b/docs/source/ide.rst new file mode 100644 index 0000000..c8dbd74 --- /dev/null +++ b/docs/source/ide.rst @@ -0,0 +1,11 @@ +.. _ide: + +Maple IDE Documentation +======================= + +Stub. + +.. _ide-serial-monitor: + +Serial Monitor +-------------- diff --git a/docs/source/index.rst b/docs/source/index.rst index ac92d4b..fdaf801 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,8 +1,3 @@ -.. libmaple documentation master file, created by - sphinx-quickstart on Thu Oct 7 06:42:30 2010. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - .. _index: Maple Documentation Index @@ -24,6 +19,7 @@ Table of contents: Maple Quickstart Guide <maple-quickstart> Maple IDE Installation Guide <maple-ide-install> + Maple IDE Documentation <ide> Maple/Arduino Compatibility Reference <compatibility> Maple Language Reference <language> Maple Library Reference <libraries> @@ -34,6 +30,7 @@ Table of contents: Maple bootloader <bootloader> Known Problems <errata> [Temporary] Arduino docs TOC <foo> + [Temporary] Wirish-only docs TOC <wirish> Indices and tables ================== diff --git a/docs/source/language.rst b/docs/source/language.rst index 5a2efad..b2ef017 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -193,7 +193,9 @@ Arduino Documentation Links | | | | +------------------------------------+------------------------------------+-----------------------------------------+ -.. _language-no-word: +.. _language-missing-features: + +Stub TODO: fill in other missing features, like analogReference() .. note:: @@ -212,7 +214,7 @@ Arduino Documentation Links can put the following at the top of the file you're porting:: typedef uint16 word; - + .. _if: http://arduino.cc/en/Reference/If .. _if...else: http://arduino.cc/en/Reference/Else .. _for: http://arduino.cc/en/Reference/For @@ -394,7 +396,7 @@ method, which behaves roughly like:: while (true) loop(); } -(The truth is a little bit more complicated, but not by much). +(The truth is a little bit more complicated, but not by much). As an example, consider a sketch with two files. The first file contains ``setup()`` and ``loop()``:: diff --git a/docs/source/libmaple.rst b/docs/source/libmaple.rst index a018cd7..b161afb 100644 --- a/docs/source/libmaple.rst +++ b/docs/source/libmaple.rst @@ -37,3 +37,4 @@ wrappers and code to imitate the Arduino programming library. Unix Toolchain Quickstart <unix-toolchain> libmaple API reference <libmaple-api> + Guide to using GCC's ARM target <arm-gcc> diff --git a/docs/source/pwm.rst b/docs/source/pwm.rst index 178d103..42dc1a5 100644 --- a/docs/source/pwm.rst +++ b/docs/source/pwm.rst @@ -114,7 +114,7 @@ Function Reference .. _pwm-overflow: -``Timer1.setOverflow(overflow)`` +``Timer[1,2,3,4].setOverflow(overflow)`` This function sets the period ("reload" or "overflow") value for an entire PWM timer bank. The value is 16bit (0 to 65535) and @@ -147,6 +147,30 @@ Function Reference This function is normally called once from, `setup()`_, but the timer can be reconfigured with a new prescaler at any time. + * Configure the prescaler and overflow values to generate a timer + * reload with a period as close to the given number of + * microseconds as possible. + * + * The return value is the overflow, which may be used to set + * channel compare values. However, if a clock that fires an + * interrupt every given number of microseconds is all that is + * desired, and the relative "phases" are unimportant, channel + * compare values may all be set to 1. + +``Timer[1,2,3,4].setPeriod(period_in_microseconds)`` + + Configure the prescaler and overflow values to generate a timer + reload with a period as close to the given number of microseconds + as possible. + + The return value is the overflow, which may be used to set channel + compare values. However, if a clock that fires an interrupt every + given number of microseconds is all that is desired, and the + relative "phases" are unimportant, channel compare values may all + be set to 1. + + + Recommended Reading ------------------- diff --git a/docs/source/timers.rst b/docs/source/timers.rst index e0e57cb..fe6ea4a 100644 --- a/docs/source/timers.rst +++ b/docs/source/timers.rst @@ -32,6 +32,8 @@ counter to reset to zero more frequently. Caveats ------- +.. _timers-pwm-conflicts: + **PWM Conflicts:** Because PWM functionality on a given pin depends on the configuration of the timer and channel, you must chose your channels carefully if you want to use both timer interrupts and PWM in @@ -196,6 +198,9 @@ from 1 to 4. Note that function call overhead means that the smallest increment rate is a couple microseconds. +.. _timers-attachinterrupt: +.. _timers-detachinterrupt: + ``Timer1.attachCompare1Interrupt(function)``/\ ``Timer1.detachCompare1Interrupt()`` This is how to attach or disable an interrupt handlers to timer diff --git a/docs/source/wirish.rst b/docs/source/wirish.rst new file mode 100644 index 0000000..2773e24 --- /dev/null +++ b/docs/source/wirish.rst @@ -0,0 +1,9 @@ + +[temporary] Wirish Functions +============================ + +.. toctree:: + :maxdepth: 2 + + wirish/pwmwrite + wirish/types diff --git a/docs/source/wirish/pwmwrite.rst b/docs/source/wirish/pwmwrite.rst new file mode 100644 index 0000000..b1f0515 --- /dev/null +++ b/docs/source/wirish/pwmwrite.rst @@ -0,0 +1,52 @@ +.. highlight:: cpp + +.. _wirish-pwmwrite: + +pwmWrite() +========== + +Writes a :ref:`PWM wave <pwm>` to a pin. You can use this to make an +LED get brighter or dimmer, control a servomotor, etc. After a call to +pwmWrite(), the pin will output a steady square wave with the given +duty cycle. You can change the duty cycle later by calling pwmWrite() +again with the same pin and a different duty. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pwmWrite + +Example +------- + +Sets the output to the LED proportional to the value read from the +potentiometer (adapted for Maple from the Arduino `analogWrite() +reference <http://www.arduino.cc/en/Reference/AnalogWrite>`_\ ):: + + + int ledPin = 13; // LED connected to pin 13 (Maple-specific) + int analogPin = 3; // potentiometer connected to analog pin 3 + int val = 0; // variable to store the read value + + void setup() { + pinMode(ledPin, OUTPUT); // sets the LED pin as output + + pinMode(analogPin, PWM); // sets the potentiometer pin as PWM + // output (Maple-specific) + } + + void loop() { + val = analogRead(analogPin); // read the input pin + + analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, + // analogWrite values from 0 to 65535 + // (Maple-specific) + } + +See Also +-------- + +- :ref:`Maple PWM tutorial <pwm>` diff --git a/docs/source/wirish/types.rst b/docs/source/wirish/types.rst new file mode 100644 index 0000000..0b78d01 --- /dev/null +++ b/docs/source/wirish/types.rst @@ -0,0 +1,6 @@ +.. _wirish-types: + +Standard types +============== + +Stub. (uint8, uint64, etc.) |