diff options
author | Marti Bolivar <mbolivar@mit.edu> | 2010-11-29 01:49:26 -0500 |
---|---|---|
committer | Marti Bolivar <mbolivar@mit.edu> | 2010-11-29 01:49:26 -0500 |
commit | 078edc158da7906ba72e7e6528e1a811e07270e7 (patch) | |
tree | 1bc7b2e8137fb5ebfc7b59d59294d7adb9e95468 | |
parent | 5e587be27a7c3bd854b686952a5c9637a2432ff0 (diff) | |
download | librambutan-078edc158da7906ba72e7e6528e1a811e07270e7.tar.gz librambutan-078edc158da7906ba72e7e6528e1a811e07270e7.zip |
Finished converting the Arduino docs
102 files changed, 2027 insertions, 1842 deletions
diff --git a/docs/README b/docs/README index b467d2d..326d278 100644 --- a/docs/README +++ b/docs/README @@ -3,46 +3,81 @@ as a Doxygen configuration file; we turn Doxygen XML output into Sphinx documentation. You can generate HTML documentation using the Makefile if you have make, or using make.bat from Windows. -You need a recent-ish version of doxygen in your PATH: +Documentation Build Steps +------------------------- - http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc +1. You need a recent-ish version of Doxygen in your PATH: -For the Doxygen-to-Sphinx bridge, we rely on a project called Breathe, -by Michael Jones. + http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc -***** You must clone the LEAFLABS VERSION OF THE breathe repository ****** +2. Install breathe, which does Doxygen-to-Sphinx conversion: - ... and then set an environment variable BREATHE_HOME to be able to -build the documentation. Something like this on bash: + Read/write version (for LeafLabs developers): $ git clone git@github.com:leaflabs/breathe.git + + Read-only version (for non-LeafLabs developers): + + $ git clone git://github.com/leaflabs/breathe.git + + After that's done, set an environment variable BREATHE_HOME to + point to where you downloaded it. Something like this on bash: + $ export BREATHE_HOME=/path/to/breathe/repo/ -You can now build the HTML docs with (on Unix): + (You'll want to put this in your shell startup script). + +3. Install Sphinx. + + From source or .egg: + + http://pypi.python.org/pypi/Sphinx#downloads + + Via easy_install: $ sudo easy_install -U Sphinx + +4. Before the first time you run Sphinx (and any time the Doxygen + comments in the libmaple source code are changed), you'll need to + rebuild the Doxygen XML output: + + $ cd libmaple/docs/source + $ doxygen + +5. Finally, you can build the documentation: + $ make html -Which will produce Doxygen documentation in doxygen/xml, and HTML -documentation (this is what you want to look at) in build/html. + (Read the Makefile for more targets). -All of the documentation itself lives in source/. The directory -source/_static is for static content like style sheets; -source/_templates contains Sphinx templates (or, it would if we had -any). +Reading and Modifying the Documentation +--------------------------------------- -The docs are written in reStructuredText (reST); it's a Python thing -that they use to produce the docs at python.org (which are beautiful, -if you've never seen them). You can read more about Sphinx here: +The net effect of the above is to produce Doxygen XML output (ignore +this) in libmaple/docs/doxygen/xml, and HTML documentation (this is +what you want) in libmaple/docs/build/html. - http://sphinx.pocoo.org/tutorial.html +Just point your web browser at the file + + libmaple/docs/build/html/index.html -Specific information on documenting C and C++ is available here: +it corresponds to the Sphinx file - http://sphinx.pocoo.org/domains.html + libmaple/docs/source/index.rst + +All of the documentation itself lives in libmaple/docs/source/. The +directory source/_static/ is for static content (like style sheets); +source/_templates/ contains Sphinx templates (or, it would, if we had +any). + +The docs are written in Sphinx's version of reStructuredText (reST); +it's a Python thing that they use to produce the docs at +http://python.org. You can read more about Sphinx here: + + http://sphinx.pocoo.org/tutorial.html -You can view the reST source for any generated page of documentation -by clicking the "Show Source" link in the sidebar. +You can view the source for any generated page of documentation by +clicking the "Show Source" link in the sidebar. -The file source/conf.py is the Sphinx configuration file; you can go -read it for more information about our setup. +The file libmaple/docs/source/conf.py is the Sphinx configuration +file; you can go read it for more information about our setup. diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index 6cb9ece..1cfd17f 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -574,3 +574,10 @@ SOFT_RESET response: - 1 - Either 0 or 1 (FAILED and OK, respectively). Will end this bootloader session and reset the processor. + +.. _bootloader-reflashing: + +Flashing A Custom Bootloader +---------------------------- + +Stub (flashing a custom bootloader) diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index cf4c2b3..7eb0a8f 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -83,34 +83,32 @@ differences, most of which are improvements: full 32-bit (4 byte) integer values instead of the regular 16-bit (2 byte) Arduino values. -* `pinMode()`_ types: any :ref:`GPIO <gpio>` (including analog pins) - can be configured into one of the following modes with a single call - to `pinMode()`_: ``OUTPUT``, ``OUTPUT_OPEN_DRAIN``, - ``INPUT_FLOATING``, ``INPUT_PULLUP``, +* :ref:`pinMode() <lang-pinmode>` types: any :ref:`GPIO <gpio>` + (including analog pins) can be configured into one of the following + modes with a single call to ```pinMode()``: ``OUTPUT``, + ``OUTPUT_OPEN_DRAIN``, ``INPUT_FLOATING``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``. Additionally, the PWM and Analog Input pins can be configured as ``INPUT_ANALOG`` and ``PWM`` respectively. See the :ref:`GPIO documentation <gpio>` for more information. - .. TODO: reference libmaple docs above when they're done - -* Serial1 syntax: like the `Arduino Mega +* ``Serial1`` syntax: like the `Arduino Mega <http://arduino.cc/en/Main/ArduinoBoardMega>`_, the Maple has - multiple USART ports. By default, Serial is not mapped to any of - them, use ``Serial1`` through ``Serial3`` instead. - - .. TODO: reference libmaple docs for Serial[n] above when they're done + multiple :ref:`USART ports <lang-serial>`. By default, ``Serial`` + is not mapped to any of them, use ``Serial1`` through ``Serial3`` + instead. * 16-bit :ref:`PWM <pwm>`: Arduino boards support 8-bit PWM, which - means that calls to `analogWrite()`_ take values between 0 (always - off) and 255 (always on). The Maple supports 16-bit PWM, so the - corresponding values should be between 0 (always off) and 65535 - (always on). + means that calls to :ref:`analogWrite() <lang-analogwrite>` take + values between 0 (always off) and 255 (always on). The Maple + supports 16-bit PWM, so the corresponding values should be between 0 + (always off) and 65535 (always on). * 12-bit :ref:`ADC <adc>`: Arduino boards support 10-bit ADC, which - means that calls to `analogRead()`_ will return values between 0 and - 1023. The Maple supports 12-bit ADC, so the same call will instead - return values between 0 and 4095. + means that calls to :ref:`analogRead() <lang-analogread>` will + return values between 0 and 1023. The Maple supports 12-bit ADC, so + the same call will instead return values between 0 and 4095. +Stub (unfinished) .. class:: ported-feature @@ -130,5 +128,4 @@ I sorta work And I am also ordinary -Stub (unfinished) diff --git a/docs/source/conf.py b/docs/source/conf.py index 288efad..74090f6 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -88,7 +88,7 @@ with open('prolog.rst', 'r') as pr: #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). @@ -105,7 +105,7 @@ pygments_style = 'sphinx' #modindex_common_prefix = [] # Warn about all references where the target cannot be found. -#nitpicky = True +nitpicky = True # -- Options for HTML output -------------------------------------------------- diff --git a/docs/source/lang/abs.rst b/docs/source/lang/abs.rst index ed95e6f..0f71d9b 100644 --- a/docs/source/lang/abs.rst +++ b/docs/source/lang/abs.rst @@ -1,13 +1,19 @@ +.. highlight:: cpp + .. _lang-abs: -abs(x) +abs() ====== -Description ------------ - (Macro) computes the absolute value of a number. +Syntax +------ + +:: + + abs(x) + Parameters ---------- diff --git a/docs/source/lang/analogwrite.rst b/docs/source/lang/analogwrite.rst index d30d4d9..3d05f44 100644 --- a/docs/source/lang/analogwrite.rst +++ b/docs/source/lang/analogwrite.rst @@ -62,7 +62,7 @@ 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-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 diff --git a/docs/source/lang/arithmetic.rst b/docs/source/lang/arithmetic.rst index 9f21627..91fe22e 100644 --- a/docs/source/lang/arithmetic.rst +++ b/docs/source/lang/arithmetic.rst @@ -2,28 +2,27 @@ .. _lang-arithmetic: -Addition, Subtraction, Multiplication, & Division +Arithmetic Operators (``+``, ``-``, ``*``, ``/``) ================================================= -.. contents:: Contents - :local: - -Description ------------ - -These operators return the sum, difference, product, or quotient -(respectively) of the two operands. The operation is conducted using -the data type of the operands, so, for example, ``9 / 4`` gives ``2`` -since 9 and 4 are :ref:`int variables <lang-int>`. +The operators ``+``, ``-``, ``*``, and ``/`` respectively evaluate to +the sum, difference, product, or quotient (respectively) of the two +operands. The operation is conducted using the data type of the +operands, so, for example, ``9 / 4`` gives ``2`` since 9 and 4 are +:ref:`int variables <lang-int>`. 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:`lang-int` with the value 2147483647 gives --2147483648). If the operands are of different types, the "larger" -type is used for the calculation. +to an :ref:`lang-int` with the value 2,147,483,647 gives +-2,147,483,648). .. _lang-arithmetic-typeconversion: +If the operands are of different types, the "larger" type is used for +the calculation. If one of the numbers (operands) are of the type +**float** or of type **double**, floating point math will be used for +the calculation. + .. 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 @@ -35,9 +34,8 @@ type is used for the calculation. 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 -calculation. +.. contents:: Contents + :local: Examples -------- diff --git a/docs/source/lang/assignment.rst b/docs/source/lang/assignment.rst index 16f0bf4..b6ad4d5 100644 --- a/docs/source/lang/assignment.rst +++ b/docs/source/lang/assignment.rst @@ -2,8 +2,8 @@ .. _lang-assignment: -= assignment operator (single equal sign) -========================================= +Assignment Operator (``=``) +=========================== Stores the value to the right of the equal sign in the variable to the left of the equal sign. diff --git a/docs/source/lang/bit.rst b/docs/source/lang/bit.rst index c342fdd..dd5c050 100644 --- a/docs/source/lang/bit.rst +++ b/docs/source/lang/bit.rst @@ -3,14 +3,10 @@ bit() ===== -Description ------------ - (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 ------ diff --git a/docs/source/lang/bitclear.rst b/docs/source/lang/bitclear.rst index 5d1eb95..941f912 100644 --- a/docs/source/lang/bitclear.rst +++ b/docs/source/lang/bitclear.rst @@ -3,9 +3,6 @@ bitClear() ========== -Description ------------ - (Macro) Clears (writes a 0 to) a bit of a numeric variable. Syntax diff --git a/docs/source/lang/bitread.rst b/docs/source/lang/bitread.rst index 9f885cf..46b4478 100644 --- a/docs/source/lang/bitread.rst +++ b/docs/source/lang/bitread.rst @@ -3,9 +3,6 @@ bitRead() ========= -Description ------------ - (Macro) Gets the value of a bit in a number. diff --git a/docs/source/lang/bitset.rst b/docs/source/lang/bitset.rst index 502c1b6..ccd76de 100644 --- a/docs/source/lang/bitset.rst +++ b/docs/source/lang/bitset.rst @@ -3,9 +3,6 @@ bitSet() ======== -Description ------------ - (Macro) Sets (writes a 1 to) a bit of a numeric variable. diff --git a/docs/source/lang/bitshift.rst b/docs/source/lang/bitshift.rst index f05d49e..e1c8de0 100644 --- a/docs/source/lang/bitshift.rst +++ b/docs/source/lang/bitshift.rst @@ -2,17 +2,13 @@ .. _lang-bitshift: -Bit shift left (``<<``), bit shift right (``>>``) -================================================= - -Description ------------ +Bit Shift Operators (``<<``, ``>>``) +==================================== (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 diff --git a/docs/source/lang/bitwisemath.rst b/docs/source/lang/bitwisemath.rst index 30e8873..28fe6bf 100644 --- a/docs/source/lang/bitwisemath.rst +++ b/docs/source/lang/bitwisemath.rst @@ -2,8 +2,8 @@ .. _lang-bitwisemath: -Bitwise AND (&), OR (\|), XOR (^), NOT (~) -========================================== +Bitwise Operators (``&``, ``|``, ``^``, ``~``) +============================================== The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming @@ -22,8 +22,8 @@ Below are descriptions and syntax for all of the operators. .. _lang-bitwisemath-and: -Bitwise AND (&) ---------------- +Bitwise AND (``&``) +------------------- The bitwise AND operator in C++ is a single ampersand, ``&``, used between two other integer expressions. Bitwise AND operates on each @@ -54,8 +54,8 @@ value 1000100 in binary, which is 68 in decimal. .. _lang-bitwisemath-or: -Bitwise OR (\|) ---------------- +Bitwise OR (``|``) +------------------ The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like the ``&`` operator, ``|`` operates independently on each bit in its @@ -78,8 +78,8 @@ uses 32):: .. _lang-bitwisemath-xor: -Bitwise 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 @@ -129,8 +129,8 @@ program to blink digital pin 13 (the LED pin on Maple):: .. _lang-bitwisemath-not: -Bitwise NOT (~) ---------------- +Bitwise NOT (``~``) +------------------- The bitwise NOT operator in C++ is the tilde character ``~``. Unlike ``&`` and ``|``, the bitwise NOT operator is applied to a single @@ -179,7 +179,7 @@ See Also -------- - :ref:`Boolean operations <lang-boolean>` (``&&``, ``||``) -- :ref:`Compound bitwise operations <lang-bitwisecompound>` (``&=``, +- :ref:`Compound bitwise operations <lang-compoundbitwise>` (``&=``, ``|=``, ``^=``). diff --git a/docs/source/lang/bitwrite.rst b/docs/source/lang/bitwrite.rst index 86df26e..b3feff2 100644 --- a/docs/source/lang/bitwrite.rst +++ b/docs/source/lang/bitwrite.rst @@ -1,13 +1,19 @@ -.. _lang-bitwrite: +.. highlight:: cpp -bitWrite(x, n, b) -================= +.. _lang-bitwrite: -Description ------------ +bitWrite() +========== (Macro) Writes a bit of a numeric variable. +Syntax +------ + +:: + + bitWrite(x, n, b) + Parameters ---------- diff --git a/docs/source/lang/boolean.rst b/docs/source/lang/boolean.rst index 6ff4097..8d6aa5c 100644 --- a/docs/source/lang/boolean.rst +++ b/docs/source/lang/boolean.rst @@ -83,7 +83,7 @@ See Also -------- - :ref:`Bitwise operators <lang-bitwisemath>` (``&``, ``|``, ``^``, ``~``) -- :ref:`Compound bitwise operators <lang-bitwisecompound>` (``&=``, +- :ref:`Compound bitwise operators <lang-compoundbitwise>` (``&=``, ``|=``, ``^=``). - :ref:`if statement <lang-if>` diff --git a/docs/source/lang/booleanvariables.rst b/docs/source/lang/booleanvariables.rst index 9d0e992..6051b8c 100644 --- a/docs/source/lang/booleanvariables.rst +++ b/docs/source/lang/booleanvariables.rst @@ -6,9 +6,8 @@ Booleans ======== A **boolean** holds one of two values, :ref:`true -<lang-constants-true>` or :ref:`false <lang-constants-false>`. -On a Maple, each boolean variable occupies one byte of memory, and has -type ``bool``. +<lang-constants-true>` or :ref:`false <lang-constants-false>`. On a +Maple, each boolean variable has type ``bool``. .. warning:: diff --git a/docs/source/lang/break.rst b/docs/source/lang/break.rst index dc50b5f..ce8ac17 100644 --- a/docs/source/lang/break.rst +++ b/docs/source/lang/break.rst @@ -2,8 +2,8 @@ .. _lang-break: -break -===== +``break`` +========= ``break`` is used to exit from a :ref:`while <lang-while>`\ , :ref:`for <lang-for>`\ , or :ref:`do/while <lang-dowhile>` loop, diff --git a/docs/source/lang/bytecast.rst b/docs/source/lang/bytecast.rst index 4ad2a89..b3f0de2 100644 --- a/docs/source/lang/bytecast.rst +++ b/docs/source/lang/bytecast.rst @@ -5,9 +5,6 @@ byte() (cast) ============= -Description ------------ - Converts a value to the :ref:`byte <lang-byte>` data type. .. note:: diff --git a/docs/source/lang/char.rst b/docs/source/lang/char.rst index 8c6dadf..b8747f3 100644 --- a/docs/source/lang/char.rst +++ b/docs/source/lang/char.rst @@ -2,11 +2,8 @@ .. _lang-char: -char -==== - -Description ------------ +``char`` +======== The ``char`` type stores a 1-byte character value (or integer with value from -128 to 127). Character literals are written in single diff --git a/docs/source/lang/charcast.rst b/docs/source/lang/charcast.rst index 844dd58..a480dec 100644 --- a/docs/source/lang/charcast.rst +++ b/docs/source/lang/charcast.rst @@ -2,11 +2,8 @@ .. _lang-charcast: -char() (cast) -============= - -Description ------------ +``char()`` (cast) +================= Converts a value to the :ref:`char <lang-char>` data type. diff --git a/docs/source/lang/comparison.rst b/docs/source/lang/comparison.rst index 8873256..b24355f 100644 --- a/docs/source/lang/comparison.rst +++ b/docs/source/lang/comparison.rst @@ -2,8 +2,8 @@ .. _lang-comparison: -Comparison Operators -==================== +Comparison Operators (``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``) +=================================================================== The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and ``>=`` are used to compare two numbers. They are :ref:`true diff --git a/docs/source/lang/arithmeticcompound.rst b/docs/source/lang/compoundarithmetic.rst index aa0dc18..420f1db 100644 --- a/docs/source/lang/arithmeticcompound.rst +++ b/docs/source/lang/compoundarithmetic.rst @@ -1,15 +1,13 @@ .. highlight:: cpp -.. _lang-arithmeticcompound: +.. _lang-compoundarithmetic: Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) =============================================================== -Description ------------ - -Perform a mathematical operation on a variable with another constant -or variable. These operators are just a convenient shorthand:: +These oparators 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; diff --git a/docs/source/lang/bitwisecompound.rst b/docs/source/lang/compoundbitwise.rst index 2b0fe2f..a4bbb24 100644 --- a/docs/source/lang/bitwisecompound.rst +++ b/docs/source/lang/compoundbitwise.rst @@ -1,9 +1,9 @@ .. highlight:: cpp -.. _lang-bitwisecompound: +.. _lang-compoundbitwise: -Compound bitwise and (&=), or (\|=), XOR (^=) -============================================= +Compound Bitwise Operators (``&=``, ``|=``, ``^=``) +=================================================== The compound bitwise operators perform their calculations at the bit level of variables. They are often used to clear and set @@ -15,10 +15,10 @@ information on bitwise operators. .. contents:: Contents :local: -.. _lang-bitwisecompound-and: +.. _lang-compoundbitwise-and: -Compound bitwise AND (&=) -------------------------- +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 @@ -48,7 +48,7 @@ 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``. -.. _lang-bitwisecompound-binconst: +.. _lang-compoundbitwise-binconst: .. note:: The above uses :ref:`binary constants <lang-constants-integers-bin>`\ . The numbers are still the same @@ -101,10 +101,10 @@ then we will have :: b == B10101000; // B10101000 == 0xA8 -.. _lang-bitwisecompound-or: +.. _lang-compoundbitwise-or: -Compound bitwise OR (\|=) -------------------------- +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 @@ -118,7 +118,7 @@ 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 -<lang-bitwisecompound-and>`\ , ``&=``). +<lang-compoundbitwise-and>`\ , ``&=``). Before doing an example of ``|=``, let's first review the Bitwise OR (``|``) operator:: @@ -132,7 +132,7 @@ 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 <lang-bitwisecompound-binconst>` above). +:ref:`note <lang-compoundbitwise-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 @@ -164,10 +164,10 @@ then we will have :: b == B10101011; // B10101011 == 0xAB -.. _lang-bitwisecompound-xor: +.. _lang-compoundbitwise-xor: -Compound bitwise XOR (\^=) --------------------------- +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 @@ -181,8 +181,8 @@ 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:`&= -<lang-bitwisecompound-and>` and :ref:`\|= -<lang-bitwisecompound-or>`; in fact, these three operators all +<lang-compoundbitwise-and>` and :ref:`\|= +<lang-compoundbitwise-or>`; in fact, these three operators all work the same in this way). Before doing an example of ``^=``, let's first review the Bitwise @@ -203,7 +203,7 @@ 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 <lang-bitwisecompound-binconst>` above):: +:ref:`note <lang-compoundbitwise-binconst>` above):: 1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask diff --git a/docs/source/lang/const.rst b/docs/source/lang/const.rst index 1658e6d..52de85f 100644 --- a/docs/source/lang/const.rst +++ b/docs/source/lang/const.rst @@ -2,8 +2,8 @@ .. _lang-const: -const Keyword -============= +``const`` +========= The ``const`` keyword stands for "constant". It is a variable *qualifier* that modifies the behavior of the variable, making a diff --git a/docs/source/lang/constants.rst b/docs/source/lang/constants.rst index b7521ed..bc5c894 100644 --- a/docs/source/lang/constants.rst +++ b/docs/source/lang/constants.rst @@ -1,11 +1,11 @@ .. _lang-constants: -constants +Constants ========= -Constants are predefined variables in the Arduino language. They -are used to make the programs easier to read. We classify constants -in groups. +Constants are like predefined variables, whose values can't +change. They are used to make the programs easier to read and modify. +This page describes the most commonly used constants. .. contents:: Contents :local: @@ -15,288 +15,290 @@ in groups. Boolean Constants ----------------- -There are two constants used to represent truth and falsity in the -Arduino language: **true**, and **false**. +There are two constants used to represent truth and falsity: ``true``, +and ``false``. .. _lang-constants-false: false ^^^^^ -false is the easier of the two to define. false is defined as 0 -(zero). +``false`` is the false ``bool`` value. An integer which is 0 evaluates +to ``false`` as a boolean. .. _lang-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 -a Boolean sense. So -1, 2 and -200 are all defined as true, too, in -a Boolean sense. +``true`` is the true ``bool`` value. As an integer, ``true`` is often +said to be 1. This is correct in the sense that ``true`` evaluates to +1 as an integer. However, any integer which is *non-zero* is ``true`` +as a :ref:`bool <lang-booleanvariables>`. So -1, 2 and -200 are all +"true", in the sense that these numbers are treated the same as +``true`` in a boolean context. +Note that the ``true`` and ``false`` constants are typed in lowercase; +unlike e.g. ``HIGH``, ``LOW``, ``INPUT``, and ``OUTPUT`` (which are +described below). -Note that the *true* and *false* constants are typed in lowercase -unlike HIGH, LOW, INPUT, & OUTPUT. +Pin Levels: HIGH and LOW +------------------------ -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**. +When reading or writing to a digital pin there are only two possible +values a pin can be set to: ``HIGH`` and ``LOW``. .. _lang-constants-high: -**HIGH** - - - -The meaning of HIGH (in reference to a pin) is somewhat different -depending on whether a pin is set to an INPUT or OUTPUT. When a pin -is configured as an INPUT with pinMode, and read with digitalRead, -the microcontroller will report HIGH if a voltage of 3 volts or -more is present at the pin. - - +HIGH +^^^^ -A pin may also be configured as an INPUT with pinMode, and -subsequently made HIGH with digitalWrite, this will set the -internal 20K pullup resistors, which will *steer* the input pin to -a HIGH reading unless it is pulled LOW by external circuitry. +The meaning of ``HIGH`` (in reference to a pin) is somewhat different +depending on whether the pin is set to ``INPUT`` or ``OUTPUT``. When a +pin is configured as an ``INPUT`` (using :ref:`pinMode() +<lang-pinmode>`), and read with :ref:`digitalRead() +<lang-digitalread>`, the microcontroller will report ``HIGH`` if a +voltage of 3 volts or more is present at the pin. +.. TODO? Following seems false; check it out sometime, leave out for now: +.. A pin may also be configured as an ``INPUT`` with ``pinMode()``, and +.. subsequently made ``HIGH`` with :ref:`digitalWrite() +.. <lang-digitalwrite>`, this will set the internal pullup resistors, +.. which will *steer* the input pin to a HIGH reading unless it is pulled +.. LOW by external circuitry. -When a pin is configured to OUTPUT with pinMode, and set to HIGH -with digitalWrite, the pin is at 5 volts. In this state it can -*source* current, e.g. light an LED that is connected through a -series resistor to ground, or to another pin configured as an -output, and set to LOW. +When a pin is configured to ``OUTPUT`` with pinMode, and set to +``HIGH`` with :ref:`digitalWrite() <lang-digitalwrite>`, the pin is at +3.3 volts. In this state it can *source* current, e.g. light an LED +that is connected through a series resistor to ground, or to another +pin configured as an output and set to ``LOW``. .. _lang-constants-low: -**LOW** +LOW +^^^ +The meaning of ``LOW`` also has a different meaning depending on +whether a pin is set to ``INPUT`` or ``OUTPUT``. When a pin is +configured as an ``INPUT`` with :ref:`pinMode() <lang-pinmode>`, and +read with :ref:`digitalRead() <lang-digitalread>`, the microcontroller +will report ``LOW`` if a voltage of 2 volts or less is present at the +pin. +When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to +``LOW`` with :ref:`digitalWrite() <lang-digitalwrite>`, the +microcontroller will attempt to keep that pin's voltage at 0V. In this +state it can *sink* current, e.g. light an LED that is connected +through a series resistor to +3.3V, or to another pin configured as an +output, and set to ``HIGH``. -The meaning of LOW also has a different meaning depending on -whether a pin is set to INPUT or OUTPUT. When a pin is configured -as an INPUT with pinMode, and read with digitalRead, the -microcontroller will report LOW if a voltage of 2 volts or less is -present at the pin. +Pin Modes +--------- +Digital pins can be used in a variety of modes. The basic modes, +``INPUT`` and ``OUTPUT``, have been introduced above. Changing a pin +from ``INPUT`` TO ``OUTPUT`` with :ref:`pinMode() <lang-pinmode>` +drastically changes the electrical behavior of the pin. - -When a pin is configured to OUTPUT with pinMode, and set to LOW -with digitalWrite, the pin is at 0 volts. In this state it can -*sink* current, e.g. light an LED that is connected through a -series resistor to, +5 volts, or to another pin configured as an -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 -changes the electrical behavior of the pin. +This section describes the basic digital pin modes (``INPUT`` and +``OUTPUT``) only. For a detailed description of all possible pin +modes, see the :ref:`pinMode() <lang-pinmode>` reference page. .. _lang-constants-input: -Pins Configured as Inputs -^^^^^^^^^^^^^^^^^^^^^^^^^ +INPUT +^^^^^ -Arduino (Atmega) pins configured as **INPUT** with pinMode() are -said to be in a high-impedance state. One way of explaining this is -that pins configured as INPUT make extremely small demands on the -circuit that they are sampling, say equivalent to a series resistor -of 100 Megohms in front of the pin. This makes them useful for -reading a sensor, but not powering an LED. +Maple (STM32) pins configured as ``INPUT`` are said to be in a +high-impedance state. One way of explaining this is that pins +configured as ``INPUT`` make extremely small demands on the circuit +that they are sampling. This makes them useful for reading a sensor, +but not powering an LED. .. _lang-constants-output: -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 -amount of current to other circuits. Atmega pins can source -(provide positive current) or sink (provide negative current) up to -40 mA (milliamps) of current to other devices/circuits. This makes -them useful for powering LED's but useless for reading sensors. -Pins configured as outputs can also be damaged or destroyed if -short circuited to either ground or 5 volt power rails. The amount -of current provided by an Atmega pin is also not enough to power -most relays or motors, and some interface circuitry will be -required. - -.. _lang-constants-fp: - -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. - -.. TODO explain that floating point literals are doubles - -.. _lang-constants-fp-f: - -.. TODO f modifiers - -Examples: +OUTPUT +^^^^^^ -``n = .005;`` +Pins configured as ``OUTPUT`` with :ref:`pinMode() <lang-pinmode>` are +said to be in a low-impedance state. This means that they can provide +a substantial amount of current to other circuits. STM32 pins can +source (provide positive current) or sink (provide negative current) +up to 50 mA (milliamps) of current to other devices/circuits. This +makes them useful for powering LEDs, but useless for reading sensors. -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 +Pins configured as outputs can also be damaged or destroyed if short +circuited to either ground or 3.3V power rails. The amount of current +provided by an STM32 pin is also not enough to power most relays or +motors, and some interface circuitry will be required. .. _lang-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 +Integer constants (or more properly speaking, integer *literals*) are +numbers used directly in a sketch, like ``123``. By default, an +integer literal is treated as a (signed) :ref:`int <lang-int>`, but +you can change this with the U and L modifiers (see :ref:`below +<lang-constants-integers-u-l>`). You can specify negative numbers by +putting a minus sign in front, like ``-123``. + +Normally, integer literals are treated as base 10 (decimal) integers, +but special notation (formatters) may be used to enter numbers in +other bases. These are summarized in the following table: + +.. list-table:: + :header-rows: 1 + + * - Base + - Example + - Formatter + - Comment + + * - 10 (decimal) + - ``123`` + - None + - + + * - 2 (binary) + - ``0b1111011`` + - Leading "0b" + - GCC extension; not standard C++ + + * - 8 (octal) + - ``0173`` + - Leading "0" + - Characters 0-7 valid + + * - 16 (hexadecimal) + - ``0x7B`` + - Leading "0x" + - Characters 0-9, A-F (or a-f) valid + +Binary constants (like ``B1111011``) for values between 0 and 255 are +supported for compatibility with Arduino only. Their use in new +programs is discouraged. .. _lang-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. +**Decimal** is base 10. This is the common number system we learn in +school. Integer literals without other prefixes are assumed to be in +decimal format. - - -Example: -:: - - 101 // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) +For example, the decimal literal ``101`` is one hundred and one: 1×10\ +:sup:`2` + 0×10\ :sup:`1` + 1×10\ :sup:`0` = 101. .. _lang-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: +**Binary** is base two. Only characters 0 and 1 are valid. Binary +literals are indicated by the prefix ``0b`` (this is a :ref:`GCC +<arm-gcc>` extension; it's not standard C++). - - -:: - - myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte +For example, the binary literal ``0b101`` is five: 1×2\ :sup:`2` + +0×2\ :sup:`1` + 1×2\ :sup:`0` = 5. .. _lang-constants-integers-oct: **Octal** is base eight. Only characters 0 through 7 are valid. Octal -values are indicated by the prefix "0". +literals are indicated by the prefix ``0``. -Example: +For example, the octal literal ``0101`` is sixty five: 1×8\ :sup:`2` + +0×8\ :sup:`1` + 1×8\ :sup:`0` = 65. -:: +.. warning:: Bugs sometimes result by (unintentionally) including a + leading "0" before an integer literal, which makes the compiler + interpret it in octal. - 0101 // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) +.. _lang-constants-integers-hex: -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``. A-F +may be typed in upper or lower case (a-f). -.. _lang-constants-integers-hex: +For example, the hexadecimal literal ``0x101`` is two hundred fifty +seven: 1×16\ :sup:`2` + 0×16\ :sup:`1` + 1×16\ :sup:`0` = 257. -**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). +The hexadecimal literal ``0xCF2`` is three thousand, three hundred +fourteen: 12×16\ :sup:`2` + 15×16\ :sup:`1` + 2×16\ :sup:`0` = 3314. +(Remember that in hex, ``A`` means 10, and counting up, ``B``\ =11, so +``C``\ =12 and ``F``\ =15). +.. _lang-constants-integers-u-l: -Example: +U and L Suffixes +^^^^^^^^^^^^^^^^ -:: +By default, an integer constant is treated as an :ref:`int +<lang-int>`, with the attendant :ref:`limitations in values +<lang-int-overflow>`. To specify an integer constant with another data +type, follow it with: - 0x101 // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) +- a ``u`` or ``U`` to interpret the constant as an unsigned value. + For example, ``33U`` is an :ref:`unsigned int <lang-unsignedint>`. -.. _lang-constants-integers-u-l: +- an ``l`` or ``L`` to interpret the constant as a long value. For + example, ``100000L`` is a :ref:`long <lang-long>`. -U & L formatters -^^^^^^^^^^^^^^^^ +- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an + :ref:`unsigned long <lang-unsignedlong>`. + +.. _lang-constants-fp: -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: +Floating-Point Constants +------------------------ +Similar to integer literals, floating point constants (properly: +floating-point *literals*) are used to make code more readable. +Floating point literals are swapped at compile time for the value to +which the expression evaluates. +A floating point literal is any number which includes a decimal point. +For instance, ``3.0`` is a floating-point literal for the number 3. +By default, a floating-point literal is a :ref:`double <lang-double>`. +In order for the literal to be interpreted as a :ref:`float +<lang-float>`, you can write ``f`` directly after it. For example, +``3.0f`` is a floating-point literal with type ``float``. +Floating point constants can also be expressed in a variety of +scientific notation. ``E`` and ``e`` are both accepted as valid +exponent indicators. Some examples are given in the following table: -- 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`` +.. list-table:: + :header-rows: 1 + * - Floating-point literal + - Evaluates to + - Alternate expression + * - ``10.0`` + - 10 + - -See also --------- + * - ``2.34E5`` + - 2.34×10\ :sup:`5` + - ``234000.0`` + * - ``67e-12`` + - 67.0×10\ :sup:`-12` + - ``0.000000000067`` -- `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>`_ +See Also +-------- +- :ref:`pinMode() <lang-pinmode>` +- :ref:`Boolean Variables <lang-booleanvariables>` +- :ref:`#define <lang-define>` +- :ref:`int <lang-int>` +- :ref:`unsigned int <lang-unsignedint>` +- :ref:`long <lang-long>` +- :ref:`unsigned long <lang-unsignedlong>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/constrain.rst b/docs/source/lang/constrain.rst index 297a2d4..d19b61c 100644 --- a/docs/source/lang/constrain.rst +++ b/docs/source/lang/constrain.rst @@ -2,14 +2,18 @@ .. _lang-constrain: -constrain(x, a, b) -================== - -Description ------------ +constrain() +=========== (Macro) Constrains a number to be within a range. +Syntax +------ + +:: + + constrain(x, a, b) + Parameters ---------- diff --git a/docs/source/lang/continue.rst b/docs/source/lang/continue.rst index 21b3984..13d1815 100644 --- a/docs/source/lang/continue.rst +++ b/docs/source/lang/continue.rst @@ -2,9 +2,8 @@ .. _lang-continue: -========== - continue -========== +``continue`` +============ The ``continue`` keyword skips the rest of the current iteration of a :ref:`while <lang-while>`\ , :ref:`for <lang-for>`\ , or @@ -12,9 +11,8 @@ The ``continue`` keyword skips the rest of the current iteration of a conditional expression of the loop, and proceeding with any subsequent iterations. - Example -======= +------- :: diff --git a/docs/source/lang/braces.rst b/docs/source/lang/curly-braces.rst index 229ad8c..a4bd3dc 100644 --- a/docs/source/lang/braces.rst +++ b/docs/source/lang/curly-braces.rst @@ -1,9 +1,9 @@ .. highlight:: cpp -.. _lang-braces: +.. _lang-curly-braces: -Curly Braces ({}) -================= +Curly Braces (``{``, ``}``) +=========================== .. contents:: Contents :local: diff --git a/docs/source/lang/define.rst b/docs/source/lang/define.rst index 30738ec..677390d 100644 --- a/docs/source/lang/define.rst +++ b/docs/source/lang/define.rst @@ -2,8 +2,8 @@ .. _lang-define: -#define -======= +``#define`` +=========== ``#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. diff --git a/docs/source/lang/digitalread.rst b/docs/source/lang/digitalread.rst index 71583ca..3502587 100644 --- a/docs/source/lang/digitalread.rst +++ b/docs/source/lang/digitalread.rst @@ -5,9 +5,6 @@ digitalRead() ============= -Description ------------ - Reads the value from a specified digital pin, either :ref:`HIGH <lang-constants-high>` or :ref:`LOW <lang-constants-low>`. diff --git a/docs/source/lang/digitalwrite.rst b/docs/source/lang/digitalwrite.rst index 419ef3a..6124d5f 100644 --- a/docs/source/lang/digitalwrite.rst +++ b/docs/source/lang/digitalwrite.rst @@ -1,116 +1,68 @@ +.. highlight:: cpp + .. _lang-digitalwrite: digitalWrite() ============== -Description ------------ - -Write a `HIGH <http://arduino.cc/en/Reference/Constants>`_ or a -`LOW <http://arduino.cc/en/Reference/Constants>`_ value to a -digital pin. - - - -If the pin has been configured as an OUTPUT with -`pinMode <http://arduino.cc/en/Reference/PinMode>`_\ (), its voltage -will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) -for HIGH, 0V (ground) for LOW. - - - -If the pin is configured as an INPUT, writing a HIGH value with -digitalWrite() will enable an internal 20K pullup resistor (see the -`tutorial on digital pins <http://arduino.cc/en/Tutorial/DigitalPins>`_). -Writing LOW will disable the pullup. The pullup resistor is enough -to light an LED dimly, so if LEDs appear to work, but very dimly, -this is a likely cause. The remedy is to set the pin to an output -with the pinMode() function. - +Write a :ref:`HIGH <lang-constants-high>` or a :ref:`LOW +<lang-constants-low>` value to a pin configured as :ref:`OUTPUT +<lang-constants-output>`. +Library Documentation +--------------------- -**NOTE:** Digital pin 13 is harder to use as a digital input than -the other digital pins because it has an LED and resistor attached -to it that's soldered to the board on most boards. If you enable -its internal 20k pull-up resistor, it will hang at around 1.7 V -instead of the expected 5V because the onboard LED and series -resistor pull the voltage level down, meaning it always returns -LOW. If you must use pin 13 as a digital input, use an external -pull down resistor. +.. doxygenfunction:: digitalWrite - - -Syntax ------- - -digitalWrite(pin, value) - - - -Parameters +Discussion ---------- -pin: the pin number - +If the pin has been configured as an ``OUTPUT`` with :ref:`pinMode() +<lang-pinmode>` its voltage will be set to the corresponding value: +3.3V for ``HIGH``, and 0V (ground) for ``LOW``. +.. TODO make the following paragraphs true, but refer the reader to +.. INPUT_PULLUP and INPUT_PULLDOWN: -value: `HIGH <http://arduino.cc/en/Reference/Constants>`_ or -`LOW <http://arduino.cc/en/Reference/Constants>`_ - - - -Returns -------- - -none - +If the pin is configured as an ``INPUT``, writing a ``HIGH`` value +with ``digitalWrite()`` will enable an internal pullup resistor. +Writing ``LOW`` will disable the pullup. The pullup resistor is enough +to light an LED dimly, so if LEDs appear to work, but very dimly, this +is a likely cause. The remedy is to set the pin to an output with the +:ref:`pinMode() <lang-pinmode>` function. +.. note:: Pin 13 is harder to use as an input than the other pins + because it has an LED and resistor soldered to it in series. If you + enable its internal pull-up resistor, it will likely hang at around + 1.1V instead of the expected 3.3V because the onboard LED and + series resistor pull the voltage level down. If you must use pin 13 + as a digital input, use an external pull-down resistor. Example ------- -:: +The following example sets pin 13 to ``HIGH``, makes a one-second-long +delay, sets the pin back to ``LOW``, and delays again, causing a +blinking pattern:: int ledPin = 13; // LED connected to digital 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 } - - -Sets pin 13 to HIGH, makes a one-second-long delay, and sets the -pin back to LOW. - - - -Note ----- - -The analog input pins can be used as digital pins, referred to as -A0, A1, etc. - - - -See also +See Also -------- - -- `pinMode <http://arduino.cc/en/Reference/PinMode>`_\ () -- `digitalRead <http://arduino.cc/en/Reference/DigitalRead>`_\ () -- `Tutorial: Digital Pins <http://arduino.cc/en/Tutorial/DigitalPins>`_ - - - +- :ref:`pinMode <lang-pinmode>` +- :ref:`digitalRead <lang-digitalread>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/double.rst b/docs/source/lang/double.rst index b4a1219..1527778 100644 --- a/docs/source/lang/double.rst +++ b/docs/source/lang/double.rst @@ -1,13 +1,10 @@ .. _lang-double: -double -====== +``double`` +========== -Description ------------ - -Double precision floating point number. Occupies 8 bytes. On Maple, -the ``double`` type has a range of approximately -1.79769×10^308 to +Double precision floating point type. Occupies 8 bytes. On Maple, the +``double`` type has a range of approximately -1.79769×10^308 to 1.79769×10^308; the ``double`` type subject to the same :ref:`overflow issues <lang-variables-rollover>` as any numeric data type. diff --git a/docs/source/lang/doublecast.rst b/docs/source/lang/doublecast.rst index 4ea1776..511fe24 100644 --- a/docs/source/lang/doublecast.rst +++ b/docs/source/lang/doublecast.rst @@ -2,11 +2,8 @@ .. _lang-doublecast: -double() (cast) -=============== - -Description ------------ +``double()`` (cast) +=================== Converts a value to the :ref:`double <lang-double>` floating point data type. Here is an example:: diff --git a/docs/source/lang/dowhile.rst b/docs/source/lang/dowhile.rst index 77e02a3..fe92226 100644 --- a/docs/source/lang/dowhile.rst +++ b/docs/source/lang/dowhile.rst @@ -2,8 +2,8 @@ .. _lang-dowhile: -do/while Loop -============= +``do``/``while`` +================ A ``do`` loop works in the same manner as a :ref:`while <lang-while>` loop, with the exception that the condition is tested diff --git a/docs/source/lang/else.rst b/docs/source/lang/else.rst deleted file mode 100644 index 863f21b..0000000 --- a/docs/source/lang/else.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. highlight:: cpp - -.. _lang-else: - -if/else -======= - -``if``/\ ``else`` allows greater control over the flow of code than -the basic :ref:`if <lang-if>` statement, by allowing multiple tests -to be grouped together. For example, an :ref:`analog input -<lang-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) { - // action A - } else { - // action B - } - -``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. - - -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:: - - if (pinFiveInput < 500) { - // do Thing A - } else if (pinFiveInput >= 1000) { - // do Thing B - } else { - // do Thing C - } - -Another way to express branching, mutually exclusive tests, is with a -:ref:`switch/case <lang-switchcase>` statement. - -See Also --------- - -- :ref:`if <lang-if>` -- :ref:`switch/case <lang-switchcase>` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/enum.rst b/docs/source/lang/enum.rst index 5ecd99c..ba82383 100644 --- a/docs/source/lang/enum.rst +++ b/docs/source/lang/enum.rst @@ -1,8 +1,53 @@ +.. highlight:: cpp + .. _lang-enum: -enum -==== +``enum`` +======== + +The ``enum`` keyword is used to specify an enumeration type. An +enumeration type is a type whose values are taken from a specified, +fixed list of constant values. + +Example +------- + +Here's an example defining an enumeration type called ``weather``, +which has values ``HOT``, ``COMFY``, and ``COLD``:: + + enum weather {HOT, COMFY, COLD}; + +Once you've defined this type, you can create variables of type +``weather``, in the same way you would with an :ref:`int <lang-int>` +or a :ref:`long <lang-long>`:: + + // create a weather variable named theWeather, with value COMFY: + weather theWeather = COMFY; + +Enumeration types are useful within :ref:`switch statements +<lang-switchcase>`. If you know that an argument is of an enumeration +type, you can make ``case`` statements for all of that type's possible +values, so you know you won't miss anything:: + + void describeWeather(weather currentWeather) { + switch(currentWeather) { + case HOT: + SerialUSB.println("it's hot out"); + break; + case COMFY: + SerialUSB.println("it's nice today"); + break; + case COLD: + SerialUSB.println("it's freezing!"); + break; + } + } + +Such a ``switch`` statement would need no :ref:`default +<lang-switchcase-default>`, since we know that ``currentWeather`` must +be either ``HOT``, ``COMFY``, or ``COLD``. -Stub. +See Also +-------- -Reference this from language.rst +- :ref:`lang-switchcase` diff --git a/docs/source/lang/float.rst b/docs/source/lang/float.rst index ef1a339..6937c8c 100644 --- a/docs/source/lang/float.rst +++ b/docs/source/lang/float.rst @@ -2,11 +2,8 @@ .. _lang-float: -float -===== - -Description ------------ +``float`` +========= Single-precision floating point number. Occupies 4 bytes. On Maple, the ``float`` type has a range of approximately -3.40282×10^38 to diff --git a/docs/source/lang/floatcast.rst b/docs/source/lang/floatcast.rst index 7476188..4766478 100644 --- a/docs/source/lang/floatcast.rst +++ b/docs/source/lang/floatcast.rst @@ -2,15 +2,12 @@ .. _lang-floatcast: -float() (cast) -============== +``float()`` (cast) +================== -Description ------------ - -Converts a value to the :ref:`float <lang-float>` data type. Here -is an example (see the :ref:`constants reference -<lang-constants-fp-f>` for an explanation of the "2.0f"):: +Converts a value to the :ref:`float <lang-float>` data type. Here is +an example (see the :ref:`constants reference <lang-constants-fp>` for +an explanation of the "2.0f"):: int x = 2; float f = float(x); // f now holds 2.0f, a float value diff --git a/docs/source/lang/for.rst b/docs/source/lang/for.rst index 6b00d7a..71c5aca 100644 --- a/docs/source/lang/for.rst +++ b/docs/source/lang/for.rst @@ -2,14 +2,8 @@ .. _lang-for: -for Loops -========= - -.. contents:: Contents - :local: - -Description ------------ +``for`` +======= A ``for`` loop is used to repeat a block of statements enclosed in curly braces. ``for`` loops are useful for performing repetitive @@ -19,6 +13,12 @@ operations, and are often used in combination with :ref:`arrays *header*, which sets up the for loop, and then a *body*, which is made up of lines of code enclosed in curly braces. +.. contents:: Contents + :local: + +Syntax +------ + 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:: diff --git a/docs/source/lang/goto.rst b/docs/source/lang/goto.rst index 96a6262..ff2f248 100644 --- a/docs/source/lang/goto.rst +++ b/docs/source/lang/goto.rst @@ -2,8 +2,8 @@ .. _lang-goto: -Labels and 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 diff --git a/docs/source/lang/highbyte.rst b/docs/source/lang/highbyte.rst index af0bfcd..50a1fa6 100644 --- a/docs/source/lang/highbyte.rst +++ b/docs/source/lang/highbyte.rst @@ -1,7 +1,11 @@ +.. highlight:: cpp + .. _lang-highbyte: -highByte(x) -=========== +highByte() +========== + +(Macro) Extracts the second lowest byte of an integral data type. .. warning:: This macro is provided for compatibility with Arduino only. It returns the second-least significant byte in an integral @@ -13,10 +17,12 @@ highByte(x) In short: we provide this so that existing Arduino code works as expected, but **strongly discourage its use** in new programs. -Description ------------ +Syntax +------ -(Macro) Extracts the second lowest byte of an integral data type. +:: + + highByte(x) Parameters ---------- diff --git a/docs/source/lang/if.rst b/docs/source/lang/if.rst index 02ba1e7..bef89e2 100644 --- a/docs/source/lang/if.rst +++ b/docs/source/lang/if.rst @@ -2,8 +2,8 @@ .. _lang-if: -if Statements -============= +``if``/``else`` +=============== An ``if`` statement is used to execute code when certain conditions are met. The general syntax for an ``if`` statement is:: @@ -15,8 +15,8 @@ are met. The general syntax for an ``if`` statement is:: 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 <lang-braces>`. If the condition is -false, the body is not executed. Here's a more concrete example:: +code inside :ref:`curly braces <lang-curly-braces>`. If the condition +is false, the body is not executed. Here's a more concrete example:: if (someVariable > 50) { // do something here @@ -70,12 +70,52 @@ 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. +``else`` +-------- + +``if``/\ ``else`` allows greater control over the flow of code than +the basic :ref:`if <lang-if>` statement, by allowing multiple tests to +be grouped together. For example, an :ref:`analog input +<lang-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) { + // action A + } else { + // action B + } + +``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. + +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:: + + if (pinFiveInput < 500) { + // do Thing A + } else if (pinFiveInput >= 1000) { + // do Thing B + } else { + // do Thing C + } + +Another way to express branching, mutually exclusive tests, is with a +:ref:`switch/case <lang-switchcase>` statement. + + See Also -------- - :ref:`boolean operators <lang-boolean>` - :ref:`comparison operators <lang-comparison>` -- :ref:`else <lang-else>` - .. include:: cc-attribution.txt diff --git a/docs/source/lang/include.rst b/docs/source/lang/include.rst index a8bc74c..74fe7af 100644 --- a/docs/source/lang/include.rst +++ b/docs/source/lang/include.rst @@ -2,8 +2,8 @@ .. _lang-include: -#include -======== +``#include`` +============ ``#include`` is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C @@ -15,7 +15,8 @@ Example 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>`:: +that is used to control :ref:`LCD displays +<libraries-liquid-crystal>`:: // include the library code: #include <LiquidCrystal.h> diff --git a/docs/source/lang/increment.rst b/docs/source/lang/increment.rst index 5536a0a..6dffa80 100644 --- a/docs/source/lang/increment.rst +++ b/docs/source/lang/increment.rst @@ -2,8 +2,8 @@ .. _lang-increment: -Increment (``++``) and Decrement (``--``) -========================================= +Increment and Decrement Operators (``++``, ``--``) +================================================== These operators increment (add one to) or decrement (subtract one from) a variable. If they come before the variable, they return its @@ -29,16 +29,9 @@ A more extended example:: // this line won't compile (notice the extra space): int y = x+ +; -Parameters ----------- - -**x**: an integer value (like an ``int``, ``long``, ``unsigned int``, -etc.). - -See also +See Also -------- -- :ref:`Compound arithmetic operators <lang-arithmeticcompound>` - +- :ref:`lang-compoundarithmetic` .. include:: cc-attribution.txt diff --git a/docs/source/lang/int.rst b/docs/source/lang/int.rst index ac2f16a..ca75f75 100644 --- a/docs/source/lang/int.rst +++ b/docs/source/lang/int.rst @@ -2,11 +2,8 @@ .. _lang-int: -int -=== - -Description ------------ +``int`` +======= The ``int`` data type represents integers. Integers are your primary data type for number storage, and store a 4 byte value. This yields a @@ -43,7 +40,7 @@ Integer Overflow ---------------- When ``int`` variables leave the range specified above, they -:ref:`roll over <lang-variable-rollover>` in the other direction. +:ref:`roll over <lang-variables-rollover>` in the other direction. Here are some examples:: int x; diff --git a/docs/source/lang/intcast.rst b/docs/source/lang/intcast.rst index 03c0c07..386fe14 100644 --- a/docs/source/lang/intcast.rst +++ b/docs/source/lang/intcast.rst @@ -2,11 +2,8 @@ .. _lang-intcast: -int() -===== - -Description ------------ +``int()`` (cast) +================ Converts a value to the :ref:`int <lang-int>` data type. Here is an example:: diff --git a/docs/source/lang/keywords.rst b/docs/source/lang/keywords.rst index 451701e..e4ebe99 100644 --- a/docs/source/lang/keywords.rst +++ b/docs/source/lang/keywords.rst @@ -3,9 +3,203 @@ Keywords ======== -Stub. +This page lists all of the C++ keywords, and either links to a +reference page explaining their use, or provides a brief description. -Include list of all C++ keywords, with links to internal documentation -as appropriate. +List of Keywords +---------------- -Reference this page from language.rst +The C++ keywords are: + +``and``, ``and_eq``, ``asm``, ``auto``, ``bitand``, ``bitor``, +``bool``, ``break``, ``case``, ``catch``, ``char``, ``class``, +``compl``, ``const``, ``const_cast``, ``continue``, ``default``, +``delete``, ``do``, ``double``, ``dynamic_cast``, ``else``, ``enum``, +``explicit``, ``export``, ``extern``, ``false``, ``float``, ``for``, +``friend``, ``goto``, ``if``, ``inline``, ``int``, ``long``, +``mutable``, ``namespace``, ``new``, ``not``, ``not_eq``, +``operator``, ``or``, ``or_eq``, ``private``, ``protected``, +``public``, ``register``, ``reinterpret_cast``, ``return``, ``short``, +``signed``, ``sizeof``, ``static``, ``static_cast``, ``struct``, +``switch``, ``template``, ``this``, ``throw``, ``true``, ``try``, +``typedef``, ``typeid``, ``typename``, ``union``, ``unsigned``, +``using``, ``virtual``, ``void``, ``volatile``, ``wchar_t``, +``while``, ``xor``, ``xor_eq`` + +Boolean Operator Synonyms +------------------------- + +- ``and`` is a synonym for :ref:`&& <lang-boolean-and>`. +- ``not`` is a synonym for :ref:`\! <lang-boolean-not>`. +- ``not_eq`` is a synonym for :ref:`\!= <lang-comparison>`. +- ``or`` is a synonym for :ref:`|| <lang-boolean-or>`. + +Bitwise Operator Synonyms +------------------------- + +- ``and_eq`` is a synonym for :ref:`&= <lang-compoundbitwise-and>`. +- ``bitand`` is a synonym for (bitwise) :ref:`& <lang-bitwisemath-and>`. +- ``bitor`` is a synonym for :ref:`\| <lang-bitwisemath-or>`. +- ``compl`` is a synonym for :ref:`~ <lang-bitwisemath-not>`. +- ``or_eq`` is a synonym for :ref:`|= <lang-compoundbitwise-or>`. +- ``xor`` is a synonym for :ref:`^ <lang-bitwisemath-xor>`. +- ``xor_eq`` is a synonym for :ref:`^= <lang-compoundbitwise-xor>`. + +Constants +--------- + +- ``true`` and ``false`` are the :ref:`boolean constants + <lang-booleanvariables>`. + +Control Flow +------------ + +- ``break`` can exit out of a :ref:`switch statement + <lang-switchcase>` or a :ref:`for <lang-for>`, :ref:`do + <lang-dowhile>`, or :ref:`while <lang-while>` loop. + +- ``case`` defines alternatives in a :ref:`switch statement <lang-switchcase>`. + +- ``continue`` will move control flow to the next iteration of the + enclosing :ref:`for <lang-for>`, :ref:`do <lang-dowhile>`, or + :ref:`while <lang-while>` loop. + +- ``default`` defines the default alternative in a :ref:`switch + statement <lang-switchcase>`. + +- ``do`` introduces a :ref:`do <lang-dowhile>` loop. + +- ``else`` is used in :ref:`if statements <lang-if>`. + +- ``for`` introduces a :ref:`for <lang-for>` loop. + +- ``goto`` :ref:`jumps <lang-goto>` to a label. + +- ``if`` introduces an :ref:`if statement <lang-if>`. + +- ``return`` :ref:`transfers flow to a function's caller <lang-return>`. + +- ``switch`` introduces a :ref:`switch statement <lang-switchcase>`. + +- ``while`` introduces a :ref:`while <lang-while>` loop. + +Types +----- + +The following keywords are used for built-in types. + +- :ref:`bool <lang-booleanvariables>` +- :ref:`lang-char` +- :ref:`lang-double` +- :ref:`lang-float` +- :ref:`lang-int` +- :ref:`lang-long` +- :ref:`short <lang-numeric-types-integral>` +- :ref:`void <lang-void>` (not really a type, but used in the absence + of one) + +The following keywords are used to introduce new types. + +- :ref:`enum <lang-enum>` + +Qualifiers +---------- + +- :ref:`static <lang-static>` can be used to declare persistent local + variables; it has other uses not documented here. + +- ``unsigned`` is used to specify an unsigned integral type. + Examples: :ref:`lang-unsignedint`, :ref:`lang-unsignedchar`, + :ref:`lang-unsignedlong`. + +- :ref:`volatile <lang-volatile>` is useful when declaring variables + that may be modified by external interrupts. + +- :ref:`const <lang-const>` is used to define constants. + +Other +----- + +These keywords are not described in the Maple documentation. For more +information, consult a C++ reference. + +- ``asm`` is used to insert literal assembly language. + +- ``auto`` is used to declare that a variable has automatic storage. + +- ``catch`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC <arm-gcc>` include ``-fno-exceptions``. + +- ``class`` is used to define classes. + +- ``const_cast`` is used in typecasting. + +- ``delete`` is used to free ``new``\ -allocated storage. Note that + dynamic memory allocation is not available by default on the Maple, + so you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``dynamic_cast`` is used in typecasting. + +- ``explicit`` is used to declare constructors that can be called only + explicitly. + +- ``export`` declares a template definition accessible to other + compilation units. + +- ``extern`` can mark a declaration as a declaration and not a + definition, and also grant external linkage to a ``const`` or + ``typedef``. + +- ``friend`` is used to declare that certain functions have access to + a class's private variables. + +- ``inline`` is a compiler hint to inline a function. + +- ``mutable`` specifies that a member can be updated, even when a + member of a ``const`` object. + +- ``namespace`` declares a new namespace. + +- ``new`` dynamically allocates space for a value. Note that dynamic + memory allocation is not available by default on the Maple, so + you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``operator`` is used to define type-specific operator overrides. + +- ``private`` declares a private class member. + +- ``protected`` declares a protected class member. + +- ``public`` declares a public class member. + +- ``register`` is a compiler hint to store a variable in a register. + +- ``reinterpret_cast`` is used in typecasting. + +- ``signed`` is the opposite of ``unsigned``. + +- ``static_cast`` is used in typecasting. + +- ``struct`` declares a new struct. + +- ``template`` introduces a template class, function, etc. + +- ``this`` is a pointer to the receiver object. + +- ``throw`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC <arm-gcc>` include ``-fno-exceptions``. + +- ``try`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC <arm-gcc>` include ``-fno-exceptions``. + +- ``typedef`` defines a type synonym. + +- ``union`` defines an untagged union. + +- ``using`` is a directive related to namespaces. + +- ``virtual`` declares a method which may be overridden. + +- ``wchar_t`` is the wide character type. diff --git a/docs/source/lang/long.rst b/docs/source/lang/long.rst index 8a19b2b..d8498c0 100644 --- a/docs/source/lang/long.rst +++ b/docs/source/lang/long.rst @@ -2,11 +2,8 @@ .. _lang-long: -long -==== - -Description ------------ +``long`` +======== 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 @@ -19,7 +16,7 @@ Way galaxy). The exact range of a ``long`` on the Maple is from <lang-variables-rollover>` as any numeric data type. Here's an example of declaring a long (see :ref:`integer constants -<lang-constants-u-l>` for an explanation of the "L" at the end of the +<lang-constants-integers-u-l>` for an explanation of the "L" at the end of the number):: // Speed of light in nanometers per second (approximate). diff --git a/docs/source/lang/longcast.rst b/docs/source/lang/longcast.rst index 16d7582..2b92345 100644 --- a/docs/source/lang/longcast.rst +++ b/docs/source/lang/longcast.rst @@ -2,11 +2,8 @@ .. _lang-longcast: -long() -====== - -Description ------------ +``long()`` (cast) +================= Converts a value to the :ref:`long <lang-long>` data type. Here is an example:: diff --git a/docs/source/lang/lowbyte.rst b/docs/source/lang/lowbyte.rst index f9fb711..58e622f 100644 --- a/docs/source/lang/lowbyte.rst +++ b/docs/source/lang/lowbyte.rst @@ -3,43 +3,23 @@ lowByte() ========= -Description ------------ - Extracts the low-order (rightmost) byte of a variable (e.g. a word). - - Syntax ------ lowByte(x) - - Parameters ---------- -x: a value of any type - - +**x**: a value of any type. However, if a non-integral type is used, +the results will be strange. Returns ------- -byte - - - -See also --------- - - -- `highByte <http://arduino.cc/en/Reference/HighByte>`_\ () -- `word <http://arduino.cc/en/Reference/WordCast>`_\ () - - - +The low byte's value (this will be between 0 and 255). .. include:: cc-attribution.txt diff --git a/docs/source/lang/map.rst b/docs/source/lang/map.rst index 40b12a8..79122b3 100644 --- a/docs/source/lang/map.rst +++ b/docs/source/lang/map.rst @@ -1,122 +1,68 @@ -.. _lang-map: - -map(value, fromLow, fromHigh, toLow, toHigh) -============================================ - -Description ------------ - -Re-maps a number from one range to another. That is, a **value** of -**fromLow** would get mapped to **toLow**, a value of **fromHigh** -to **toHigh**, values in-between to values in-between, etc. - +.. highlight:: cpp +.. _lang-map: -Does not constrain values to within the range, because out-of-range -values are sometimes intended and useful. The constrain() function -may be used either before or after this function, if limits to the -ranges are desired. +map() +===== +Re-maps a number from one range to another. +.. contents:: Contents + :local: -Note that the "lower bounds" of either range may be larger or -smaller than the "upper bounds" so the map() function may be used -to reverse a range of numbers, for example +Library Documentation +--------------------- +.. doxygenfunction:: map +Discussion +---------- -``y = map(x, 1, 50, 50, 1);`` +``map()`` does not constrain values to within the range, because +out-of-range values are sometimes intended and useful. The +:ref:`constrain() <lang-constrain>` macro may be used either before or +after this function, if limits to the ranges are desired. +Note that the "lower bounds" of either range may be larger or smaller +than the "upper bounds" so that ``map()`` may be used to reverse a +range of numbers; for example:: + y = map(x, 1, 50, 50, 1); The function also handles negative numbers well, so that this -example - - - -``y = map(x, 1, 50, 50, -100);`` - - +example :: -is also valid and works well. + y = map(x, 1, 50, 50, -100); +is also valid. - -The map() function uses integer math so will not generate +The ``map()`` function uses integer math (its arguments and return +values all have type :ref:`long <lang-long>`), so it will not generate fractions, when the math might indicate that it should do so. -Fractional remainders are truncated, and are not rounded or -averaged. - - - -Parameters ----------- - -value: the number to map - - - -fromLow: the lower bound of the value's current range - - - -fromHigh: the upper bound of the value's current range - - - -toLow: the lower bound of the value's target range - - - -toHigh: the upper bound of the value's target range - - - -Returns -------- - -The mapped value. - - +Fractional remainders are truncated, and are not rounded or averaged. Example ------- :: - /* Map an analog value to 8 bits (0 to 255) */ - void setup() {} + /* Map an ADC reading (12 bits) to 16-bit PWM (0 to 65,535) */ - void loop() - { - int val = analogRead(0); - val = map(val, 0, 1023, 0, 255); - analogWrite(9, val); + void setup() { + pinMode(0, INPUT_ANALOG); + pinMode(9, PWM); } - - -Appendix -~~~~~~~~ - -For the mathematically inclined, here's the whole function - - - -:: - - long map(long x, long in_min, long in_max, long out_min, long out_max) - { - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + void loop() { + int val = analogRead(0); + val = map(val, 0, 4095, 0, 65535); + analogWrite(9, val); } - See Also -------- - -- `constrain <http://arduino.cc/en/Reference/Constrain>`_\ () - +- :ref:`constrain() <lang-constrain>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/max.rst b/docs/source/lang/max.rst index 7dbf6a7..d38eebe 100644 --- a/docs/source/lang/max.rst +++ b/docs/source/lang/max.rst @@ -2,15 +2,17 @@ .. _lang-max: -max(x, y) -========= - -Description ------------ +max() +===== (Macro) Calculates the maximum of two numbers. +Syntax +------ + +:: + max(x, y) Parameters ---------- diff --git a/docs/source/lang/micros.rst b/docs/source/lang/micros.rst index 711c013..f12976b 100644 --- a/docs/source/lang/micros.rst +++ b/docs/source/lang/micros.rst @@ -1,69 +1,46 @@ +.. highlight:: cpp + .. _lang-micros: micros() ======== -Description ------------ - -Returns the number of microseconds since the Arduino board began -running the current program. This number will overflow (go back to -zero), after approximately 70 minutes. On 16 MHz Arduino boards -(e.g. Duemilanove and Nano), this function has a resolution of four -microseconds (i.e. the value returned is always a multiple of -four). On 8 MHz Arduino boards (e.g. the LilyPad), this function -has a resolution of eight microseconds. - - - -*Note*: there are 1,000 microseconds in a millisecond and 1,000,000 -microseconds in a second. +Returns the number of microseconds since the Maple board began running +the current program. This number will overflow (go back to zero), +after approximately 70 minutes. +.. note:: There are 1,000 microseconds in a millisecond, and 1,000,000 + microseconds in a second. +Library Documentation +--------------------- -Parameters ----------- - -None - - - -Returns -------- - -Number of microseconds since the program started (*unsigned long*) - - +.. doxygenfunction:: micros Example ------- :: - unsigned long time; + unsigned int time; - void setup(){ - Serial.begin(9600); + void setup() { } - void loop(){ - Serial.print("Time: "); + + void loop() { + SerialUSB.print("Time: "); time = micros(); - //prints time since program started - Serial.println(time); + // prints time since program started + SerialUSB.println(time); // wait a second so as not to send massive amounts of data delay(1000); } - - -See also +See Also -------- - -- `millis <http://arduino.cc/en/Reference/Millis>`_\ () -- `delay <http://arduino.cc/en/Reference/Delay>`_\ () -- `delayMicroseconds <http://arduino.cc/en/Reference/DelayMicroseconds>`_\ () - - +- :ref:`millis() <lang-millis>` +- :ref:`delay() <lang-delay>` +- :ref:`delayMicroseconds() <lang-delaymicroseconds>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/millis.rst b/docs/source/lang/millis.rst index 6ebfff5..54e4507 100644 --- a/docs/source/lang/millis.rst +++ b/docs/source/lang/millis.rst @@ -1,70 +1,52 @@ +.. highlight:: cpp + .. _lang-millis: millis() ======== -Description ------------ - -Returns the number of milliseconds since the Arduino board began -running the current program. This number will overflow (go back to -zero), after approximately 50 days. - - - -Parameters ----------- - -None - - - -Returns -------- - -Number of milliseconds since the program started (*unsigned long*) +Returns the number of milliseconds since the Maple board began running +the current program. This number will overflow (go back to zero) after +approximately 50 days. +Library Documentation +--------------------- +.. doxygenfunction:: millis Example ------- -:: +The following time prints the value returned by ``millis()`` roughly +once per second:: - unsigned long time; + unsigned int time; - void setup(){ - Serial.begin(9600); + void setup() { } - void loop(){ - Serial.print("Time: "); + + void loop() { + SerialUSB.print("Time: "); time = millis(); - //prints time since program started + // prints time since program started Serial.println(time); + // wait a second so as not to send massive amounts of data delay(1000); } +Tip +--- +Since the return value for ``millis()`` is an :ref:`unsigned long +<lang-unsignedlong>`, overflow errors may occur if you try to do math +with other data types, such as :ref:`ints <lang-int>`. -Tip: ----- - -Note that the parameter for millis is an unsigned long, errors may -be generated if a programmer tries to do math with other datatypes -such as ints. - - - -See also +See Also -------- - -- `micros <http://arduino.cc/en/Reference/Micros>`_\ () -- `delay <http://arduino.cc/en/Reference/Delay>`_\ () -- `delayMicroseconds <http://arduino.cc/en/Reference/DelayMicroseconds>`_\ () -- `Tutorial: Blink Without Delay <http://arduino.cc/en/Tutorial/BlinkWithoutDelay>`_ - - +- :ref:`micros <lang-micros>` +- :ref:`delay <lang-delay>` +- :ref:`delayMicroseconds <lang-delaymicroseconds>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/min.rst b/docs/source/lang/min.rst index ffbf1ee..1245f6f 100644 --- a/docs/source/lang/min.rst +++ b/docs/source/lang/min.rst @@ -2,15 +2,17 @@ .. _lang-min: -min(x, y) -========= - -Description ------------ +min() +===== (Macro) Calculates the minimum of two numbers. +Syntax +------ + +:: + min(x,y) Parameters ---------- @@ -19,13 +21,11 @@ Parameters **y**: the second number; may be any number or numeric expression. - Returns ------- The smaller of the two numbers. - Example ------- diff --git a/docs/source/lang/modulo.rst b/docs/source/lang/modulo.rst index 9e0dabd..289fba0 100644 --- a/docs/source/lang/modulo.rst +++ b/docs/source/lang/modulo.rst @@ -2,11 +2,8 @@ .. _lang-modulo: -% (modulo) -========== - -Description ------------ +Modulo Operator (``%``) +======================= Calculates the `remainder <http://en.wikipedia.org/wiki/Remainder>`_ when one integer is divided by another. It is useful for keeping a @@ -17,9 +14,7 @@ Syntax :: - result = dividend % divisor - - + dividend % divisor Parameters ---------- @@ -67,11 +62,9 @@ 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 -------- - :ref:`Arithmetic <lang-arithmetic>` - .. include:: cc-attribution.txt diff --git a/docs/source/lang/numeric-types.rst b/docs/source/lang/numeric-types.rst new file mode 100644 index 0000000..9d2be48 --- /dev/null +++ b/docs/source/lang/numeric-types.rst @@ -0,0 +1,79 @@ +.. _lang-numeric-types: + +Numeric types +============= + +This document serves as a reference for all of the built-in numeric +types which are available when programming in the IDE. Programmers +using the :ref:`command-line tools <unix-toolchain>` will have access +to these types as long as they have imported ``wirish.h``; several are +defined in in `libmaple_types.h +<https://github.com/leaflabs/libmaple/blob/master/libmaple/libmaple_types.h>`_. + +.. _lang-numeric-types-integral: + +Integral types +-------------- + +.. cpp:type:: char + + 8-bit integer value. + +.. cpp:type:: short + + 16-bit integer value. + +.. cpp:type:: int + + 32-bit integer value. + +.. cpp:type:: long + + 64-bit integer value. + +.. cpp:type:: long long + + 64-bit integer value. + +.. cpp:type:: int8 + + Synonym for ``char``. + +.. cpp:type:: uint8 + + Synonym for ``unsigned char``. + +.. cpp:type:: int16 + + Synonym for ``short``. + +.. cpp:type:: uint16 + + Synonym for ``unsigned short``. + +.. cpp:type:: int32 + + Synonym for ``int``. + +.. cpp:type:: uint32 + + Synonym for ``unsigned int`` + +.. cpp:type:: int64 + + Synonym for ``long long`` + +.. cpp:type:: uint64 + + Synonym for ``unsigned long long``. + +Floating-Point Types +-------------------- + +.. cpp:type:: float + + 32-bit, IEEE 754 single-precision floating-point type. + +.. cpp:type:: double + + 64-bit, IEEE 754 double-precision floating-point type. diff --git a/docs/source/lang/pinmode.rst b/docs/source/lang/pinmode.rst index aed23d6..b9095da 100644 --- a/docs/source/lang/pinmode.rst +++ b/docs/source/lang/pinmode.rst @@ -18,50 +18,51 @@ Library Documentation Discussion ---------- -pinMode() is usually called within :ref:`lang-setup` in order to +``pinMode()`` is usually called within :ref:`lang-setup` in order to configure a pin for a certain usage (although it may be called anywhere). - Example ------- - :: - +:: int ledPin = 13; // LED connected to digital 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 } - - Arduino Compatibility --------------------- -The libmaple implementation of pinMode() supports OUTPUT and INPUT -modes with a meaning identical to that of the Arduino function. +.. TODO check out Arduino vs. Maple static discilpline cutoffs to +.. ensure accuracy of following: + +The libmaple implementation of ``pinMode()`` supports the ``INPUT`` +and ``OUTPUT`` modes with semantics identical to that of the Arduino +function (however, be advised that the Maple, as a 3.3V device, will +only drive 3.3V to an ``OUTPUT`` pin that has been set ``HIGH``). + +``INPUT_ANALOG`` and ``PWM`` modes were added because the Maple does +not distinguish between analog and digital pins the same way the +Arduino does. Unlike the Arduino, you **must call** ``pinMode()`` to +set up a pin for these purposes before a call to, e.g., +:ref:`lang-analogRead`. In practice, this should only add a few lines +to your :ref:`lang-setup` function. -INPUT_ANALOG and PWM modes were added because the Maple does not -distinguish between analog and digital pins the same way the Arduino -does. Unlike the Arduino, you **must call pinMode**\ () to set up a pin -for these purposes before a call to, e.g., :ref:`lang-analogRead`. -In practice, this should only add a few lines of pinMode() calls to -your :ref:`lang-setup` function. +.. TODO verify following before putting it in: -OUTPUT_OPEN_DRAIN, INPUT_PULLUP, INPUT_PULLDOWN, and PWM_OPEN_DRAIN -modes represent functionality not currently available on Arduino -boards. +.. ``OUTPUT_OPEN_DRAIN``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``, and +.. ``PWM_OPEN_DRAIN`` modes represent functionality not currently +.. available on Arduino boards. See also -------- diff --git a/docs/source/lang/pointer.rst b/docs/source/lang/pointer.rst index bc48d7d..0a42270 100644 --- a/docs/source/lang/pointer.rst +++ b/docs/source/lang/pointer.rst @@ -1,15 +1,19 @@ .. _lang-pointer: -The pointer operators: & (reference) and \* (dereference) -========================================================= +Pointer Operators (``&``, ``*``) +================================ +The pointer operators ``&`` (reference) and ``*`` (dereference) are +different from the bitwise math operator :ref:`& +<lang-bitwisemath-and>` and the arithmetic operator :ref:`* +<lang-arithmetic>`. Pointers are one of the more complicated subjects for beginners in -learning C, and it is possible to write the vast majority of -Arduino sketches without ever encountering pointers. However for -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. +learning C, and it is possible to write many useful Arduino sketches +without ever encountering pointers. However, for manipulating certain +data structures, the use of pointers can simplify the code, improve +its efficiency, and generally provide many benefits that would be +difficult to achieve without the use of pointers. Introducing pointers is somewhat outside the scope of this documentation. However, a good `pointer tutorial @@ -20,9 +24,8 @@ the section on `pointers in C <http://en.wikipedia.org/wiki/Pointer_%28computing%29#C_pointers>`_. See Also -======== +-------- - http://xkcd.com/138/ - .. include:: cc-attribution.txt diff --git a/docs/source/lang/pow.rst b/docs/source/lang/pow.rst index dbe89b6..4280400 100644 --- a/docs/source/lang/pow.rst +++ b/docs/source/lang/pow.rst @@ -1,7 +1,7 @@ .. _lang-pow: -pow(base, exponent) -=================== +pow() +===== Calculates the value of a number raised to a power. @@ -10,13 +10,7 @@ Library Documentation .. doxygenfunction:: pow -Example -------- - -``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. +.. TODO LATER some examples See Also -------- diff --git a/docs/source/lang/pwmwrite.rst b/docs/source/lang/pwmwrite.rst index acc0240..7a1d51f 100644 --- a/docs/source/lang/pwmwrite.rst +++ b/docs/source/lang/pwmwrite.rst @@ -23,9 +23,7 @@ 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>`_):: - +potentiometer:: int ledPin = 13; // LED connected to pin 13 (Maple) int analogPin = 3; // potentiometer connected to analog pin 3 diff --git a/docs/source/lang/random.rst b/docs/source/lang/random.rst index 51bee67..f2a9762 100644 --- a/docs/source/lang/random.rst +++ b/docs/source/lang/random.rst @@ -1,95 +1,73 @@ +.. highlight:: cpp + .. _lang-random: random() ======== -Description ------------ - -The random function generates pseudo-random numbers. - - - -Syntax ------- - -random(max) -random(min, max) - - - -Parameters ----------- - -min - lower bound of the random value, inclusive *(optional)* - +The ``random()`` function generates pseudo-random numbers. +.. TODO keep tracking Sphinx/Breathe's ability to reference overloaded +.. functions so we can use doxygenfunction instead of manually +.. documenting this. -max - upper bound of the random value, exclusive +Library Documentation +--------------------- +.. cpp:function:: random(long max) + Same as a call to ``random(0, max)``. -Returns -------- - -a random number between min and max-1 (*long*) +.. cpp:function:: random(long min, long max) + Generate a pseudo-random number with given lower and upper bounds. + *Parameters* -Note: ------ + - ``min`` - Lower bound on the returned value, inclusive + - ``max`` - Upper bound on the returned value, exclusive -If it is important for a sequence of values generated by random() -to differ, on subsequent executions of a sketch, use randomSeed() -to initialize the random number generator with a fairly random -input, such as analogRead() on an unconnected pin. + *Returns*: A pseudo-random number in the range [min, max). +Discussion +---------- +If it is important for a sequence of values generated by +:ref:`random() <lang-random>` to differ, on subsequent executions of a +sketch, use :ref:`randomSeed() <lang-randomseed>` to initialize the +random number generator with a fairly random input, such as +:ref:`analogRead() <lang-analogread>` on an unconnected pin. -Conversely, it can occasionally be useful to use pseudo-random +Conversely, it can occasionally be useful to use pseudorandom sequences that repeat exactly. This can be accomplished by calling -randomSeed() with a fixed number, before starting the random +``randomSeed()`` with a fixed number, before starting the random sequence. - - Example ------- -:: +The following sketch initializes the random seed based on an :ref:`ADC +<adc>` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +<ide-serial-monitor>` each time it is run:: long randNumber; - void setup(){ - Serial.begin(9600); - - // if analog input pin 0 is unconnected, random analog - // noise will cause the call to randomSeed() to generate - // different seed numbers each time the sketch runs. - // randomSeed() will then shuffle the random function. + void setup() { + pinMode(0, INPUT_ANALOG); randomSeed(analogRead(0)); } void loop() { - // print a random number from 0 to 299 randNumber = random(300); - Serial.println(randNumber); - - // print a random number from 10 to 19 - randNumber = random(10, 20); - Serial.println(randNumber); + SerialUSB.println(randNumber); delay(50); } - - -See also +See Also -------- - -- `randomSeed <http://arduino.cc/en/Reference/RandomSeed>`_\ () - - +- :ref:`randomSeed() <lang-randomseed>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/randomseed.rst b/docs/source/lang/randomseed.rst index 3dcf4db..d0a15b7 100644 --- a/docs/source/lang/randomseed.rst +++ b/docs/source/lang/randomseed.rst @@ -1,73 +1,60 @@ -.. _lang-randomseed: +.. highlight:: cpp -randomSeed(seed) -================ +.. _lang-randomseed: -Description ------------ +randomSeed() +============ -randomSeed() initializes the pseudo-random number generator, +``randomSeed()`` initializes the `pseudorandom number generator +<http://en.wikipedia.org/wiki/Pseudorandom_number_generator>`_, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same. +Library Documentation +--------------------- -If it is important for a sequence of values generated by random() -to differ, on subsequent executions of a sketch, use randomSeed() -to initialize the random number generator with a fairly random -input, such as analogRead() on an unconnected pin. +.. doxygenfunction:: randomSeed +Discussion +---------- +If it is important for a sequence of values generated by +:ref:`random() <lang-random>` to differ, on subsequent executions of a +sketch, use ``randomSeed()`` to initialize the random number generator +with a fairly random input, such as :ref:`analogRead() +<lang-analogread>` on an unconnected pin. -Conversely, it can occasionally be useful to use pseudo-random +Conversely, it can occasionally be useful to use pseudorandom sequences that repeat exactly. This can be accomplished by calling -randomSeed() with a fixed number, before starting the random +``randomSeed()`` with a fixed number, before starting the random sequence. - - -Parameters ----------- - -long, int - pass a number to generate the seed. - - - -Returns -------- - -no returns - - - Example ------- -:: +The following sketch initializes the random seed based on an :ref:`ADC +<adc>` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +<ide-serial-monitor>` each time it is run:: long randNumber; - void setup(){ - Serial.begin(9600); + void setup() { + pinMode(0, INPUT_ANALOG); randomSeed(analogRead(0)); } - void loop(){ + void loop() { randNumber = random(300); - Serial.println(randNumber); + SerialUSB.println(randNumber); delay(50); } - - -See also +See Also -------- - -- `random <http://arduino.cc/en/Reference/Random>`_ - - - +- :ref:`random() <lang-random>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/return.rst b/docs/source/lang/return.rst index e1b2924..7b5039e 100644 --- a/docs/source/lang/return.rst +++ b/docs/source/lang/return.rst @@ -2,11 +2,11 @@ .. _lang-return: -return -====== +``return`` +========== -(Keyword) Terminates a function and return a value from a function to -the calling function, if the function has non-``void`` return type. +Terminates a function and return a value from a function to the +calling function, if the function has non-``void`` return type. Syntax: ------- diff --git a/docs/source/lang/scope.rst b/docs/source/lang/scope.rst index 8e8bb13..7b65bab 100644 --- a/docs/source/lang/scope.rst +++ b/docs/source/lang/scope.rst @@ -2,8 +2,8 @@ .. _lang-scope: -Variable Scope -============== +Scope +===== Variables in the C++ programming language, which Maple uses (all of your sketches are C++ programs in disguise), have a property called @@ -25,8 +25,8 @@ of a function (like :ref:`setup() <lang-setup>` and :ref:`loop() A local variable can only be "seen" inside of a particular function. You can declare a variable to be local to a function by declaring it -inside of the :ref:`curly braces <lang-braces>` which enclose that -function. +inside of the :ref:`curly braces <lang-curly-braces>` which enclose +that function. When programs start to get larger and more complex, local variables are a useful way to ensure that a function has exclusive access to its diff --git a/docs/source/lang/semicolon.rst b/docs/source/lang/semicolon.rst index 4cf7b9f..8164616 100644 --- a/docs/source/lang/semicolon.rst +++ b/docs/source/lang/semicolon.rst @@ -2,8 +2,8 @@ .. _lang-semicolon: -Semicolon (;) -============= +Semicolon (``;``) +================= Used to end a line of code. Example:: diff --git a/docs/source/lang/serial.rst b/docs/source/lang/serial.rst index 743f921..f96547d 100644 --- a/docs/source/lang/serial.rst +++ b/docs/source/lang/serial.rst @@ -1,68 +1,219 @@ .. _lang-serial: -Serial -====== +Serial Ports (``Serial1``, ``Serial2``, ``Serial3``) +==================================================== -Used for communication between the Arduino board and a computer or -other devices. All Arduino boards have at least one serial port -(also known as a UART or USART): **Serial**. It communicates on -digital pins 0 (RX) and 1 (TX) as well as with the computer via -USB. Thus, if you use these functions, you cannot also use pins 0 -and 1 for digital input or output. +Used for communication between the Maple board and a computer or other +devices. +.. contents:: Contents + :local: +Introduction +------------ -You can use the Arduino environment's built-in serial monitor to -communicate with an Arduino board. Click the serial monitor button -in the toolbar and select the same baud rate used in the call to -begin(). +The Maple has three serial ports (also known as a UARTs or USARTs): +``Serial1``, ``Serial2``, and ``Serial3``. They communicate using the +pins summarized in the following table: +.. list-table:: + :header-rows: 1 + * - Serial port + - Pins (TX, RX) -The Arduino Mega has three additional serial ports: **Serial1** on -pins 19 (RX) and 18 (TX), **Serial2** on pins 17 (RX) and 16 (TX), -**Serial3** on pins 15 (RX) and 14 (TX). To use these pins to -communicate with your personal computer, you will need an -additional USB-to-serial adaptor, as they are not connected to the -Mega's USB-to-serial adaptor. To use them to communicate with an -external TTL serial device, connect the TX pin to your device's RX -pin, the RX to your device's TX pin, and the ground of your Mega to -your device's ground. (Don't connect these pins directly to an -RS232 serial port; they operate at +/- 12V and can damage your -Arduino board.) + * - ``Serial1`` + - 7, 8 + * - ``Serial2`` + - 1, 0 + * - ``Serial3`` + - 29, 30 -Functions ---------- +Thus, if you use a particular serial port, you cannot also use its +communication pins for other purposes at the same time. +Unlike the Arduino, none of these serial ports is connected to the USB +port on the Maple board. Thus, to use these pins to communicate with +your personal computer, you will need an additional USB-to-serial +adaptor. -- `begin <http://arduino.cc/en/Serial/Begin>`_\ () -- `end <http://arduino.cc/en/Serial/End>`_\ () -- `available <http://arduino.cc/en/Serial/Available>`_\ () -- `read <http://arduino.cc/en/Serial/Read>`_\ () -- `flush <http://arduino.cc/en/Serial/Flush>`_\ () -- `print <http://arduino.cc/en/Serial/Print>`_\ () +If you want to communicate with the Maple using the provided USB port, +use :ref:`SerialUSB <lang-serialusb>` instead. + +To use them to communicate with an external TTL serial device, connect +the TX pin to your device's RX pin, the RX to your device's TX pin, +and the ground of your Maple to your device's ground. + +.. warning:: Don't connect these pins directly to an RS232 serial + port; they operate at +/- 12V and can damage your board. + + +Library Documentation +--------------------- + +All of the ``Serial[1,2,3]`` objects are instances of the +``HardwareSerial`` class, which is documented in this section. (This +means that you can use any of these functions on any of ``Serial1``, +``Serial2``, and ``Serial3``). + +.. cpp:class:: HardwareSerial + + Serial port class. Predefined instances are Serial1, Serial2, and + Serial3. + +.. cpp:function:: HardwareSerial::begin(unsigned int baud) + + Set up a ``HardwareSerial`` object for communications. This method + must be called before attempting to use the ``HardwareSerial`` + object (typically, you call this in your :ref:`setup() + <lang-setup>` function). + +.. cpp:function:: HardwareSerial::end() + + Disables the USART associated with this object, allowing any + associated TX and RX pins to be used for other purposes. + +.. cpp:function:: unsigned int HardwareSerial::available() + + Returns the number of bytes available for reading. + +.. cpp:function:: unsigned char HardwareSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + <HardwareSerial::available>`), the call will block until one + becomes available. + +.. cpp:function:: HardwareSerial::flush() + + Removes the contents of the Serial's associated USART RX FIFO. + That is, clears any buffered characters, so that the next character + read is guaranteed to be new. + +.. cpp:function:: HardwareSerial::print(unsigned char b) + + Print the given byte over the USART. + +.. cpp:function:: HardwareSerial::print(char c) + + Print the given character over the USART. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: HardwareSerial::print(const char *str) + + Print the given null-terminated string over the USART. + +.. cpp:function:: HardwareSerial::print(int n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned int n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned long n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n, int base) + + Print the digits of ``n`` over the USART, in base ``base`` (which + may be between 2 and 16). The ``base`` value 2 corresponds to + binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. Negative + values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. .. _lang-serial-println: -- `println <http://arduino.cc/en/Serial/Println>`_\ () -- `write <http://arduino.cc/en/Serial/Write>`_\ () +.. cpp:function:: HardwareSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println() + + Prints ``"\r\n"`` over the USART. + +.. cpp:function:: HardwareSerial::write(unsigned char ch) + + Sends one character over the USART. This function is currently + blocking, although nonblocking writes are a planned future + extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: HardwareSerial::write(const char* str) + + Send the given null-terminated character string over the USART. + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. +.. cpp:function:: HardwareSerial::write(void *buf, unsigned int size) -Examples --------- + Writes the first ``size`` bytes of ``buf`` over the USART. Each + byte is transmitted as an individual character. + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. -- `ASCII Table <http://arduino.cc/en/Tutorial/ASCIITable>`_ -- `Dimmer <http://arduino.cc/en/Tutorial/Dimmer>`_ -- `Graph <http://arduino.cc/en/Tutorial/Graph>`_ -- `Physical Pixel <http://arduino.cc/en/Tutorial/PhysicalPixel>`_ -- `Virtual Color Mixer <http://arduino.cc/en/Tutorial/VirtualColorMixer>`_ -- `Serial Call Response <http://arduino.cc/en/Tutorial/SerialCallResponse>`_ -- `Serial Call Response ASCII <http://arduino.cc/en/Tutorial/SerialCallResponseASCII>`_ +.. TODO LATER port these examples over +.. Examples +.. -------- +.. - `ASCII Table <http://arduino.cc/en/Tutorial/ASCIITable>`_ +.. - `Dimmer <http://arduino.cc/en/Tutorial/Dimmer>`_ +.. - `Graph <http://arduino.cc/en/Tutorial/Graph>`_ +.. - `Physical Pixel <http://arduino.cc/en/Tutorial/PhysicalPixel>`_ +.. - `Virtual Color Mixer <http://arduino.cc/en/Tutorial/VirtualColorMixer>`_ +.. - `Serial Call Response <http://arduino.cc/en/Tutorial/SerialCallResponse>`_ +.. - `Serial Call Response ASCII <http://arduino.cc/en/Tutorial/SerialCallResponseASCII>`_ .. include:: cc-attribution.txt diff --git a/docs/source/lang/serialusb.rst b/docs/source/lang/serialusb.rst index 730fb07..9beee82 100644 --- a/docs/source/lang/serialusb.rst +++ b/docs/source/lang/serialusb.rst @@ -1,8 +1,240 @@ +.. highlight:: cpp + .. _lang-serialusb: -Serial over USB Communications -============================== +``SerialUSB`` +============= + +Used for communication between the Maple board and a computer. + +.. contents:: Contents + :local: + +Introduction +------------ + +In addition to three :ref:`serial ports <lang-serial>`, the Maple's +STM32 microprocessor includes a dedicated USB peripheral. This +peripheral is used to emulate a regular serial port for use as a +terminal (text read/write). The emulated terminal is relatively slow +and inefficient; it is best for transferring data at regular serial +speeds (kilobaud). + +Library access to the emulated serial port is provided through the +``SerialUSB`` object. You can mostly use ``SerialUSB`` as a drop-in +replacement for ``Serial1``, ``Serial2``, and ``Serial3``. + +.. warning:: The ``SerialUSB`` functionality includes a 50 millisecond + timeout for writes, and does not try to detect if the USB host is + "really" connected, or just enumerated and initialized. + + This means that if you have a number of calls to one of the + ``SerialUSB`` ``write()`` or ``print()`` functions in your code, + and you are not monitoring the emulated on a computer, your program + will run much, much slower than if it is being monitored or totally + disconnected (run off of a battery). + + You can avoid this behavior by :ref:`deciphering the port status + using the DTR and RTS line status <lang-serialusb-safe-print>`; the + behavior of these control lines is platform dependent and we no + longer interpret them by default. + +Library Documentation +--------------------- + +The ``SerialUSB`` object is an instance of the ``USBSerial`` class, +which is documented in this section. This means that you can use any +of these functions by writing +``SerialUSB.functionName(arguments...)``. For example, to print the +message "hello, world!", you can write ``USBSerial.println("hello, +world!")``. + +.. cpp:class:: USBSerial + + Emulated serial-over-USB class. ``SerialUSB`` is the predefined + instance. + +.. cpp:function:: USBSerial::begin() + + Set up the USB peripheral for emulated serial communication. The + peripheral is configured this way by default; calling this function + should only be necessary if you have disabled the peripheral using + ``SerialUSB.end()``. + +.. _lang-serialusb-end: + +.. cpp:function:: USBSerial::end() + + Disables the USB peripheral. + +.. cpp:function:: unsigned int USBSerial::available() + + Returns the number of bytes available for reading. + +.. cpp:function:: unsigned char USBSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + <USBSerial::available>`), the call will block until one + becomes available. + +.. cpp:function:: USBSerial::flush() + + Removes the contents of the Serial's associated input buffer. That + is, clears any buffered characters, so that the next character read + is guaranteed to be new. + +.. cpp:function:: USBSerial::print(unsigned char b) + + Print the given byte over the USB connection. + +.. cpp:function:: USBSerial::print(char c) + + Print the given character over the USB connection. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: USBSerial::print(const char *str) + + Print the given null-terminated string over the USB connection. + +.. cpp:function:: USBSerial::print(int n) + + Print the argument's digits over the USB connection, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned int n) + + Print the argument's digits over the USB connection, in decimal format. + +.. cpp:function:: USBSerial::print(long n) + + Print the argument's digits over the USB connection, in decimal + format. Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned long n) + + Print the argument's digits over the USB connection, in decimal + format. + +.. cpp:function:: USBSerial::print(long n, int base) + + Print the digits of ``n`` over the USB connection, in base ``base`` + (which may be between 2 and 16). The ``base`` value 2 corresponds + to binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. .. _lang-serialusb-println: -Stub. +.. cpp:function:: USBSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println() + + Prints ``"\r\n"`` over the USB connection. + +.. cpp:function:: USBSerial::write(unsigned char ch) + + Sends one character over the USB connection. This function is + currently blocking, although nonblocking writes are a planned + future extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(const char* str) + + Send the given null-terminated character string over the USB + connection. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(void *buf, unsigned int size) + + Writes the first ``size`` bytes of ``buf`` over the USB connection. + Each byte is transmitted as an individual character. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +Examples +-------- + +.. _lang-serialusb-safe-print: + +**Safe print**: This function should run smoothly and not block; the +LED should blink at roughly the same speed whether being monitored, +running from battery, or connected but not monitored. You may need to +experiment with the DTR/RTS logic for your platform and device +configuration. :: + + #define LED_PIN 13 + + void setup() { + /* Set up the LED to blink */ + pinMode(LED_PIN, OUTPUT); + } + + void loop() { + // LED will stay off if we are disconnected; + // will blink quickly if USB is unplugged (battery etc) + if(SerialUSB.isConnected()) { + digitalWrite(LED_PIN, 1); + } + delay(100); + + // If this logic fails to detect if bytes are going to + // be read by the USB host, then the println() will fully + // many times, causing a very slow LED blink. + // If the characters are printed and read, the blink will + // only slow a small amount when "really" connected, and fast + // when the virtual port is only configured. + if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { + for(int i=0; i<10; i++) { + SerialUSB.println(123456,BIN); + } + } + digitalWrite(LED_PIN, 0); + delay(100); + } + diff --git a/docs/source/lang/setup.rst b/docs/source/lang/setup.rst index 6b142d2..837ddd6 100644 --- a/docs/source/lang/setup.rst +++ b/docs/source/lang/setup.rst @@ -1,34 +1,29 @@ +.. highlight:: cpp + .. _lang-setup: setup() ======= -The setup() function is called when a sketch starts. Use it to -initialize variables, pin modes, start using libraries, etc. The -setup function will only run once, after each powerup or reset of -the Arduino board. - - +The ``setup()`` function is called when a sketch starts. Use it to +initialize :ref:`variables <lang-variables>`, :ref:`pin modes +<lang-pinmode>`, start using :ref:`libraries <libraries>`, etc. The +``setup()`` function will only run once, after each power-up or reset +of the Maple board. Example -~~~~~~~ +------- :: + int buttonPin = 38; - int buttonPin = 3; - - void setup() - { - Serial.begin(9600); + void setup() { pinMode(buttonPin, INPUT); } - void loop() - { + void loop() { // ... } - - .. include:: cc-attribution.txt diff --git a/docs/source/lang/sizeof.rst b/docs/source/lang/sizeof.rst index 409a6d7..eae509c 100644 --- a/docs/source/lang/sizeof.rst +++ b/docs/source/lang/sizeof.rst @@ -2,8 +2,8 @@ .. _lang-sizeof: -sizeof() -======== +``sizeof()`` +============ The ``sizeof`` operator on the Maple returns the number of bytes needed to store a value of a given type\ [#fcharsize]_. This can be diff --git a/docs/source/lang/sq.rst b/docs/source/lang/sq.rst index a14817f..bd32648 100644 --- a/docs/source/lang/sq.rst +++ b/docs/source/lang/sq.rst @@ -2,14 +2,18 @@ .. _lang-sq: -sq(a) -===== - -Description ------------ +sq() +==== (Macro) computes the square of a number. +Syntax +------ + +:: + + sq(a) + Parameters ---------- diff --git a/docs/source/lang/static.rst b/docs/source/lang/static.rst index 4646db1..5d1802e 100644 --- a/docs/source/lang/static.rst +++ b/docs/source/lang/static.rst @@ -2,8 +2,8 @@ .. _lang-static: -Static -====== +``static`` +========== The ``static`` keyword can be used to create variables that are visible to only one function. However, unlike local variables that get diff --git a/docs/source/lang/string.rst b/docs/source/lang/string.rst index 92c3f69..0a270da 100644 --- a/docs/source/lang/string.rst +++ b/docs/source/lang/string.rst @@ -5,9 +5,6 @@ Strings ======= -Description ------------ - Text strings can be represented in two ways. You can 1. Use the :ref:`String <lang-stringclass>` data type, which is diff --git a/docs/source/lang/switchcase.rst b/docs/source/lang/switchcase.rst index 46c47d8..b484bc5 100644 --- a/docs/source/lang/switchcase.rst +++ b/docs/source/lang/switchcase.rst @@ -2,12 +2,12 @@ .. _lang-switchcase: -switch / case statements -======================== +``switch``\ /\ ``case`` +======================= -Like :ref:`if/else <lang-else>` blocks, A ``switch`` statement -controls program flow by allowing you to specify different code that -should be executed under various cases. +Like :ref:`if <lang-if>` statements, A ``switch`` statement controls +program flow by allowing you to specify different code that should be +executed under various cases. The general syntax looks like this:: @@ -27,7 +27,6 @@ Where ``var`` is a variable whose value to investigate, and the ``val1``, ``val2`` after each ``case`` are constant values that ``var`` might be. - Description ----------- @@ -80,6 +79,8 @@ a ``break`` has been reached, so the program continues by calling ``afterTheSwitch()``. This is usually not what you want, which is why each ``case`` usually has a ``break`` at the end. +.. _lang-switchcase-default: + 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, @@ -104,14 +105,14 @@ two, ``doThing2()`` gets called. If ``var`` is anything else, optional. If you're missing one and none of the ``case`` statements match, the ``switch`` does nothing at all, as if it weren't there. -``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. +``switch`` statements are often used with an :ref:`enum <lang-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. See also: --------- -- :ref:`if...else <lang-else>` +- :ref:`if/else <lang-if>` .. include:: cc-attribution.txt diff --git a/docs/source/lang/types.rst b/docs/source/lang/types.rst deleted file mode 100644 index d095da1..0000000 --- a/docs/source/lang/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _lang-types: - -Built-in types -============== - -Stub. (explain all built-in integral and floating-point types, -including ``uint8`` style ones). diff --git a/docs/source/lang/interrupts.rst b/docs/source/lang/unimplemented/interrupts.rst index 5ca7041..55b8e93 100644 --- a/docs/source/lang/interrupts.rst +++ b/docs/source/lang/unimplemented/interrupts.rst @@ -3,9 +3,6 @@ interrupts() ============ -Description ------------ - Re-enables interrupts (after they've been disabled by `noInterrupts <http://arduino.cc/en/Reference/NoInterrupts>`_\ ()). Interrupts allow certain important tasks to happen in the @@ -59,4 +56,4 @@ See Also -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/nointerrupts.rst b/docs/source/lang/unimplemented/nointerrupts.rst index 2043c91..fb2e5f9 100644 --- a/docs/source/lang/nointerrupts.rst +++ b/docs/source/lang/unimplemented/nointerrupts.rst @@ -56,4 +56,4 @@ See Also -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/notone.rst b/docs/source/lang/unimplemented/notone.rst index 22432e2..485c9c5 100644 --- a/docs/source/lang/notone.rst +++ b/docs/source/lang/unimplemented/notone.rst @@ -47,4 +47,4 @@ See also -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/pulsein.rst b/docs/source/lang/unimplemented/pulsein.rst index 7bbe84c..2b52428 100644 --- a/docs/source/lang/pulsein.rst +++ b/docs/source/lang/unimplemented/pulsein.rst @@ -79,4 +79,4 @@ Example -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/shiftout.rst b/docs/source/lang/unimplemented/shiftout.rst index e76cc01..ff3852f 100644 --- a/docs/source/lang/shiftout.rst +++ b/docs/source/lang/unimplemented/shiftout.rst @@ -133,4 +133,4 @@ Example -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/stringclass.rst b/docs/source/lang/unimplemented/stringclass.rst index 5e53f08..cdd385d 100644 --- a/docs/source/lang/stringclass.rst +++ b/docs/source/lang/unimplemented/stringclass.rst @@ -6,4 +6,4 @@ String Class Stub. -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/stringobject.rst b/docs/source/lang/unimplemented/stringobject.rst index d7f287c..e47ed7e 100644 --- a/docs/source/lang/stringobject.rst +++ b/docs/source/lang/unimplemented/stringobject.rst @@ -6,12 +6,11 @@ String Description ----------- -The String class, part of the core as of version 0019, allows you -to use and manipulate strings of text in more complex ways than -`character arrays <http://arduino.cc/en/Reference/String>`_ do. You -can concatenate Strings, append to them, search for and replace -substrings, and more. It takes more memory than a simple character -array, but it is also more useful. +The String class, part of the core as of version 0019, allows you to +use and manipulate strings of text in more complex ways than character +arrays do. You can concatenate Strings, append to them, search for and +replace substrings, and more. It takes more memory than a simple +character array, but it is also more useful. @@ -81,11 +80,10 @@ See Also -------- -- `string <http://arduino.cc/en/Reference/String>`_: character - arrays +- `Character array strings <http://arduino.cc/en/Reference/String>`_ - `Variable Declaration <http://arduino.cc/en/Reference/VariableDeclaration>`_ -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/tone.rst b/docs/source/lang/unimplemented/tone.rst index 96f0a7c..f83bf6b 100644 --- a/docs/source/lang/tone.rst +++ b/docs/source/lang/unimplemented/tone.rst @@ -78,4 +78,4 @@ See also -.. include:: cc-attribution.txt +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unsignedchar.rst b/docs/source/lang/unsignedchar.rst index c49690d..5b946ed 100644 --- a/docs/source/lang/unsignedchar.rst +++ b/docs/source/lang/unsignedchar.rst @@ -2,11 +2,8 @@ .. _lang-unsignedchar: -unsigned char -============= - -Description ------------ +``unsigned char`` +================= An unsigned version of the :ref:`char <lang-char>` data type. An ``unsigned char`` occupies 1 byte of memory; it stores an integer from diff --git a/docs/source/lang/unsignedint.rst b/docs/source/lang/unsignedint.rst index aa5cc1b..f6311da 100644 --- a/docs/source/lang/unsignedint.rst +++ b/docs/source/lang/unsignedint.rst @@ -2,11 +2,8 @@ .. _lang-unsignedint: -unsigned int -============ - -Description ------------ +``unsigned int`` +================ An ``unsigned int`` (unsigned integer) is the same as an :ref:`int <lang-int>` in that it stores a 4 byte integer value. However, diff --git a/docs/source/lang/unsignedlong.rst b/docs/source/lang/unsignedlong.rst index 2ca49f8..14a4fc3 100644 --- a/docs/source/lang/unsignedlong.rst +++ b/docs/source/lang/unsignedlong.rst @@ -2,11 +2,8 @@ .. _lang-unsignedlong: -unsigned long -============= - -Description ------------ +``unsigned long`` +================= An unsigned version of the :ref:`long <lang-long>` data type. An ``unsigned long`` occupies 8 bytes of memory; it stores an integer @@ -19,8 +16,8 @@ won't store negative numbers; it is also subject to the same Here is an example of declaring an ``unsigned long`` variable named ``c``, then giving it value 299,792,458,000,000,000 (see :ref:`integer -constants <lang-constants-u-l>` for an explanation of the "L" at the -end of the number):: +constants <lang-constants-integers-u-l>` for an explanation of the "L" +at the end of the number):: // Speed of light in nanometers per second (approximate). unsigned long c = 299792458000000000L; diff --git a/docs/source/lang/variables.rst b/docs/source/lang/variables.rst index 05a4f96..9094cd5 100644 --- a/docs/source/lang/variables.rst +++ b/docs/source/lang/variables.rst @@ -37,8 +37,8 @@ named ``inputVariable2``, with an initial value of ``0``:: int inputVariable2 = 0; The Maple environment comes ready to use with many useful types of -variables. See the :ref:`built-in types <lang-types>` page for more -information. +variables. See the :ref:`built-in types <lang-numeric-types>` page +for more information. Here are a few examples of declaring variables of different types:: @@ -116,8 +116,8 @@ he goes past the left side of the screen, he reappears on the right:: x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" Each numeric type's reference page includes its range. See the -:ref:`built-in types <lang-types>` reference for links to each type's -reference page. +:ref:`built-in types <lang-numeric-types>` reference for links to each +type's reference page. Using Variables --------------- @@ -149,7 +149,7 @@ See Also -------- - :ref:`lang-scope` -- :ref:`lang-types` +- :ref:`lang-numeric-types` .. rubric:: Footnotes diff --git a/docs/source/lang/void.rst b/docs/source/lang/void.rst index bc7a3dc..88bd448 100644 --- a/docs/source/lang/void.rst +++ b/docs/source/lang/void.rst @@ -1,40 +1,31 @@ +.. highlight:: cpp + .. _lang-void: -void -==== +``void`` +======== -The void keyword is used only in function declarations. It +The ``void`` keyword is used only in function declarations. It indicates that the function is expected to return no information to -the function from which it was called. - - +the function from which it was called, or that it expects no arguments +from its caller. -Example: --------- +Example +------- :: // actions are performed in the functions "setup" and "loop" // but no information is reported to the larger program - void setup() - { + void setup() { // ... } - void loop() - { + void loop() { // ... } - - - -See also --------- - -`function declaration <http://arduino.cc/en/Reference/FunctionDeclaration>`_ - - +.. TODO doc page on function declaration? .. include:: cc-attribution.txt diff --git a/docs/source/lang/volatile.rst b/docs/source/lang/volatile.rst index a0ef671..276bb6a 100644 --- a/docs/source/lang/volatile.rst +++ b/docs/source/lang/volatile.rst @@ -1,37 +1,31 @@ -.. _lang-volatile: - -volatile keyword -================ - -volatile is a keyword known as a variable *qualifier*, it is -usually used before the datatype of a variable, to modify the way -in which the compiler and subsequent program treats the variable. - - - -Declaring a variable volatile is a directive to the compiler. The -compiler is software which translates your C/C++ code into the -machine code, which are the real instructions for the Atmega chip -in the Arduino. - - +.. highlight:: cpp -Specifically, it directs the compiler to load the variable from RAM -and not from a storage register, which is a temporary memory -location where program variables are stored and manipulated. Under -certain conditions, the value for a variable stored in registers -can be inaccurate. +.. _lang-volatile: +``volatile`` +============ +The ``volatile`` keyword known is a variable *qualifier*. It is +usually used before the datatype of a variable, to modify the way in +which the compiler treats the variable. -A variable should be declared volatile whenever its value can be -changed by something beyond the control of the code section in -which it appears, such as a concurrently executing thread. In the -Arduino, the only place that this is likely to occur is in sections -of code associated with interrupts, called an interrupt service -routine. +Declaring a variable ``volatile`` is a directive to the compiler. The +compiler is software which translates your C++ code into the machine +code, which are the real instructions for the STM32 chip in the +Maple. (The particular compiler we provide for use with the Maple is a +version of :ref:`GCC <arm-gcc>`). +Specifically, it directs the compiler to read the variable's value +fresh every time it is used, rather than "backing up" the value and +reading from its backup copy. (Compilers often "back up" a variable's +value in RAM into a storage location called a *register*; this is done +for efficiency). +A variable should be declared ``volatile`` whenever its value can be +changed by something beyond the control of the code section in which +it appears, such as an :ref:`external interrupt +<external-interrupts>`. On the Maple, the only place that this is +likely to occur is in sections of code associated with interrupts. Example ------- @@ -43,31 +37,29 @@ Example int pin = 13; volatile int state = LOW; - void setup() - { + void setup() { pinMode(pin, OUTPUT); attachInterrupt(0, blink, CHANGE); } - void loop() - { + void loop() { digitalWrite(pin, state); } - void blink() - { - state = !state; + void blink() { + if (state == HIGH) { + state = LOW; + } else { + // state must be HIGH + state = HIGH; + } } - - See also -------- - -- `AttachInterrupt <http://arduino.cc/en/Reference/AttachInterrupt>`_ - - - +- :ref:`External Interrupts <external-interrupts>` +- :ref:`lang-attachinterrupt` +- :ref:`lang-detachinterrupt` .. include:: cc-attribution.txt diff --git a/docs/source/lang/while.rst b/docs/source/lang/while.rst index be1ea14..9047d05 100644 --- a/docs/source/lang/while.rst +++ b/docs/source/lang/while.rst @@ -1,37 +1,28 @@ -.. _lang-while: - -while Loops -=========== - -Description ------------ - -**while** loops will loop continuously, and infinitely, until the -expression inside the parenthesis, () becomes false. Something must -change the tested variable, or the **while** loop will never exit. -This could be in your code, such as an incremented variable, or an -external condition, such as testing a sensor. +.. highlight:: cpp +.. _lang-while: +``while`` +========= Syntax ------ :: - while(expression){ - // statement(s) + while (expression) { + // block of code } +Description +----------- - -Parameters ----------- - -expression - a (boolean) C statement that evaluates to true or -false - - +``while`` loops will repeat the statements inside their associated +block of code until the expression inside the parentheses becomes +:ref:`false <lang-constants-false>`. Something must change the tested +expressions' value, or the ``while`` loop will never exit. This could +be in your code, such as an incremented variable, or an external +condition, such as testing a sensor. Example ------- @@ -39,11 +30,9 @@ Example :: var = 0; - while(var < 200){ + while(var < 200) { // do something repetitive 200 times var++; } - - .. include:: cc-attribution.txt diff --git a/docs/source/language-index.rst b/docs/source/language-index.rst index 90b3d79..ddc7849 100644 --- a/docs/source/language-index.rst +++ b/docs/source/language-index.rst @@ -6,126 +6,23 @@ Language Reference Index This is the index of the :ref:`language reference <language>` documentation. -Not converted Arduino docs: - .. toctree:: :maxdepth: 1 + :glob: - lang/pwmwrite - lang/types - lang/serialusb + lang/* -Finished: +.. Unfinished, unimplemented in libmaple: .. toctree:: - :maxdepth: 1 - - lang/abs - lang/analogread - lang/pinmode - lang/arithmetic - lang/array - lang/assignment - lang/attachinterrupt - lang/bit - lang/bitclear - lang/bitread - lang/bitset - lang/bitshift - lang/analogwrite - lang/bitwisemath - lang/bitwisecompound - lang/bitwrite - lang/boolean - lang/booleanvariables - lang/braces - lang/break - lang/byte - lang/bytecast - lang/char - lang/charcast - lang/comments - lang/const - lang/constrain - lang/continue - lang/cos - lang/define - lang/delay - lang/delaymicroseconds - lang/detachinterrupt - lang/digitalread - lang/double - lang/doublecast - lang/dowhile - lang/else - lang/float - lang/floatcast - lang/for - lang/goto - lang/highbyte - lang/if - lang/comparison - lang/include - lang/increment - lang/arithmeticcompound - lang/int - lang/intcast - lang/long - lang/longcast - lang/loop - lang/max - lang/min - lang/modulo - lang/pointer - lang/pow - lang/return - lang/scope - lang/semicolon - lang/sin - lang/sizeof - lang/sqrt - lang/sq - lang/static - lang/string - lang/switchcase - lang/tan - lang/unsignedchar - lang/unsignedint - lang/unsignedlong - lang/variables + :hidden: -Unfinished; straightforward to convert: - -.. toctree:: - :maxdepth: 1 - - lang/void - lang/volatile - lang/while - lang/keywords - lang/enum - -Unfinished, requires libmaple/Arduino knowledge: - -.. toctree:: - :maxdepth: 1 + lang/unimplemented/interrupts.rst + lang/unimplemented/nointerrupts.rst + lang/unimplemented/notone.rst + lang/unimplemented/pulsein.rst + lang/unimplemented/shiftout.rst + lang/unimplemented/stringclass.rst + lang/unimplemented/stringobject.rst + lang/unimplemented/tone.rst - lang/constants - lang/digitalwrite - lang/notone - lang/serial - lang/interrupts - lang/analogwrite - lang/nointerrupts - lang/pulsein - lang/stringobject - lang/tone - lang/random - lang/randomseed - lang/setup - lang/map - lang/shiftout - lang/micros - lang/millis - lang/lowbyte - lang/stringclass diff --git a/docs/source/language.rst b/docs/source/language.rst index 0a79fb0..350b0c3 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -52,6 +52,9 @@ Unique Maple Additions Maple Language Reference ------------------------ +The following table summarizes the available language features. A +more exhaustive index is available at the :ref:`language-index`. + +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ | Structure | Variables | Functions | | | | | @@ -63,151 +66,154 @@ Maple Language Reference | | |* :ref:`digitalWrite() <lang-digitalwrite>` | |**Control Structures** |* :ref:`INPUT <lang-constants-input>` | | | | | :ref:`OUTPUT <lang-constants-output>` |* :ref:`digitalRead() <lang-digitalread>` | -|* :ref:`if <lang-if>` | | | +|* :ref:`if/else <lang-if>` | | | | |* :ref:`true <lang-constants-true>` | | | -|* :ref:`if...else <lang-else>` | :ref:`false <lang-constants-false>` |**Analog I/O** | -| | | | -|* :ref:`for <lang-for>` |* :ref:`integer constants |* :ref:`analogRead() <lang-analogread>` | -| | <lang-constants-integers>` | | -|* :ref:`switch/case <lang-switchcase>` | |* :ref:`pwmWrite() <lang-pwmwrite>` | -| |* :ref:`floating point constants | (:ref:`analogWrite() <lang-analogwrite>` is | -|* :ref:`while <lang-while>` | <lang-constants-fp>` | also available, though its use is discouraged) | +|* :ref:`for <lang-for>` | :ref:`false <lang-constants-false>` |**Analog I/O** | | | | | -|* :ref:`do...while <lang-dowhile>` | | | -| |**Data Types** |**Advanced I/O** | +|* :ref:`switch/case <lang-switchcase>` |* :ref:`Constants |* :ref:`analogRead() <lang-analogread>` | +| | <lang-constants>` (:ref:`integers | | +|* :ref:`while <lang-while>` | <lang-constants-integers>`, :ref:`floating |* :ref:`pwmWrite() <lang-pwmwrite>` | +| | point <lang-constants-fp>`) | (:ref:`analogWrite() <lang-analogwrite>` is | +|* :ref:`do...while <lang-dowhile>` | | also available, though its use is discouraged) | +| |**Data Types** | | |* :ref:`break <lang-break>` | | | -| | The size of each datatype, in bytes, is |* tone(): TODO | +| | The size of each datatype, in bytes, is |**Advanced I/O** | |* :ref:`continue <lang-continue>` | given in parentheses where appropriate. | | -| | |* noTone(): TODO | +| | |* tone(): TODO | |* :ref:`return <lang-return>` | *Note*: The ``word`` type is (deliberately) | | -| | :ref:`not supported <language-no-word>`. |* shiftOut(): TODO | +| | :ref:`not supported <language-no-word>`. |* noTone(): TODO | |* :ref:`goto <lang-goto>` | | | -| |* :ref:`void <lang-void>` |* pulseIn(): TODO | +| |* :ref:`void <lang-void>` |* shiftOut(): TODO | +| | | | +|**Further syntax** |* :ref:`boolean <lang-boolean>` (1 byte) |* pulseIn(): TODO | | | | | -|**Further syntax** |* :ref:`boolean <lang-boolean>` (1 byte) | | -| | |**Time** | |* :ref:`; (semicolon) <lang-semicolon>` |* :ref:`char <lang-char>` (1 byte) | | -| | |* :ref:`millis() <lang-millis>` | -|* :ref:`{} (curly braces) <lang-braces>` |* :ref:`unsigned char | | -| | <lang-unsignedchar>` (1 byte) |* :ref:`micros() <lang-micros>` | -|* :ref:`// (single-line comment) | | | -| <lang-comments-singleline>` |* :ref:`byte <lang-byte>` (1 byte) |* :ref:`delay() <lang-delay>` | +| | |**Time** | +|* :ref:`{} (curly braces) |* :ref:`unsigned char | | +| <lang-curly-braces>` | <lang-unsignedchar>` (1 byte) |* :ref:`millis() <lang-millis>` | | | | | -|* :ref:`/\* \*/ (multi-line comment) |* :ref:`int <lang-int>` (4 bytes) |* :ref:`delayMicroseconds() | -| <lang-comments-multiline>` | | <lang-delaymicroseconds>` | -| |* :ref:`unsigned int <lang-unsignedint>` | | -|* :ref:`#define <lang-define>` | (4 bytes) | | -| | |**Math** | -|* :ref:`#include <lang-include>` |* :ref:`long <lang-long>` (8 bytes) | | -| | |* :ref:`min() <lang-min>` | +|* :ref:`// (single-line comment) |* :ref:`byte <lang-byte>` (1 byte) |* :ref:`micros() <lang-micros>` | +| <lang-comments-singleline>` | | | +| |* :ref:`int <lang-int>` (4 bytes) |* :ref:`delay() <lang-delay>` | +|* :ref:`/\* \*/ (multi-line comment) | | | +| <lang-comments-multiline>` |* :ref:`unsigned int <lang-unsignedint>` |* :ref:`delayMicroseconds() | +| | (4 bytes) | <lang-delaymicroseconds>` | +|* :ref:`#define <lang-define>` | | | +| |* :ref:`long <lang-long>` (8 bytes) | | +|* :ref:`#include <lang-include>` | |**Math** | | |* :ref:`unsigned long <lang-unsignedlong>` | | -|**Arithmetic Operators** | (8 bytes) |* :ref:`max() <lang-max>` | +| | (8 bytes) |* :ref:`min() <lang-min>` | +|**Arithmetic Operators** | | | +| |* :ref:`float <lang-float>` (4 bytes) |* :ref:`max() <lang-max>` | +|* :ref:`= <lang-assignment>` | | | +| (assignment operator) |* :ref:`double <lang-double>` (8 bytes) |* :ref:`abs() <lang-abs>` | | | | | -|* :ref:`= <lang-assignment>` |* :ref:`float <lang-float>` (4 bytes) |* :ref:`abs() <lang-abs>` | -| (assignment operator) | | | -| |* :ref:`double <lang-double>` (8 bytes) |* :ref:`constrain() <lang-constrain>` | -|* :ref:`+ <lang-arithmetic>` (addition) | | | -| |* :ref:`string <lang-string>` |* :ref:`map() <lang-constrain>` | -|* :ref:`- <lang-arithmetic>` | | | -| (subtraction) |* :ref:`array <lang-array>` |* :ref:`pow() <lang-pow>` | +|* :ref:`+ <lang-arithmetic>` (addition) |* :ref:`Strings <lang-string>` |* :ref:`constrain() <lang-constrain>` | | | | | -|* :ref:`* <lang-arithmetic>` |* See also: :ref:`built-in types reference |* :ref:`sqrt() <lang-sqrt>` | -| (multiplication) | <lang-types>`. | | +|* :ref:`- <lang-arithmetic>` |* :ref:`Arrays <lang-array>` |* :ref:`map() <lang-map>` | +| (subtraction) | | | +| |* :ref:`enum <lang-enum>` |* :ref:`pow() <lang-pow>` | +|* :ref:`* <lang-arithmetic>` | | | +| (multiplication) |* :ref:`Numeric types <lang-numeric-types>` |* :ref:`sqrt() <lang-sqrt>` | | | | | -|* :ref:`/ <lang-arithmetic>` (division) | |**Trigonometry** | -| |**Conversion** | | -|* :ref:`% <lang-modulo>` (modulo) | |* :ref:`sin() <lang-sin>` | -| |* :ref:`char() <lang-charcast>` | | -| | |* :ref:`cos() <lang-cos>` | -|**Comparison Operators** |* :ref:`byte() <lang-bytecast>` | | -| | |* :ref:`tan() <lang-tan>` | -|* :ref:`== <lang-comparison>` (equal to) |* :ref:`int() <lang-intcast>` | | +|* :ref:`/ <lang-arithmetic>` (division) |**Conversion** | | +| | |**Trigonometry** | +|* :ref:`% <lang-modulo>` (modulo) |* :ref:`char() <lang-charcast>` | | +| | |* :ref:`sin() <lang-sin>` | +| |* :ref:`byte() <lang-bytecast>` | | +|**Comparison Operators** | |* :ref:`cos() <lang-cos>` | +| |* :ref:`int() <lang-intcast>` | | +|* :ref:`== <lang-comparison>` (equal to) | |* :ref:`tan() <lang-tan>` | +| |* :ref:`long() <lang-longcast>` | | +|* :ref:`\!= <lang-comparison>` | | | +| (not equal to) |* :ref:`float() <lang-floatcast>` |**Random Numbers** | | | | | -|* :ref:`\!= <lang-comparison>` |* :ref:`long() <lang-longcast>` |**Random Numbers** | -| (not equal to) | | | -| |* :ref:`float() <lang-floatcast>` |* :ref:`randomSeed() <lang-randomseed>` | -|* :ref:`< <lang-comparison>` (less than) | | | -| |* :ref:`double() <lang-doublecast>` |* :ref:`random() <lang-random>` | -|* :ref:`> <lang-comparison>` | | | -| (greater than) | | | -| |**Variable Scope & Qualifiers** |**Bits and Bytes** | -|* :ref:`<= <lang-comparison>` | | | -| (less than or equal to) |* :ref:`variables <lang-variables>`, |* :ref:`lowByte() <lang-lowbyte>` | -| | :ref:`scope <lang-variables-scope>` | | -|* :ref:`>= <lang-comparison>` | |* :ref:`highByte() <lang-highbyte>` is | -| (greater than or equal to) |* :ref:`static <lang-static>` | provided, though its use is discouraged. | +|* :ref:`< <lang-comparison>` (less than) |* :ref:`double() <lang-doublecast>` |* :ref:`randomSeed() <lang-randomseed>` | | | | | -| |* :ref:`volatile <lang-volatile>` |* :ref:`bitRead() <lang-bitread>` | -|**Boolean Operators** | | | -| |* :ref:`const <lang-const>` |* :ref:`bitWrite() <lang-bitwrite>` | -|* :ref:`&& <lang-boolean-and>` (and) | | | -| | |* :ref:`bitSet() <lang-bitset>` | -|* :ref:`|| <lang-boolean-or>` (or) |**Utilities** | | -| | |* :ref:`bitClear() <lang-bitclear>` | -|* :ref:`\! <lang-boolean-not>` (not) |* :ref:`sizeof() <lang-sizeof>` | | -| | (``sizeof`` operator) |* :ref:`bit() <lang-bit>` | +|* :ref:`> <lang-comparison>` | |* :ref:`random() <lang-random>` | +| (greater than) |**Variable Scope & Qualifiers** | | | | | | -|**Pointer Operators** | | | -| | |**External Interrupts** | -|* :ref:`* dereference operator | | | -| <lang-pointer>` | |* :ref:`Reference Page <external-interrupts>` | +|* :ref:`<= <lang-comparison>` |* :ref:`variables <lang-variables>`, |**Bits and Bytes** | +| (less than or equal to) | :ref:`scope <lang-variables-scope>` | | +| | |* :ref:`lowByte() <lang-lowbyte>` | +|* :ref:`>= <lang-comparison>` |* :ref:`static <lang-static>` | | +| (greater than or equal to) | |* :ref:`highByte() <lang-highbyte>` is | +| |* :ref:`volatile <lang-volatile>` | provided, though its use is discouraged. | | | | | -|* :ref:`& reference operator | |* :ref:`attachInterrupt() | -| <lang-pointer>` | | <lang-attachinterrupt>` | +|**Boolean Operators** |* :ref:`const <lang-const>` |* :ref:`bitRead() <lang-bitread>` | | | | | -| | |* :ref:`detachInterrupt() | -|**Bitwise Operators** | | <lang-detachinterrupt>` | +|* :ref:`&& <lang-boolean-and>` (and) | |* :ref:`bitWrite() <lang-bitwrite>` | +| |**Utilities** | | +|* :ref:`|| <lang-boolean-or>` (or) | |* :ref:`bitSet() <lang-bitset>` | +| |* :ref:`sizeof() <lang-sizeof>` | | +|* :ref:`\! <lang-boolean-not>` (not) | |* :ref:`bitClear() <lang-bitclear>` | | | | | +| | |* :ref:`bit() <lang-bit>` | +|**Pointer Operators** | | | +| | | | +|* :ref:`* dereference operator | |**External Interrupts** | +| <lang-pointer>` | | | +| | |* :ref:`Reference Page <external-interrupts>` | +|* :ref:`& reference operator | | | +| <lang-pointer>` | |* :ref:`attachInterrupt() | +| | | <lang-attachinterrupt>` | +| | | | +|**Bitwise Operators** | |* :ref:`detachInterrupt() | +| | | <lang-detachinterrupt>` | |* :ref:`& <lang-bitwisemath-and>` | | | -| (bitwise and) | |**Interrupts** | +| (bitwise and) | | | +| | |**Interrupts** | +|* :ref:`| <lang-bitwisemath-or>` | | | +| (bitwise or) | |* interrupts(): TODO | | | | | -|* :ref:`| <lang-bitwisemath-or>` | |* interrupts(): TODO | -| (bitwise or) | | | -| | |* noInterrupts(): TODO | -|* :ref:`^ <lang-bitwisemath-xor>` | | | +|* :ref:`^ <lang-bitwisemath-xor>` | |* noInterrupts(): TODO | | (bitwise xor) | | | -| | |**Communication** | -|* :ref:`~ <lang-bitwisemath-not>` | | | -| (bitwise not) | |* :ref:`SerialUSB <lang-serialusb>` | | | | | -|* :ref:`\<\< <lang-bitshift>` | |* :ref:`Serial <lang-serial>` | -| (shift left) | | | -| | |**Looking for something else?** | -|* :ref:`>> <lang-bitshift>` | | | -| (shift right) | | See the :ref:`libraries` page for interfacing with| +|* :ref:`~ <lang-bitwisemath-not>` | |**Communication** | +| (bitwise not) | | | +| | |* :ref:`SerialUSB <lang-serialusb>` | +|* :ref:`\<\< <lang-bitshift>` | | | +| (shift left) | |* :ref:`Serial <lang-serial>` | +| | | | +|* :ref:`>> <lang-bitshift>` | |**Looking for something else?** | +| (shift right) | | | +| | | See the :ref:`libraries` page for interfacing with| | | | particular types of hardware. Maple links | -| | | against `newlib <http://sourceware.org/newlib/>`_ | -|**Compound Operators** | | and allows the use of any of its functions; see | -| | | its documentation for more details. | -|* :ref:`++ <lang-increment>` | | | +|**Compound Operators** | | against `newlib <http://sourceware.org/newlib/>`_ | +| | | and allows the use of any of its functions; see | +|* :ref:`++ <lang-increment>` | | its documentation for more details. | | (increment) | | | | | | | |* :ref:`- - <lang-increment>` | | | | (decrement) | | | | | | | -|* :ref:`+= <lang-arithmeticcompound>` | | | +|* :ref:`+= <lang-compoundarithmetic>` | | | | (compound add) | | | | | | | |* :ref:`-= | | | -| <lang-arithmeticcompound>` (compound | | | +| <lang-compoundarithmetic>` (compound | | | | subtract) | | | | | | | |* :ref:`*= | | | -| <lang-arithmeticcompound>` (compound | | | +| <lang-compoundarithmetic>` (compound | | | | multiply) | | | | | | | |* :ref:`/= | | | -| <lang-arithmeticcompound>` (compound | | | +| <lang-compoundarithmetic>` (compound | | | | divide) | | | | | | | |* :ref:`&= | | | -| <lang-arithmeticcompound>` (compound | | | +| <lang-compoundbitwise>` (compound | | | | bitwise and) | | | | | | | |* :ref:`|= | | | -| <lang-arithmeticcompound>` (compound | | | +| <lang-compoundbitwise>` (compound | | | | bitwise or) | | | | | | | +|**Keywords** | | | +| | | | +|* :ref:`C++ Keywords <lang-keywords>` | | | +| | | | | | | | +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 6a97b0e..6ecdf07 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -18,7 +18,7 @@ in the description of the library. .. contents:: Contents :local: -.. _liquid_crystal: +.. _libraries-liquid-crystal: LiquidCrystal ------------- @@ -32,7 +32,7 @@ At this time, no incompatibilities between the Maple and Arduino versions are known. Any observed differences should be considered bugs, and reported on the forums. -.. _wire: +.. _libraries-wire: Wire ---- diff --git a/docs/source/spi.rst b/docs/source/spi.rst index 4cfd7e7..ca9415c 100644 --- a/docs/source/spi.rst +++ b/docs/source/spi.rst @@ -35,7 +35,7 @@ Function Reference ``Spi.begin(freq, endianness, mode)`` - ``begin`` is usually called in `setup()`_ to configure the + ``begin`` is usually called in :ref:`lang-setup` to configure the baudrate of the given SPI port and to set up the header pins appropriately. ``freq`` is one of the set listed :ref:`above <spi-speeds>`; ``endianness`` is either ``LSBFIRST`` or diff --git a/docs/source/timers.rst b/docs/source/timers.rst index fe6ea4a..948805b 100644 --- a/docs/source/timers.rst +++ b/docs/source/timers.rst @@ -2,9 +2,8 @@ .. _timers: -======== - Timers -======== +Timers +====== There are four general purpose timers in the Maple microcontroller that can be configured to generate periodic or delayed events with @@ -52,7 +51,7 @@ configuration being the same. **Jitter:** other interrupts (USB, Serial, SysTick, or other timers) can and will get called before or during the timer - interrupt routines, causing pseudo-random delays and other + interrupt routines, causing pseudorandom delays and other frustrations. Disabling the USB port (by calling ``SerialUSB.end()``, or just @@ -90,7 +89,7 @@ General Timer Modes :ref:`PWM docs <pwm>` for more information on this mode. .. note:: - + ``Timer1.setChannel1Mode(TIMER_PWM)`` may not work as expected; if you want PWM functionality on a channel, make sure you don't set it to something else. @@ -240,7 +239,7 @@ LED blink void setup() { - // Set up the LED to blink + // Set up the LED to blink pinMode(LED_PIN, OUTPUT); // Setup Timer @@ -251,13 +250,13 @@ LED blink } void loop() { - // Nothing! It's all in the interrupts + // Nothing! It's all in the interrupts } void handler_led(void) { toggle ^= 1; digitalWrite(LED_PIN, toggle); - } + } Racing Counters ^^^^^^^^^^^^^^^ @@ -287,7 +286,7 @@ Racing Counters Timer3.setOverflow(30000); Timer4.setOverflow(30000); Timer3.setCompare1(1000); // somewhere in the middle - Timer4.setCompare1(1000); + Timer4.setCompare1(1000); Timer3.attachCompare1Interrupt(handler1); Timer4.attachCompare1Interrupt(handler2); Timer3.resume(); @@ -296,9 +295,9 @@ Racing Counters void loop() { // Display the running counts - SerialUSB.print("Count 1: "); + SerialUSB.print("Count 1: "); SerialUSB.print(count1); - SerialUSB.print("\t\tCount 2: "); + SerialUSB.print("\t\tCount 2: "); SerialUSB.println(count2); // Run... while BUT is held, pause Count2 @@ -314,7 +313,7 @@ Racing Counters void handler1(void) { count1++; - } + } void handler2(void) { count2++; - } + } diff --git a/docs/source/troubleshooting.rst b/docs/source/troubleshooting.rst index 9d452d1..7b80a3f 100644 --- a/docs/source/troubleshooting.rst +++ b/docs/source/troubleshooting.rst @@ -30,10 +30,8 @@ use :ref:`perpetual bootloader mode My board is bricked! I can't upload via the bootloader no matter what! ---------------------------------------------------------------------- -Use the hardcoded serial STM32 serial bootloader to re-flash the -bootloader. - -.. TODO insert docs on reflashing the bootloader +Use the hardcoded serial STM32 serial bootloader to :ref:`re-flash the +bootloader <bootloader-reflashing>`. If it really is bricked, and you think it's our fault, `contact us <http://leaflabs.com/contact>`_\ ! @@ -100,18 +98,18 @@ a board selected. The work-around is to restart the IDE. Mysterious! ``NullPointerException`` ------------------------ -A classic! Make sure you have selected a board from the pulldown menu. +A classic! Make sure you have selected a board from the pulldown menu. .. TODO: remove when Python version is released ``undefined reference to setup()/loop()`` ----------------------------------------- -Your sketch/program either does not include one of the `setup -<setup()>`_ or `loop <loop()>`_ functions, or it was not found by the -compiler. Your program must include both ``void setup()`` and ``void -loop()`` functions; they don't have to do anything, but they **must** -be there. +Your sketch/program either does not include one of the :ref:`setup() +<lang-setup>` or `loop() <lang-loop>` functions, or it was not found +by the compiler. Your program must include both ``void setup()`` and +``void loop()`` functions; they don't have to do anything, but they +**must** be there. You can start with an example program (to see one in the IDE, click on File > Examples > Stubs > BareMinimum) to get the basic structure. @@ -152,7 +150,7 @@ is several times more FLASH memory available for user programs. ``No DFU capable USB device found`` ----------------------------------- -This probably means you don't have a Maple plugged in or powered on! +This probably means you don't have a Maple plugged in or powered on! I have multiple Maples installed; how do I know which one will get flashed? --------------------------------------------------------------------------- diff --git a/docs/source/unix-toolchain.rst b/docs/source/unix-toolchain.rst index 2bb584a..e6039a2 100644 --- a/docs/source/unix-toolchain.rst +++ b/docs/source/unix-toolchain.rst @@ -97,12 +97,12 @@ This step is fairly straightforward: do a git clone of the `libmaple repository <http://github.com/leaflabs/libmaple>`_ to some directory, then download and extract the ARM compiler toolchain. -The :file:`arm/bin/` directory will need to be added to -:envvar:`PATH`; you can check that this worked by entering -``arm-none-`` and hitting tab to auto-complete (bash should show a -bunch of results). Regardless of where you put the toolchain, make -sure to preserve its internal directory layout, as the binaries make -relative path calls and references. +The :file:`arm/bin/` directory will need to be added to ``PATH``; you +can check that this worked by entering ``arm-none-`` and hitting tab +to auto-complete (bash should show a bunch of results). Regardless of +where you put the toolchain, make sure to preserve its internal +directory layout, as the binaries make relative path calls and +references. .. _toolchain-udev: @@ -176,7 +176,7 @@ You will need the following tools to get started: :file:`/Applications/OpenMoko Flasher.app/Contents/Mac OS/dfu-util` To get access to it from the command line, just make a symbolic link - to the binary from some place on your :envvar:`PATH`:: + to the binary from some place on your ``PATH``:: $ ln -s /Applications/OpenMoko\ Flasher.app/Contents/Mac\ OS/dfu-util \ /somewhere/on/your/PATH/dfu-util @@ -241,7 +241,7 @@ live with :: $ export PATH=$PATH:~/libmaple/arm/bin After that's done, you'll probably want to update your shell startup -script so :file:`~/libmaple/arm/bin` stays in your :envvar:`PATH`. +script so :file:`~/libmaple/arm/bin` stays in your ``PATH``. **So far, so good?** @@ -350,8 +350,8 @@ Starting your own projects -------------------------- So everything worked, and you want to start your own project? Great! -It's easy. Just set the environment variable :envvar:`LIB_MAPLE_HOME` -in your shell startup script to point to the libmaple repository you +It's easy. Just set the environment variable ``LIB_MAPLE_HOME`` in +your shell startup script to point to the libmaple repository you cloned (this tutorial assumes you put it in :file:`~/libmaple`). For example, if you use bash as your shell, just put this line in your :file:`~/.bashrc` or :file:`~/.bash_profile`:: @@ -417,10 +417,9 @@ but it might be helpful for people who are allergic to `vim <http://www.gnu.org/software/emacs/>`_. The simple configuration described here just calls down to the :file:`Makefile`, so follow the above directions to get the command line tools configured (you'll -definitely need the arm-none-eabi-* tools on your :envvar:`PATH`), -then `install Code::Blocks -<http://www.codeblocks.org/downloads/26>`_. You can do this on Linux -with:: +definitely need the arm-none-eabi-* tools on your ``PATH``), then +`install Code::Blocks <http://www.codeblocks.org/downloads/26>`_. You +can do this on Linux with:: $ sudo aptitude install codeblocks @@ -434,8 +433,8 @@ to get a feel for how it all works. To create your own "libmaple" project, start with an "Empty Project" with the "Folder to create project in" set to your -:envvar:`LIB_MAPLE_HOME`. Make sure that the "Resulting filename" is -in the top level directory as well. +``LIB_MAPLE_HOME``. Make sure that the "Resulting filename" is in the +top level directory as well. .. image:: /_static/img/codeblocks_newproject.png :align: center diff --git a/docs/source/usb.rst b/docs/source/usb.rst index baabde5..5494b06 100644 --- a/docs/source/usb.rst +++ b/docs/source/usb.rst @@ -6,21 +6,6 @@ USB ===== -.. note:: Changes and Caveats - - The SerialUSB functionality was modified for the 0.0.6 IDE - release. It now includes a 50 millisecond timeout for writes and - does not try to detect if the USB host is "really" connected or - just enumerated and initialized. This means that if you have a - number of SerialUSB writes or prints in your code and you are not - monitoring on a computer your program will run much, much slower - than if it is being monitored or totally disconnected (battery). - - You can avoid this behavior by :ref:`deciphering the port status - <usb-safe-print>` using the DTR and RTS line status; the behavior - of these control lines is platform dependent and we no longer - interpret them by default. - The Maple STM32 microprocessor includes a dedicated USB peripheral which can be configured to act as a general USB slave device with transfer rates up to 12Mbps (it unfortunately can't be configured as a @@ -30,152 +15,21 @@ and second, to emulate a regular serial port for use as a terminal (text read/write). The emulated terminal is relatively slow and inefficient; it is best -for transferring data at regular serial speeds (kilobaud). Users -requiring faster data transfer should consider implementing a -different communications protocol; the Maple could be reprogrammed to -appear as a mass storage device (thumb drive), human interface device -(mouse or keyboard), microphone, or any other USB device. +for transferring data at regular serial speeds (kilobaud). Library +support for accessing the emulated terminal is available at the +:ref:`SerialUSB <lang-serialusb>` reference. -The SerialUSB channel is also used as part of the auto-reset feature -of the IDE to program the board (on Maple Rev3): a :ref:`magic +The SerialUSB channel is used as part of the auto-reset feature of the +IDE to program the board on Maple Rev 3 and Rev 5: a :ref:`magic sequence of control line toggles and transmitted data <bootloader-rev3>` causes the Maple to reset itself and enter bootloader mode. As an unfortunate consequence, the auto-reset will not work if the IDE can not access the serial port, either due to a conflict with another program (serial monitor) or because the interface has been disabled from the Maple side (through -``SerialUSB.end()``). - -Function Reference ------------------- - -``SerialUSB.print(...)``/\ ``SerialUSB.println(...)`` - - Writes data into the port buffer to be transmitted as soon as - possible. Accepts strings (``char*``). If a raw integer is passed - the corresponding ASCII character will be transmitted; to print - out a number in human readable form add a second parameter with - the base system. For example, to print out the decimal number - "1234", use ``SerialUSB.print(1234, DEC)``; to print out the - binary number "1001", use ``SerialUSB.print(9, BIN)``. - -.. _usb-write: - -``SerialUSB.write(bytes)`` - - ``write`` is a lower-level function that writes bytes directly - into the buffer. :ref:`print() <usb-print>` often calls this - function dozens of times to write out a single formatted number; - user code can optimize raw data speed by calling this function - with 64-byte chunks instead. - -``SerialUSB.available()``/\ ``SerialUSB.read()`` - - ``SerialUSB.read()`` will return the next available character - (``byte``) that has been received over the port. - ``SerialUSB.available()`` returns how many such bytes are actually - available. If there is no data, ``read`` will block/fail, so the - usual program structure is to poll with ``available`` and only - ``read`` if there are data to read. - -``SerialUSB.read(buffer, length)`` - - An alternative version of ``SerialUSB.read``; will write the next - ``length`` available characters into the array ``buffer``. - -``SerialUSB.pending()`` - - Returns the number of bytes waiting in the transmit - buffer. Usercode can use this to prevent any blocking/waiting when - using the direct :ref:`write <usb-write>` functions, or to check - if data was actually requested/received by the host. - -``SerialUSB.getRTS()`` - - Returns the state (1 or 0) of the virtual RTS ("ready to send") - line. This can be used to guess if the USB host is actively - waiting for data (e.g., if a serial monitor program is running) or - just "configured" (i.e., the virtual serial port is configured, - but no program is reading data). - -``SerialUSB.getDTR()`` - - Returns the state (1 or 0) of the virtual DTR ("data terminal - ready") line. This can be used to guess if the USB host is - actively waiting for data (e.g., if a serial monitor program is - running) or just "configured" (i.e., the virtual serial port is - configured, but no program is reading data). - -.. TODO deprecate crap out of above two functions; write a sane API - -``SerialUSB.isConnected()`` - - Returns 1 if the USB host is connected and the virtual serial - interface is initialized (though not necessarily active). - Otherwise, returns 0. - -``SerialUSB.end()``/\ ``SerialUSB.begin()`` - - The USB peripheral is enabled by default so that the auto-reset - feature will work, but it can be disabled/restarted at any time - with the ``SerialUSB.end()`` and ``SerialUSB.begin()`` - functions. - - ``SerialUSB.end()`` is a relatively hard shutdown, similar to - unplugging the board; this may crash or confuse any programs - running host-side. Note that calling this function will require - the Maple to be put into :ref:`perpetual bootloader mode - <troubleshooting-perpetual-bootloader>` before another program can - be uploaded onto it, unless ``SerialUSB.begin()`` is called before - the upload is attempted. - - It's probably wise to wait a few seconds between calls to - ``SerialUSB.end()`` and ``SerialUSB.begin()`` (or to - ``SerialUSB.begin()`` and ``SerialUSB.print()``) to let the - computer reconfigure. - -Code Examples -------------- - -.. _usb-safe-print: - -Safe Print -^^^^^^^^^^ - -This function should run smoothly and not block; the LED should blink -at roughly the same speed whether being monitored, running from -battery, or connected but not monitored. You may need to experiment -with the DTR/RTS logic for your platform and device configuration. :: - - #define LED_PIN 13 - - void setup() { - /* Set up the LED to blink */ - pinMode(LED_PIN, OUTPUT); - } - - void loop() { - // LED will stay off if we are disconnected; - // will blink quickly if USB is unplugged (battery etc) - if(SerialUSB.isConnected()) { - digitalWrite(LED_PIN, 1); - } - delay(100); - - // If this logic fails to detect if bytes are going to - // be read by the USB host, then the println() will fully - // many times, causing a very slow LED blink. - // If the characters are printed and read, the blink will - // only slow a small amount when "really" connected, and fast - // when the virtual port is only configured. - if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { - for(int i=0; i<10; i++) { - SerialUSB.println(123456,BIN); - } - } - digitalWrite(LED_PIN, 0); - delay(100); - } +:ref:`SerialUSB.end() <lang-serialusb-end>`). A solution to the +second problem is the use of :ref:`perpetual bootloader mode +<troubleshooting-perpetual-bootloader>`. Recommended Reading ------------------- diff --git a/libmaple/usb/usb_callbacks.c b/libmaple/usb/usb_callbacks.c index 4cdaf73..250acea 100644 --- a/libmaple/usb/usb_callbacks.c +++ b/libmaple/usb/usb_callbacks.c @@ -8,19 +8,19 @@ #include "usb_hardware.h" ONE_DESCRIPTOR Device_Descriptor = { - (uint8*)&usbVcomDescriptor_Device, - sizeof(USB_Descriptor_Device) + (uint8*)&usbVcomDescriptor_Device, + sizeof(USB_Descriptor_Device) }; ONE_DESCRIPTOR Config_Descriptor = { - (uint8*)&usbVcomDescriptor_Config, - 0x43//sizeof(USB_Descriptor_Config) + (uint8*)&usbVcomDescriptor_Config, + 0x43//sizeof(USB_Descriptor_Config) }; ONE_DESCRIPTOR String_Descriptor[3] = { - {(uint8*)&usbVcomDescriptor_LangID, USB_DESCRIPTOR_STRING_LEN(1)}, - {(uint8*)&usbVcomDescriptor_iManufacturer,USB_DESCRIPTOR_STRING_LEN(8)}, - {(uint8*)&usbVcomDescriptor_iProduct, USB_DESCRIPTOR_STRING_LEN(8)} + {(uint8*)&usbVcomDescriptor_LangID, USB_DESCRIPTOR_STRING_LEN(1)}, + {(uint8*)&usbVcomDescriptor_iManufacturer,USB_DESCRIPTOR_STRING_LEN(8)}, + {(uint8*)&usbVcomDescriptor_iProduct, USB_DESCRIPTOR_STRING_LEN(8)} }; uint8 last_request = 0; @@ -42,12 +42,12 @@ RESET_STATE reset_state = DTR_UNSET; uint8 line_dtr_rts = 0; void vcomDataTxCb(void) { - /* do whatever after data has been sent to host */ + /* do whatever after data has been sent to host */ - /* allows usbSendBytes to stop blocking */ + /* allows usbSendBytes to stop blocking */ - countTx = 0; + countTx = 0; } /* we could get arbitrarily complicated here for speed purposes @@ -56,296 +56,296 @@ void vcomDataTxCb(void) { in the fifo. this number will be reincremented after calls to usbReceiveBytes */ void vcomDataRxCb(void) { - /* do whatever after data has been received from host */ - - /* setEPRxCount on the previous cycle should garuntee - we havnt received more bytes than we can fit */ - uint8 newBytes = GetEPRxCount(VCOM_RX_ENDP); - /* assert (newBytes <= maxNewBytes); */ - - /* todo, not checking very carefully for edge cases. USUALLY, - if we emit the reset pulse and send 4 bytes, then newBytes - should be 4. But its POSSIBLE that this would be violated - in some cases */ - - /* magic number, {0x31, 0x45, 0x41, 0x46} is "1EAF" */ - char chkBuf[4]; - char cmpBuf[4] = {0x31, 0x45, 0x41, 0x46}; - if (reset_state == DTR_NEGEDGE) { - reset_state = DTR_LOW; - - if (newBytes >= 4) { - unsigned int target = (unsigned int)usbWaitReset | 0x1; - - PMAToUserBufferCopy(chkBuf,VCOM_RX_ADDR,4); - - int i; - USB_Bool cmpMatch = TRUE; - for (i=0; i<4; i++) { - if (chkBuf[i] != cmpBuf[i]) { - cmpMatch = FALSE; - } - } - - if (cmpMatch) { - asm volatile("mov r0, %[stack_top] \n\t" // Reset the stack - "mov sp, r0 \n\t" - "mov r0, #1 \n\t" - "mov r1, %[target_addr] \n\t" - "mov r2, %[cpsr] \n\t" - "push {r2} \n\t" // Fake xPSR - "push {r1} \n\t" // Target address for PC - "push {r0} \n\t" // Fake LR - "push {r0} \n\t" // Fake R12 - "push {r0} \n\t" // Fake R3 - "push {r0} \n\t" // Fake R2 - "push {r0} \n\t" // Fake R1 - "push {r0} \n\t" // Fake R0 - "mov lr, %[exc_return] \n\t" - "bx lr" - : - : [stack_top] "r" (STACK_TOP), - [target_addr] "r" (target), - [exc_return] "r" (EXC_RETURN), - [cpsr] "r" (DEFAULT_CPSR) - : "r0", "r1", "r2"); - /* should never get here */ - } + /* do whatever after data has been received from host */ + + /* setEPRxCount on the previous cycle should garuntee + we havnt received more bytes than we can fit */ + uint8 newBytes = GetEPRxCount(VCOM_RX_ENDP); + /* assert (newBytes <= maxNewBytes); */ + + /* todo, not checking very carefully for edge cases. USUALLY, + if we emit the reset pulse and send 4 bytes, then newBytes + should be 4. But its POSSIBLE that this would be violated + in some cases */ + + /* magic number, {0x31, 0x45, 0x41, 0x46} is "1EAF" */ + char chkBuf[4]; + char cmpBuf[4] = {0x31, 0x45, 0x41, 0x46}; + if (reset_state == DTR_NEGEDGE) { + reset_state = DTR_LOW; + + if (newBytes >= 4) { + unsigned int target = (unsigned int)usbWaitReset | 0x1; + + PMAToUserBufferCopy(chkBuf,VCOM_RX_ADDR,4); + + int i; + USB_Bool cmpMatch = TRUE; + for (i=0; i<4; i++) { + if (chkBuf[i] != cmpBuf[i]) { + cmpMatch = FALSE; + } + } + + if (cmpMatch) { + asm volatile("mov r0, %[stack_top] \n\t" // Reset the stack + "mov sp, r0 \n\t" + "mov r0, #1 \n\t" + "mov r1, %[target_addr] \n\t" + "mov r2, %[cpsr] \n\t" + "push {r2} \n\t" // Fake xPSR + "push {r1} \n\t" // Target address for PC + "push {r0} \n\t" // Fake LR + "push {r0} \n\t" // Fake R12 + "push {r0} \n\t" // Fake R3 + "push {r0} \n\t" // Fake R2 + "push {r0} \n\t" // Fake R1 + "push {r0} \n\t" // Fake R0 + "mov lr, %[exc_return] \n\t" + "bx lr" + : + : [stack_top] "r" (STACK_TOP), + [target_addr] "r" (target), + [exc_return] "r" (EXC_RETURN), + [cpsr] "r" (DEFAULT_CPSR) + : "r0", "r1", "r2"); + /* should never get here */ + } + } } - } - if (recvBufIn + newBytes < VCOM_RX_EPSIZE) { - PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,newBytes); - recvBufIn += newBytes; - } else { - /* we have to copy the data in two chunks because we roll over - the edge of the circular buffer */ - uint8 tailBytes = VCOM_RX_EPSIZE - recvBufIn; - uint8 remaining = newBytes - tailBytes; + if (recvBufIn + newBytes < VCOM_RX_EPSIZE) { + PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,newBytes); + recvBufIn += newBytes; + } else { + /* we have to copy the data in two chunks because we roll over + the edge of the circular buffer */ + uint8 tailBytes = VCOM_RX_EPSIZE - recvBufIn; + uint8 remaining = newBytes - tailBytes; - PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,tailBytes); - PMAToUserBufferCopy(&vcomBufferRx[0], VCOM_RX_ADDR,remaining); + PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,tailBytes); + PMAToUserBufferCopy(&vcomBufferRx[0], VCOM_RX_ADDR,remaining); - recvBufIn = (recvBufIn + newBytes ) % VCOM_RX_EPSIZE; - } + recvBufIn = (recvBufIn + newBytes ) % VCOM_RX_EPSIZE; + } - maxNewBytes -= newBytes; - SetEPRxCount(VCOM_RX_ENDP,maxNewBytes); - SetEPRxValid(VCOM_RX_ENDP); + maxNewBytes -= newBytes; + SetEPRxCount(VCOM_RX_ENDP,maxNewBytes); + SetEPRxValid(VCOM_RX_ENDP); } void vcomManagementCb(void) { -/* unused. This enpoint would callback if we had sent a linestate - changed notification */ + /* unused. This enpoint would callback if we had sent a linestate + changed notification */ } u8* vcomGetSetLineCoding(uint16 length) { - if (length == 0) { - pInformation->Ctrl_Info.Usb_wLength = sizeof(USB_Line_Coding); - } - return (uint8*)&line_coding; + if (length == 0) { + pInformation->Ctrl_Info.Usb_wLength = sizeof(USB_Line_Coding); + } + return (uint8*)&line_coding; } vcomSetLineState(void) { } void usbInit(void) { - pInformation->Current_Configuration = 0; - usbPowerOn(); + pInformation->Current_Configuration = 0; + usbPowerOn(); - _SetISTR(0); - wInterrupt_Mask = ISR_MSK; - _SetCNTR(wInterrupt_Mask); + _SetISTR(0); + wInterrupt_Mask = ISR_MSK; + _SetCNTR(wInterrupt_Mask); - usbEnbISR(); - bDeviceState = UNCONNECTED; + usbEnbISR(); + bDeviceState = UNCONNECTED; } void usbReset(void) { - pInformation->Current_Configuration = 0; + pInformation->Current_Configuration = 0; - /* current feature is current bmAttributes */ - pInformation->Current_Feature = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED); + /* current feature is current bmAttributes */ + pInformation->Current_Feature = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED); - _SetBTABLE(USB_BTABLE_ADDRESS); + _SetBTABLE(USB_BTABLE_ADDRESS); - /* setup control endpoint 0 */ - _SetEPType(ENDP0, EP_CONTROL); - _SetEPTxStatus(ENDP0, EP_TX_STALL); - _SetEPRxAddr(ENDP0,VCOM_CTRL_RX_ADDR); - _SetEPTxAddr(ENDP0,VCOM_CTRL_TX_ADDR); - Clear_Status_Out(ENDP0); + /* setup control endpoint 0 */ + _SetEPType(ENDP0, EP_CONTROL); + _SetEPTxStatus(ENDP0, EP_TX_STALL); + _SetEPRxAddr(ENDP0,VCOM_CTRL_RX_ADDR); + _SetEPTxAddr(ENDP0,VCOM_CTRL_TX_ADDR); + Clear_Status_Out(ENDP0); - SetEPRxCount(ENDP0, pProperty->MaxPacketSize); - SetEPRxValid(ENDP0); - - /* setup management endpoint 1 */ - SetEPType (VCOM_NOTIFICATION_ENDP, EP_INTERRUPT); - SetEPTxAddr (VCOM_NOTIFICATION_ENDP, VCOM_NOTIFICATION_ADDR); - SetEPTxStatus (VCOM_NOTIFICATION_ENDP, EP_TX_NAK); - SetEPRxStatus (VCOM_NOTIFICATION_ENDP, EP_RX_DIS); - - /* setup data endpoint OUT (rx) */ -/* SetEPType (VCOM_RX_ENDP, EP_BULK); */ -/* SetEPRxAddr (VCOM_RX_ENDP, VCOM_RX_ADDR); */ -/* SetEPRxCount (VCOM_RX_ENDP, VCOM_RX_EPSIZE); */ -/* // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); */ -/* SetEPRxStatus (VCOM_RX_ENDP, EP_RX_VALID); */ - - SetEPType (3, EP_BULK); - SetEPRxAddr (3, 0x110); - SetEPRxCount (3,64); - // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); - SetEPRxStatus (3, EP_RX_VALID); - - /* setup data endpoint IN (tx) */ - SetEPType (VCOM_TX_ENDP, EP_BULK); - SetEPTxAddr (VCOM_TX_ENDP, VCOM_TX_ADDR); - SetEPTxStatus (VCOM_TX_ENDP, EP_TX_NAK); - SetEPRxStatus (VCOM_TX_ENDP, EP_RX_DIS); - - bDeviceState = ATTACHED; - SetDeviceAddress(0); - - /* reset the rx fifo */ - recvBufIn = 0; - recvBufOut = 0; - maxNewBytes = VCOM_RX_EPSIZE; - countTx = 0; + SetEPRxCount(ENDP0, pProperty->MaxPacketSize); + SetEPRxValid(ENDP0); + + /* setup management endpoint 1 */ + SetEPType (VCOM_NOTIFICATION_ENDP, EP_INTERRUPT); + SetEPTxAddr (VCOM_NOTIFICATION_ENDP, VCOM_NOTIFICATION_ADDR); + SetEPTxStatus (VCOM_NOTIFICATION_ENDP, EP_TX_NAK); + SetEPRxStatus (VCOM_NOTIFICATION_ENDP, EP_RX_DIS); + + /* setup data endpoint OUT (rx) */ + /* SetEPType (VCOM_RX_ENDP, EP_BULK); */ + /* SetEPRxAddr (VCOM_RX_ENDP, VCOM_RX_ADDR); */ + /* SetEPRxCount (VCOM_RX_ENDP, VCOM_RX_EPSIZE); */ + /* // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); */ + /* SetEPRxStatus (VCOM_RX_ENDP, EP_RX_VALID); */ + + SetEPType (3, EP_BULK); + SetEPRxAddr (3, 0x110); + SetEPRxCount (3,64); + // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); + SetEPRxStatus (3, EP_RX_VALID); + + /* setup data endpoint IN (tx) */ + SetEPType (VCOM_TX_ENDP, EP_BULK); + SetEPTxAddr (VCOM_TX_ENDP, VCOM_TX_ADDR); + SetEPTxStatus (VCOM_TX_ENDP, EP_TX_NAK); + SetEPRxStatus (VCOM_TX_ENDP, EP_RX_DIS); + + bDeviceState = ATTACHED; + SetDeviceAddress(0); + + /* reset the rx fifo */ + recvBufIn = 0; + recvBufOut = 0; + maxNewBytes = VCOM_RX_EPSIZE; + countTx = 0; } void usbStatusIn(void) { - /* adjust the usart line coding - if we wish to couple the CDC line coding - with the real usart port */ + /* adjust the usart line coding + if we wish to couple the CDC line coding + with the real usart port */ } void usbStatusOut(void) { } RESULT usbDataSetup(uint8 request) { - uint8 *(*CopyRoutine)(uint16); - CopyRoutine = NULL; - - if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { - switch (request) { - case (GET_LINE_CODING): - CopyRoutine = vcomGetSetLineCoding; - last_request = GET_LINE_CODING; - break; - case (SET_LINE_CODING): - CopyRoutine = vcomGetSetLineCoding; - last_request = SET_LINE_CODING; - break; - default: break; + uint8 *(*CopyRoutine)(uint16); + CopyRoutine = NULL; + + if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { + switch (request) { + case (GET_LINE_CODING): + CopyRoutine = vcomGetSetLineCoding; + last_request = GET_LINE_CODING; + break; + case (SET_LINE_CODING): + CopyRoutine = vcomGetSetLineCoding; + last_request = SET_LINE_CODING; + break; + default: break; + } } - } - if (CopyRoutine == NULL) { - return USB_UNSUPPORT; - } + if (CopyRoutine == NULL) { + return USB_UNSUPPORT; + } - pInformation->Ctrl_Info.CopyData = CopyRoutine; - pInformation->Ctrl_Info.Usb_wOffset = 0; - (*CopyRoutine)(0); - return USB_SUCCESS; + pInformation->Ctrl_Info.CopyData = CopyRoutine; + pInformation->Ctrl_Info.Usb_wOffset = 0; + (*CopyRoutine)(0); + return USB_SUCCESS; } RESULT usbNoDataSetup(u8 request) { - uint8 new_signal; - - /* we support set com feature but dont handle it */ - if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { - - switch (request) { - case (SET_COMM_FEATURE): - return USB_SUCCESS; - case (SET_CONTROL_LINE_STATE): - /* to reset the board, pull both dtr and rts low - then pulse dtr by itself */ - new_signal = pInformation->USBwValues.bw.bb0 & (CONTROL_LINE_DTR | CONTROL_LINE_RTS); - line_dtr_rts = new_signal & 0x03; - - switch (reset_state) { - /* no default, covered enum */ - case DTR_UNSET: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_HIGH: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_NEGEDGE; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_NEGEDGE: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_LOW: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - } - - return USB_SUCCESS; + uint8 new_signal; + + /* we support set com feature but dont handle it */ + if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { + + switch (request) { + case (SET_COMM_FEATURE): + return USB_SUCCESS; + case (SET_CONTROL_LINE_STATE): + /* to reset the board, pull both dtr and rts low + then pulse dtr by itself */ + new_signal = pInformation->USBwValues.bw.bb0 & (CONTROL_LINE_DTR | CONTROL_LINE_RTS); + line_dtr_rts = new_signal & 0x03; + + switch (reset_state) { + /* no default, covered enum */ + case DTR_UNSET: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_HIGH: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_NEGEDGE; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_NEGEDGE: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_LOW: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + } + + return USB_SUCCESS; + } } - } - return USB_UNSUPPORT; + return USB_UNSUPPORT; } RESULT usbGetInterfaceSetting(uint8 interface, uint8 alt_setting) { - if (alt_setting > 0) { - return USB_UNSUPPORT; - } else if (interface > 1) { - return USB_UNSUPPORT; - } + if (alt_setting > 0) { + return USB_UNSUPPORT; + } else if (interface > 1) { + return USB_UNSUPPORT; + } - return USB_SUCCESS; + return USB_SUCCESS; } u8* usbGetDeviceDescriptor(u16 length) { - return Standard_GetDescriptorData(length, &Device_Descriptor); + return Standard_GetDescriptorData(length, &Device_Descriptor); } u8* usbGetConfigDescriptor(u16 length) { - return Standard_GetDescriptorData(length, &Config_Descriptor); + return Standard_GetDescriptorData(length, &Config_Descriptor); } u8* usbGetStringDescriptor(u16 length) { - uint8 wValue0 = pInformation->USBwValue0; + uint8 wValue0 = pInformation->USBwValue0; - if (wValue0 > 2) { - return NULL; - } - return Standard_GetDescriptorData(length, &String_Descriptor[wValue0]); + if (wValue0 > 2) { + return NULL; + } + return Standard_GetDescriptorData(length, &String_Descriptor[wValue0]); } /* internal callbacks to respond to standard requests */ void usbSetConfiguration(void) { - if (pInformation->Current_Configuration != 0) { - bDeviceState = CONFIGURED; - } + if (pInformation->Current_Configuration != 0) { + bDeviceState = CONFIGURED; + } } void usbSetDeviceAddress(void) { - bDeviceState = ADDRESSED; + bDeviceState = ADDRESSED; } diff --git a/wirish/comm/HardwareSerial.h b/wirish/comm/HardwareSerial.h index 17be49f..fdfc06d 100644 --- a/wirish/comm/HardwareSerial.h +++ b/wirish/comm/HardwareSerial.h @@ -33,6 +33,13 @@ #include "Print.h" +/* NB: this class documented "by hand" (i.e., not using Doxygen) in: + + libmaple/docs/source/lang/serial.rst + + If you alter the public HardwareSerial interface, you must update + the documentation accordingly. */ + class HardwareSerial : public Print { private: uint8 usart_num; @@ -50,7 +57,7 @@ class HardwareSerial : public Print { uint8 rx_pin, uint8 timer_num, uint8 compare_num); - void begin(uint32); + void begin(uint32 baud); void end(void); uint32 available(void); uint8 read(void); diff --git a/wirish/io.h b/wirish/io.h index f01efcb..24f2611 100644 --- a/wirish/io.h +++ b/wirish/io.h @@ -79,8 +79,8 @@ typedef enum WiringPinMode { when it is closer to 0v (ground) it is low. If no external circuit is pulling the pin voltage to high or low, it will tend to randomly oscillate and be very - sensitive to noise (eg a breath of air across the pin - will cause the state to flip). */ + sensitive to noise (e.g., a breath of air across the pin + might cause the state to flip). */ INPUT_ANALOG, /**< This is a special mode for when the pin will be used for analog (not digital) reads. Enables ADC @@ -101,7 +101,7 @@ typedef enum WiringPinMode { the state will be low unless an external device is specifically pulling the pin up to 3.3v, in which case the "gentle" pull down will not - effect the state of the input. */ + affect the state of the input. */ INPUT_FLOATING, /**< Synonym for INPUT. */ |