From 95783b750fda95f5f4c1fac00ab24da03b31b517 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Mon, 25 Oct 2010 21:15:28 -0400 Subject: arduino language reference nearing completion, properly CC-BY-SA 3.0 attributed --- libmaple/timers.c | 6 +- libmaple/timers.h | 216 +++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 186 insertions(+), 36 deletions(-) (limited to 'libmaple') diff --git a/libmaple/timers.c b/libmaple/timers.c index c369d1f..3a2cad7 100644 --- a/libmaple/timers.c +++ b/libmaple/timers.c @@ -289,15 +289,15 @@ void timer_set_mode(uint8 timer_num, uint8 channel, TimerMode mode) { /* This sets the compare value (aka the trigger) for a given timer * channel */ void timer_set_compare_value(uint8 timer_num, - uint8 compare_num, + uint8 channel, uint16 value) { /* The faster version of this function is the inline timer_pwm_write_ccr */ timer_port *timer = timer_dev_table[timer_num].base; - ASSERT(compare_num > 0 && compare_num <= 4); + ASSERT(channel > 0 && channel <= 4); - switch(compare_num) { + switch(channel) { case 1: timer->CCR1 = value; break; diff --git a/libmaple/timers.h b/libmaple/timers.h index d180bab..f5694ac 100644 --- a/libmaple/timers.h +++ b/libmaple/timers.h @@ -142,7 +142,7 @@ typedef enum TimerMode { TIMER_PWM, /**< This is the default mode for pins after initialization. */ TIMER_OUTPUTCOMPARE, /**< In this mode, the timer counts from 0 to - the overflow value repeatedly; every time + its reload value repeatedly; every time the counter value reaches one of the channel compare values, the corresponding interrupt is fired. */ @@ -191,8 +191,10 @@ typedef struct { uint16 RESERVED19; } timer_port; -/* timer device numbers */ -enum { +/** + * All possible timer device numbers. + */ +typedef enum { TIMER1, TIMER2, TIMER3, @@ -201,7 +203,7 @@ enum { TIMER6, // High density only; no compare TIMER7, // High density only; no compare TIMER8, // High density only -}; +} timer_num_t; /* timer descriptor */ struct timer_dev { @@ -213,37 +215,185 @@ struct timer_dev { extern struct timer_dev timer_dev_table[]; -/* Turn on timer with prescale as the divisor - * void timer_init(uint32 timer, uint16 prescale) - * timer -> {1-4} - * prescale -> {1-65535} +/** + * Turn on timer with prescale as the clock divisor. + * + * @param timer Timer number. Valid values are TIMER1, TIMER2, + * TIMER3, TIMER4, and (on high-density devices) TIMER5, TIMER8. + * + * @param prescale value in the range 1--65535 to use as a prescaler + * for timer counter increment frequency. + * + * @see timer_set_prescaler() + * @see timer_set_mode() + */ +void timer_init(uint8 timer, uint16 prescale); + +/** + * Quickly disable all timers. Calling this function is faster than, + * e.g., calling timer_set_mode() for all available timers/channels. */ -void timer_init(uint8, uint16); void timer_disable_all(void); -uint16 timer_get_count(uint8); -void timer_set_count(uint8,uint16); -void timer_pause(uint8); -void timer_resume(uint8); -void timer_set_prescaler(uint8 timer_num, uint16 prescale); -void timer_set_reload(uint8 timer_num, uint16 max_reload); -void timer_set_mode(uint8 timer_num, uint8 compare_num, uint8 mode); -void timer_set_compare_value(uint8 timer_num, uint8 compare_num, uint16 value); -void timer_attach_interrupt(uint8 timer_num, uint8 compare_num, - voidFuncPtr handler); -void timer_detach_interrupt(uint8 timer_num, uint8 compare_num); - -/* Turn on PWM with duty_cycle on the specified channel in timer. - * This function takes in a pointer to the corresponding CCR - * register for the pin cause it saves pwmWrite() a couple of - * cycles. - * - * void timer_pwm(uint8 channel, uint8 duty_cycle); - * channel -> {TIMERx_CHn_CCR} - * duty_cycle -> {0-65535} - * - * PRECONDITIONS: - * pin has been set to alternate function output - * timer has been initialized + +/** + * Returns the timer's counter value. Due to function call overhead, + * this value is likely to be inaccurate if the counter is running + * with a low prescaler. + * + * @param timer the timer whose counter to return. + */ +uint16 timer_get_count(uint8 timer); + +/** + * Sets the counter value for the given timer. + * + * @param timer the timer whose counter to set. + * + * @param value the new counter value. + */ +void timer_set_count(uint8 timer, uint16 value); + +/** + * Stops the timer's counter from incrementing. Does not modify the + * timer's mode or settings. + * + * @param timer the timer to pause. + * + * @see timer_resume() + */ +void timer_pause(uint8 timer); + +/** + * Starts the counter for the given timer. Does not modify the + * timer's mode or settings. The timer will begin counting on the + * first rising clock cycle after it has been re-enabled using this + * function. + * + * @param timer the timer to resume. + * + * @see timer_pause() + */ +void timer_resume(uint8 timer); + +/** + * Sets the prescaler for the given timer. The prescaler acts as a + * clock divider of the STM32 72MHz system clock, in that the timer's + * counter will subsequently increment with frequency equal to 72MHz / + * prescale. + * + * Note that the timer will continue with its current prescaler until + * the next time its counter reaches its overflow value, starting a + * counting cycle. The new prescale value will be in effect for that + * subsequent counting cycle. + * + * @param timer the timer whose prescaler to set. + * + * @param prescale the new prescaler, from 1--65,535. + */ +void timer_set_prescaler(uint8 timer, uint16 prescale); + +/** + * Sets the reload value for the entire timer. + * + * After this function returns, the timer's counter will reset to 0 + * after it has reached the value max_reload. + * + * @param timer the timer whose reload to set. + * + * @param max_reload the new reload value. + */ +void timer_set_reload(uint8 timer, uint16 max_reload); + +/** + * Set the mode of an individual timer channel. + * + * @param timer the timer whose channel mode to set. + * + * @param channel the channel whose mode to set (1 <= channel <= 4). + * + * @param mode the new mode value. Currently acceptable values + * include TIMER_DISABLED, TIMER_PWM, and TIMER_OUTPUTCOMPARE. Note + * that timer_disable_all() will disable all timers and all channels + * much more quickly than repeated calls to this function with mode + * TIMER_DISABLED. + * + * @see TimerMode + * + * @see timer_disable_all() + */ +void timer_set_mode(uint8 timer, uint8 channel, TimerMode mode); + +/** + * Sets the compare value for a given timer channel. Useful for + * scheduling when interrupt handlers will be called. + * + * @param timer the timer whose channel compare to set. + * + * @param channel the channel whose compare to set (1 <= channel <= 4). + * + * @param compare the new compare value. This new value must be less + * than or equal to the timer's reload value. + * + * @see timer_attach_interrupt() + * + * @see timer_detach_interrupt() + * + * @see timer_set_reload() + */ +void timer_set_compare_value(uint8 timer, uint8 channel, uint16 compare); + +/** + * Attach an interrupt handler for the given timer and channel. The + * handler will be called whenever the timer's counter reaches the + * compare value for the given timer and channel. + * + * @param timer the timer whose channel to register with an interrupt handler. + * + * @param channel the channel with which the new handler will be + * associated. timer_set_compare_value() can be used to set the value + * which the timer's counter must reach before handler is called (1 <= + * channel <= 4). + * + * @param handler the interrupt handler to call once the timer reaches + * the given channel's compare value. + * + * @pre The channel's mode must be set to TIMER_OUTPUTCOMPARE, or the + * interrupt handler will not get called. + * + * @see timer_set_compare_value() + * + * @see timer_detach_interrupt() + * + * @see timer_set_mode() + */ +void timer_attach_interrupt(uint8 timer, uint8 channel, voidFuncPtr handler); + +/** + * Detach the interrupt handler for the given timer channel, if any. + * After this function returns, any handler attached to the given + * channel will no longer be called. + * + * @param timer the timer whose channel to detach the interrupt + * handler from. + * + * @param channel the channel from which to detach the interrupt handler. + * + * @see timer_attach_interrupt() + */ +void timer_detach_interrupt(uint8 timer, uint8 channel); + +/** + * Turn on PWM with duty_cycle. + * + * @param channel TIMERx_CHn_CCR, where x goes from 1 to NR_TIMERS, + * and n goes from 1 to 4. + * + * @param duty_cycle 0--65535. duty_cycle=0 means always off; + * duty_cycle=65535 means always on. + * + * @pre Pin has been set to alternate function output. + * + * @pre Timer has been initialized. */ static inline void timer_pwm_write_ccr(TimerCCR CCR, uint16 duty_cycle) { *CCR = duty_cycle; -- cgit v1.2.3 From 078edc158da7906ba72e7e6528e1a811e07270e7 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Mon, 29 Nov 2010 01:49:26 -0500 Subject: Finished converting the Arduino docs --- docs/README | 83 +++-- docs/source/bootloader.rst | 7 + docs/source/compatibility.rst | 35 +- docs/source/conf.py | 4 +- docs/source/lang/abs.rst | 14 +- docs/source/lang/analogwrite.rst | 2 +- docs/source/lang/arithmetic.rst | 32 +- docs/source/lang/arithmeticcompound.rst | 46 --- docs/source/lang/assignment.rst | 4 +- docs/source/lang/bit.rst | 4 - docs/source/lang/bitclear.rst | 3 - docs/source/lang/bitread.rst | 3 - docs/source/lang/bitset.rst | 3 - docs/source/lang/bitshift.rst | 8 +- docs/source/lang/bitwisecompound.rst | 231 ------------ docs/source/lang/bitwisemath.rst | 22 +- docs/source/lang/bitwrite.rst | 16 +- docs/source/lang/boolean.rst | 2 +- docs/source/lang/booleanvariables.rst | 5 +- docs/source/lang/braces.rst | 109 ------ docs/source/lang/break.rst | 4 +- docs/source/lang/bytecast.rst | 3 - docs/source/lang/char.rst | 7 +- docs/source/lang/charcast.rst | 7 +- docs/source/lang/comparison.rst | 4 +- docs/source/lang/compoundarithmetic.rst | 44 +++ docs/source/lang/compoundbitwise.rst | 231 ++++++++++++ docs/source/lang/const.rst | 4 +- docs/source/lang/constants.rst | 410 ++++++++++----------- docs/source/lang/constrain.rst | 14 +- docs/source/lang/continue.rst | 8 +- docs/source/lang/curly-braces.rst | 109 ++++++ docs/source/lang/define.rst | 4 +- docs/source/lang/digitalread.rst | 3 - docs/source/lang/digitalwrite.rst | 116 ++---- docs/source/lang/double.rst | 11 +- docs/source/lang/doublecast.rst | 7 +- docs/source/lang/dowhile.rst | 4 +- docs/source/lang/else.rst | 54 --- docs/source/lang/enum.rst | 53 ++- docs/source/lang/float.rst | 7 +- docs/source/lang/floatcast.rst | 13 +- docs/source/lang/for.rst | 16 +- docs/source/lang/goto.rst | 4 +- docs/source/lang/highbyte.rst | 16 +- docs/source/lang/if.rst | 52 ++- docs/source/lang/include.rst | 7 +- docs/source/lang/increment.rst | 15 +- docs/source/lang/int.rst | 9 +- docs/source/lang/intcast.rst | 7 +- docs/source/lang/interrupts.rst | 62 ---- docs/source/lang/keywords.rst | 202 +++++++++- docs/source/lang/long.rst | 9 +- docs/source/lang/longcast.rst | 7 +- docs/source/lang/lowbyte.rst | 26 +- docs/source/lang/map.rst | 124 ++----- docs/source/lang/max.rst | 12 +- docs/source/lang/micros.rst | 65 ++-- docs/source/lang/millis.rst | 70 ++-- docs/source/lang/min.rst | 14 +- docs/source/lang/modulo.rst | 13 +- docs/source/lang/nointerrupts.rst | 59 --- docs/source/lang/notone.rst | 50 --- docs/source/lang/numeric-types.rst | 79 ++++ docs/source/lang/pinmode.rst | 43 +-- docs/source/lang/pointer.rst | 21 +- docs/source/lang/pow.rst | 12 +- docs/source/lang/pulsein.rst | 82 ----- docs/source/lang/pwmwrite.rst | 4 +- docs/source/lang/random.rst | 90 ++--- docs/source/lang/randomseed.rst | 69 ++-- docs/source/lang/return.rst | 8 +- docs/source/lang/scope.rst | 8 +- docs/source/lang/semicolon.rst | 4 +- docs/source/lang/serial.rst | 235 +++++++++--- docs/source/lang/serialusb.rst | 238 +++++++++++- docs/source/lang/setup.rst | 27 +- docs/source/lang/shiftout.rst | 136 ------- docs/source/lang/sizeof.rst | 4 +- docs/source/lang/sq.rst | 14 +- docs/source/lang/static.rst | 4 +- docs/source/lang/string.rst | 3 - docs/source/lang/stringclass.rst | 9 - docs/source/lang/stringobject.rst | 91 ----- docs/source/lang/switchcase.rst | 23 +- docs/source/lang/tone.rst | 81 ---- docs/source/lang/types.rst | 7 - docs/source/lang/unimplemented/interrupts.rst | 59 +++ docs/source/lang/unimplemented/nointerrupts.rst | 59 +++ docs/source/lang/unimplemented/notone.rst | 50 +++ docs/source/lang/unimplemented/pulsein.rst | 82 +++++ docs/source/lang/unimplemented/shiftout.rst | 136 +++++++ docs/source/lang/unimplemented/stringclass.rst | 9 + docs/source/lang/unimplemented/stringobject.rst | 89 +++++ docs/source/lang/unimplemented/tone.rst | 81 ++++ docs/source/lang/unsignedchar.rst | 7 +- docs/source/lang/unsignedint.rst | 7 +- docs/source/lang/unsignedlong.rst | 11 +- docs/source/lang/variables.rst | 10 +- docs/source/lang/void.rst | 33 +- docs/source/lang/volatile.rst | 76 ++-- docs/source/lang/while.rst | 41 +-- docs/source/language-index.rst | 127 +------ docs/source/language.rst | 204 ++++++----- docs/source/libraries.rst | 4 +- docs/source/spi.rst | 2 +- docs/source/timers.rst | 25 +- docs/source/troubleshooting.rst | 20 +- docs/source/unix-toolchain.rst | 31 +- docs/source/usb.rst | 162 +------- libmaple/usb/usb_callbacks.c | 468 ++++++++++++------------ wirish/comm/HardwareSerial.h | 9 +- wirish/io.h | 6 +- 113 files changed, 2937 insertions(+), 2752 deletions(-) delete mode 100644 docs/source/lang/arithmeticcompound.rst delete mode 100644 docs/source/lang/bitwisecompound.rst delete mode 100644 docs/source/lang/braces.rst create mode 100644 docs/source/lang/compoundarithmetic.rst create mode 100644 docs/source/lang/compoundbitwise.rst create mode 100644 docs/source/lang/curly-braces.rst delete mode 100644 docs/source/lang/else.rst delete mode 100644 docs/source/lang/interrupts.rst delete mode 100644 docs/source/lang/nointerrupts.rst delete mode 100644 docs/source/lang/notone.rst create mode 100644 docs/source/lang/numeric-types.rst delete mode 100644 docs/source/lang/pulsein.rst delete mode 100644 docs/source/lang/shiftout.rst delete mode 100644 docs/source/lang/stringclass.rst delete mode 100644 docs/source/lang/stringobject.rst delete mode 100644 docs/source/lang/tone.rst delete mode 100644 docs/source/lang/types.rst create mode 100644 docs/source/lang/unimplemented/interrupts.rst create mode 100644 docs/source/lang/unimplemented/nointerrupts.rst create mode 100644 docs/source/lang/unimplemented/notone.rst create mode 100644 docs/source/lang/unimplemented/pulsein.rst create mode 100644 docs/source/lang/unimplemented/shiftout.rst create mode 100644 docs/source/lang/unimplemented/stringclass.rst create mode 100644 docs/source/lang/unimplemented/stringobject.rst create mode 100644 docs/source/lang/unimplemented/tone.rst (limited to 'libmaple') 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 ` (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() ` types: any :ref:`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 ` for more information. - .. TODO: reference libmaple docs above when they're done - -* Serial1 syntax: like the `Arduino Mega +* ``Serial1`` syntax: like the `Arduino Mega `_, 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 `. By default, ``Serial`` + is not mapped to any of them, use ``Serial1`` through ``Serial3`` + instead. * 16-bit :ref:`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() ` 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 `: 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() ` 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 ` for more information. Another fix is to consult the :ref:`pin mapping mega table -` to find the timer which controls PWM on the +` 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 `. +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 `. 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 `_\ , by Bjarne @@ -35,9 +34,8 @@ type is used for the calculation. see the Wikipedia page on `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/arithmeticcompound.rst b/docs/source/lang/arithmeticcompound.rst deleted file mode 100644 index aa0dc18..0000000 --- a/docs/source/lang/arithmeticcompound.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. highlight:: cpp - -.. _lang-arithmeticcompound: - -Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) -=============================================================== - -Description ------------ - -Perform a mathematical operation on a variable with another constant -or variable. These operators are just a convenient shorthand:: - - x += y; // equivalent to the expression x = x + y; - x -= y; // equivalent to the expression x = x - y; - x *= y; // equivalent to the expression x = x * y; - x /= y; // equivalent to the expression x = x / y; - -Here is an example:: - - int x = 2; - int y = 10; - - x += 4; // x now contains 6 - x -= 3; // x now contains 3 - x *= y; // x now contains 30 - x /= 2; // x now contains 15 - x += max(20, 6); // x now contains 35 - x -= sq(5); // x now contains 15 - -Parameters ----------- - -**x**: a numeric variable - -**y**: a numeric variable, number constant, or any other expression -that evaluates to a number (e.g. call to a function that returns a -number). - -See Also --------- - -- :ref:`Arithmetic operators ` - - -.. include:: cc-attribution.txt 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 `_ in `The Arduino Playground `_\ ) - 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/bitwisecompound.rst b/docs/source/lang/bitwisecompound.rst deleted file mode 100644 index 2b0fe2f..0000000 --- a/docs/source/lang/bitwisecompound.rst +++ /dev/null @@ -1,231 +0,0 @@ -.. highlight:: cpp - -.. _lang-bitwisecompound: - -Compound bitwise and (&=), or (\|=), XOR (^=) -============================================= - -The compound bitwise operators perform their calculations at the -bit level of variables. They are often used to clear and set -specific bits of a variable. - -See the :ref:`bitwise math tutorial ` for more -information on bitwise operators. - -.. contents:: Contents - :local: - -.. _lang-bitwisecompound-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 -is often referred to in programming guides as "clearing" or -"resetting" bits. In a program, writing the line ``x &= y;`` is -equivalent to writing ``x = x & y;``. That is, the value of ``x`` -after the line will be equal to its old value bitwise ANDed with the -value of ``y``:: - - x &= y; // equivalent to x = x & y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any :ref:`integer value -` (like ``3`` or ``0x20``) for ``y``. - -Before doing an example of ``&=``, let's first review the Bitwise AND -(``&``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 0 0 1 (operand1 & operand2) = result - -As shown above, bits that are "bitwise ANDed" with 0 become 0, while -bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` -is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & -B11111111`` equals ``b``. - -.. _lang-bitwisecompound-binconst: - -.. note:: The above uses :ref:`binary constants - `\ . The numbers are still the same - value in other representations, they just might not be as easy to - understand. - - Normally, in C and C++ code, :ref:`hexadecimal - ` or :ref:`octal - ` are used when we're interested in - an integer's bits, rather than its value as a number. - - While hexadecimal and octal literals might be harder to understand - at first, you should really take the time to learn them. They're - part of C, C++, and many other programming languages, while binary - constants are available only for compatibility with Arduino. - - Also, ``B00000000`` is shown for clarity, but zero in any number - format is zero. - -So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while -leaving the rest of the variable's bits unchanged, use the compound -bitwise AND operator ``&=`` with the constant ``B11111100`` -(hexadecimal ``0xFC``\ ):: - - 1 0 1 0 1 0 1 0 variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - 1 0 1 0 1 0 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -Here is the same representation with the variable's bits replaced -with the symbol ``x``\ :: - - x x x x x x x x variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - x x x x x x 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -So, using a byte variable ``b``\ , if we say:: - - b = B10101010; // B10101010 == 0xAA - b &= B11111100; // B11111100 == 0xFC - -then we will have :: - - b == B10101000; // B10101000 == 0xA8 - -.. _lang-bitwisecompound-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 -a program, writing the line ``x |= y;`` is equivalent to writing ``x = -x | y;``. That is, the value of ``x`` after the line will be equal to -its old value bitwise ORed with the value of ``y``:: - - x |= y; // equivalent to x = x | y; - -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 -`\ , ``&=``). - -Before doing an example of ``|=``, let's first review the Bitwise OR -(``|``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) = result - -Bits that are "bitwise ORed" with 0 are unchanged, while bits that are -"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` -variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` -equals ``B11111111`` (here we've used binary constants; see the -:ref:`note ` above). - -So, to set bits 0 and 1 of a one-byte variable, while leaving the rest -of the variable unchanged, use the compound bitwise OR operator -(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -Here is the same representation with the variable's bits replaced with -the symbol ``x``:: - - x x x x x x x x variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - x x x x x x 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b |= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101011; // B10101011 == 0xAB - -.. _lang-bitwisecompound-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 -variable. In a program, writing the line ``x ^= y;`` is equivalent to -writing ``x = x ^ y;``. That is, the value of ``x`` after the line -will be equal to its old value bitwise XORed with the value of ``y``:: - - x ^= y; // equivalent to x = x ^ y; - -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:`&= -` and :ref:`\|= -`; in fact, these three operators all -work the same in this way). - -Before doing an example of ``^=``, let's first review the Bitwise -XOR operator, ``^``:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 0 (operand1 ^ operand2) = result - -One way to look at bitwise XOR is that each bit in the result is a 1 -if the input bits are different, or 0 if they are the same. Another -way to think about it is that the result bit will be 1 when *exactly* -one (no more, no less) of the input bits is 1; otherwise, it will be -zero. This means that if you XOR a bit with 1, it will change (or -toggle) its value, while if you XOR a bit with 0, it stays the same. - -So, to toggle bits 0 and 1 of a one-byte variable, while leaving the -rest of the variable unchanged, use the compound bitwise XOR operator -``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see -:ref:`note ` above):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged toggled - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b ^= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101001; // B10101001 == 0xA9 - -See Also --------- - -- :ref:`Boolean operations ` (``&&``, ``||``) -- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) - - -.. include:: cc-attribution.txt 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 ` (``&&``, ``||``) -- :ref:`Compound bitwise operations ` (``&=``, +- :ref:`Compound bitwise operations ` (``&=``, ``|=``, ``^=``). 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 ` (``&``, ``|``, ``^``, ``~``) -- :ref:`Compound bitwise operators ` (``&=``, +- :ref:`Compound bitwise operators ` (``&=``, ``|=``, ``^=``). - :ref:`if statement ` 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 -` or :ref:`false `. -On a Maple, each boolean variable occupies one byte of memory, and has -type ``bool``. +` or :ref:`false `. On a +Maple, each boolean variable has type ``bool``. .. warning:: diff --git a/docs/source/lang/braces.rst b/docs/source/lang/braces.rst deleted file mode 100644 index 229ad8c..0000000 --- a/docs/source/lang/braces.rst +++ /dev/null @@ -1,109 +0,0 @@ -.. highlight:: cpp - -.. _lang-braces: - -Curly Braces ({}) -================= - -.. contents:: Contents - :local: - -Introduction ------------- - -Curly braces (also referred to as just "braces" or as "curly -brackets") are a major part of the C and C++ programming -languages. They are used in several different constructs, outlined -below, and this can sometimes be confusing for beginners. - -An opening curly brace, ``{`` must always be followed by a closing -curly brace ``}``. This is a condition that is often referred to as -the braces being *balanced*. The Maple IDE (integrated development -environment) includes a convenient feature to check the balance of -curly braces. Just select a brace, or even click the insertion point -immediately following a brace, and its companion will be highlighted\ -[#fbug]_\ . - -Beginning programmers, and programmers coming to C++ from languages -without braces, often find using them confusing or daunting. - -Because the use of the curly brace is so varied, it is good -programming practice to type the closing brace immediately after -typing the opening brace when inserting a construct which requires -curly braces. Then insert some blank lines between your braces and -begin inserting statements. Your braces, and your attitude, will never -become unbalanced. - -Unbalanced braces can often lead to cryptic, impenetrable compiler -errors that can sometimes be hard to track down in a large program. -Because of their varied usages, braces are also incredibly important -to the syntax of a program and moving a brace one or two lines will -usually dramatically affect the meaning of a program. - -The main uses of curly braces ------------------------------ - -**Functions**:: - - // a function body needs braces around it - void myFunction(datatype argument) { - // ... function body goes in here ... - } - -**Loops** (see the :ref:`while `\ , :ref:`for -`\ , and :ref:`do/while ` loop reference -pages for more information):: - - // you should put braces around the body of a loop: - - while (boolean expression) { - // code inside the loop goes here - } - - for (initialisation; termination condition; incrementing expr) { - // code inside the loop goes here - } - - do { - // code inside the loop goes here - } while (boolean expression); - - -**Conditional statements** (see the :ref:`if statement ` -reference page for more information):: - - // you should put braces around the body of an "if", "else if", - // or "else": - - if (boolean expression) { - // code inside the "if" - } - else if (boolean expression) { - // code inside the "else if" - } - else { - // code inside the "else" - } - -**Switch statements** (see the :ref:`switch statement -` reference page for more information):: - - switch (var) { - case 1: - doThing1(); - break; - case 2: - doThing2(); - break; - } - -.. rubric:: Footnotes - -.. TODO remove this once IDE 0.1.0 released - -.. [#fbug] At present this feature is slightly buggy as the IDE will - often find (incorrectly) a brace in text that has been commented - out. - - -.. include:: cc-attribution.txt 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 `\ , :ref:`for `\ , or :ref:`do/while ` 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 ` 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 ` 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/compoundarithmetic.rst b/docs/source/lang/compoundarithmetic.rst new file mode 100644 index 0000000..420f1db --- /dev/null +++ b/docs/source/lang/compoundarithmetic.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-compoundarithmetic: + +Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) +=============================================================== + +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; + x *= y; // equivalent to the expression x = x * y; + x /= y; // equivalent to the expression x = x / y; + +Here is an example:: + + int x = 2; + int y = 10; + + x += 4; // x now contains 6 + x -= 3; // x now contains 3 + x *= y; // x now contains 30 + x /= 2; // x now contains 15 + x += max(20, 6); // x now contains 35 + x -= sq(5); // x now contains 15 + +Parameters +---------- + +**x**: a numeric variable + +**y**: a numeric variable, number constant, or any other expression +that evaluates to a number (e.g. call to a function that returns a +number). + +See Also +-------- + +- :ref:`Arithmetic operators ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/compoundbitwise.rst b/docs/source/lang/compoundbitwise.rst new file mode 100644 index 0000000..a4bbb24 --- /dev/null +++ b/docs/source/lang/compoundbitwise.rst @@ -0,0 +1,231 @@ +.. highlight:: cpp + +.. _lang-compoundbitwise: + +Compound Bitwise Operators (``&=``, ``|=``, ``^=``) +=================================================== + +The compound bitwise operators perform their calculations at the +bit level of variables. They are often used to clear and set +specific bits of a variable. + +See the :ref:`bitwise math tutorial ` for more +information on bitwise operators. + +.. contents:: Contents + :local: + +.. _lang-compoundbitwise-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 +is often referred to in programming guides as "clearing" or +"resetting" bits. In a program, writing the line ``x &= y;`` is +equivalent to writing ``x = x & y;``. That is, the value of ``x`` +after the line will be equal to its old value bitwise ANDed with the +value of ``y``:: + + x &= y; // equivalent to x = x & y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any :ref:`integer value +` (like ``3`` or ``0x20``) for ``y``. + +Before doing an example of ``&=``, let's first review the Bitwise AND +(``&``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + +As shown above, bits that are "bitwise ANDed" with 0 become 0, while +bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` +is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & +B11111111`` equals ``b``. + +.. _lang-compoundbitwise-binconst: + +.. note:: The above uses :ref:`binary constants + `\ . The numbers are still the same + value in other representations, they just might not be as easy to + understand. + + Normally, in C and C++ code, :ref:`hexadecimal + ` or :ref:`octal + ` are used when we're interested in + an integer's bits, rather than its value as a number. + + While hexadecimal and octal literals might be harder to understand + at first, you should really take the time to learn them. They're + part of C, C++, and many other programming languages, while binary + constants are available only for compatibility with Arduino. + + Also, ``B00000000`` is shown for clarity, but zero in any number + format is zero. + +So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while +leaving the rest of the variable's bits unchanged, use the compound +bitwise AND operator ``&=`` with the constant ``B11111100`` +(hexadecimal ``0xFC``\ ):: + + 1 0 1 0 1 0 1 0 variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + 1 0 1 0 1 0 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +Here is the same representation with the variable's bits replaced +with the symbol ``x``\ :: + + x x x x x x x x variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + x x x x x x 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +So, using a byte variable ``b``\ , if we say:: + + b = B10101010; // B10101010 == 0xAA + b &= B11111100; // B11111100 == 0xFC + +then we will have :: + + b == B10101000; // B10101000 == 0xA8 + +.. _lang-compoundbitwise-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 +a program, writing the line ``x |= y;`` is equivalent to writing ``x = +x | y;``. That is, the value of ``x`` after the line will be equal to +its old value bitwise ORed with the value of ``y``:: + + x |= y; // equivalent to x = x | y; + +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 +`\ , ``&=``). + +Before doing an example of ``|=``, let's first review the Bitwise OR +(``|``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Bits that are "bitwise ORed" with 0 are unchanged, while bits that are +"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` +variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` +equals ``B11111111`` (here we've used binary constants; see the +:ref:`note ` above). + +So, to set bits 0 and 1 of a one-byte variable, while leaving the rest +of the variable unchanged, use the compound bitwise OR operator +(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +Here is the same representation with the variable's bits replaced with +the symbol ``x``:: + + x x x x x x x x variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + x x x x x x 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b |= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101011; // B10101011 == 0xAB + +.. _lang-compoundbitwise-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 +variable. In a program, writing the line ``x ^= y;`` is equivalent to +writing ``x = x ^ y;``. That is, the value of ``x`` after the line +will be equal to its old value bitwise XORed with the value of ``y``:: + + x ^= y; // equivalent to x = x ^ y; + +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:`&= +` and :ref:`\|= +`; in fact, these three operators all +work the same in this way). + +Before doing an example of ``^=``, let's first review the Bitwise +XOR operator, ``^``:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + +One way to look at bitwise XOR is that each bit in the result is a 1 +if the input bits are different, or 0 if they are the same. Another +way to think about it is that the result bit will be 1 when *exactly* +one (no more, no less) of the input bits is 1; otherwise, it will be +zero. This means that if you XOR a bit with 1, it will change (or +toggle) its value, while if you XOR a bit with 0, it stays the same. + +So, to toggle bits 0 and 1 of a one-byte variable, while leaving the +rest of the variable unchanged, use the compound bitwise XOR operator +``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see +:ref:`note ` above):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged toggled + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b ^= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101001; // B10101001 == 0xA9 + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) + + +.. include:: cc-attribution.txt 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 `. 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() +`), and read with :ref:`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() +.. `, 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() `, 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() `, and +read with :ref:`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() `, 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() ` +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() ` 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() ` 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 `_'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 `, but +you can change this with the U and L modifiers (see :ref:`below +`). 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 +` 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 +`, with the attendant :ref:`limitations in values +`. 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-constants-integers-u-l: +- an ``l`` or ``L`` to interpret the constant as a long value. For + example, ``100000L`` is a :ref:`long `. -U & L formatters -^^^^^^^^^^^^^^^^ +- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an + :ref:`unsigned long `. + +.. _lang-constants-fp: -By default, an integer constant is treated as an -`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 `. +In order for the literal to be interpreted as a :ref:`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() `_ -- `Integer Constants `_ -- `boolean variables `_ -- `#define `_ -- `byte `_ -- `int `_ -- `unsigned int `_ -- `long `_ -- `unsigned long `_ +See Also +-------- +- :ref:`pinMode() ` +- :ref:`Boolean Variables ` +- :ref:`#define ` +- :ref:`int ` +- :ref:`unsigned int ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`float ` +- :ref:`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 `\ , :ref:`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/curly-braces.rst b/docs/source/lang/curly-braces.rst new file mode 100644 index 0000000..a4bd3dc --- /dev/null +++ b/docs/source/lang/curly-braces.rst @@ -0,0 +1,109 @@ +.. highlight:: cpp + +.. _lang-curly-braces: + +Curly Braces (``{``, ``}``) +=========================== + +.. contents:: Contents + :local: + +Introduction +------------ + +Curly braces (also referred to as just "braces" or as "curly +brackets") are a major part of the C and C++ programming +languages. They are used in several different constructs, outlined +below, and this can sometimes be confusing for beginners. + +An opening curly brace, ``{`` must always be followed by a closing +curly brace ``}``. This is a condition that is often referred to as +the braces being *balanced*. The Maple IDE (integrated development +environment) includes a convenient feature to check the balance of +curly braces. Just select a brace, or even click the insertion point +immediately following a brace, and its companion will be highlighted\ +[#fbug]_\ . + +Beginning programmers, and programmers coming to C++ from languages +without braces, often find using them confusing or daunting. + +Because the use of the curly brace is so varied, it is good +programming practice to type the closing brace immediately after +typing the opening brace when inserting a construct which requires +curly braces. Then insert some blank lines between your braces and +begin inserting statements. Your braces, and your attitude, will never +become unbalanced. + +Unbalanced braces can often lead to cryptic, impenetrable compiler +errors that can sometimes be hard to track down in a large program. +Because of their varied usages, braces are also incredibly important +to the syntax of a program and moving a brace one or two lines will +usually dramatically affect the meaning of a program. + +The main uses of curly braces +----------------------------- + +**Functions**:: + + // a function body needs braces around it + void myFunction(datatype argument) { + // ... function body goes in here ... + } + +**Loops** (see the :ref:`while `\ , :ref:`for +`\ , and :ref:`do/while ` loop reference +pages for more information):: + + // you should put braces around the body of a loop: + + while (boolean expression) { + // code inside the loop goes here + } + + for (initialisation; termination condition; incrementing expr) { + // code inside the loop goes here + } + + do { + // code inside the loop goes here + } while (boolean expression); + + +**Conditional statements** (see the :ref:`if statement ` +reference page for more information):: + + // you should put braces around the body of an "if", "else if", + // or "else": + + if (boolean expression) { + // code inside the "if" + } + else if (boolean expression) { + // code inside the "else if" + } + else { + // code inside the "else" + } + +**Switch statements** (see the :ref:`switch statement +` reference page for more information):: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + +.. rubric:: Footnotes + +.. TODO remove this once IDE 0.1.0 released + +.. [#fbug] At present this feature is slightly buggy as the IDE will + often find (incorrectly) a brace in text that has been commented + out. + + +.. include:: cc-attribution.txt 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 ` or :ref:`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 `_ or a -`LOW `_ value to a -digital pin. - - - -If the pin has been configured as an OUTPUT with -`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 `_). -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 ` or a :ref:`LOW +` value to a pin configured as :ref:`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() +` 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 `_ or -`LOW `_ - - - -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() ` 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 `_\ () -- `digitalRead `_\ () -- `Tutorial: Digital Pins `_ - - - +- :ref:`pinMode ` +- :ref:`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 ` 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 ` 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 ` 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 ` statement, by allowing multiple tests -to be grouped together. For example, an :ref:`analog input -` 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 ` statement. - -See Also --------- - -- :ref:`if ` -- :ref:`switch/case ` - - -.. 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 ` +or a :ref:`long `:: + + // create a weather variable named theWeather, with value COMFY: + weather theWeather = COMFY; + +Enumeration types are useful within :ref:`switch statements +`. 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 +`, 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 ` data type. Here -is an example (see the :ref:`constants reference -` for an explanation of the "2.0f"):: +Converts a value to the :ref:`float ` data type. Here is +an example (see the :ref:`constants reference ` 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 `. If the condition is -false, the body is not executed. Here's a more concrete example:: +code inside :ref:`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 ` statement, by allowing multiple tests to +be grouped together. For example, an :ref:`analog input +` 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 ` statement. + + See Also -------- - :ref:`boolean operators ` - :ref:`comparison operators ` -- :ref:`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 `_) includes a library -that is used to control :ref:`LCD displays `:: +that is used to control :ref:`LCD displays +`:: // include the library code: #include 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 ` - +- :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 ` in the other direction. +:ref:`roll over ` 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 ` data type. Here is an example:: diff --git a/docs/source/lang/interrupts.rst b/docs/source/lang/interrupts.rst deleted file mode 100644 index 5ca7041..0000000 --- a/docs/source/lang/interrupts.rst +++ /dev/null @@ -1,62 +0,0 @@ -.. _lang-interrupts: - -interrupts() -============ - -Description ------------ - -Re-enables interrupts (after they've been disabled by -`noInterrupts `_\ ()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None - - - -Returns -------- - -None - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `noInterrupts `_\ () -- `attachInterrupt `_\ () -- `detachInterrupt `_\ () - - - - -.. include:: cc-attribution.txt 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:`&& `. +- ``not`` is a synonym for :ref:`\! `. +- ``not_eq`` is a synonym for :ref:`\!= `. +- ``or`` is a synonym for :ref:`|| `. + +Bitwise Operator Synonyms +------------------------- + +- ``and_eq`` is a synonym for :ref:`&= `. +- ``bitand`` is a synonym for (bitwise) :ref:`& `. +- ``bitor`` is a synonym for :ref:`\| `. +- ``compl`` is a synonym for :ref:`~ `. +- ``or_eq`` is a synonym for :ref:`|= `. +- ``xor`` is a synonym for :ref:`^ `. +- ``xor_eq`` is a synonym for :ref:`^= `. + +Constants +--------- + +- ``true`` and ``false`` are the :ref:`boolean constants + `. + +Control Flow +------------ + +- ``break`` can exit out of a :ref:`switch statement + ` or a :ref:`for `, :ref:`do + `, or :ref:`while ` loop. + +- ``case`` defines alternatives in a :ref:`switch statement `. + +- ``continue`` will move control flow to the next iteration of the + enclosing :ref:`for `, :ref:`do `, or + :ref:`while ` loop. + +- ``default`` defines the default alternative in a :ref:`switch + statement `. + +- ``do`` introduces a :ref:`do ` loop. + +- ``else`` is used in :ref:`if statements `. + +- ``for`` introduces a :ref:`for ` loop. + +- ``goto`` :ref:`jumps ` to a label. + +- ``if`` introduces an :ref:`if statement `. + +- ``return`` :ref:`transfers flow to a function's caller `. + +- ``switch`` introduces a :ref:`switch statement `. + +- ``while`` introduces a :ref:`while ` loop. + +Types +----- + +The following keywords are used for built-in types. + +- :ref:`bool ` +- :ref:`lang-char` +- :ref:`lang-double` +- :ref:`lang-float` +- :ref:`lang-int` +- :ref:`lang-long` +- :ref:`short ` +- :ref:`void ` (not really a type, but used in the absence + of one) + +The following keywords are used to introduce new types. + +- :ref:`enum ` + +Qualifiers +---------- + +- :ref:`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 ` is useful when declaring variables + that may be modified by external interrupts. + +- :ref:`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 ` 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 ` include ``-fno-exceptions``. + +- ``try`` is used in exception handling. Note that the default + flags we pass to :ref:`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 ` as any numeric data type. Here's an example of declaring a long (see :ref:`integer constants -` for an explanation of the "L" at the end of the +` 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 ` 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 `_\ () -- `word `_\ () - - - +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() ` 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 `), 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 `_\ () - +- :ref:`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 `_\ () -- `delay `_\ () -- `delayMicroseconds `_\ () - - +- :ref:`millis() ` +- :ref:`delay() ` +- :ref:`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 +`, overflow errors may occur if you try to do math +with other data types, such as :ref:`ints `. -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 `_\ () -- `delay `_\ () -- `delayMicroseconds `_\ () -- `Tutorial: Blink Without Delay `_ - - +- :ref:`micros ` +- :ref:`delay ` +- :ref:`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 `_ 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() `_. - See Also -------- - :ref:`Arithmetic ` - .. include:: cc-attribution.txt diff --git a/docs/source/lang/nointerrupts.rst b/docs/source/lang/nointerrupts.rst deleted file mode 100644 index 2043c91..0000000 --- a/docs/source/lang/nointerrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-nointerrupts: - -noInterrupts() -============== - -Description ------------ - -Disables interrupts (you can re-enable them with interrupts()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None. - - - -Returns -------- - -None. - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `interrupts `_\ () - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/notone.rst b/docs/source/lang/notone.rst deleted file mode 100644 index 22432e2..0000000 --- a/docs/source/lang/notone.rst +++ /dev/null @@ -1,50 +0,0 @@ -.. _lang-notone: - -noTone() -======== - -Description ------------ - -Stops the generation of a square wave triggered by -`tone `_\ (). Has no effect if -no tone is being generated. - - - -**NOTE:** if you want to play different pitches on multiple pins, -you need to call noTone() on one pin before calling tone() on the -next pin. - - - -Syntax ------- - -noTone(pin) - - - -Parameters ----------- - -pin: the pin on which to stop generating the tone - - - -Returns -------- - -nothing - - - -See also --------- - - -- `tone `_ () - - - -.. 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 ` will have access +to these types as long as they have imported ``wirish.h``; several are +defined in in `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:`& +` and the arithmetic operator :ref:`* +`. 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 `_. 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 `_ -function in the Arduino playground for more on this. +.. TODO LATER some examples See Also -------- diff --git a/docs/source/lang/pulsein.rst b/docs/source/lang/pulsein.rst deleted file mode 100644 index 7bbe84c..0000000 --- a/docs/source/lang/pulsein.rst +++ /dev/null @@ -1,82 +0,0 @@ -.. _lang-pulsein: - -pulseIn() -========= - -Description ------------ - -Reads a pulse (either HIGH or LOW) on a pin. For example, if -**value** is **HIGH**, **pulseIn()** waits for the pin to go -**HIGH**, starts timing, then waits for the pin to go **LOW** and -stops timing. Returns the length of the pulse in microseconds. -Gives up and returns 0 if no pulse starts within a specified time -out. - - - -The timing of this function has been determined empirically and -will probably show errors in longer pulses. Works on pulses from 10 -microseconds to 3 minutes in length. - - - -Syntax ------- - -pulseIn(pin, value) -pulseIn(pin, value, timeout) - - - -Parameters ----------- - -pin: the number of the pin on which you want to read the pulse. -(*int*) - - - -value: type of pulse to read: either -`HIGH `_ or -`LOW `_. (*int*) - - - -timeout (optional): the number of microseconds to wait for the -pulse to start; default is one second (*unsigned long*) - - - -Returns -------- - -the length of the pulse (in microseconds) or 0 if no pulse started -before the timeout (*unsigned long*) - - - -Example -------- - -:: - - - - int pin = 7; - unsigned long duration; - - void setup() - { - pinMode(pin, INPUT); - } - - void loop() - { - duration = pulseIn(pin, HIGH); - } - - - - -.. include:: cc-attribution.txt 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 `_):: - +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() ` to differ, on subsequent executions of a +sketch, use :ref:`randomSeed() ` to initialize the +random number generator with a fairly random input, such as +:ref:`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 +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`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 `_\ () - - +- :ref:`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 +`_, 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() ` 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() +` 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 +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`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 `_ - - - +- :ref:`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() ` 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 ` which enclose that -function. +inside of the :ref:`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 `_\ () -- `end `_\ () -- `available `_\ () -- `read `_\ () -- `flush `_\ () -- `print `_\ () +If you want to communicate with the Maple using the provided USB port, +use :ref:`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() + ` 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 + `), 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 `_\ () -- `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 `_ -- `Dimmer `_ -- `Graph `_ -- `Physical Pixel `_ -- `Virtual Color Mixer `_ -- `Serial Call Response `_ -- `Serial Call Response ASCII `_ +.. TODO LATER port these examples over +.. Examples +.. -------- +.. - `ASCII Table `_ +.. - `Dimmer `_ +.. - `Graph `_ +.. - `Physical Pixel `_ +.. - `Virtual Color Mixer `_ +.. - `Serial Call Response `_ +.. - `Serial Call Response ASCII `_ .. 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 `, 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 `; 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 + `), 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 `, :ref:`pin modes +`, start using :ref:`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/shiftout.rst b/docs/source/lang/shiftout.rst deleted file mode 100644 index e76cc01..0000000 --- a/docs/source/lang/shiftout.rst +++ /dev/null @@ -1,136 +0,0 @@ -.. _lang-shiftout: - -shiftOut() -========== - -Description ------------ - -Shifts out a byte of data one bit at a time. Starts from either the -most (i.e. the leftmost) or least (rightmost) significant bit. Each -bit is written in turn to a data pin, after which a clock pin is -pulsed to indicate that the bit is available. - - - -This is a software implementation; Arduino (as of 0019) also -provides an `SPI library `_ -that uses the hardware implementation. - - - -Syntax ------- - -shiftOut(dataPin, clockPin, bitOrder, value) - - - -Parameters ----------- - -dataPin: the pin on which to output each bit (*int*) - - - -clockPin: the pin to toggle once the **dataPin** has been set to -the correct value (*int*) - - - -bitOrder: which order to shift out the bits; either **MSBFIRST** or -**LSBFIRST**. -(Most Significant Bit First, or, Least Significant Bit First) - - - -value: the data to shift out. (*byte*) - - - -Returns -------- - -None - - - -Note ----- - -The **dataPin** and **clockPin** must already be configured as -outputs by a call to -`pinMode `_\ (). - - - -**shiftOut** is currently written to output 1 byte (8 bits) so it -requires a two step operation to output values larger than 255. - -:: - - // Do this for MSBFIRST serial - int data = 500; - // shift out highbyte - shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); - // shift out lowbyte - shiftOut(data, clock, MSBFIRST, data); - - // Or do this for LSBFIRST serial - data = 500; - // shift out lowbyte - shiftOut(dataPin, clock, LSBFIRST, data); - // shift out highbyte - shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); - - - -Example -------- - -*For accompanying circuit, see the `tutorial on controlling a 74HC595 shift register `_.* - - - -:: - - //**************************************************************// - // Name : shiftOutCode, Hello World // - // Author : Carlyn Maw,Tom Igoe // - // Date : 25 Oct, 2006 // - // Version : 1.0 // - // Notes : Code for using a 74HC595 Shift Register // - // : to count from 0 to 255 // - //**************************************************************** - - //Pin connected to ST_CP of 74HC595 - int latchPin = 8; - //Pin connected to SH_CP of 74HC595 - int clockPin = 12; - ////Pin connected to DS of 74HC595 - int dataPin = 11; - - void setup() { - //set pins to output because they are addressed in the main loop - pinMode(latchPin, OUTPUT); - pinMode(clockPin, OUTPUT); - pinMode(dataPin, OUTPUT); - } - - void loop() { - //count up routine - for (int j = 0; j < 256; j++) { - //ground latchPin and hold low for as long as you are transmitting - digitalWrite(latchPin, LOW); - shiftOut(dataPin, clockPin, LSBFIRST, j); - //return the latch pin high to signal chip that it - //no longer needs to listen for information - digitalWrite(latchPin, HIGH); - delay(1000); - } - } - - - - -.. 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 ` data type, which is diff --git a/docs/source/lang/stringclass.rst b/docs/source/lang/stringclass.rst deleted file mode 100644 index 5e53f08..0000000 --- a/docs/source/lang/stringclass.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _lang-stringclass: - -String Class -============ - -Stub. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/stringobject.rst b/docs/source/lang/stringobject.rst deleted file mode 100644 index d7f287c..0000000 --- a/docs/source/lang/stringobject.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. _lang-stringobject: - -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 `_ 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. - - - -For reference, character arrays are referred to as strings with a -small s, and instances of the String class are referred to as -Strings with a capital S. Note that constant strings, specified in -"double quotes" are treated as char arrays, not instances of the -String class. - - - -Functions ---------- - - -- `String `_\ () -- `charAt `_\ () -- `compareTo `_\ () -- `concat `_\ () -- `endsWith `_\ () -- `equals `_\ () -- `equalsIgnoreCase `_\ () -- `getBytes `_\ () -- `indexOf `_\ () -- `lastIndexOf `_\ () -- `length `_\ () -- `replace `_\ () -- `setCharAt `_\ () -- `startsWith `_\ () -- `substring `_\ () -- `toCharArray `_\ () -- `toLowerCase `_\ () -- `toUpperCase `_\ () -- `trim `_\ () - - - -Operators ---------- - - -- `[] (element access) `_ -- `+ (concatenation) `_ -- `== (comparison) `_ - - - -Examples --------- - - -- `StringConstructors `_ -- `StringAdditionOperator `_ -- `StringIndexOf `_ -- `StringAppendOperator `_ -- `StringLengthTrim `_ -- `StringCaseChanges `_ -- `StringReplace `_ -- `StringCharacters `_ -- `StringStartsWithEndsWith `_ -- `StringComparisonOperators `_ -- `StringSubstring `_ - - - -See Also --------- - - -- `string `_: character - arrays -- `Variable Declaration `_ - - - - -.. include:: cc-attribution.txt 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 ` blocks, A ``switch`` statement -controls program flow by allowing you to specify different code that -should be executed under various cases. +Like :ref:`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 ` +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 ` +- :ref:`if/else ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/tone.rst b/docs/source/lang/tone.rst deleted file mode 100644 index 96f0a7c..0000000 --- a/docs/source/lang/tone.rst +++ /dev/null @@ -1,81 +0,0 @@ -.. _lang-tone: - -tone() -====== - -Description ------------ - -Generates a square wave of the specified frequency (and 50% duty -cycle) on a pin. A duration can be specified, otherwise the wave -continues until a call to -`noTone `_\ (). The pin can be -connected to a piezo buzzer or other speaker to play tones. - - - -Only one tone can be generated at a time. If a tone is already -playing on a different pin, the call to tone() will have no effect. -If the tone is playing on the same pin, the call will set its -frequency. - - - -Use of the tone() function will interfere with PWM output on pins 3 -and 11 (on boards other than the Mega). - - - -**NOTE:** if you want to play different pitches on multiple pins, -you need to call noTone() on one pin before calling tone() on the -next pin. - - - -Syntax ------- - -tone(pin, frequency) -tone(pin, frequency, duration) - - - -Parameters ----------- - -pin: the pin on which to generate the tone - - - -frequency: the frequency of the tone in hertz - - - -duration: the duration of the tone in milliseconds (optional) - - - -Returns -------- - -nothing - - - -See also --------- - - -- `noTone `_\ () -- `analogWrite `_\ () -- `Tutorial:Tone `_ -- `Tutorial:Pitch follower `_ -- `Tutorial:Simple Keyboard `_ -- `Tutorial: multiple tones `_ - - -- `Tutorial: PWM `_ - - - -.. 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/unimplemented/interrupts.rst b/docs/source/lang/unimplemented/interrupts.rst new file mode 100644 index 0000000..55b8e93 --- /dev/null +++ b/docs/source/lang/unimplemented/interrupts.rst @@ -0,0 +1,59 @@ +.. _lang-interrupts: + +interrupts() +============ + +Re-enables interrupts (after they've been disabled by +`noInterrupts `_\ ()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None + + + +Returns +------- + +None + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `noInterrupts `_\ () +- `attachInterrupt `_\ () +- `detachInterrupt `_\ () + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/nointerrupts.rst b/docs/source/lang/unimplemented/nointerrupts.rst new file mode 100644 index 0000000..fb2e5f9 --- /dev/null +++ b/docs/source/lang/unimplemented/nointerrupts.rst @@ -0,0 +1,59 @@ +.. _lang-nointerrupts: + +noInterrupts() +============== + +Description +----------- + +Disables interrupts (you can re-enable them with interrupts()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None. + + + +Returns +------- + +None. + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `interrupts `_\ () + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/notone.rst b/docs/source/lang/unimplemented/notone.rst new file mode 100644 index 0000000..485c9c5 --- /dev/null +++ b/docs/source/lang/unimplemented/notone.rst @@ -0,0 +1,50 @@ +.. _lang-notone: + +noTone() +======== + +Description +----------- + +Stops the generation of a square wave triggered by +`tone `_\ (). Has no effect if +no tone is being generated. + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +noTone(pin) + + + +Parameters +---------- + +pin: the pin on which to stop generating the tone + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `tone `_ () + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/pulsein.rst b/docs/source/lang/unimplemented/pulsein.rst new file mode 100644 index 0000000..2b52428 --- /dev/null +++ b/docs/source/lang/unimplemented/pulsein.rst @@ -0,0 +1,82 @@ +.. _lang-pulsein: + +pulseIn() +========= + +Description +----------- + +Reads a pulse (either HIGH or LOW) on a pin. For example, if +**value** is **HIGH**, **pulseIn()** waits for the pin to go +**HIGH**, starts timing, then waits for the pin to go **LOW** and +stops timing. Returns the length of the pulse in microseconds. +Gives up and returns 0 if no pulse starts within a specified time +out. + + + +The timing of this function has been determined empirically and +will probably show errors in longer pulses. Works on pulses from 10 +microseconds to 3 minutes in length. + + + +Syntax +------ + +pulseIn(pin, value) +pulseIn(pin, value, timeout) + + + +Parameters +---------- + +pin: the number of the pin on which you want to read the pulse. +(*int*) + + + +value: type of pulse to read: either +`HIGH `_ or +`LOW `_. (*int*) + + + +timeout (optional): the number of microseconds to wait for the +pulse to start; default is one second (*unsigned long*) + + + +Returns +------- + +the length of the pulse (in microseconds) or 0 if no pulse started +before the timeout (*unsigned long*) + + + +Example +------- + +:: + + + + int pin = 7; + unsigned long duration; + + void setup() + { + pinMode(pin, INPUT); + } + + void loop() + { + duration = pulseIn(pin, HIGH); + } + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/shiftout.rst b/docs/source/lang/unimplemented/shiftout.rst new file mode 100644 index 0000000..ff3852f --- /dev/null +++ b/docs/source/lang/unimplemented/shiftout.rst @@ -0,0 +1,136 @@ +.. _lang-shiftout: + +shiftOut() +========== + +Description +----------- + +Shifts out a byte of data one bit at a time. Starts from either the +most (i.e. the leftmost) or least (rightmost) significant bit. Each +bit is written in turn to a data pin, after which a clock pin is +pulsed to indicate that the bit is available. + + + +This is a software implementation; Arduino (as of 0019) also +provides an `SPI library `_ +that uses the hardware implementation. + + + +Syntax +------ + +shiftOut(dataPin, clockPin, bitOrder, value) + + + +Parameters +---------- + +dataPin: the pin on which to output each bit (*int*) + + + +clockPin: the pin to toggle once the **dataPin** has been set to +the correct value (*int*) + + + +bitOrder: which order to shift out the bits; either **MSBFIRST** or +**LSBFIRST**. +(Most Significant Bit First, or, Least Significant Bit First) + + + +value: the data to shift out. (*byte*) + + + +Returns +------- + +None + + + +Note +---- + +The **dataPin** and **clockPin** must already be configured as +outputs by a call to +`pinMode `_\ (). + + + +**shiftOut** is currently written to output 1 byte (8 bits) so it +requires a two step operation to output values larger than 255. + +:: + + // Do this for MSBFIRST serial + int data = 500; + // shift out highbyte + shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); + // shift out lowbyte + shiftOut(data, clock, MSBFIRST, data); + + // Or do this for LSBFIRST serial + data = 500; + // shift out lowbyte + shiftOut(dataPin, clock, LSBFIRST, data); + // shift out highbyte + shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); + + + +Example +------- + +*For accompanying circuit, see the `tutorial on controlling a 74HC595 shift register `_.* + + + +:: + + //**************************************************************// + // Name : shiftOutCode, Hello World // + // Author : Carlyn Maw,Tom Igoe // + // Date : 25 Oct, 2006 // + // Version : 1.0 // + // Notes : Code for using a 74HC595 Shift Register // + // : to count from 0 to 255 // + //**************************************************************** + + //Pin connected to ST_CP of 74HC595 + int latchPin = 8; + //Pin connected to SH_CP of 74HC595 + int clockPin = 12; + ////Pin connected to DS of 74HC595 + int dataPin = 11; + + void setup() { + //set pins to output because they are addressed in the main loop + pinMode(latchPin, OUTPUT); + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + } + + void loop() { + //count up routine + for (int j = 0; j < 256; j++) { + //ground latchPin and hold low for as long as you are transmitting + digitalWrite(latchPin, LOW); + shiftOut(dataPin, clockPin, LSBFIRST, j); + //return the latch pin high to signal chip that it + //no longer needs to listen for information + digitalWrite(latchPin, HIGH); + delay(1000); + } + } + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/stringclass.rst b/docs/source/lang/unimplemented/stringclass.rst new file mode 100644 index 0000000..cdd385d --- /dev/null +++ b/docs/source/lang/unimplemented/stringclass.rst @@ -0,0 +1,9 @@ +.. _lang-stringclass: + +String Class +============ + +Stub. + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/stringobject.rst b/docs/source/lang/unimplemented/stringobject.rst new file mode 100644 index 0000000..e47ed7e --- /dev/null +++ b/docs/source/lang/unimplemented/stringobject.rst @@ -0,0 +1,89 @@ +.. _lang-stringobject: + +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 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. + + + +For reference, character arrays are referred to as strings with a +small s, and instances of the String class are referred to as +Strings with a capital S. Note that constant strings, specified in +"double quotes" are treated as char arrays, not instances of the +String class. + + + +Functions +--------- + + +- `String `_\ () +- `charAt `_\ () +- `compareTo `_\ () +- `concat `_\ () +- `endsWith `_\ () +- `equals `_\ () +- `equalsIgnoreCase `_\ () +- `getBytes `_\ () +- `indexOf `_\ () +- `lastIndexOf `_\ () +- `length `_\ () +- `replace `_\ () +- `setCharAt `_\ () +- `startsWith `_\ () +- `substring `_\ () +- `toCharArray `_\ () +- `toLowerCase `_\ () +- `toUpperCase `_\ () +- `trim `_\ () + + + +Operators +--------- + + +- `[] (element access) `_ +- `+ (concatenation) `_ +- `== (comparison) `_ + + + +Examples +-------- + + +- `StringConstructors `_ +- `StringAdditionOperator `_ +- `StringIndexOf `_ +- `StringAppendOperator `_ +- `StringLengthTrim `_ +- `StringCaseChanges `_ +- `StringReplace `_ +- `StringCharacters `_ +- `StringStartsWithEndsWith `_ +- `StringComparisonOperators `_ +- `StringSubstring `_ + + + +See Also +-------- + + +- `Character array strings `_ +- `Variable Declaration `_ + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/tone.rst b/docs/source/lang/unimplemented/tone.rst new file mode 100644 index 0000000..f83bf6b --- /dev/null +++ b/docs/source/lang/unimplemented/tone.rst @@ -0,0 +1,81 @@ +.. _lang-tone: + +tone() +====== + +Description +----------- + +Generates a square wave of the specified frequency (and 50% duty +cycle) on a pin. A duration can be specified, otherwise the wave +continues until a call to +`noTone `_\ (). The pin can be +connected to a piezo buzzer or other speaker to play tones. + + + +Only one tone can be generated at a time. If a tone is already +playing on a different pin, the call to tone() will have no effect. +If the tone is playing on the same pin, the call will set its +frequency. + + + +Use of the tone() function will interfere with PWM output on pins 3 +and 11 (on boards other than the Mega). + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +tone(pin, frequency) +tone(pin, frequency, duration) + + + +Parameters +---------- + +pin: the pin on which to generate the tone + + + +frequency: the frequency of the tone in hertz + + + +duration: the duration of the tone in milliseconds (optional) + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `noTone `_\ () +- `analogWrite `_\ () +- `Tutorial:Tone `_ +- `Tutorial:Pitch follower `_ +- `Tutorial:Simple Keyboard `_ +- `Tutorial: multiple tones `_ + + +- `Tutorial: PWM `_ + + + +.. 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 ` 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 ` 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 ` 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 ` for an explanation of the "L" at the -end of the number):: +constants ` 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 ` page for more -information. +variables. See the :ref:`built-in 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 ` reference for links to each type's -reference page. +:ref:`built-in 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 `_ - - +.. 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 `). +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 +`. 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 `_ - - - +- :ref:`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 `. 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 ` 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() ` | |**Control Structures** |* :ref:`INPUT ` | | | | | :ref:`OUTPUT ` |* :ref:`digitalRead() ` | -|* :ref:`if ` | | | +|* :ref:`if/else ` | | | | |* :ref:`true ` | | | -|* :ref:`if...else ` | :ref:`false ` |**Analog I/O** | -| | | | -|* :ref:`for ` |* :ref:`integer constants |* :ref:`analogRead() ` | -| | ` | | -|* :ref:`switch/case ` | |* :ref:`pwmWrite() ` | -| |* :ref:`floating point constants | (:ref:`analogWrite() ` is | -|* :ref:`while ` | ` | also available, though its use is discouraged) | +|* :ref:`for ` | :ref:`false ` |**Analog I/O** | | | | | -|* :ref:`do...while ` | | | -| |**Data Types** |**Advanced I/O** | +|* :ref:`switch/case ` |* :ref:`Constants |* :ref:`analogRead() ` | +| | ` (:ref:`integers | | +|* :ref:`while ` | `, :ref:`floating |* :ref:`pwmWrite() ` | +| | point `) | (:ref:`analogWrite() ` is | +|* :ref:`do...while ` | | also available, though its use is discouraged) | +| |**Data Types** | | |* :ref:`break ` | | | -| | The size of each datatype, in bytes, is |* tone(): TODO | +| | The size of each datatype, in bytes, is |**Advanced I/O** | |* :ref:`continue ` | given in parentheses where appropriate. | | -| | |* noTone(): TODO | +| | |* tone(): TODO | |* :ref:`return ` | *Note*: The ``word`` type is (deliberately) | | -| | :ref:`not supported `. |* shiftOut(): TODO | +| | :ref:`not supported `. |* noTone(): TODO | |* :ref:`goto ` | | | -| |* :ref:`void ` |* pulseIn(): TODO | +| |* :ref:`void ` |* shiftOut(): TODO | +| | | | +|**Further syntax** |* :ref:`boolean ` (1 byte) |* pulseIn(): TODO | | | | | -|**Further syntax** |* :ref:`boolean ` (1 byte) | | -| | |**Time** | |* :ref:`; (semicolon) ` |* :ref:`char ` (1 byte) | | -| | |* :ref:`millis() ` | -|* :ref:`{} (curly braces) ` |* :ref:`unsigned char | | -| | ` (1 byte) |* :ref:`micros() ` | -|* :ref:`// (single-line comment) | | | -| ` |* :ref:`byte ` (1 byte) |* :ref:`delay() ` | +| | |**Time** | +|* :ref:`{} (curly braces) |* :ref:`unsigned char | | +| ` | ` (1 byte) |* :ref:`millis() ` | | | | | -|* :ref:`/\* \*/ (multi-line comment) |* :ref:`int ` (4 bytes) |* :ref:`delayMicroseconds() | -| ` | | ` | -| |* :ref:`unsigned int ` | | -|* :ref:`#define ` | (4 bytes) | | -| | |**Math** | -|* :ref:`#include ` |* :ref:`long ` (8 bytes) | | -| | |* :ref:`min() ` | +|* :ref:`// (single-line comment) |* :ref:`byte ` (1 byte) |* :ref:`micros() ` | +| ` | | | +| |* :ref:`int ` (4 bytes) |* :ref:`delay() ` | +|* :ref:`/\* \*/ (multi-line comment) | | | +| ` |* :ref:`unsigned int ` |* :ref:`delayMicroseconds() | +| | (4 bytes) | ` | +|* :ref:`#define ` | | | +| |* :ref:`long ` (8 bytes) | | +|* :ref:`#include ` | |**Math** | | |* :ref:`unsigned long ` | | -|**Arithmetic Operators** | (8 bytes) |* :ref:`max() ` | +| | (8 bytes) |* :ref:`min() ` | +|**Arithmetic Operators** | | | +| |* :ref:`float ` (4 bytes) |* :ref:`max() ` | +|* :ref:`= ` | | | +| (assignment operator) |* :ref:`double ` (8 bytes) |* :ref:`abs() ` | | | | | -|* :ref:`= ` |* :ref:`float ` (4 bytes) |* :ref:`abs() ` | -| (assignment operator) | | | -| |* :ref:`double ` (8 bytes) |* :ref:`constrain() ` | -|* :ref:`+ ` (addition) | | | -| |* :ref:`string ` |* :ref:`map() ` | -|* :ref:`- ` | | | -| (subtraction) |* :ref:`array ` |* :ref:`pow() ` | +|* :ref:`+ ` (addition) |* :ref:`Strings ` |* :ref:`constrain() ` | | | | | -|* :ref:`* ` |* See also: :ref:`built-in types reference |* :ref:`sqrt() ` | -| (multiplication) | `. | | +|* :ref:`- ` |* :ref:`Arrays ` |* :ref:`map() ` | +| (subtraction) | | | +| |* :ref:`enum ` |* :ref:`pow() ` | +|* :ref:`* ` | | | +| (multiplication) |* :ref:`Numeric types ` |* :ref:`sqrt() ` | | | | | -|* :ref:`/ ` (division) | |**Trigonometry** | -| |**Conversion** | | -|* :ref:`% ` (modulo) | |* :ref:`sin() ` | -| |* :ref:`char() ` | | -| | |* :ref:`cos() ` | -|**Comparison Operators** |* :ref:`byte() ` | | -| | |* :ref:`tan() ` | -|* :ref:`== ` (equal to) |* :ref:`int() ` | | +|* :ref:`/ ` (division) |**Conversion** | | +| | |**Trigonometry** | +|* :ref:`% ` (modulo) |* :ref:`char() ` | | +| | |* :ref:`sin() ` | +| |* :ref:`byte() ` | | +|**Comparison Operators** | |* :ref:`cos() ` | +| |* :ref:`int() ` | | +|* :ref:`== ` (equal to) | |* :ref:`tan() ` | +| |* :ref:`long() ` | | +|* :ref:`\!= ` | | | +| (not equal to) |* :ref:`float() ` |**Random Numbers** | | | | | -|* :ref:`\!= ` |* :ref:`long() ` |**Random Numbers** | -| (not equal to) | | | -| |* :ref:`float() ` |* :ref:`randomSeed() ` | -|* :ref:`< ` (less than) | | | -| |* :ref:`double() ` |* :ref:`random() ` | -|* :ref:`> ` | | | -| (greater than) | | | -| |**Variable Scope & Qualifiers** |**Bits and Bytes** | -|* :ref:`<= ` | | | -| (less than or equal to) |* :ref:`variables `, |* :ref:`lowByte() ` | -| | :ref:`scope ` | | -|* :ref:`>= ` | |* :ref:`highByte() ` is | -| (greater than or equal to) |* :ref:`static ` | provided, though its use is discouraged. | +|* :ref:`< ` (less than) |* :ref:`double() ` |* :ref:`randomSeed() ` | | | | | -| |* :ref:`volatile ` |* :ref:`bitRead() ` | -|**Boolean Operators** | | | -| |* :ref:`const ` |* :ref:`bitWrite() ` | -|* :ref:`&& ` (and) | | | -| | |* :ref:`bitSet() ` | -|* :ref:`|| ` (or) |**Utilities** | | -| | |* :ref:`bitClear() ` | -|* :ref:`\! ` (not) |* :ref:`sizeof() ` | | -| | (``sizeof`` operator) |* :ref:`bit() ` | +|* :ref:`> ` | |* :ref:`random() ` | +| (greater than) |**Variable Scope & Qualifiers** | | | | | | -|**Pointer Operators** | | | -| | |**External Interrupts** | -|* :ref:`* dereference operator | | | -| ` | |* :ref:`Reference Page ` | +|* :ref:`<= ` |* :ref:`variables `, |**Bits and Bytes** | +| (less than or equal to) | :ref:`scope ` | | +| | |* :ref:`lowByte() ` | +|* :ref:`>= ` |* :ref:`static ` | | +| (greater than or equal to) | |* :ref:`highByte() ` is | +| |* :ref:`volatile ` | provided, though its use is discouraged. | | | | | -|* :ref:`& reference operator | |* :ref:`attachInterrupt() | -| ` | | ` | +|**Boolean Operators** |* :ref:`const ` |* :ref:`bitRead() ` | | | | | -| | |* :ref:`detachInterrupt() | -|**Bitwise Operators** | | ` | +|* :ref:`&& ` (and) | |* :ref:`bitWrite() ` | +| |**Utilities** | | +|* :ref:`|| ` (or) | |* :ref:`bitSet() ` | +| |* :ref:`sizeof() ` | | +|* :ref:`\! ` (not) | |* :ref:`bitClear() ` | | | | | +| | |* :ref:`bit() ` | +|**Pointer Operators** | | | +| | | | +|* :ref:`* dereference operator | |**External Interrupts** | +| ` | | | +| | |* :ref:`Reference Page ` | +|* :ref:`& reference operator | | | +| ` | |* :ref:`attachInterrupt() | +| | | ` | +| | | | +|**Bitwise Operators** | |* :ref:`detachInterrupt() | +| | | ` | |* :ref:`& ` | | | -| (bitwise and) | |**Interrupts** | +| (bitwise and) | | | +| | |**Interrupts** | +|* :ref:`| ` | | | +| (bitwise or) | |* interrupts(): TODO | | | | | -|* :ref:`| ` | |* interrupts(): TODO | -| (bitwise or) | | | -| | |* noInterrupts(): TODO | -|* :ref:`^ ` | | | +|* :ref:`^ ` | |* noInterrupts(): TODO | | (bitwise xor) | | | -| | |**Communication** | -|* :ref:`~ ` | | | -| (bitwise not) | |* :ref:`SerialUSB ` | | | | | -|* :ref:`\<\< ` | |* :ref:`Serial ` | -| (shift left) | | | -| | |**Looking for something else?** | -|* :ref:`>> ` | | | -| (shift right) | | See the :ref:`libraries` page for interfacing with| +|* :ref:`~ ` | |**Communication** | +| (bitwise not) | | | +| | |* :ref:`SerialUSB ` | +|* :ref:`\<\< ` | | | +| (shift left) | |* :ref:`Serial ` | +| | | | +|* :ref:`>> ` | |**Looking for something else?** | +| (shift right) | | | +| | | See the :ref:`libraries` page for interfacing with| | | | particular types of hardware. Maple links | -| | | against `newlib `_ | -|**Compound Operators** | | and allows the use of any of its functions; see | -| | | its documentation for more details. | -|* :ref:`++ ` | | | +|**Compound Operators** | | against `newlib `_ | +| | | and allows the use of any of its functions; see | +|* :ref:`++ ` | | its documentation for more details. | | (increment) | | | | | | | |* :ref:`- - ` | | | | (decrement) | | | | | | | -|* :ref:`+= ` | | | +|* :ref:`+= ` | | | | (compound add) | | | | | | | |* :ref:`-= | | | -| ` (compound | | | +| ` (compound | | | | subtract) | | | | | | | |* :ref:`*= | | | -| ` (compound | | | +| ` (compound | | | | multiply) | | | | | | | |* :ref:`/= | | | -| ` (compound | | | +| ` (compound | | | | divide) | | | | | | | |* :ref:`&= | | | -| ` (compound | | | +| ` (compound | | | | bitwise and) | | | | | | | |* :ref:`|= | | | -| ` (compound | | | +| ` (compound | | | | bitwise or) | | | | | | | +|**Keywords** | | | +| | | | +|* :ref:`C++ 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 `; ``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 ` 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 `. If it really is bricked, and you think it's our fault, `contact us `_\ ! @@ -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 -`_ or `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() +` or `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 `_ 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 `_. 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 -`_. You can do this on Linux -with:: +definitely need the arm-none-eabi-* tools on your ``PATH``), then +`install Code::Blocks `_. 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 - ` 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 ` 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 ` 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() ` 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 ` 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 - ` 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() `). A solution to the +second problem is the use of :ref:`perpetual bootloader mode +`. 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. */ -- cgit v1.2.3 From d744fb826f4a6d6ce560f3b78f2e63a1f9666d9e Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Wed, 15 Dec 2010 01:50:56 -0500 Subject: Finalized 0.0.9 documentation. --- docs/Doxyfile | 11 +- docs/source/_static/img/jtag-wiring.png | Bin 40550 -> 33637 bytes docs/source/bootloader.rst | 710 ++++++++++++------------ docs/source/compatibility.rst | 22 +- docs/source/cpp.rst | 13 - docs/source/external-interrupts.rst | 1 - docs/source/gpio.rst | 16 +- docs/source/home.rst | 32 -- docs/source/i2c.rst | 1 - docs/source/index.rst | 20 +- docs/source/jtag.rst | 27 +- docs/source/lang/api/analogread.rst | 35 -- docs/source/lang/api/analogwrite.rst | 50 +- docs/source/lang/api/constants.rst | 23 + docs/source/lang/api/hardwarespi.rst | 152 +++++ docs/source/lang/api/hardwaretimer.rst | 368 ++++++++++++ docs/source/lang/api/interrupts.rst | 47 ++ docs/source/lang/api/isbuttonpressed.rst | 17 + docs/source/lang/api/nointerrupts.rst | 47 ++ docs/source/lang/api/pinmode.rst | 2 + docs/source/lang/api/pwmwrite.rst | 15 +- docs/source/lang/api/serialusb.rst | 11 +- docs/source/lang/api/toggleled.rst | 17 + docs/source/lang/api/togglepin.rst | 17 + docs/source/lang/api/waitforbuttonpress.rst | 17 + docs/source/lang/cpp/built-in-types.rst | 95 ++++ docs/source/lang/cpp/keywords.rst | 2 +- docs/source/lang/cpp/numeric-types.rst | 79 --- docs/source/lang/cpp/variables.rst | 6 +- docs/source/lang/cpp/void.rst | 10 +- docs/source/lang/unimplemented/interrupts.rst | 59 -- docs/source/lang/unimplemented/nointerrupts.rst | 59 -- docs/source/language-index.rst | 40 +- docs/source/language.rst | 233 ++++---- docs/source/libraries.rst | 67 ++- docs/source/libs/servo.rst | 108 ++++ docs/source/pwm.rst | 103 +--- docs/source/spi.rst | 55 +- docs/source/timers.rst | 231 ++------ docs/source/troubleshooting.rst | 27 +- docs/source/usart.rst | 1 - docs/source/usb.rst | 1 - libmaple/libmaple_types.h | 2 + libmaple/timers.h | 109 ++-- support/scripts/copy-to-ide | 16 +- wirish/HardwareTimer.cpp | 1 - wirish/HardwareTimer.h | 69 ++- wirish/comm/HardwareSPI.h | 23 +- wirish/ext_interrupts.h | 4 +- wirish/io.h | 2 +- wirish/wirish_math.h | 6 +- 51 files changed, 1784 insertions(+), 1295 deletions(-) delete mode 100644 docs/source/cpp.rst delete mode 100644 docs/source/home.rst create mode 100644 docs/source/lang/api/hardwarespi.rst create mode 100644 docs/source/lang/api/hardwaretimer.rst create mode 100644 docs/source/lang/api/interrupts.rst create mode 100644 docs/source/lang/api/isbuttonpressed.rst create mode 100644 docs/source/lang/api/nointerrupts.rst create mode 100644 docs/source/lang/api/toggleled.rst create mode 100644 docs/source/lang/api/togglepin.rst create mode 100644 docs/source/lang/api/waitforbuttonpress.rst create mode 100644 docs/source/lang/cpp/built-in-types.rst delete mode 100644 docs/source/lang/cpp/numeric-types.rst delete mode 100644 docs/source/lang/unimplemented/interrupts.rst delete mode 100644 docs/source/lang/unimplemented/nointerrupts.rst create mode 100644 docs/source/libs/servo.rst (limited to 'libmaple') diff --git a/docs/Doxyfile b/docs/Doxyfile index 88b8764..3290843 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -318,7 +318,7 @@ EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. -EXTRACT_STATIC = NO +EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. @@ -1335,13 +1335,13 @@ ENABLE_PREPROCESSING = YES # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. -MACRO_EXPANSION = NO +MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. -EXPAND_ONLY_PREDEF = NO +EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. @@ -1369,7 +1369,8 @@ INCLUDE_FILE_PATTERNS = # undefined via #undef or recursively expanded use the := operator # instead of the = operator. -PREDEFINED = __cplusplus +PREDEFINED = ALWAYS_INLINE= \ + __cplusplus # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. @@ -1462,7 +1463,7 @@ HIDE_UNDOC_RELATIONS = YES # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) -HAVE_DOT = YES +HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will diff --git a/docs/source/_static/img/jtag-wiring.png b/docs/source/_static/img/jtag-wiring.png index 9c63e82..8f31f99 100644 Binary files a/docs/source/_static/img/jtag-wiring.png and b/docs/source/_static/img/jtag-wiring.png differ diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index d42c050..57833ed 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -138,447 +138,447 @@ This time, however, no DFU transaction is initiated, and the bootloader gives way to user code, closing down the DFU pipe and bringing up the USB serial. -.. _bootloader-rev6: - -Maple Rev6 - The Serial Bootloader (Tentative) ----------------------------------------------- - -.. note:: This section documents an in-progress version of the Maple - bootloader. **No Maples yet sold use this bootloader protocol**. - It has not been yet been publicly released, and its interface is - not stable. - -The bootloader in Rev3/Rev5 works well on Linux, acceptably on Mac, -but was unsatisfactory on Windows. Unlike the other operating systems, -Windows needed to be manually pointed to both the driver to use for -programming (DFU, via `libusb `_) and the -driver to use for serial communication (usbser.sys, built in to -Windows). Since Maple operates in only one of these modes at a time, -driver installation was unnecessarily complicated. It was necessary to -bring Maple into the correct mode before installing each of the -drivers. Furthermore, because libusb is not bundled with Windows, and -its driver is not signed, Windows 7 users have been forced to -laboriously disable driver signing checks. Finally, Windows hates the -constant switching of the device between Serial and DFU modes (during -programming), and often prompts users to install drivers that are -already installed. We have therefore decided to abandon DFU. - -In our new bootloader scheme, Maple is simply a serial device. -Windows comes bundled with usbser.sys, so no driver signing is -required. The IDE installation process is greatly simplified, there -is no more switching back and forth between "modes", and we can build -in new functionality outside the DFU spec. - -The first incarnation of this serial-only bootloader leaves libmaple -and user code untouched. However, during programming, instead of -calling :command:`dfu-util` to upload code we will now call a newly -written utility script similar to `avr-dude -`_. The high level -operation of the bootloader will remain the same - come on at startup, -wait for an upload operation or timeout, and jump to user code. - -The second version of this bootloader will eliminate this dependence -on resetting and timing out by having the bootloader run in the -background. It will additionally own the serial port. In this scheme, -sending data over the COM port while DTR is pulled low results in that -packet being captured by the bootloader and interpreted as a -bootloader command. When the user uploads a new program, the -bootloader will overwrite the old one, reset the various peripheral -registers, and jump to user code. All of this will occur without -resetting the chip and thus causing Maple to connect and disconnect -from your computer (which seems to cause many problems). - -The final version of this bootloader scheme will involve a separate -microcontroller, whose responsibilities are to drive the USB port, -program the main processor, and offer some amount of debugging -capability. This will allow user sketches to run on the bare metal of -the main processor, without any bootloader hiding underneath. This -approach is similar to the approaches taken by mbed and the Arduino -Uno. - -Regardless of which generation of the new serial bootloader you are -working with, the command interface is the same. The low level -communication protocol is inspired by STK-500, the protocol used to -program many AVR-based development boards. The protocol is a -packetized query-response scheme. The host PC initiates every -transaction, and for every query sent to the bootloader, a single -response will be returned (or the system times out). Data is -transmitted over 115.2kbps, 8 data bits, 1 stop bit, no parity -bit. Every query or response follows the same packet format that looks -like this: - -.. _bootloader-packet-structure: - -Packet Structure -^^^^^^^^^^^^^^^^ - -A bootloader packet is composed of a sequence of fields, as follows. - -.. list-table:: - :header-rows: 1 - - * - Field - - Length (bytes) - - Value - - Description - - * - START - - 1 - - 0x1B - - Magic constant, indicates bootloader packet - - * - SEQUENCE_NUM - - 1 - - 0--0xFF - - Queries and responses must have the same sequence number; rolls - over to 0 after 0xFF - - * - MESSAGE_SIZE - - 2 - - 0--0xFFFF - - Size of message body, currently limited to a 1024B=1KB maximum - - * - TOKEN - - 1 - - 0x7F - - Differs from STK500 value of 0x0E - - * - MESSAGE_BODY - - Variable, determined by MESSAGE_SIZE field - - Command query or response - - See :ref:`next section ` - - * - CHECKSUM - - 4 - - XOR of all other 32-bit words in packet - - See :ref:`below ` - -.. _bootloader-checksum: - -.. highlight:: cpp - -.. note:: When computing the checksum, the words in a packet are - interpreted big-endian (as if the packet were a sequence of 32-bit, - big-endian unsigned integers). If the end of the MESSAGE_BODY is - not aligned with a four-byte boundary, then the checksum will treat - it as if it was padded with zero bytes to a four-byte boundary. - - As a concrete example, an entire GET_INFO query (see :ref:`below - `), including the packet structure, is - comprised of the byte sequence :: - - {0x1B, 0x7F, 0x00, 0x01, 0x7F, 0x00, 0x64, 0x7F, 0x00, 0x01} - - The SEQUENCE_NUM of this query is 0x7F. +.. .. _bootloader-rev6: + +.. Maple Rev6 - The Serial Bootloader (Tentative) +.. ---------------------------------------------- + +.. .. note:: This section documents an in-progress version of the Maple +.. bootloader. **No Maples yet sold use this bootloader protocol**. +.. It has not been yet been publicly released, and its interface is +.. not stable. + +.. The bootloader in Rev3/Rev5 works well on Linux, acceptably on Mac, +.. but was unsatisfactory on Windows. Unlike the other operating systems, +.. Windows needed to be manually pointed to both the driver to use for +.. programming (DFU, via `libusb `_) and the +.. driver to use for serial communication (usbser.sys, built in to +.. Windows). Since Maple operates in only one of these modes at a time, +.. driver installation was unnecessarily complicated. It was necessary to +.. bring Maple into the correct mode before installing each of the +.. drivers. Furthermore, because libusb is not bundled with Windows, and +.. its driver is not signed, Windows 7 users have been forced to +.. laboriously disable driver signing checks. Finally, Windows hates the +.. constant switching of the device between Serial and DFU modes (during +.. programming), and often prompts users to install drivers that are +.. already installed. We have therefore decided to abandon DFU. + +.. In our new bootloader scheme, Maple is simply a serial device. +.. Windows comes bundled with usbser.sys, so no driver signing is +.. required. The IDE installation process is greatly simplified, there +.. is no more switching back and forth between "modes", and we can build +.. in new functionality outside the DFU spec. + +.. The first incarnation of this serial-only bootloader leaves libmaple +.. and user code untouched. However, during programming, instead of +.. calling :command:`dfu-util` to upload code we will now call a newly +.. written utility script similar to `avr-dude +.. `_. The high level +.. operation of the bootloader will remain the same - come on at startup, +.. wait for an upload operation or timeout, and jump to user code. + +.. The second version of this bootloader will eliminate this dependence +.. on resetting and timing out by having the bootloader run in the +.. background. It will additionally own the serial port. In this scheme, +.. sending data over the COM port while DTR is pulled low results in that +.. packet being captured by the bootloader and interpreted as a +.. bootloader command. When the user uploads a new program, the +.. bootloader will overwrite the old one, reset the various peripheral +.. registers, and jump to user code. All of this will occur without +.. resetting the chip and thus causing Maple to connect and disconnect +.. from your computer (which seems to cause many problems). + +.. The final version of this bootloader scheme will involve a separate +.. microcontroller, whose responsibilities are to drive the USB port, +.. program the main processor, and offer some amount of debugging +.. capability. This will allow user sketches to run on the bare metal of +.. the main processor, without any bootloader hiding underneath. This +.. approach is similar to the approaches taken by mbed and the Arduino +.. Uno. + +.. Regardless of which generation of the new serial bootloader you are +.. working with, the command interface is the same. The low level +.. communication protocol is inspired by STK-500, the protocol used to +.. program many AVR-based development boards. The protocol is a +.. packetized query-response scheme. The host PC initiates every +.. transaction, and for every query sent to the bootloader, a single +.. response will be returned (or the system times out). Data is +.. transmitted over 115.2kbps, 8 data bits, 1 stop bit, no parity +.. bit. Every query or response follows the same packet format that looks +.. like this: + +.. .. _bootloader-packet-structure: + +.. Packet Structure +.. ^^^^^^^^^^^^^^^^ + +.. A bootloader packet is composed of a sequence of fields, as follows. + +.. .. list-table:: +.. :header-rows: 1 + +.. * - Field +.. - Length (bytes) +.. - Value +.. - Description + +.. * - START +.. - 1 +.. - 0x1B +.. - Magic constant, indicates bootloader packet + +.. * - SEQUENCE_NUM +.. - 1 +.. - 0--0xFF +.. - Queries and responses must have the same sequence number; rolls +.. over to 0 after 0xFF + +.. * - MESSAGE_SIZE +.. - 2 +.. - 0--0xFFFF +.. - Size of message body, currently limited to a 1024B=1KB maximum + +.. * - TOKEN +.. - 1 +.. - 0x7F +.. - Differs from STK500 value of 0x0E + +.. * - MESSAGE_BODY +.. - Variable, determined by MESSAGE_SIZE field +.. - Command query or response +.. - See :ref:`next section ` + +.. * - CHECKSUM +.. - 4 +.. - XOR of all other 32-bit words in packet +.. - See :ref:`below ` + +.. .. _bootloader-checksum: + +.. .. highlight:: cpp + +.. .. note:: When computing the checksum, the words in a packet are +.. interpreted big-endian (as if the packet were a sequence of 32-bit, +.. big-endian unsigned integers). If the end of the MESSAGE_BODY is +.. not aligned with a four-byte boundary, then the checksum will treat +.. it as if it was padded with zero bytes to a four-byte boundary. -.. highlight:: sh +.. As a concrete example, an entire GET_INFO query (see :ref:`below +.. `), including the packet structure, is +.. comprised of the byte sequence :: + +.. {0x1B, 0x7F, 0x00, 0x01, 0x7F, 0x00, 0x64, 0x7F, 0x00, 0x01} + +.. The SEQUENCE_NUM of this query is 0x7F. + +.. .. highlight:: sh -.. _bootloader-commands: +.. .. _bootloader-commands: -Commands -^^^^^^^^ +.. Commands +.. ^^^^^^^^ -The packet structure overhead is for reliability. The actual queries -and responses are transacted inside of the message body. Following -the STK-500 protocol, each query or response begins with the single -byte command field. For each query, the resultant response must begin -with the same CMD byte. For each type of command, the structure of -queries and responses is of fixed size. +.. The packet structure overhead is for reliability. The actual queries +.. and responses are transacted inside of the message body. Following +.. the STK-500 protocol, each query or response begins with the single +.. byte command field. For each query, the resultant response must begin +.. with the same CMD byte. For each type of command, the structure of +.. queries and responses is of fixed size. -Also following STK-500, fields longer than 1 byte are transmitted MSB -first (big-endian). However, READ and WRITE commands operate byte-wise -(not word-wise); it is up to the host PC to ensure that alignment and -ordering issues are handled appropriately. +.. Also following STK-500, fields longer than 1 byte are transmitted MSB +.. first (big-endian). However, READ and WRITE commands operate byte-wise +.. (not word-wise); it is up to the host PC to ensure that alignment and +.. ordering issues are handled appropriately. -.. _bootloader-get-info: +.. .. _bootloader-get-info: -GET_INFO -"""""""" +.. GET_INFO +.. """""""" -Used to query device characteristics. +.. Used to query device characteristics. -GET_INFO Query: +.. GET_INFO Query: -.. list-table:: - :header-rows: 1 +.. .. list-table:: +.. :header-rows: 1 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - GET_INFO - - 1 - - Value 0 +.. * - GET_INFO +.. - 1 +.. - Value 0 -GET_INFO Response: +.. GET_INFO Response: -.. list-table:: - :header-rows: 1 - :widths: 4 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - GET_INFO - - 1 - - Value 0 +.. * - GET_INFO +.. - 1 +.. - Value 0 - * - Endianness - - 1 - - 0 indicates little-endian, 1 indicates big-endian. - (Currently returns 0; this field allows for future - expansion). +.. * - Endianness +.. - 1 +.. - 0 indicates little-endian, 1 indicates big-endian. +.. (Currently returns 0; this field allows for future +.. expansion). - * - Available Ram - - 4 - - In bytes +.. * - Available Ram +.. - 4 +.. - In bytes - * - Available Flash - - 4 - - In bytes +.. * - Available Flash +.. - 4 +.. - In bytes - * - Flash Page Size - - 2 - - In bytes +.. * - Flash Page Size +.. - 2 +.. - In bytes - * - Starting Address (FLASH) - - 4 - - Usually 0x08005000 +.. * - Starting Address (FLASH) +.. - 4 +.. - Usually 0x08005000 - * - Starting Address (RAM) - - 4 - - Usually 0x200000C0 +.. * - Starting Address (RAM) +.. - 4 +.. - Usually 0x200000C0 - * - Bootloader Version - - 4 - - Current version 0x00060000 (MAJ,MIN) +.. * - Bootloader Version +.. - 4 +.. - Current version 0x00060000 (MAJ,MIN) -.. _bootloader-erase-page: +.. .. _bootloader-erase-page: -ERASE_PAGE -"""""""""" +.. ERASE_PAGE +.. """""""""" -Used to erase flash pages. +.. Used to erase flash pages. -ERASE_PAGE query: +.. ERASE_PAGE query: -.. list-table:: - :header-rows: 1 - :widths: 4 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - ERASE_PAGE - - 1 - - Value 1 +.. * - ERASE_PAGE +.. - 1 +.. - Value 1 - * - ADDRESS - - 4 - - Will erase whichever page contains ADDRESS +.. * - ADDRESS +.. - 4 +.. - Will erase whichever page contains ADDRESS -ERASE_PAGE response: +.. ERASE_PAGE response: -.. list-table:: - :header-rows: 1 - :widths: 3 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 3 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - ERASE_PAGE - - 1 - - Value 1 +.. * - ERASE_PAGE +.. - 1 +.. - Value 1 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success) +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success) -WRITE_BYTES -""""""""""" +.. WRITE_BYTES +.. """"""""""" -Used to write to RAM or flash. +.. Used to write to RAM or flash. -WRITE_BYTES query: +.. WRITE_BYTES query: -.. list-table:: - :header-rows: 1 - :widths: 4 4 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 4 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - WRITE_BYTES - - 1 - - Value 2 +.. * - WRITE_BYTES +.. - 1 +.. - Value 2 - * - Starting Address - - 4 - - Can address arbitrary RAM, or :ref:`cleared - ` flash pages. +.. * - Starting Address +.. - 4 +.. - Can address arbitrary RAM, or :ref:`cleared +.. ` flash pages. - * - DATA - - MESSAGE_SIZE - 5 - - See :ref:`Packet Structure ` +.. * - DATA +.. - MESSAGE_SIZE - 5 +.. - See :ref:`Packet Structure ` -WRITE_BYTES response: +.. WRITE_BYTES response: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - WRITE_BYTES - - 1 - - Value 2 +.. * - WRITE_BYTES +.. - 1 +.. - Value 2 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success). Will fail if writes were - made to uncleared pages. Does not clean up failed writes - (memory will be left in an undefined state). +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success). Will fail if writes were +.. made to uncleared pages. Does not clean up failed writes +.. (memory will be left in an undefined state). -READ_BYTES -"""""""""" +.. READ_BYTES +.. """""""""" -Used to read from RAM or flash. +.. Used to read from RAM or flash. -READ_BYTES query: +.. READ_BYTES query: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - READ_BYTES - - 1 - - Value 3 +.. * - READ_BYTES +.. - 1 +.. - Value 3 - * - ADDRESS - - 4 - - Start of block to read. Must be a multiple of 4. +.. * - ADDRESS +.. - 4 +.. - Start of block to read. Must be a multiple of 4. - * - LENGTH - - 2 - - Maximum number of bytes to read (currently, this may be at most - 1024 = 1KB). Must be a multiple of 4. +.. * - LENGTH +.. - 2 +.. - Maximum number of bytes to read (currently, this may be at most +.. 1024 = 1KB). Must be a multiple of 4. -READ_BYTES response: +.. READ_BYTES response: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - READ_BYTES - - 1 - - Value 3 +.. * - READ_BYTES +.. - 1 +.. - Value 3 - * - DATA - - MESSAGE_SIZE - 1 - - Contains read bytes. The actual number of bytes read may be - less than the LENGTH field of the corresponding READ_BYTES - query. If this section is of length 0, this should be - interpreted as a read failure. See - :ref:`bootloader-packet-structure`. +.. * - DATA +.. - MESSAGE_SIZE - 1 +.. - Contains read bytes. The actual number of bytes read may be +.. less than the LENGTH field of the corresponding READ_BYTES +.. query. If this section is of length 0, this should be +.. interpreted as a read failure. See +.. :ref:`bootloader-packet-structure`. -JUMP_TO_USER -"""""""""""" +.. JUMP_TO_USER +.. """""""""""" -Causes the bootloader to jump to user code's starting address. +.. Causes the bootloader to jump to user code's starting address. -JUMP_TO_USER query: +.. JUMP_TO_USER query: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - JUMP_TO_USER - - 1 - - Value 4 +.. * - JUMP_TO_USER +.. - 1 +.. - Value 4 - * - Location - - 1 - - 0 means jump to flash starting address, 1 means jump to RAM - starting address. See the :ref:`bootloader-get-info` command - for more information. +.. * - Location +.. - 1 +.. - 0 means jump to flash starting address, 1 means jump to RAM +.. starting address. See the :ref:`bootloader-get-info` command +.. for more information. -JUMP_TO_USER response: +.. JUMP_TO_USER response: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - JUMP_TO_USER - - 1 - - Value 4 +.. * - JUMP_TO_USER +.. - 1 +.. - Value 4 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success). If successful, after the - response is sent, the bootloader ends this session and jumps to - the user code in flash or RAM as specified in the query's - Location field. +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success). If successful, after the +.. response is sent, the bootloader ends this session and jumps to +.. the user code in flash or RAM as specified in the query's +.. Location field. -SOFT_RESET -"""""""""" +.. SOFT_RESET +.. """""""""" -Engages a full software reset. +.. Engages a full software reset. -SOFT_RESET query: +.. SOFT_RESET query: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - SOFT_RESET - - 1 - - Value 5 +.. * - SOFT_RESET +.. - 1 +.. - Value 5 -SOFT_RESET response: +.. SOFT_RESET response: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - SOFT_RESET - - 1 - - Value 5 +.. * - SOFT_RESET +.. - 1 +.. - Value 5 - * - SUCCESS - - 1 - - Either 0 or 1 (FAILED and OK, respectively). Will end this - bootloader session and reset the processor. +.. * - SUCCESS +.. - 1 +.. - Either 0 or 1 (FAILED and OK, respectively). Will end this +.. bootloader session and reset the processor. .. _bootloader-reflashing: diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index a070b42..848a3d3 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -119,8 +119,6 @@ differences, most of which are improvements: Shield and Device Compatibility ------------------------------- -.. TODO update for 0.0.9 - .. list-table:: :header-rows: 1 @@ -134,7 +132,7 @@ Shield and Device Compatibility * - WiFi Shield - Yes! - - Tested; no library yet (expected for 0.0.9) + - Tested; preliminary library support * - MIDI shield - Yes! @@ -146,7 +144,8 @@ Shield and Device Compatibility * - Bluetooth shield - Unknown - - + - Some Bluetooth <-> UART boards have been tested and are known + to work. * - Cellular shield - Unknown @@ -158,11 +157,12 @@ Library Porting Status The state of currently ported Arduino libraries is the :ref:`libraries`. -.. TODO update for 0.0.9; update as libraries are ported. +.. TODO Update as libraries are ported. .. list-table:: :header-rows: 1 + * - Library - Ported? - Notes @@ -180,9 +180,11 @@ The state of currently ported Arduino libraries is the - Planned * - EEPROM - - No - - The Maple doesn't have EEPROM; use flash instead. Perhaps this - library could be emulated? + - (Unsupported) third-party emulation + - The Maple doesn't have EEPROM; it uses flash instead. There is + an `EEPROM emulation library + `_ by + `x893 `_, but we haven't tested it. * - Firmata - Not yet @@ -192,6 +194,10 @@ The state of currently ported Arduino libraries is the - Not yet - Planned + * - Servo + - **Yes** + - :ref:`Included since IDE 0.0.9 ` + * - SoftwareSerial - Not yet - Planned diff --git a/docs/source/cpp.rst b/docs/source/cpp.rst deleted file mode 100644 index a20578e..0000000 --- a/docs/source/cpp.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. _cpp: - -============== -C++ for Maple -============== - -.. _index-language-index-cpp-index: - -.. toctree:: - :maxdepth: 1 - :glob: - - lang/cpp/* \ No newline at end of file diff --git a/docs/source/external-interrupts.rst b/docs/source/external-interrupts.rst index 79492ef..5187ca4 100644 --- a/docs/source/external-interrupts.rst +++ b/docs/source/external-interrupts.rst @@ -121,6 +121,5 @@ Recommended Reading * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/gpio.rst b/docs/source/gpio.rst index ee2b6eb..4017862 100644 --- a/docs/source/gpio.rst +++ b/docs/source/gpio.rst @@ -14,9 +14,9 @@ peripheral functions. This page documents those capabilities, by pin. The current and voltage limitations have not been copied over from the STM32 datasheet (see the :ref:`Recommended Reading ` for a link). In particular, a number of -GPIO pins are 5v tolerant (which means that applying 5v to a pin and -reading it as input or allowing it to drain to ground will not damage -that pin), while some are not. +GPIO pins are 5V tolerant (which means that applying 5 volts to a pin +and reading it as input or allowing it to drain to ground will not +damage that pin), while some are not. .. contents:: Contents :local: @@ -26,11 +26,10 @@ that pin), while some are not. Pin Mapping Mega Table ---------------------- -This huge reference table shows the available functionality on every -GPIO pin, by peripheral type. The "STM32" column refers to the port -and number that the header is connected to on the microcontroller. -The "5v?" column documents whether or not the pin is 5v tolerant (see -above). +This table shows the available functionality on every GPIO pin, by +peripheral type. The "STM32" column refers to the port and number that +the header is connected to on the microcontroller. The "5V?" column +documents whether or not the pin is 5 volt tolerant (see above). .. csv-table:: :header: "Pin", "STM32", ":ref:`ADC `", ":ref:`Timer `", ":ref:`I2C `", ":ref:`UART `", ":ref:`SPI `", "5v?" @@ -99,6 +98,5 @@ Recommended Reading STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/home.rst b/docs/source/home.rst deleted file mode 100644 index db5b56e..0000000 --- a/docs/source/home.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. _home: - -======================== -Maple Documentation Home -======================== - - -Welcome! - -Maple is a user-friendly prototyping platform developed by LeafLabs in Cambridge, MA. Using Maple, creators with any level of experience can implement beautiful ideas that require the power of a 32-bit processor. For more details about Maple's hardware, please see its :ref:`technical specifications `. To start using your Maple, keep reading - -.. _home-Getting-Started: - -Getting Started -^^^^^^^^^^^^^^^ - -:ref:`Quickstart ` - -:ref:`IDE Anatomy ` - -:ref:`Basic Language Reference ` - -:ref:`Tech Specs` - -.. _home-Problem-Solving: - -Problem Solving -^^^^^^^^^^^^^^^ - -Check out our :ref:`troubleshooting ` and :ref:`known problems` pages. - -If you don't find what you're looking for, hit the `forums `_ to ask the LeafLabs team and other Maple users questions. Good luck, and have fun! diff --git a/docs/source/i2c.rst b/docs/source/i2c.rst index 6e5b946..b4a996b 100644 --- a/docs/source/i2c.rst +++ b/docs/source/i2c.rst @@ -80,7 +80,6 @@ Recommended Reading * `Arduino i2c/TWI reference `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Application Note on Advanced I2C Usage diff --git a/docs/source/index.rst b/docs/source/index.rst index c552dd4..825ec81 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,7 +1,15 @@ .. _index: Maple Documentation Contents -============================= +============================ + +Welcome! This is the Maple documentation index. If you just bought a +Maple, you probably want to head to the :ref:`quickstart +`. If you're having problems, check out the +:ref:`troubleshooting ` and :ref:`known problems +` pages. + +Have fun! .. _index-usage: @@ -15,7 +23,7 @@ Maple Documentation Contents IDE Anatomy .. _index-maple-programming: - + **Maple Programming:** .. toctree:: @@ -29,7 +37,7 @@ Maple Documentation Contents Bootloader - Troubleshooting + Troubleshooting Known Problems .. _index-hardware: @@ -38,7 +46,7 @@ Maple Documentation Contents .. toctree:: :maxdepth: 1 - + i2c pwm gpio @@ -55,8 +63,8 @@ Maple Documentation Contents .. toctree:: :maxdepth: 1 - + Technical Specifications Complete Language Index - + diff --git a/docs/source/jtag.rst b/docs/source/jtag.rst index 7cfba5f..e3c8111 100644 --- a/docs/source/jtag.rst +++ b/docs/source/jtag.rst @@ -15,24 +15,24 @@ and hardware peripherals (we use it when working on :ref:`libmaple Note that the STM32 on the Maple has a built-in low level serial debugger which could also be used to flash bootloaders, and that the :ref:`ASSERT ` framework allows basic debugging over -a USART serial channel. We expect only advanced users to use this -feature. +a USART serial channel. We expect only fairly advanced users to use +this feature. .. contents:: Contents :local: - Wiring Diagram -------------- .. figure:: /_static/img/jtag-wiring.png :align: center :alt: JTAG wiring diagram + :width: 7.4in - JTAG wiring diagram to connect a standard 20-pin ARM JTAG device to - the 8-pin JTAG port on the Maple. - -.. FIXME jtag wiring diagram (above) looks terrible; replace it + JTAG wiring diagram (`large version + `_) + to connect a standard 20-pin ARM JTAG device to the 8-pin JTAG port + on the Maple. The Maple has holes for a 8-pin JTAG header but that header is not soldered on by default. If you know ahead of time that you'll be @@ -42,14 +42,7 @@ probably solder one on for no charge. Otherwise, you can simply attach standard 0.1" pitch male header pins (either the exact 4x2 block or two 4-pin pieces of breakaway straight header). For a one-off usage hack, the header can be jammed in the holes and twisted to -ensure electrical contact; this is what we do to flash our bootloader. - -The above schematic assumes that the header has been soldered on to -the *bottom* of the board, not the top; most ribbon cable connectors -will interfere with the power header. If you don't want a header -coming off the bottom, you can use a slim connector and invert this -diagram appropriately. - +ensure electrical contact. Compatible Devices ------------------ @@ -65,6 +58,8 @@ Recommended Reading * `STM32/gdb/OpenOCD HOWTO `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) +* There's a `thread on JTAG + `_ in our `forum`_ + which you may find useful. diff --git a/docs/source/lang/api/analogread.rst b/docs/source/lang/api/analogread.rst index c614aca..35c6fbc 100644 --- a/docs/source/lang/api/analogread.rst +++ b/docs/source/lang/api/analogread.rst @@ -32,11 +32,6 @@ Before calling analogRead() on a pin, that pin must first be configured for analog input, using :ref:`lang-pinMode` (you only have to do this once, so it's usually done in :ref:`lang-setup`\ ). -It takes about 0.8 microseconds (.0000008 seconds) to read an analog -input, so the maximum sample rate using this function is approximately -1.3 million samples per second\ [#fsamp]_. - - Parameter Discussion -------------------- @@ -115,40 +110,10 @@ Some basic tools to accomplish this are `resistor dividers . However, opamps and other powered components can also be used if greater precision is required. -Finally, On the Arduino, it takes significantly longer to read analog -input: about 100 microseconds (0.0001 s), so the maximum reading rate -is 10,000 times a second. - - See also -------- - :ref:`ADC note ` - `(Arduino) Tutorial: Analog Input Pins `_ - -.. rubric:: Footnotes - -.. [#fsamp] This is based on the current configuration of a 55.5 cycle - sample time, at 72 MHz. However, the minimum sample time *possible* - is 1.5 cycles, leading to a theoretical maximum of approximately 48 - million samples per second (of course, doing anything with the - readings also consumes cycles, so this maximum can't be reached in - practice). - - See the `STM32 Reference Manual `_, §§11.12.4--5 - (pp. 225--226), for more information on the low-level bit twiddling - currently necessary to change the sample time. For examples of how - the ADCs are configured in libmaple, see `adc.h - `_ - and `adc.c - `_\ - . Be aware that changing the sample time has important - consequences related to the impedance of the device connected to - the input pin. If you want to make changes, as a minimum, you - should first read ST's application notes on `ADC modes - `_ and `ADC oversampling - `_. - - .. include:: cc-attribution.txt diff --git a/docs/source/lang/api/analogwrite.rst b/docs/source/lang/api/analogwrite.rst index 01820ef..9147b96 100644 --- a/docs/source/lang/api/analogwrite.rst +++ b/docs/source/lang/api/analogwrite.rst @@ -11,19 +11,18 @@ analogWrite() .. note:: On the Maple, calling analogWrite() is the same as calling - :ref:`lang-pwmwrite`\ ; see that function's documentation for more - information. + :ref:`lang-pwmwrite`\ ; we recommend using that function directly + instead. This is because PWM is not true analog output (i.e., is not the output of a `DAC `_\ ), so - the function is badly named. For instance, **analogWrite() has + the function is badly named. For instance, analogWrite() **has absolutely nothing to do with** :ref:`lang-analogread`\ , which is potentially confusing. - The alias of analogWrite() to pwmWrite() is provided (sigh) for the - sake of compatibility with Arduino, but we recommend using - :ref:`lang-pwmwrite` when writing new software, for clarity. + The alias of analogWrite() to pwmWrite() is provided for the sake + of compatibility with Arduino only. .. contents:: Contents :local: @@ -97,23 +96,21 @@ Difference 3: No PWM on pin 10 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, -9, 11, 12, and 14, or twelve pins in total. That is at least as -*many* PWM pins as any Arduino board, but there are differences in -*which* pins support it. +9, 11, 12, 14, 24, 27, and 28 or fifteen pins in total. That's *more* +PWM-capable pins as any Arduino board, but there are differences in +*which* pins support PWM. * On **most Arduino boards** (those with the ATmega168 or ATmega328; this includes the **Arduino Uno**), this function works on pins 3, 5, 6, 9, 10, and 11, or six pins total. Note that these boards support PWM on pin 10, while Maple does not. -* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins - total. Note that this board supports PWM on pins 4, 10, and 13, - while the Maple does not. Maple supports PWM on pins 0, 1, and 14, - which the Mega does not, making the total number of pins supporting - PWM equal on these boards. +* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve + pins total. Note that this board supports PWM on pins 4, 10, and + 13, while the Maple does not. -* **Older Arduino boards** with an ATmega8 only support analogWrite() on - pins 9, 10, and 11. Maple does not support PWM on pin 10. +* **Older Arduino boards** with an ATmega8 only support analogWrite() + on pins 9, 10, and 11. Maple does not support PWM on pin 10. In all cases, Arduino boards support PWM on pin 10, unlike Maple. We did our best to make PWM as pin-compatible as possible; however, @@ -125,7 +122,8 @@ work on any Arduino board and on Maple. The "safe" pins, which work on most recent Arduino boards, the Arduino Mega and the Maple, are pins 3, 5, 6, 9, and 11. Thus, if you want your project to be as portable as possible between Maple and Arduino, we recommend using the -"safest" pins first, then the "safe" pins, as necessary. +"safest" pins first, then the "safe" pins, then any other pins, as +necessary. Difference 4: PWM frequency ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -138,17 +136,23 @@ Hz, or 1.1 KHz. This is because the PWM frequency is the frequency of the timer which controls PWM output on the particular pin (\ :ref:`the PWM tutorial has the details `\ ). -If your application absolutely requires Arduino's PWM frequency (it -probably doesn't), then the steps are: +If your application definitely requires Arduino's PWM frequency, then +the steps are: -1. Figure out which timer controls PWM output on your pin (\ :ref:`this table ` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. +1. Figure out which :ref:`timer ` controls PWM + output on your pin (\ :ref:`this table ` is your + friend here). Let's say it's ``Timern``\ , where ``n`` is some + number 1, 2, 3, or 4. -2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. +2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's + period to approximately 2041 microseconds, which is a frequency of + approximately 490 Hz. Be aware that this will change the period for the **entire timer**\ , and will affect anything else in your program that depends on that -timer. One example is :ref:`interrupts `\ . -You've been :ref:`warned `\ . +timer. The important examples are :ref:`timer interrupts +` and :ref:`PWM +`\ . See also -------- diff --git a/docs/source/lang/api/constants.rst b/docs/source/lang/api/constants.rst index bc5c894..4426293 100644 --- a/docs/source/lang/api/constants.rst +++ b/docs/source/lang/api/constants.rst @@ -288,6 +288,29 @@ exponent indicators. Some examples are given in the following table: - 67.0×10\ :sup:`-12` - ``0.000000000067`` +.. _lang-constants-board: + +Board-Specific Constants +------------------------ + +This section documents constants whose value might change across +different LeafLabs boards. You can use these constants to help ensure +that your code will be portable across different boards. + +.. TODO replace "upcoming" when Mini, Native come out + +.. _lang-constants-led: + +- ``BOARD_LED_PIN``: the number of the pin which connects to the + built-in LED. On the Maple, this is pin 13, but it's not guaranteed + to be the same in upcoming boards like the Maple Mini. + +.. _lang-constants-but: + +- ``BOARD_BUTTON_PIN``: the number of the pin which connects to the + built-in button (labeled "BUT"). On the Maple, this is pin 38, but + it's not guaranteed to be the same in other boards. + See Also -------- diff --git a/docs/source/lang/api/hardwarespi.rst b/docs/source/lang/api/hardwarespi.rst new file mode 100644 index 0000000..c71b2c3 --- /dev/null +++ b/docs/source/lang/api/hardwarespi.rst @@ -0,0 +1,152 @@ +.. highlight:: cpp + +.. _lang-hardwarespi: + +HardwareSPI +=========== + +This class is used for creating objects to manage the Maple's built-in +SPI ports. The Maple has two SPI ports. The relevant pins +corresponding to each port's logic signals are documented in the +following table (and on the Maple silkscreen): + +.. _lang-hardwarespi-pinout: + +.. list-table:: + :header-rows: 1 + + * - Port number + - NSS + - MOSI + - MISO + - SCK + + * - 1 + - 10 + - 11 + - 12 + - 13 + + * - 2 + - 31 + - 32 + - 33 + - 34 + +If you use a SPI port, you cannot simultaneously use its associated +pins for other purposes. + +Library Documentation +--------------------- + +HardwareSPI Class Reference +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can use the SPI interface by including a declaration ``HardwareSPI +Spi(number);`` at the start of the sketch or program. The ``number`` +must be either 1 or 2 and specifies which port to use. Once this is +done, you can call any of the methods documented here using +``Spi.method(arguments)``; for example, ``Spi.send(0x13)`` would send +the value ``0x13`` into the port buffer to be transmitted as soon as +possible. + +.. cpp:class:: HardwareSPI + + Class for interacting with SPI. + +.. cpp:function:: HardwareSPI::HardwareSPI(uint32 spi_num) + + Construct an object for managing a SPI peripheral. ``spi_num`` + must be 1 or 2; see the :ref:`table above + ` for pinout information. + +.. cpp:function:: void HardwareSPI::begin(SPIFrequency freq, uint32 endianness, uint32 mode) + + Configure the baudrate of the given SPI port and set up the header + pins appropriately. + + Parameters: + + - ``freq``: one of the ``SPIFrequency`` values, given :ref:`below + `. + + - ``endianness``: either ``LSBFIRST`` (little-endian) or + ``MSBFIRST`` (big-endian). + + - ``mode``: one of 0, 1, 2, or 3, and specifies which SPI mode is + used. The mode number determines a combination of polarity and + phase according to the following table: + + .. list-table:: + :header-rows: 1 + + * - Mode + - Polarity + - Phase + + * - 0 + - 0 + - 0 + + * - 1 + - 0 + - 1 + + * - 2 + - 1 + - 0 + + * - 3 + - 1 + - 1 + + For more information on polarity and phase, see the + :ref:`external references, below `. + +.. cpp:function:: void HardwareSPI::begin() + + A convenience ``begin()``, equivalent to ``begin(SPI_1_125MHZ, + MSBFIRST, 0)``. + +.. cpp:function:: uint8 HardwareSpi::send(uint8 *data, uint32 length) + + Writes ``data`` into the port buffer to be transmitted as soon as + possible, where ``length`` is the number of bytes to send from + ``data``. Returns the last byte shifted back from slave. + +.. cpp:function:: uint8 HardwareSpi::send(uint8 data) + + Writes the single byte ``data`` into the port buffer to be + transmitted as soon as possible. Returns the data byte shifted + back from the slave. + +.. cpp:function:: uint8 HardwareSpi::recv() + + Reads a byte from the peripheral. Returns the next byte in the + buffer. + +SPI Speeds +^^^^^^^^^^ + +.. _lang-hardwarespi-spifrequency: + +The possible SPI speeds are configured using the ``SPIFrequency`` enum: + +.. doxygenenum:: SPIFrequency + +.. _lang-hardwarespi-seealso: + +See Also +-------- + +* `Wikipedia Article on Serial Peripheral Interface Bus (SPI) + `_ +* `Arduino reference on SPI + `_ +* `Hardcore SPI on Arduino `_ by kik64 +* STMicro documentation for STM32F103RB microcontroller: + + * `Datasheet `_ (pdf) + * `Reference Manual `_ (pdf) + + diff --git a/docs/source/lang/api/hardwaretimer.rst b/docs/source/lang/api/hardwaretimer.rst new file mode 100644 index 0000000..258471b --- /dev/null +++ b/docs/source/lang/api/hardwaretimer.rst @@ -0,0 +1,368 @@ +.. highlight:: cpp + +.. _lang-hardwaretimer: + +HardwareTimer +============= + +This class defines the public API for interfacing with the STM32's +built-in timer peripherals. More information on these peripherals +(including code examples) is available in the :ref:`timers reference +`. + +Library Documentation +--------------------- + +HardwareTimer Class Reference +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To interact with a particular timer, call one of the methods +documented below on one of the predefined ``HardwareTimer`` instances. +For example, to set the prescale factor on timer 1 to 5, call +``Timer1.setPrescaleFactor(5)``. + +.. cpp:class:: HardwareTimer + + Class for interacting with a timer. There are four predefined + instances available on the Maple: ``Timer1``, ``Timer2``, + ``Timer3``, and ``Timer4``. + +.. _lang-hardwaretimer-attachinterrupt: + +.. cpp:function:: void HardwareTimer::attachInterrupt(int channel, voidFuncPtr handler) + + Attach an interrupt handler to the given ``channel``. This + interrupt handler will be called when the timer's counter reaches + the given channel :ref:`compare ` + value. + + ``handler`` should be a function which takes no arguments and has + :ref:`void ` value; i.e. it should have signature :: + + void handler(void); + + You can later detach the interrupt using :ref:`detachInterrupt() + `. + + .. note:: The function (often called an *interrupt service + routine*, or ISR) should attempt to return as quickly as + possible. :ref:`Blinking the LED `, some + logic, :ref:`PWM ` updates, and :ref:`Serial + ` writes are fine; writing to + :ref:`SerialUSB ` or :ref:`waiting + ` for user input can take a long + time and prevent other interrupts from firing on time. + + Tip: if you have a :ref:`delay() ` in your + ISR, you're probably doing it wrong. + +.. cpp:function:: void HardwareTimer::attachCompare1Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(1, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare2Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(2, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare3Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(3, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare4Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(4, handler)``. + +.. _lang-hardwaretimer-setchannelmode: + +.. cpp:function:: void HardwareTimer::setChannelMode(int channel, TimerMode mode) + + Set the given channel of this timer to the given :ref:`mode + `. The parameter ``channel`` is one of + 1, 2, 3, and 4, and corresponds to the compare channel you would + like to set. Refer to the full :ref:`pin mapping table + ` to match up timer channels and pin + numbers. + +.. cpp:function:: void HardwareTimer::setChannel1Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(1, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel2Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(2, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel3Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(3, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel4Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(4, mode)``. + +.. _lang-hardwaretimer-getcompare: + +.. cpp:function:: uint16 HardwareTimer::getCompare(int channel) + + Gets the compare value for the given ``channel``, from 1 to 4. See + :ref:`setCompare() `. + +.. cpp:function:: uint16 HardwareTimer::getCompare1() + + Equivalent to :ref:`getCompare `\ + ``(1, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare2() + + Equivalent to :ref:`getCompare `\ + ``(2, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare3() + + Equivalent to :ref:`getCompare `\ + ``(3, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare4() + + Equivalent to :ref:`getCompare `\ + ``(4, mode)``. + +.. _lang-hardwaretimer-setcompare: + +.. cpp:function:: void HardwareTimer::setCompare(int channel, uint16 compare) + + Sets the compare value for the given ``channel`` to ``compare``. + If ``compare`` is greater than this timer's overflow value, it will + be truncated to the overflow value. The default compare value is + 65,535 (the largest unsigned 16-bit integer value). + + When the counter reaches this value the interrupt for this channel + will fire if the given ``channel`` :ref:`mode + ` is ``TIMER_OUTPUTCOMPARE`` and + an interrupt is :ref:`attached + `. + + By default, this only changes the relative offsets between events + on a single timer ("phase"); they don't control the frequency with + which they occur. However, a common trick is to increment the + compare value manually in the interrupt handler so that the event + will fire again after the increment period. There can be a + different increment value for each channel, so this trick allows + events to be programmed at 4 different rates on a single + timer. Note that function call overheads mean that the smallest + increment rate is at least a few microseconds. + +.. cpp:function:: void HardwareTimer::setCompare1(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(1, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare2(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(2, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare3(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(3, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare4(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(4, compare)``. + +.. cpp:function:: uint16 HardwareTimer::getCount() + + Gets the current timer count. Due to function call overhead, the + return value will be increasingly accurate with smaller prescale + values. Also see :ref:`setCount() `. + +.. _lang-hardwaretimer-setcount: + +.. cpp:function:: void HardwareTimer::setCount(uint16 val) + + Set the timer's current count to ``val``. + + Note that there is some function call overhead associated with + calling this method, so using it is not a robust way to get + multiple timers to share a count value. + + If ``val`` exceeds the timer's :ref:`overflow value + `, it is truncated to the overflow + value. + + +.. _lang-hardwaretimer-detachinterrupt: + +.. cpp:function:: void HardwareTimer::detachInterrupt(int channel) + + Remove the interrupt handler attached to the given ``channel``, if + any. The handler will no longer be called by this timer. + +.. cpp:function:: void HardwareTimer::detachCompare1Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(1)``. + +.. cpp:function:: void HardwareTimer::detachCompare2Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(2)``. + +.. cpp:function:: void HardwareTimer::detachCompare3Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(3)``. + +.. cpp:function:: void HardwareTimer::detachCompare4Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(4)``. + +.. _lang-hardwaretimer-generateupdate: + +.. cpp:function:: void HardwareTimer::generateUpdate() + + Re-initializes the counter (to 0 in upcounting mode, which is the + default), and generates an update of the prescale and overflow + registers. + +.. _lang-hardwaretimer-getoverflow: + +.. cpp:function:: uint16 HardwareTimer::getOverflow() + + Gets the timer's overflow value. See :ref:`setOverflow() + `. + +.. _lang-hardwaretimer-setoverflow: + +.. cpp:function:: void HardwareTimer::setOverflow(uint16 val) + + Sets the timer overflow (or "reload") value to ``val``. + + When the timer's counter reaches this, value it resets to + zero. Its default value is 65535 (the largest unsigned 16-bit + integer); setting the overflow to anything lower will cause + interrupts to be called more frequently (see :ref:`setPeriod() + ` function for a shortcut). + + After the next :ref:`timer update + `, this number will be the + maximum value for the timer's channel compare values. + +.. _lang-hardwaretimer-pause: + +.. cpp:function:: void HardwareTimer::pause() + + Stop the timer's counter, without affecting its configuration. + + The timer will no longer count or fire interrupts after this + function is called, until it is resumed. This function is useful + during timer setup periods, in order to prevent interrupts from + firing before the timer is fully configured. + + Note that there is some function call overhead associated with this + method, so using it in concert with :ref:`resume() + ` is not a robust way to align multiple + timers to the same count value. + +.. _lang-hardwaretimer-setperiod: + +.. cpp:function:: uint16 HardwareTimer::setPeriod(uint32 microseconds) + + Configure the :ref:`prescaler + ` and :ref:`overflow + ` values to generate a timer reload + with a period as close to the given number of ``microseconds`` as + possible. + + The return value is the new overflow value, which may be used to + set channel compare values. However, if a clock that fires an + interrupt every given number of microseconds is all that is + desired, and the relative "phases" are unimportant, channel compare + values may all be set to 1. + +.. _lang-hardwaretimer-getprescalefactor: + +.. cpp:function:: uint16 HardwareTimer::getPrescaleFactor() + + Returns the timer's prescale factor. See + :ref:`setPrescaleFactor() `. + +.. _lang-hardwaretimer-setprescalefactor: + +.. cpp:function:: void HardwareTimer::setPrescaleFactor(uint16 factor) + + Set the timer's prescale factor to ``factor``. + + The prescaler acts as a clock divider to slow down the rate at + which the counter increments. + + For example, the system clock rate is 72MHz, so the counter will + reach 65535 in (13.89 nanoseconds) × (65535 counts) = (910.22 + microseconds), or about a thousand times a second. If the + prescaler equals 1098, then the clock rate is effectively 72MHz / + 1098 = 65.56KHz, and the counter will reach 65536 in (15.25 + microseconds) × (65536 counts) = (0.999 seconds), or about once + per second. + + The :ref:`setPeriod() ` method may + also be used as a convenient alternative. + +.. cpp:function:: void HardwareTimer::resume() + + Resume a paused timer, without affecting its configuration. + + The timer will resume counting and firing interrupts as + appropriate. + + Note that there is some function call overhead associated with + using this method, so using it in concert with :ref:`pause() + ` is not a robust way to align multiple + timers to the same count value. + +.. cpp:function:: timer_dev_num HardwareTimer::getTimerNum() + + Returns the :ref:`timer device number + ` associated with the timer. For + example, ``Timer1.getTimerNum()`` would return ``TIMER1``. + + In most cases, you should not need to use this function. If you do + use it, be careful; the constant ``TIMER1`` is *not equal* to the + number 1; similarly, ``TIMER2`` is *not* the number 2, etc. Be + sure to refer to the timer device number by name. + +.. _lang-hardwaretimer-modes: + +Timer Modes +^^^^^^^^^^^ +.. doxygenenum:: TimerMode + +.. _lang-hardwaretimer-timer-dev-num: + +Timer Device Numbers +^^^^^^^^^^^^^^^^^^^^ + +These provide a lower-level interface for interacting with timers. +They are mostly useful in context with the :ref:`getTimer() +` function. **Be careful** when using +these not to confuse e.g. ``TIMER1`` with the number 1; they are +different. + +.. doxygenenum:: timer_dev_num + +.. _lang-hardwaretimer-convenience: + +.. _lang-hardwaretimer-gettimer: + +Other Functions +^^^^^^^^^^^^^^^ +.. doxygenfunction:: getTimer diff --git a/docs/source/lang/api/interrupts.rst b/docs/source/lang/api/interrupts.rst new file mode 100644 index 0000000..58fd2cc --- /dev/null +++ b/docs/source/lang/api/interrupts.rst @@ -0,0 +1,47 @@ +.. highlight:: cpp + +.. _lang-interrupts: + +interrupts() +============ + +Re-enables interrupts (after they've been disabled by +:ref:`noInterrupts() `). Interrupts allow certain +important tasks to happen in the background, and certain interrupts +are enabled by default. + +Some functions will not work while interrupts are disabled, and both +incoming and outgoing communication may be ignored. Interrupts can +slightly disrupt the timing of code, however, and may be disabled for +particularly critical sections of code. + +Library Documentation +--------------------- + +.. doxygenfunction:: interrupts + +Example +------- + +:: + + void setup() {} + + void loop() { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + +See Also +-------- + +- :ref:`noInterrupts() ` +- :ref:`attachInterrupt() ` +- :ref:`detachInterrupt() ` +- :ref:`Timers reference ` +- :ref:`Timer API ` +- :ref:`External interrupts ` + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/api/isbuttonpressed.rst b/docs/source/lang/api/isbuttonpressed.rst new file mode 100644 index 0000000..dbff0c9 --- /dev/null +++ b/docs/source/lang/api/isbuttonpressed.rst @@ -0,0 +1,17 @@ +.. _lang-isbuttonpressed: + +isButtonPressed() +================= + +Check whether the board's built-in button (labeled BUT on the +silkscreen) is pressed. + +Library Documentation +--------------------- + +.. doxygenfunction:: isButtonPressed + +See Also +-------- + +- :ref:`lang-waitforbuttonpress` diff --git a/docs/source/lang/api/nointerrupts.rst b/docs/source/lang/api/nointerrupts.rst new file mode 100644 index 0000000..68f0498 --- /dev/null +++ b/docs/source/lang/api/nointerrupts.rst @@ -0,0 +1,47 @@ +.. highlight:: cpp + +.. _lang-nointerrupts: + +noInterrupts() +============== + +Description +----------- + +Disables interrupts. Interrupts allow certain important tasks to +happen in the background and are enabled by default. Some functions +will not work while interrupts are disabled, and incoming +communication may be ignored. Interrupts can slightly disrupt the +timing of code, however, and may be disabled for particularly critical +sections of code. + +Library Documentation +--------------------- + +.. doxygenfunction:: noInterrupts + +Example +------- + +:: + + void setup() {} + + void loop() { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + +See Also +-------- + +- :ref:`interrupts() ` +- :ref:`attachInterrupt() ` +- :ref:`detachInterrupt() ` +- :ref:`Timers reference ` +- :ref:`Timer API ` +- :ref:`External interrupts ` + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/api/pinmode.rst b/docs/source/lang/api/pinmode.rst index b9095da..03cbcfa 100644 --- a/docs/source/lang/api/pinmode.rst +++ b/docs/source/lang/api/pinmode.rst @@ -13,6 +13,8 @@ Library Documentation .. doxygenfunction:: pinMode +.. _lang-pinmode-wiringpinmode: + .. doxygenenum:: WiringPinMode Discussion diff --git a/docs/source/lang/api/pwmwrite.rst b/docs/source/lang/api/pwmwrite.rst index 7a1d51f..2c858ab 100644 --- a/docs/source/lang/api/pwmwrite.rst +++ b/docs/source/lang/api/pwmwrite.rst @@ -11,6 +11,13 @@ pwmWrite(), the pin will output a steady square wave with the given duty cycle. You can change the duty cycle later by calling pwmWrite() again with the same pin and a different duty. +On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, +9, 11, 12, 14, 24, 27, and 28. + +The Arduino function :ref:`analogWrite() ` is an +alias for ``pwmWrite()``, but it is badly named, and its use is +discouraged. + .. contents:: Contents :local: @@ -25,12 +32,11 @@ Example Sets the output to the LED proportional to the value read from the potentiometer:: - int ledPin = 13; // LED connected to pin 13 (Maple) int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { - pinMode(ledPin, OUTPUT); // sets the LED pin as output + pinMode(BOARD_LED_PIN, OUTPUT); // sets the LED pin as output pinMode(analogPin, PWM); // sets the potentiometer pin as PWM // output @@ -39,8 +45,9 @@ potentiometer:: void loop() { val = analogRead(analogPin); // read the input pin - analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, - // analogWrite values from 0 to 65535 + analogWrite(BOARD_LED_PIN, val / 16); // analogRead values go from 0 + // to 4095, analogWrite values + // from 0 to 65535 } See Also diff --git a/docs/source/lang/api/serialusb.rst b/docs/source/lang/api/serialusb.rst index af3a7e0..e1d12bf 100644 --- a/docs/source/lang/api/serialusb.rst +++ b/docs/source/lang/api/serialusb.rst @@ -52,7 +52,9 @@ world!")``. .. cpp:class:: USBSerial Emulated serial-over-USB class. ``SerialUSB`` is the predefined - instance. + (singleton) instance. + +.. _lang-serialusb-begin: .. cpp:function:: USBSerial::begin() @@ -65,7 +67,12 @@ world!")``. .. cpp:function:: USBSerial::end() - Disables the USB peripheral. + Disables the USB peripheral. Note that using this function will + terminate all USB communications between the Maple and the USB + host; in particular, it implies that you won't be able to upload + any new programs without resetting the board or using + :ref:`perpetual bootloader mode + `. .. cpp:function:: unsigned int USBSerial::available() diff --git a/docs/source/lang/api/toggleled.rst b/docs/source/lang/api/toggleled.rst new file mode 100644 index 0000000..0cc20c2 --- /dev/null +++ b/docs/source/lang/api/toggleled.rst @@ -0,0 +1,17 @@ +.. _lang-toggleled: + +toggleLED() +=========== + +Switches the LED from off to on, or on to off. + +Library Documentation +--------------------- + +.. doxygenfunction:: toggleLED + +See Also +-------- + +- :ref:`BOARD_LED_PIN ` +- :ref:`togglePin() ` diff --git a/docs/source/lang/api/togglepin.rst b/docs/source/lang/api/togglepin.rst new file mode 100644 index 0000000..290718d --- /dev/null +++ b/docs/source/lang/api/togglepin.rst @@ -0,0 +1,17 @@ +.. _lang-togglepin: + +togglePin() +=========== + +Switches a digital output pin from :ref:`HIGH ` +to :ref:`LOW `, or from LOW to HIGH. + +Library Documentation +--------------------- + +.. doxygenfunction:: togglePin + +See Also +-------- + +- :ref:`toggleLED() ` diff --git a/docs/source/lang/api/waitforbuttonpress.rst b/docs/source/lang/api/waitforbuttonpress.rst new file mode 100644 index 0000000..34c5066 --- /dev/null +++ b/docs/source/lang/api/waitforbuttonpress.rst @@ -0,0 +1,17 @@ +.. _lang-waitforbuttonpress: + +waitForButtonPress() +==================== + +Wait for the board's built-in button (labeled BUT on the silkscreen) +to be pressed, possibly with timeout. + +Library Documentation +--------------------- + +.. doxygenfunction:: waitForButtonPress + +See Also +-------- + +- :ref:`lang-isbuttonpressed` diff --git a/docs/source/lang/cpp/built-in-types.rst b/docs/source/lang/cpp/built-in-types.rst new file mode 100644 index 0000000..1323db8 --- /dev/null +++ b/docs/source/lang/cpp/built-in-types.rst @@ -0,0 +1,95 @@ +.. highlight:: cpp + +.. _lang-built-in-types: + +================ + Built-in Types +================ + +This document serves as a reference for many of the built-in types +which are available when programming in the IDE. Programmers using +the :ref:`command-line tools ` will have access to +these types as long as they have imported `wirish.h +`_; +several are defined in in `libmaple_types.h +`_. + +.. _lang-built-in-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. + +Other Types +----------- + +.. cpp:type:: voidFuncPtr + + Pointer to a function that takes no arguments and returns nothing, i.e. + + :: + + typedef void (*voidFuncPtr)(void); + diff --git a/docs/source/lang/cpp/keywords.rst b/docs/source/lang/cpp/keywords.rst index e4ebe99..e3bc20d 100644 --- a/docs/source/lang/cpp/keywords.rst +++ b/docs/source/lang/cpp/keywords.rst @@ -94,7 +94,7 @@ The following keywords are used for built-in types. - :ref:`lang-float` - :ref:`lang-int` - :ref:`lang-long` -- :ref:`short ` +- :ref:`short ` - :ref:`void ` (not really a type, but used in the absence of one) diff --git a/docs/source/lang/cpp/numeric-types.rst b/docs/source/lang/cpp/numeric-types.rst deleted file mode 100644 index 9d2be48..0000000 --- a/docs/source/lang/cpp/numeric-types.rst +++ /dev/null @@ -1,79 +0,0 @@ -.. _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 ` will have access -to these types as long as they have imported ``wirish.h``; several are -defined in in `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/cpp/variables.rst b/docs/source/lang/cpp/variables.rst index 9094cd5..e6da0c9 100644 --- a/docs/source/lang/cpp/variables.rst +++ b/docs/source/lang/cpp/variables.rst @@ -37,7 +37,7 @@ 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 ` page +variables. See the :ref:`built-in types ` page for more information. Here are a few examples of declaring variables of different types:: @@ -116,7 +116,7 @@ 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 ` reference for links to each +:ref:`built-in types ` reference for links to each type's reference page. Using Variables @@ -149,7 +149,7 @@ See Also -------- - :ref:`lang-scope` -- :ref:`lang-numeric-types` +- :ref:`lang-built-in-types` .. rubric:: Footnotes diff --git a/docs/source/lang/cpp/void.rst b/docs/source/lang/cpp/void.rst index 88bd448..88c9c64 100644 --- a/docs/source/lang/cpp/void.rst +++ b/docs/source/lang/cpp/void.rst @@ -5,10 +5,12 @@ ``void`` ======== -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, or that it expects no arguments -from its caller. +.. cpp:type:: void + + The ``void`` keyword is used in function declarations. It indicates + that the function is expected to return no information to the + function from which it was called, or that it expects no arguments + from its caller. Example ------- diff --git a/docs/source/lang/unimplemented/interrupts.rst b/docs/source/lang/unimplemented/interrupts.rst deleted file mode 100644 index 55b8e93..0000000 --- a/docs/source/lang/unimplemented/interrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-interrupts: - -interrupts() -============ - -Re-enables interrupts (after they've been disabled by -`noInterrupts `_\ ()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None - - - -Returns -------- - -None - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `noInterrupts `_\ () -- `attachInterrupt `_\ () -- `detachInterrupt `_\ () - - - - -.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/nointerrupts.rst b/docs/source/lang/unimplemented/nointerrupts.rst deleted file mode 100644 index fb2e5f9..0000000 --- a/docs/source/lang/unimplemented/nointerrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-nointerrupts: - -noInterrupts() -============== - -Description ------------ - -Disables interrupts (you can re-enable them with interrupts()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None. - - - -Returns -------- - -None. - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `interrupts `_\ () - - - - -.. include:: /lang/cc-attribution.txt diff --git a/docs/source/language-index.rst b/docs/source/language-index.rst index 7843cb0..e160e2b 100644 --- a/docs/source/language-index.rst +++ b/docs/source/language-index.rst @@ -4,37 +4,37 @@ Complete Language Index ======================= -This is the index of Maple's :ref:`language reference ` documentation. The 'Maple API' column includes language specific to Maple as a microcontroller development platform, while the language in 'C++ for Maple' is more generally applied. - -# Fix above explanation +This is the index of Maple's :ref:`language reference +` documentation. The "Maple API" column provides +API references for documented libmaple functionality. The "C++ for +Maple".. pages are adaptations of the Arduino C++ documentation to the +.. Maple, and are intended as a minimal reference/refresher for +.. programmers familiar with the Arduino language. .. _index-language-index-cpp: .. _index-language-index-api: -+--------------------------------------------+----------------------------------------------+ -| Maple API | :ref:`C++ for Maple ` | -| | | -+============================================+==============================================+ -| | | -| .. toctree:: | .. toctree:: | -| :maxdepth: 1 | :maxdepth: 1 | -| :glob: | :glob: | -| | | -| lang/api/* | lang/cpp/* | -| | | -+--------------------------------------------+----------------------------------------------+ - -.. Unfinished, unimplemented in libmaple: ++----------------------------------+------------------------------------+ +| Maple API | C++ for Maple | +| | | ++==================================+====================================+ +| | | +| .. toctree:: | .. toctree:: | +| :maxdepth: 1 | :maxdepth: 1 | +| :glob: | :glob: | +| | | +| lang/api/* | lang/cpp/* | +| | | ++----------------------------------+------------------------------------+ + +.. Unimplemented in libmaple or not part of current release: .. toctree:: :hidden: - 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 - diff --git a/docs/source/language.rst b/docs/source/language.rst index 8e5d454..018eb8c 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -52,8 +52,8 @@ 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`. +The following table summarizes the available core language features. +A more exhaustive index is available at the :ref:`language-index`. +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ | Structure | Variables | Functions | @@ -67,129 +67,129 @@ more exhaustive index is available at the :ref:`language-index`. |**Control Structures** |* :ref:`INPUT ` | | | | | :ref:`OUTPUT ` |* :ref:`digitalRead() ` | |* :ref:`if/else ` | | | -| |* :ref:`true ` | | | -|* :ref:`for ` | :ref:`false ` |**Analog I/O** | +| |* :ref:`true ` | |* :ref:`togglePin() ` | +|* :ref:`for ` | :ref:`false ` | | +| | |* :ref:`toggleLED() ` | +|* :ref:`switch/case ` |* :ref:`BOARD_LED_PIN ` | | | +| | :ref:`BOARD_BUTTON_PIN `|* :ref:`isButtonPressed() ` | +|* :ref:`while ` | | | +| |* :ref:`Constants |* :ref:`waitForButtonPress() | +|* :ref:`do...while ` | ` (:ref:`integers | ` | +| | `, :ref:`floating | | +|* :ref:`break ` | point `) |**Analog I/O** | | | | | -|* :ref:`switch/case ` |* :ref:`Constants |* :ref:`analogRead() ` | -| | ` (:ref:`integers | | -|* :ref:`while ` | `, :ref:`floating |* :ref:`pwmWrite() ` | -| | point `) | (:ref:`analogWrite() ` is | -|* :ref:`do...while ` | | also available, though its use is discouraged) | -| |**Data Types** | | -|* :ref:`break ` | | | -| | The size of each datatype, in bytes, is |**Advanced I/O** | -|* :ref:`continue ` | given in parentheses where appropriate. | | -| | |* tone(): TODO | -|* :ref:`return ` | *Note*: The ``word`` type is (deliberately) | | -| | :ref:`not supported `. |* noTone(): TODO | -|* :ref:`goto ` | | | -| |* :ref:`void ` |* shiftOut(): TODO | +|* :ref:`continue ` |**Data Types** |* :ref:`analogRead() ` | | | | | -|**Further syntax** |* :ref:`boolean ` (1 byte) |* pulseIn(): TODO | +|* :ref:`return ` | The size of each datatype, in bytes, is |* :ref:`pwmWrite() ` | +| | given in parentheses where appropriate. | (:ref:`analogWrite() ` is | +|* :ref:`goto ` | | also available, though its use is discouraged) | +| | *Note*: The ``word`` type is (deliberately) | | +| | :ref:`not supported `. | | +|**Further syntax** | |**Advanced I/O** | +| |* :ref:`void ` | | +|* :ref:`; (semicolon) ` | |* tone(): TODO | +| |* :ref:`boolean ` (1 byte) | | +|* :ref:`{} (curly braces) | |* noTone(): TODO | +| ` |* :ref:`char ` (1 byte) | | +| | |* shiftOut(): TODO | +|* :ref:`// (single-line comment) |* :ref:`unsigned char | | +| ` | ` (1 byte) |* pulseIn(): TODO | | | | | -|* :ref:`; (semicolon) ` |* :ref:`char ` (1 byte) | | -| | |**Time** | -|* :ref:`{} (curly braces) |* :ref:`unsigned char | | -| ` | ` (1 byte) |* :ref:`millis() ` | +|* :ref:`/\* \*/ (multi-line comment) |* :ref:`byte ` (1 byte) | | +| ` | |**Time** | +| |* :ref:`int ` (4 bytes) | | +|* :ref:`#define ` | |* :ref:`millis() ` | +| |* :ref:`unsigned int ` | | +|* :ref:`#include ` | (4 bytes) |* :ref:`micros() ` | | | | | -|* :ref:`// (single-line comment) |* :ref:`byte ` (1 byte) |* :ref:`micros() ` | -| ` | | | -| |* :ref:`int ` (4 bytes) |* :ref:`delay() ` | -|* :ref:`/\* \*/ (multi-line comment) | | | -| ` |* :ref:`unsigned int ` |* :ref:`delayMicroseconds() | -| | (4 bytes) | ` | -|* :ref:`#define ` | | | -| |* :ref:`long ` (8 bytes) | | -|* :ref:`#include ` | |**Math** | -| |* :ref:`unsigned long ` | | -| | (8 bytes) |* :ref:`min() ` | +| |* :ref:`long ` (8 bytes) |* :ref:`delay() ` | |**Arithmetic Operators** | | | -| |* :ref:`float ` (4 bytes) |* :ref:`max() ` | -|* :ref:`= ` | | | -| (assignment operator) |* :ref:`double ` (8 bytes) |* :ref:`abs() ` | +| |* :ref:`unsigned long ` |* :ref:`delayMicroseconds() | +|* :ref:`= ` | (8 bytes) | ` | +| (assignment operator) | | | +| |* :ref:`float ` (4 bytes) | | +|* :ref:`+ ` (addition) | |**Math** | +| |* :ref:`double ` (8 bytes) | | +|* :ref:`- ` | |* :ref:`min() ` | +| (subtraction) |* :ref:`Strings ` | | +| | |* :ref:`max() ` | +|* :ref:`* ` |* :ref:`Arrays ` | | +| (multiplication) | |* :ref:`abs() ` | +| |* :ref:`enum ` | | +|* :ref:`/ ` (division) | |* :ref:`constrain() ` | +| |* :ref:`Numeric types ` | | +|* :ref:`% ` (modulo) | |* :ref:`map() ` | +| |**Conversion** | | +| | |* :ref:`pow() ` | +|**Comparison Operators** |* :ref:`char() ` | | +| | |* :ref:`sqrt() ` | +|* :ref:`== ` (equal to) |* :ref:`byte() ` | | | | | | -|* :ref:`+ ` (addition) |* :ref:`Strings ` |* :ref:`constrain() ` | +|* :ref:`\!= ` |* :ref:`int() ` |**Trigonometry** | +| (not equal to) | | | +| |* :ref:`long() ` |* :ref:`sin() ` | +|* :ref:`< ` (less than) | | | +| |* :ref:`float() ` |* :ref:`cos() ` | +|* :ref:`> ` | | | +| (greater than) |* :ref:`double() ` |* :ref:`tan() ` | | | | | -|* :ref:`- ` |* :ref:`Arrays ` |* :ref:`map() ` | -| (subtraction) | | | -| |* :ref:`enum ` |* :ref:`pow() ` | -|* :ref:`* ` | | | -| (multiplication) |* :ref:`Numeric types ` |* :ref:`sqrt() ` | +|* :ref:`<= ` | | | +| (less than or equal to) |**Variable Scope & Qualifiers** |**Random Numbers** | | | | | -|* :ref:`/ ` (division) |**Conversion** | | -| | |**Trigonometry** | -|* :ref:`% ` (modulo) |* :ref:`char() ` | | -| | |* :ref:`sin() ` | -| |* :ref:`byte() ` | | -|**Comparison Operators** | |* :ref:`cos() ` | -| |* :ref:`int() ` | | -|* :ref:`== ` (equal to) | |* :ref:`tan() ` | -| |* :ref:`long() ` | | -|* :ref:`\!= ` | | | -| (not equal to) |* :ref:`float() ` |**Random Numbers** | +|* :ref:`>= ` |* :ref:`variables `, |* :ref:`randomSeed() ` | +| (greater than or equal to) | :ref:`scope ` | | +| | |* :ref:`random() ` | +| |* :ref:`static ` | | +|**Boolean Operators** | | | +| |* :ref:`volatile ` |**Bits and Bytes** | +|* :ref:`&& ` (and) | | | +| |* :ref:`const ` |* :ref:`lowByte() ` | +|* :ref:`|| ` (or) | | | +| | |* :ref:`highByte() ` is | +|* :ref:`\! ` (not) |**Utilities** | provided, though its use is discouraged. | | | | | -|* :ref:`< ` (less than) |* :ref:`double() ` |* :ref:`randomSeed() ` | -| | | | -|* :ref:`> ` | |* :ref:`random() ` | -| (greater than) |**Variable Scope & Qualifiers** | | -| | | | -|* :ref:`<= ` |* :ref:`variables `, |**Bits and Bytes** | -| (less than or equal to) | :ref:`scope ` | | -| | |* :ref:`lowByte() ` | -|* :ref:`>= ` |* :ref:`static ` | | -| (greater than or equal to) | |* :ref:`highByte() ` is | -| |* :ref:`volatile ` | provided, though its use is discouraged. | -| | | | -|**Boolean Operators** |* :ref:`const ` |* :ref:`bitRead() ` | -| | | | -|* :ref:`&& ` (and) | |* :ref:`bitWrite() ` | -| |**Utilities** | | -|* :ref:`|| ` (or) | |* :ref:`bitSet() ` | -| |* :ref:`sizeof() ` | | -|* :ref:`\! ` (not) | |* :ref:`bitClear() ` | -| | | | -| | |* :ref:`bit() ` | +| |* :ref:`sizeof() ` |* :ref:`bitRead() ` | |**Pointer Operators** | | | +| | |* :ref:`bitWrite() ` | +|* :ref:`* dereference operator | | | +| ` | |* :ref:`bitSet() ` | | | | | -|* :ref:`* dereference operator | |**External Interrupts** | +|* :ref:`& reference operator | |* :ref:`bitClear() ` | | ` | | | -| | |* :ref:`Reference Page ` | -|* :ref:`& reference operator | | | -| ` | |* :ref:`attachInterrupt() | -| | | ` | +| | |* :ref:`bit() ` | | | | | -|**Bitwise Operators** | |* :ref:`detachInterrupt() | -| | | ` | +|**Bitwise Operators** | | | +| | |**External Interrupts** | |* :ref:`& ` | | | -| (bitwise and) | | | -| | |**Interrupts** | -|* :ref:`| ` | | | -| (bitwise or) | |* interrupts(): TODO | +| (bitwise and) | |* :ref:`Reference Page ` | | | | | -|* :ref:`^ ` | |* noInterrupts(): TODO | -| (bitwise xor) | | | +|* :ref:`| ` | |* :ref:`attachInterrupt() | +| (bitwise or) | | ` | | | | | -|* :ref:`~ ` | |**Communication** | -| (bitwise not) | | | -| | |* :ref:`SerialUSB ` | -|* :ref:`\<\< ` | | | -| (shift left) | |* :ref:`Serial ` | +|* :ref:`^ ` | |* :ref:`detachInterrupt() | +| (bitwise xor) | | ` | | | | | -|* :ref:`>> ` | |**Looking for something else?** | -| (shift right) | | | -| | | See the :ref:`libraries` page for interfacing with| -| | | particular types of hardware. Maple links | -|**Compound Operators** | | against `newlib `_ | -| | | and allows the use of any of its functions; see | -|* :ref:`++ ` | | its documentation for more details. | -| (increment) | | | +|* :ref:`~ ` | | | +| (bitwise not) | |**Interrupts** | | | | | -|* :ref:`- - ` | | | -| (decrement) | | | +|* :ref:`\<\< ` | |* :ref:`interrupts() ` | +| (shift left) | | | +| | |* :ref:`noInterrupts() ` | +|* :ref:`>> ` | | | +| (shift right) | | | +| | |**Communication** | | | | | -|* :ref:`+= ` | | | -| (compound add) | | | +|**Compound Operators** | |* :ref:`SerialUSB ` | | | | | +|* :ref:`++ ` | |* :ref:`Serial ` | +| (increment) | | | +| | |**Looking for something else?** | +|* :ref:`- - ` | | | +| (decrement) | | See the :ref:`libraries` page for interfacing with| +| | | particular types of hardware. Maple links | +|* :ref:`+= ` | | against `newlib `_ | +| (compound add) | | and allows the use of any of its functions; see | +| | | its documentation for more details. | |* :ref:`-= | | | | ` (compound | | | | subtract) | | | @@ -222,6 +222,8 @@ more exhaustive index is available at the :ref:`language-index`. Missing Arduino Features ------------------------ +.. _langage-missing-analogreference: + **analogReference()** It is not possible to implement this function on the Maple @@ -256,8 +258,6 @@ Unimplemented Arduino Features The following Wiring/Arduino features are currently unimplemented on the Maple. However, they will be present in future versions: -- `interrupts() `_ -- `noInterrupts() `_ - `noTone() `_ - `pulseIn() `_ - `shiftOut() `_ @@ -272,7 +272,11 @@ the Maple. However, they will be present in future versions: C++ for Maple -------------- -If you haven't programmed in C++, or if you just need to jog your memory, you may want to check out our :ref:`C++ for Maple Index`. It covers programming ideas and C++ that will definitely come in handy. + +If you haven't programmed in C++, or if you just need to jog your +memory, you may want to check out our :ref:`Language Index +`. It provides some introductory coverage of +programming ideas and C++. .. _arduino_c_for_c_hackers: @@ -366,9 +370,7 @@ contains ``setup()`` and ``loop()``:: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } The second file contains the (not very useful) implementation for @@ -388,9 +390,7 @@ Then the results of the concatenation process might be :: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } int choose_a_pin(void); @@ -415,9 +415,7 @@ Which could plausibly be turned into the final source file :: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } int choose_a_pin(void); @@ -441,7 +439,6 @@ Recommended Reading * `newlib Documentation `_ * STMicro documentation for STM32F103RB microcontroller: - * `All documents `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Programming Manual `_ (assembly language and register reference) diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 567aec8..7623963 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -21,13 +21,69 @@ in the description of the library. .. contents:: Contents :local: +.. toctree:: + :hidden: + + libs/servo.rst + +.. _libraries-servo: + +Servo +----- + +The Servo library is provided for convenient control of RC +servomotors. For more information, see the :ref:`Servo ` +reference. + +**Compatibility Note** + +The Servo class provides a public interface identical to the Arduino +version's documented functionality (as of Arduino 0021), so in most +cases, this library will be a drop-in replacement. + +However, there are some differences, essentially at the level of +implementation details. + +The major difference is that while the Arduino implementation drives +the servos with "bit-banged" :ref:`PWM `, the Maple +implementation uses :ref:`timers ` to drive the PWM directly. + +Consequently, **the Maple implementation only allows Servo instances +to** :ref:`attach ` **to pins that support PWM**. + +To determine if a pin supports PWM (15 Maple pins do), you can either +check if "PWM" appears next to its number on the Maple silkscreen, or +consult the :ref:`pwmWrite() ` documentation. + +RC Servos expect a pulse approximately every 20ms. In the Maple +implementation, :ref:`periods ` are set +for entire timers, rather than individual channels. Thus, +``attach()``\ ing a Servo to a pin can interfere with other pins +associated with the same timer\ [#fard-servo]_. + +Because of this, we recommend connecting multiple servomotors to pins +which share a timer, in order to keep as many timers free for other +purposes as possible. Consult the :ref:`table provided in the timers +reference ` to match up pins and timer +channels. + +Another difference: although it is not publicly documented to do so, +the Arduino implementation of `attach() +`_ returns the timer +channel associated with the newly-attached pin, or 0 on failure (as of +Arduino 0021). The Maple implementation returns true on success, and +false on failure (and this is its documented behavior). + .. _libraries-liquid-crystal: LiquidCrystal ------------- +.. TODO 0.0.10 make our own LiquidCrystal docs + The LiquidCrystal library allows Maple to control LCD screens. For -more information, see the Arduino LiquidCrystal documentation. +more information, see the `Arduino LiquidCrystal documentation +`_. **Compatibility Note** @@ -57,6 +113,8 @@ the hardware i2c peripheral on the stm32 as well as the DMA for performance. Support for slave, smBUS, and multimaster modes are also slated for inclusion in the enhanced Wire port. +.. TODO 0.0.10 Wire docs in the cpp domain in own page under /libs/ + Wire Function Reference ^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,3 +185,10 @@ Wire Function Reference Returns the number of bytes which are still available for reading (with ``Wire.receive()``) from the last call to ``Wire.requestFrom(uint8, int)``. + +.. rubric:: Footnotes + +.. [#fard-servo] The Arduino implementation also captures timer + channels in groups as more Servo objects are attached, but the + details of which channels have their periods reset when are + slightly different. diff --git a/docs/source/libs/servo.rst b/docs/source/libs/servo.rst new file mode 100644 index 0000000..f92fd91 --- /dev/null +++ b/docs/source/libs/servo.rst @@ -0,0 +1,108 @@ +.. highlight:: cpp + +.. _libs-servo: + +======= + Servo +======= + +This documents the Servo library for controlling RC servomotors. It +is implemented as a thin layer over the built-in :ref:`timer +peripherals `. + +You can use this library in the :ref:`IDE ` by choosing the Servo +item under the Sketch > Import Library... menu. + +If you are using the :ref:`Unix toolchain `, the +library is located in ``$LIB_MAPLE_HOME/libraries/Servo/``. + +Servo Class Reference +--------------------- + +You can construct a Servo object by including the declaration :: + + Servo servo; + +in your sketch. This will create a Servo object called ``servo``. +You can then use any of its methods; for instance, to control a +servomotor attached to pin 9, you could write :: + + servo.attach(9); + +.. cpp:class:: Servo + + Class for controlling RC servomotors via :ref:`timers `. + +.. _libs-servo-attach: + +.. cpp:function:: bool Servo::attach(uint8 pin, uint16 min, uint16 max) + + Attach this Servo object to the given ``pin``. The pin must be + capable of PWM. You can check this by seeing if "PWM" is written + next to its number on the Maple silkscreen, or by consulting the + :ref:`pwmWrite() ` documentation. + + Sets this pin's :ref:`mode ` to :ref:`PWM + `, and returns true if successful. + Does nothing and returns false if the pin doesn't support PWM. + + Parameter ``min`` is the pulse width corresponding to 0 degrees; + ``max`` is the pulse width corresponding to 180 degrees (both are + in microseconds). + +.. cpp:function:: bool Servo::attach(uint8 pin) + + Equivalent to :ref:`attach(pin, 544, 2400) `. + +.. _libs-servo-attached: + +.. cpp:function:: int Servo::attached() const + + If currently attached (via :ref:`attach() `) to + a pin, returns that pin's number. Returns ``NOT_ATTACHED`` + otherwise. + +.. cpp:function:: bool Servo::detach() + + If this Servo object is currently attached to pin, stops driving + the servo by setting a zero pulse width (this is accomplished by + setting the associated :ref:`channel mode + ` to ``TIMER_DISABLED``). + + Subsequently, calling :ref:`attached() ` will + return ``NOT_ATTACHED``. + +.. cpp:function:: void Servo::write(unsigned int value) + + If ``value`` is less than ``SERVO_MAX_WRITE_ANGLE`` (which, for + Arduino compatibility, is 200), it's interpreted as an angle in + degrees. Otherwise, it's treated as a pulse width in microseconds. + + Drives the servo to target the given angle, based on a linear + interpolation of the ``min`` and ``max`` pulse widths determined + when :ref:`attach() ` was called. + + Be aware that some (especially lower-cost) servos have fairly + non-linear maps between pulse width and target angle. Make sure to + test your motor before relying on this method. + +.. cpp:function:: void Servo::writeMicroseconds(uint16 pulseWidth) + + Drives the servo using a ``pulseWidth``-microsecond pulse. + + If ``pulseWidth`` is outside of the [``min``, ``max``\ ] pulse + width range set during :ref:`attach() `, it will + be clamped to lie in this range. + +.. cpp:function:: int Servo::read() const + + Returns the servo's target angle, in degrees. This will be clamped + to lie between 0 (when the pulse width is at most ``min``) and 180 + (when the pulse width is at least ``max``). + +.. cpp:function:: uint16 Servo::readMicroseconds() const + + Returns the pulse width of the wave currently driving the servo, in + microseconds. This will be clamped to lie in the [``min``, + ``max``\ ] pulse width range set during :ref:`attach() + `. diff --git a/docs/source/pwm.rst b/docs/source/pwm.rst index fd72842..1a8f4df 100644 --- a/docs/source/pwm.rst +++ b/docs/source/pwm.rst @@ -28,9 +28,9 @@ Note that unlike the Arduino, the Maple does not have PWM functionality on pin D10; all other pins are :ref:`compatible `. -The following table shows which :ref:`timer ` generates which -PWM outputs. See the :ref:`pin mapping table ` -to track down exactly which timer *channel* corresponds to each pin. +The following table shows which timer can generate which PWM +outputs. See the :ref:`pin mapping table ` to +track down exactly which timer *channel* corresponds to each pin. .. _pwm-timer-table: @@ -65,12 +65,13 @@ The Maple has 16-bit PWM resolution, which means that the counter and variables can be as large as 65535, as opposed to 255 with 8-bit resolution. With a 72MHz clock rate, a PWM output could have maximum period of about one millisecond; using a :ref:`prescaler -` (clock divider) in front of the counter can increase -this maximum period. Setting the :ref:`period ` to -something other than the maximum value gives further control over the -total length of the waveform. However, this effectively limits the -resolution with which the duty can be modified: the duty must be less -than or equal to the period. +` (clock divider) in front of +the counter can increase this maximum period. Setting the +:ref:`period ` to something other than +the maximum value gives further control over the total length of the +waveform. However, this effectively limits the resolution with which +the duty can be modified: the duty must be less than or equal to the +period. Here are some commonly used PWM configurations (note that servos are notoriously variable, especially the lower cost models): @@ -93,82 +94,13 @@ notoriously variable, especially the lower cost models): Function Reference ------------------ -``pinMode(pin_num, PWM)`` - - This command is usually called from :ref:`setup() ` to - tell the microcontroller that pin_num should be configured to PWM - output. ``PWM`` implies regular driven OUTPUT; ``PWM_OPEN_DRAIN`` - is also available (see the list of :ref:`GPIO modes ` - for more information). - -.. _pwm-pwmwrite: - -``pwmWrite(pin_num, value)`` - - This command sets the PWM duty. User code is expected to determine - and honor the maximum value (based on the configured period). As a - convenience, ``analogWrite`` is an alias for ``pwmWrite`` to ease - porting Arduino code, though period and duty will have to be - recalibrated (see :ref:`compatibility `). - -.. _pwm-overflow: - -``Timer[1,2,3,4].setOverflow(overflow)`` - - This function sets the period ("reload" or "overflow") value for - an entire PWM timer bank. The value is 16bit (0 to 65535) and - determines the maximum value that can be written with - :ref:`pwmWrite() ` corresponding to 100% duty - cycle. This also affects the PWM frequency: the higher reload is, - the lower the PWM frequency will be. - - The PWM output pin starts HIGH, then the timer begins counting up - from zero (with frequency equal to 72MHz/:ref:`prescaler - `) until it hits the duty value, at which point it - drops to LOW. The timer then continues counting up until it hits - the total period (set with this function), at which point the - cycle starts again. - -.. _pwm-prescaler: - -``Timer[1,2,3,4].setPrescaleFactor(prescale)`` - - Find the appropriate timer for a given PWM header using the table - :ref:`above `, then set the prescaler. A - prescaler is a clock divider. The timer will normally count with - frequency equal to the STM32's normal clock (72MHz); this - corresponds to setting ``prescale`` to 1 (which is the default). - - If a longer frequency is desired, use a larger ``prescale`` value. - For instance, an 8MHz frequency can be achieved by setting - ``prescale`` to 9, since 72MHz / 9 = 8MHz. - - This function is normally called once from, :ref:`lang-setup`, but - the timer can be reconfigured with a new prescaler at any time. - - * Configure the prescaler and overflow values to generate a timer - * reload with a period as close to the given number of - * microseconds as possible. - * - * The return value is the overflow, which may be used to set - * channel compare values. However, if a clock that fires an - * interrupt every given number of microseconds is all that is - * desired, and the relative "phases" are unimportant, channel - * compare values may all be set to 1. - -``Timer[1,2,3,4].setPeriod(period_in_microseconds)`` - - Configure the prescaler and overflow values to generate a timer - reload with a period as close to the given number of microseconds - as possible. - - The return value is the overflow, which may be used to set channel - compare values. However, if a clock that fires an interrupt every - given number of microseconds is all that is desired, and the - relative "phases" are unimportant, channel compare values may all - be set to 1. - - +- :ref:`lang-pinmode` +- :ref:`lang-pwmwrite` +- :ref:`Timer API` (especially :ref:`setOverflow() + `, :ref:`setPrescaleFactor() + `, and :ref:`setPeriod() + `). +- :ref:`Timers reference `. Recommended Reading ------------------- @@ -182,6 +114,5 @@ Recommended Reading * `So You Want To Use PWM, Eh? `_ at Non-Lexical Vocables * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/spi.rst b/docs/source/spi.rst index ca9415c..ba43eef 100644 --- a/docs/source/spi.rst +++ b/docs/source/spi.rst @@ -4,54 +4,16 @@ SPI ===== -The Maple has two SPI ports. The first has NSS on D10, MOSI on D11, -MISO on D12, and SCK on D13. The second has NSS on D31, SCK on D32, -MISO on D33, and MOSI on D34. +The Serial Peripheral Interface Bus (SPI) is a serial data transfer +protocol useful for interacting with a wide variety of hardware +peripherals. -.. _spi-speeds: +The Maple has two SPI ports. The first has NSS on D10, MOSI on +D11, MISO on D12, and SCK on D13. The second has NSS on D31, SCK on +D32, MISO on D33, and MOSI on D34. -Each port can be configured at one of the following speeds: - -* ``SPI_18MHZ``: 18 MHz -* ``SPI_9MHZ``: 9 MHz -* ``SPI_4_5MHZ``: 4.5 MHz -* ``SPI_2_25MHZ``: 2.25 MHz -* ``SPI_1_125MHZ``: 1.124 MHz -* ``SPI_562_500KHZ``: 562.500 KHz -* ``SPI_281_250KHZ``: 281.250 KHz -* ``SPI_140_625KHZ``: 140.625 KHz - -.. contents:: Contents - :local: - -Function Reference ------------------- - -``HardwareSPI Spi(number);`` - - This declaration must be included at the start of any sketch or - program that uses the SPI interface. The argument number is either - 1 or 2 and specifies which port to use. - -``Spi.begin(freq, endianness, mode)`` - - ``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 - `; ``endianness`` is either ``LSBFIRST`` or - ``MSBFIRST``; mode is one of 0, 1, 2, 3, and specifies which "SPI - Mode" is used (see specification docs linked below). - -``Spi.begin()`` - - A default ``begin`` with no arguments is provided for the lazy; it - is equivalent to ``Spi.begin(SPI_1_125MHZ, MSBFIRST, 0)``. - -``Spi.send(data, size)`` - - Writes data into the port buffer to be transmitted as soon as - possible. ``data`` should be an array of type ``byte*``; ``size`` - should be the number of elements in ``data``. +The public libmaple API for managing the SPI ports is the +:ref:`HardwareSpi ` class. Recommended Reading ------------------- @@ -63,7 +25,6 @@ Recommended Reading * `Hardcore SPI on Arduino `_ by kik64 * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/timers.rst b/docs/source/timers.rst index 948805b..56dd686 100644 --- a/docs/source/timers.rst +++ b/docs/source/timers.rst @@ -8,25 +8,46 @@ Timers There are four general purpose timers in the Maple microcontroller that can be configured to generate periodic or delayed events with minimal work done by the microcontroller. For example, the :ref:`PWM -` channels, once enabled, generate regular square-wave signals on -specific output pins that will continue even if the microcontroller is -busy crunching numbers or handling communications interrupts. By -attaching interrupt handlers to these channels (instead of just -changing the voltage on an external pin), more complex events like -printing to a serial port, updating a variable, or emitting a whale -mating call can be scheduled. You can even modify the configuration of -the timer itself at a regular interval; the possibilities are endless! - -The four timers each have four separate compare channels. Each timer -is a single 16-bit counter that can be configured with both a -prescaler and an overflow value. The prescaler acts as a divider of -the 72MHz system clock; without prescaling the counter would get up to -65536 (2 to the 16th power) and roll over more than a thousand times a -second; even with the full prescaler it rolls over about once a -minute. The overflow value is the maximum value the counter will go up -to. It defaults to the full 65535; smaller values will cause the -counter to reset to zero more frequently. +` channels can generate regular square-wave signals on specific +output pins without consuming extra clock cycles. By attaching +interrupt handlers to these channels (instead of just changing the +voltage on an external pin), more complex events can be scheduled. + +.. contents:: Contents + :local: + +Introduction +------------ + +.. _timers-prescale: + +The four timers each have four separate compare channels. Each channel +has an associated 16-bit counter that can be configured with a 16-bit +prescaler and a 16-bit overflow value. The prescaler determines how +fast the counter changes, while the overflow value determines when it +gets reset. + +The prescaler acts as a divider of the 72MHz system clock. That is, +with a prescaler of 1, the channel's counter increments with a +frequency of 72MHz, rolling over (passing the maximum 16-bit unsigned +integer value of 65,535) more than a thousand times a second. With a +prescaler of 7200, it has a frequency of (72/7200) MHz = 10 KHz, +rolling over approximately every 6.55 seconds. + +The overflow value is the maximum value the counter will go up to. It +defaults to the full 65,535; smaller values will cause the counter to +reset to zero more frequently. + +Whenever a channel's counter reaches its overflow value, an "update +event" interrupt is generated. You can configure the Maple to notify +you when this takes place, by registering an interrupt handler, which +is a function that will be called when the update event occurs. + +libmaple Reference +------------------ +The libmaple API for interacting with timers is documented at the +:ref:`HardwareTimer reference `. Caveats ------- @@ -36,9 +57,18 @@ Caveats **PWM Conflicts:** Because PWM functionality on a given pin depends on the configuration of the timer and channel, you must chose your channels carefully if you want to use both timer interrupts and PWM in -the same program. Refer to the full :ref:`pin mapping table -` to match up timer channels and Maple header -pin numbers. +the same program. Refer to the following table to match up timer +channels and Maple header pin numbers: + +.. _timers-pin-channel-map: + +.. csv-table:: + :header: Timer, Ch. 1 pin, Ch. 2 pin, Ch. 3 pin, Ch. 4 pin + + ``Timer1``, 6, 7, 8, -- + ``Timer2``, 2, 3, 1, 0 + ``Timer3``, 12, 11, 27, 28 + ``Timer4``, 5, 9, 14, 24 **Overhead:** there is some overhead associated with function and interrupt calls (loading and unloading the stack, preparing state, @@ -59,7 +89,8 @@ configuration being the same. auto-reset and communications functionality. This will require that you put your Maple into :ref:`perpetual bootloader mode ` before uploading a new - program to it. + program to it (or somehow causing your program to re-enable serial + over USB using :ref:`SerialUSB.begin() `). Disabling SysTick with ``systick_disable()`` helps as well. However, calling this function will break the ``micros()`` and @@ -73,33 +104,6 @@ a handler isn't going to block other interrupts from firing (e.g. USB, Serial, SysTick) if those other interrupts are important for your program. -.. _timers-modes: - -General Timer Modes -------------------- - -``TIMER_DISABLED`` - - Exactly what it sounds like: the timer stops counting, interrupts - are not called, and no state changes are output. - -``TIMER_PWM`` - - This is the default mode for pins after initialization. See the - :ref:`PWM docs ` 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. - -``TIMER_OUTPUTCOMPARE`` - - In this mode, the timer counts from 0 to the overflow value - repeatedly; every time the counter value reaches one of the - channel compare values, the corresponding interrupt is fired. - SysTick Peripheral ------------------ @@ -111,136 +115,22 @@ VGA code, where the timing jitters are transformed into visual jags in the image. The SysTick peripheral can be disabled by calling ``systick_disable()``, and re-enabled using ``systick_resume()``. -Function Reference ------------------- - -For all of these functions, ``Timer1`` can be replaced with -``Timer2``, ``Timer3``, or ``Timer4``; the channel numbers also range -from 1 to 4. - -``Timer1.pause()``/\ ``Timer1.resume()`` - - These functions start and stop the counter without affecting the - rest of the configuration. These functions can be used during the - setup period to prevent interrupts from firing before they are - completely configured. Note that there is some function call - overhead with these functions, so they are not a perfect way to - align multiple timers to the same count value. - -``Timer1.setOverflow(val)`` - - Sets the overflow (or "reload") value for the whole timer; when - the counter reaches this value it resets to zero. Defaults to - 65535 (the largest unsigned 16bit integer); setting it to anything - lower will cause interrupts to be called more frequently (see the - setPeriod function below for a shortcut). This number sets the - maximum value for the channel compare values. - -``Timer1.setPrescaleFactor(val)`` - - The prescaler acts as a clock divider to slow down the rate at - which the counter increments. For example, the system clock rate - is 72MHz, so the counter will reach 65535 in (13.89 nanoseconds) * - (65535 counts) = (910.22 microseconds), or about a thousand times - a second. If you set the prescaler to 1098, then the clock rate is - effectively 65.56KHz, and the counter will reach 65536 in (15.25 - microseconds) * (65536 counts) = (0.999 seconds), or just about - once a second. Use the :ref:`setPeriod ` - function below if you are allergic to math! - -.. _timers-set-period: - -``Timer1.setPeriod(val)`` - - This tricky trick will configure the prescaler and overflow values - to generate a timer reload with a period as close to val - microseconds as possible. It returns the chosen overflow value, - which you can then use to set the channel compare values - appropriately: if you just want the interrupts to fire when the - clock rolls over and you don't care about the relative "phase", - you can always set the channel compare values to 1. - - Remember: a microsecond is 1/1,000,000th of a second, or 1/1,000 - of a millisecond. The prescaler itself is 16bit, so the longest - period that can be configured is 1/(72MHz) * (2^32) = (59.65 - seconds) or about a minute. You can get around this by creating an - interrupt that increments a 32-bit variable, by using the - ``millis()`` function, or by interfacing with an external - real-time-clock chip. - -``Timer1.setCount(val)``/\ ``Timer1.getCount()`` - - These functions let you mess with the counter's brains - directly. You can probably make it not work if you try! The timer - is 16bit, so ``val`` and the return value of ``getCount`` are - ``uint16``. - -``Timer1.setChannel1Mode(MODE)`` - - This sets the given channel (here 1) of the given timer (here 1) - to the given mode. See the :ref:`list above ` for - possible values; for interrupts you want ``TIMER_OUTPUTCOMPARE``. - -``Timer1.setCompare1(val)`` - - Sets the compare value for the given channel; when the counter - reaches this value the interrupt for this channel will fire if the - channel is in output compare mode and an interrupt is attached. - - By default this only changes the relative offsets between events - on a single timer ("phase"); they don't control the frequency with - which they occur. However, a common trick is to increment the - compare value manually in the interrupt handler so that the event - will fire again after the increment period. There can be a - different increment value for each channel, so this trick allows - events to be programmed at 4 different rates on a single timer! - Note that function call overhead means that the smallest increment - rate is a couple microseconds. - -.. _timers-attachinterrupt: -.. _timers-detachinterrupt: - -``Timer1.attachCompare1Interrupt(function)``/\ ``Timer1.detachCompare1Interrupt()`` - - This is how to attach or disable an interrupt handlers to timer - channels; this what will get called when the counter reaches the - compare value set with ``setCompareN(val)``. ``function`` - (sometimes referred to as an ISR: "interrupt service routine") - should be of a type that does not accept or return any values - (C/C++ programmers: ``void (function*)(void)``). They are just - like any other function in your sketch/program and must be - initialized at the top of the file and defined below. - - ``function`` should try to do what it has to do as fast as - possible. Blinking the LED, some logic, PWM updates, and Serial - writes are fine; writing to SerialUSB or waiting for user input - can take a long time and other compare interrupts won't fire. Tip: - if you have a ``delay()`` in your ISR, you're probably doing it - wrong. - - Stay vigilant here... function pointers are serious business, and - once you go down that path you'll find yourself in a `forest of - parentheses `_ before you know it. - Code Examples ------------- LED blink ^^^^^^^^^ -\ :: +:: - #define LED_PIN 13 #define LED_RATE 500000 // in microseconds; should give 0.5Hz toggles void handler_led(void); - int toggle = 0; - void setup() { // Set up the LED to blink - pinMode(LED_PIN, OUTPUT); + pinMode(BOARD_LED_PIN, OUTPUT); // Setup Timer Timer2.setChannel1Mode(TIMER_OUTPUTCOMPARE); @@ -254,16 +144,13 @@ LED blink } void handler_led(void) { - toggle ^= 1; - digitalWrite(LED_PIN, toggle); + toggleLED(); } Racing Counters ^^^^^^^^^^^^^^^ -\ :: - - #define BUTTON_PIN 38 +:: void handler_count1(void); void handler_count2(void); @@ -274,7 +161,7 @@ Racing Counters void setup() { // Set up BUT for input - pinMode(BUTTON_PIN, INPUT_PULLUP); + pinMode(BOARD_BUTTON_PIN, INPUT_PULLUP); // Setup Counting Timers Timer3.setChannel1Mode(TIMER_OUTPUTCOMPARE); @@ -302,7 +189,7 @@ Racing Counters // Run... while BUT is held, pause Count2 for(int i = 0; i<1000; i++) { - if(digitalRead(BUTTON_PIN)) { + if(digitalRead(BOARD_BUTTON_PIN)) { Timer4.pause(); } else { Timer4.resume(); diff --git a/docs/source/troubleshooting.rst b/docs/source/troubleshooting.rst index 0c10d01..f3052d9 100644 --- a/docs/source/troubleshooting.rst +++ b/docs/source/troubleshooting.rst @@ -150,7 +150,11 @@ 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. +Try unplugging and plugging your Maple or pressing the RESET button. + +This can also happen if you disable the USB peripheral, e.g. using +:ref:`SerialUSB.end() `. I have multiple Maples installed; how do I know which one will get flashed? --------------------------------------------------------------------------- @@ -161,19 +165,26 @@ board. There's no solution to this problem for now: you'll have to just plug in the Maples one at a time. If this is a real problem let us know and we'll see if we can come up with a better solution. +My flash programs don't seem to stick; they behave like they are RAM! +--------------------------------------------------------------------- + +If you have uploaded a program to RAM, this will take priority over +any program subsequently uploaded to flash. We'll be removing this +bug in a later version of the bootloader. For now, you can fix this +by unplugging your Maple to clear the contents of RAM, then plugging +it back in. + +If you are using the :ref:`Unix toolchain `, Make sure +you :command:`make clean` when switching between FLASH and RAM +targets; :command:`make` isn't smart enough to rebuild everything that +needs to be for the new target. + .. _troubleshooting-shell: ===================== Command-line issues ===================== -My flash programs don't seem to stick; they behave like they are RAM! ---------------------------------------------------------------------- - -Make sure you :command:`make clean` when switching between FLASH and -RAM targets; :command:`make` isn't smart enough to rebuild everything -that needs to be for the new target. - [Linux] ``cdc_acm 3-1:1.0: no more free acm devices`` ----------------------------------------------------- diff --git a/docs/source/usart.rst b/docs/source/usart.rst index c0334a9..3beb3fc 100644 --- a/docs/source/usart.rst +++ b/docs/source/usart.rst @@ -30,6 +30,5 @@ Recommended Reading * `Arduino reference on Serial `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/usb.rst b/docs/source/usb.rst index 5494b06..f502f31 100644 --- a/docs/source/usb.rst +++ b/docs/source/usb.rst @@ -39,7 +39,6 @@ Recommended Reading * Linux Kernel documentation for `USB ACM `_ and `USB Serial `_ * STMicro documentation for STM32F103RB microcontroller: - * `All documents `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Programming Manual `_ (pdf; assembly diff --git a/libmaple/libmaple_types.h b/libmaple/libmaple_types.h index a976a9e..8d216a8 100644 --- a/libmaple/libmaple_types.h +++ b/libmaple/libmaple_types.h @@ -45,6 +45,8 @@ typedef void (*voidFuncPtr)(void); #define __io volatile +#define ALWAYS_INLINE inline __attribute__((always_inline)) + #ifndef NULL #define NULL 0 #endif diff --git a/libmaple/timers.h b/libmaple/timers.h index 7589283..8d28f60 100644 --- a/libmaple/timers.h +++ b/libmaple/timers.h @@ -228,16 +228,16 @@ extern struct timer_dev timer_dev_table[]; /** * Initializes timer with prescale as the clock divisor. * - * @param timer Timer number. Valid values are TIMER1, TIMER2, - * TIMER3, TIMER4, and (on high-density devices) TIMER5, TIMER8. + * @param timer_num Timer number. * * @param prescale value in the range 1--65535 to use as a prescaler * for timer counter increment frequency. * + * @see timer_dev_num * @see timer_set_prescaler() * @see timer_set_mode() */ -void timer_init(timer_dev_num, uint16); +void timer_init(timer_dev_num timer_num, uint16 prescale); /** * Quickly disable all timers. Calling this function is faster than, @@ -250,34 +250,34 @@ void timer_disable_all(void); * this value is likely to be inaccurate if the counter is running * with a low prescaler. * - * @param timer the timer whose counter to return. + * @param timer_num the timer whose counter to return. * * @pre Timer has been initialized. */ -uint16 timer_get_count(timer_dev_num); +uint16 timer_get_count(timer_dev_num timer_num); /** * Sets the counter value for the given timer. * - * @param timer the timer whose counter to set. + * @param timer_num the timer whose counter to set. * * @param value the new counter value. * * @pre Timer has been initialized. */ -void timer_set_count(timer_dev_num,uint16); +void timer_set_count(timer_dev_num timer_num, uint16 value); /** * Stops the timer's counter from incrementing. Does not modify the * timer's mode or settings. * - * @param timer the timer to pause. + * @param timer_num the timer to pause. * * @see timer_resume() * * @pre Timer has been initialized. */ -void timer_pause(timer_dev_num); +void timer_pause(timer_dev_num timer_num); /** * Starts the counter for the given timer. Does not modify the @@ -285,17 +285,19 @@ void timer_pause(timer_dev_num); * first rising clock cycle after it has been re-enabled using this * function. * - * @param timer the timer to resume. + * @param timer_num the timer to resume. * * @see timer_pause() * * @pre Timer has been initialized. */ -void timer_resume(timer_dev_num); +void timer_resume(timer_dev_num timer_num); /** * Returns the prescaler for the given timer. * + * @param timer_num the timer whose prescaler to return. + * * @see timer_set_prescaler() * * @pre Timer has been initialized. @@ -308,7 +310,7 @@ uint16 timer_get_prescaler(timer_dev_num timer_num); * per clock cycle). This prescale does not take effect until the * next update event. * - * @param timer the timer whose prescaler to set. + * @param timer_num the timer whose prescaler to set. * * @param prescale the new prescaler. * @@ -331,10 +333,6 @@ uint16 timer_get_reload(timer_dev_num timer_num); * After this function returns, the timer's counter will reset to 0 * after it has reached the value max_reload. * - * @param timer the timer whose reload to set. - * - * @param max_reload the new reload value. - * * @pre Timer has been initialized. */ void timer_set_reload(timer_dev_num timer_num, uint16 max_reload); @@ -344,52 +342,32 @@ void timer_set_reload(timer_dev_num timer_num, uint16 max_reload); /** * Set the mode of an individual timer channel. * - * @param timer the timer whose channel mode to set. - * - * @param channel the channel whose mode to set (1 <= channel <= 4). - * - * @param mode the new mode value. Currently acceptable values - * include TIMER_DISABLED, TIMER_PWM, and TIMER_OUTPUTCOMPARE. Note - * that timer_disable_all() will disable all timers and all channels - * much more quickly than repeated calls to this function with mode - * TIMER_DISABLED. - * - * @see TimerMode - * * @see timer_disable_all() - * + * @see TimerMode + * @see timer_dev_num * @pre Timer has been initialized. */ -void timer_set_mode(timer_dev_num timer_num, uint8 channel_num, uint8 mode); +void timer_set_mode(timer_dev_num timer_num, uint8 channel, TimerMode mode); /** * Get the compare value for the given timer channel. * @see timer_set_compare_value() - * + * @see timer_dev_num * @pre Timer has been initialized. */ -uint16 timer_get_compare_value(timer_dev_num timer_num, uint8 channel_num); +uint16 timer_get_compare_value(timer_dev_num timer_num, uint8 channel); /** * Sets the compare value for a given timer channel. Useful for * scheduling when interrupt handlers will be called. * - * @param timer the timer whose channel compare to set. - * - * @param channel the channel whose compare to set (1 <= channel <= 4). - * - * @param compare the new compare value. This new value must be less - * than or equal to the timer's reload value. - * * @see timer_attach_interrupt() - * * @see timer_detach_interrupt() - * * @see timer_set_reload() - * + * @see timer_dev_num * @pre Timer has been initialized. */ -void timer_set_compare_value(timer_dev_num timer_num, uint8 channel_num, +void timer_set_compare_value(timer_dev_num timer_num, uint8 channel, uint16 value); /** @@ -397,44 +375,27 @@ void timer_set_compare_value(timer_dev_num timer_num, uint8 channel_num, * After this function returns, any handler attached to the given * channel will no longer be called. * - * @param timer the timer whose channel to detach the interrupt - * handler from. - * - * @param channel the channel from which to detach the interrupt handler. - * * @see timer_attach_interrupt() - * * @pre Timer has been initialized. + * @see timer_dev_num */ -void timer_detach_interrupt(timer_dev_num timer_num, uint8 channel_num); +void timer_detach_interrupt(timer_dev_num timer_num, uint8 channel); /** * Attach an interrupt handler for the given timer and channel. The - * handler will be called whenever the timer's counter reaches the - * compare value for the given timer and channel. - * - * @param timer the timer whose channel to register with an interrupt handler. - * - * @param channel the channel with which the new handler will be - * associated. timer_set_compare_value() can be used to set the value - * which the timer's counter must reach before handler is called (1 <= - * channel <= 4). - * - * @param handler the interrupt handler to call once the timer reaches - * the given channel's compare value. - * - * @pre The channel's mode must be set to TIMER_OUTPUTCOMPARE, or the - * interrupt handler will not get called. + * given ISR, handler, will be called whenever the timer's counter + * reaches the compare value for the given timer and channel. * * @see timer_set_compare_value() - * * @see timer_detach_interrupt() - * * @see timer_set_mode() - * + * @see timer_dev_num + * @see voidFuncPtr * @pre Timer has been initialized. + * @pre The channel's mode must be set to TIMER_OUTPUTCOMPARE, or the + * interrupt handler will not get called. */ -void timer_attach_interrupt(timer_dev_num timer_num, uint8 channel_num, +void timer_attach_interrupt(timer_dev_num timer_num, uint8 channel, voidFuncPtr handler); /** @@ -449,18 +410,18 @@ void timer_generate_update(timer_dev_num timer_num); /** * Turn on PWM with duty_cycle. * - * @param channel TIMERx_CHn_CCR, where x goes from 1 to NR_TIMERS, + * @param ccr TIMERx_CHn_CCR, where x goes from 1 to NR_TIMERS, * and n goes from 1 to 4. * - * @param duty_cycle 0--65535. duty_cycle=0 means always off; - * duty_cycle=65535 means always on. + * @param duty_cycle: A number between 0 and + * timer_get_compare_value(TIMERx, y), where x and y are as above. * * @pre Pin has been set to alternate function output. * * @pre Timer has been initialized. */ -static inline void timer_pwm_write_ccr(TimerCCR CCR, uint16 duty_cycle) { - *CCR = duty_cycle; +static inline void timer_pwm_write_ccr(TimerCCR ccr, uint16 duty_cycle) { + *ccr = duty_cycle; } #ifdef __cplusplus diff --git a/support/scripts/copy-to-ide b/support/scripts/copy-to-ide index 5bf52a4..c6b4c16 100755 --- a/support/scripts/copy-to-ide +++ b/support/scripts/copy-to-ide @@ -4,9 +4,7 @@ # repository. # Change this -DEST=`pwd`/../maple-ide/hardware/leaflabs/cores/maple/ - -ARCH=`uname -a` +DEST=`pwd`/../maple-ide-java/hardware/leaflabs/cores/maple FILES="LICENSE ./libmaple/*.h @@ -21,8 +19,8 @@ FILES="LICENSE ./wirish/*.cpp ./wirish/comm/*.cpp ./wirish/comm/*.h - ./support/ld/maple/ - ./support/ld/maple_native/ + ./support/ld/maple + ./support/ld/maple_native ./support/ld/libcs3-lanchon-stm32.a ./support/ld/names.inc" @@ -34,9 +32,9 @@ then exit -1 fi -echo "Then delete the old files..." -rm -r $DEST/*.c $DEST/*.cpp $DEST/*.h $DEST/*.cxx $DEST/*.ld $DEST/*.inc $DEST/*.a $DEST/maple/ $DEST/maple_native/ +echo "\nThen delete the old files..." +rm -r $DEST/*.c $DEST/*.cpp $DEST/*.h $DEST/*.cxx $DEST/*.inc $DEST/*.a $DEST/maple $DEST/maple_native -echo "Finally copy the new source files!" -cp -r $FILES $DEST +echo "\nFinally copy the new source files!" +cp -R $FILES $DEST echo "Done." diff --git a/wirish/HardwareTimer.cpp b/wirish/HardwareTimer.cpp index 92c6adf..354663e 100644 --- a/wirish/HardwareTimer.cpp +++ b/wirish/HardwareTimer.cpp @@ -221,7 +221,6 @@ HardwareTimer* getTimer(timer_dev_num timerNum) { return &Timer8; #endif default: - ASSERT(0); return 0; } } diff --git a/wirish/HardwareTimer.h b/wirish/HardwareTimer.h index c72175f..4034b1f 100644 --- a/wirish/HardwareTimer.h +++ b/wirish/HardwareTimer.h @@ -89,7 +89,7 @@ class HardwareTimer { * * Note that there is some function call overhead associated with * using this method, so using it in concert with - * HardwareTimer::resume() is not a robust way to align multiple + * HardwareTimer::pause() is not a robust way to align multiple * timers to the same count value. * * @see HardwareTimer::pause() @@ -103,7 +103,7 @@ class HardwareTimer { uint16 getPrescaleFactor(); /** - * Set the timer prescale. + * Set the timer's prescale factor. * * The prescaler acts as a clock divider to slow down the rate at * which the counter increments. @@ -155,7 +155,7 @@ class HardwareTimer { * Set the current timer count. * * Note that there is some function call overhead associated with - * callign this method, so using it is not a robust way to get + * calling this method, so using it is not a robust way to get * multiple timers to share a count value. * * @param val The new count value to set. If this value exceeds @@ -184,10 +184,6 @@ class HardwareTimer { /** * Set the given channel of this timer to the given 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! - * * @param channel Timer channel, from 1 to 4 * @param mode Mode to set */ @@ -228,24 +224,24 @@ class HardwareTimer { */ uint16 getCompare(int channel); - /** Like getCompare(1) */ + /** Equivalent to getCompare(1) */ uint16 getCompare1(); - /** Like getCompare(2) */ + /** Equivalent to getCompare(2) */ uint16 getCompare2(); - /** Like getCompare(3) */ + /** Equivalent to getCompare(3) */ uint16 getCompare3(); - /** Like getCompare(4) */ + /** Equivalent to getCompare(4) */ uint16 getCompare4(); /** * Sets the compare value for the given channel. * * When the counter reaches this value the interrupt for this - * channel will fire if channel 1 mode is TIMER_OUTPUTCOMPARE and - * an interrupt is attached. + * channel will fire if the channel mode is TIMER_OUTPUTCOMPARE + * and an interrupt is attached. * * By default, this only changes the relative offsets between * events on a single timer ("phase"); they don't control the @@ -259,32 +255,33 @@ class HardwareTimer { * few microseconds. * * @param channel the channel whose compare to set, from 1 to 4. - * @param val The compare value to set. If greater than this - * timer's overflow value, it will be truncated to the - * overflow value. + * @param compare The compare value to set. If greater than this + * timer's overflow value, it will be truncated to + * the overflow value. * * @see TimerMode * @see HardwareTimer::setChannelMode() + * @see HardwareTimer::attachInterrupt() */ void setCompare(int channel, uint16 compare); /** - * Like setCompare(1, compare). + * Equivalent to setCompare(1, compare). */ void setCompare1(uint16 compare); /** - * Like setCompare(2, compare). + * Equivalent to setCompare(2, compare). */ void setCompare2(uint16 compare); /** - * Like setCompare(3, compare). + * Equivalent to setCompare(3, compare). */ void setCompare3(uint16 compare); /** - * Like setCompare(4, compare). + * Equivalent to setCompare(4, compare). */ void setCompare4(uint16 compare); @@ -313,25 +310,25 @@ class HardwareTimer { void attachInterrupt(int channel, voidFuncPtr handler); /** - * Like attachCompareInterrupt(1, handler). + * Equivalent to attachCompareInterrupt(1, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare1Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(2, handler). + * Equivalent to attachCompareInterrupt(2, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare2Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(3, handler). + * Equivalent to attachCompareInterrupt(3, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare3Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(4, handler). + * Equivalent to attachCompareInterrupt(4, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare4Interrupt(voidFuncPtr handler); @@ -346,25 +343,25 @@ class HardwareTimer { void detachInterrupt(int channel); /** - * Like detachInterrupt(1). + * Equivalent to detachInterrupt(1). * @see HardwareTimer::detachInterrupt() */ void detachCompare1Interrupt(void); /** - * Like detachInterrupt(2). + * Equivalent to detachInterrupt(2). * @see HardwareTimer::detachInterrupt() */ void detachCompare2Interrupt(void); /** - * Like detachInterrupt(3). + * Equivalent to detachInterrupt(3). * @see HardwareTimer::detachInterrupt() */ void detachCompare3Interrupt(void); /** - * Like detachInterrupt(4). + * Equivalent to detachInterrupt(4). * @see HardwareTimer::detachInterrupt() */ void detachCompare4Interrupt(void); @@ -394,6 +391,22 @@ extern HardwareTimer Timer5; extern HardwareTimer Timer8; #endif +/** + * Get one of the pre-instantiated HardwareTimer instances, given a + * timer device number. + * + * Be careful not to pass an actual number to this function. For + * example, getTimer(1) will not return Timer1. Use a real + * timer_dev_num, e.g. TIMER1, TIMER2, etc. + * + * @param timerNum the timer device number, e.g. TIMER1. + * + * @return Pointer to the HardwareTimer instance corresponding to the + * given timer device number. If timerNum is TIMER_INVALID, returns a + * null pointer. + * + * @see timer_dev_num + */ HardwareTimer* getTimer(timer_dev_num timerNum); #endif diff --git a/wirish/comm/HardwareSPI.h b/wirish/comm/HardwareSPI.h index 03d1ea1..7241d0b 100644 --- a/wirish/comm/HardwareSPI.h +++ b/wirish/comm/HardwareSPI.h @@ -29,18 +29,23 @@ #ifndef _HARDWARESPI_H_ #define _HARDWARESPI_H_ +/** + * Defines the possible SPI communication speeds. + */ typedef enum SPIFrequency { - SPI_18MHZ = 0, - SPI_9MHZ = 1, - SPI_4_5MHZ = 2, - SPI_2_25MHZ = 3, - SPI_1_125MHZ = 4, - SPI_562_500KHZ = 5, - SPI_281_250KHZ = 6, - SPI_140_625KHZ = 7, - MAX_SPI_FREQS = 8, + SPI_18MHZ = 0, /**< 18 MHz */ + SPI_9MHZ = 1, /**< 9 MHz */ + SPI_4_5MHZ = 2, /**< 4.5 MHz */ + SPI_2_25MHZ = 3, /**< 2.25 MHZ */ + SPI_1_125MHZ = 4, /**< 1.125 MHz */ + SPI_562_500KHZ = 5, /**< 562.500 KHz */ + SPI_281_250KHZ = 6, /**< 281.250 KHz */ + SPI_140_625KHZ = 7, /**< 140.625 KHz */ + MAX_SPI_FREQS = 8, /**< The number of SPI frequencies. */ } SPIFrequency; +/* Documented by hand in docs/source/lang/api/hardwarespi.rst; if you + make any changes, make sure to update this document. */ class HardwareSPI { private: uint32 spi_num; diff --git a/wirish/ext_interrupts.h b/wirish/ext_interrupts.h index 057c0d3..304e267 100644 --- a/wirish/ext_interrupts.h +++ b/wirish/ext_interrupts.h @@ -86,7 +86,7 @@ void detachInterrupt(uint8 pin); * * @see noInterrupts() */ -static inline __attribute__((always_inline)) void interrupts() { +static ALWAYS_INLINE void interrupts() { nvic_globalirq_enable(); } @@ -100,7 +100,7 @@ static inline __attribute__((always_inline)) void interrupts() { * * @see interrupts() */ -static inline __attribute__((always_inline)) void noInterrupts() { +static ALWAYS_INLINE void noInterrupts() { nvic_globalirq_disable(); } diff --git a/wirish/io.h b/wirish/io.h index 547dc8e..2d22dcd 100644 --- a/wirish/io.h +++ b/wirish/io.h @@ -145,7 +145,7 @@ void digitalWrite(uint8 pin, uint8 value); * @return LOW or HIGH. * @see pinMode() */ -uint32 digitalRead(uint8); +uint32 digitalRead(uint8 pin); /** * Read an analog value from pin. This function blocks during ADC diff --git a/wirish/wirish_math.h b/wirish/wirish_math.h index 4156722..14614ba 100644 --- a/wirish/wirish_math.h +++ b/wirish/wirish_math.h @@ -79,8 +79,10 @@ long random(long min, long max); * @return the mapped value. */ /* TODO: profile code bloat due to inlining this */ -inline 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; +inline long map(long value, long fromStart, long fromEnd, + long toStart, long toEnd) { + return (value - fromStart) * (toEnd - toStart) / (fromEnd - fromStart) + + toStart; } #define PI 3.1415926535897932384626433832795 -- cgit v1.2.3