diff options
Diffstat (limited to 'docs/source/lang/api')
51 files changed, 3929 insertions, 0 deletions
diff --git a/docs/source/lang/api/abs.rst b/docs/source/lang/api/abs.rst new file mode 100644 index 0000000..d9f1ca3 --- /dev/null +++ b/docs/source/lang/api/abs.rst @@ -0,0 +1,48 @@ +.. highlight:: cpp + +.. _lang-abs: + + +abs() +====== + +(Macro) computes the absolute value of a number. + +Syntax +------ + +:: + + abs(x) + +Parameters +---------- + +**x**: the number. + +Returns +------- + +**x**: if **x** is greater than or equal to 0. + +**-x**: if **x** is less than 0. + +Warning +------- + +Because of the way ``abs()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + abs(a++); // avoid this - yields incorrect results + + abs(a); // use this instead - + a++; // keep other operations outside abs() + + +Arduino Compatibility +--------------------- + +Maple's implementation of ``abs()`` is compatible with Arduino. + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/analogread.rst b/docs/source/lang/api/analogread.rst new file mode 100644 index 0000000..6665a94 --- /dev/null +++ b/docs/source/lang/api/analogread.rst @@ -0,0 +1,119 @@ +.. highlight:: cpp + +.. _lang-analogread: + +.. _lang-api-analogread: + +analogRead() +============ + +Used to perform ADC conversion. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: analogRead + +Discussion +---------- + +Reads the value from the specified analog pin. The Maple boards +contain 16-channel, 12-bit analog to digital converters. This means +that a converter will map input voltages between 0 and 3.3 volts into +integer values between 0 and 4095. However, a number of factors +interfere with getting full accuracy and precision. For more +information, see :ref:`adc`. + +Before calling analogRead() on a pin, that pin must first be +configured for analog input, using :ref:`lang-pinMode`. You only have +to do this once, so it's usually done in :ref:`lang-setup`\ . + +Parameter Discussion +-------------------- + +The pin parameter is the number of the analog input pin to read from. +The pins which support analog to digital conversion have ``AIN`` +listed underneath their number on your board's silkscreen. These pin +numbers are available to your program in the :ref:`boardADCPins +<lang-board-values-adc-pins>` board-specific array. The number of +pins which are capable of analog to digital conversion on your board +is given by the ``BOARD_NR_ADC_PINS`` constant. These values are +documented for each board in the :ref:`Board Hardware Documentation +<index-boards>` pages. + +.. note:: Pin 3 is not marked ``AIN`` on the silkscreen for Maple + revisions through Rev 5; however **it does work** as an analog + input pin. + +Note +---- + +If the analog input pin is not connected to anything, the value +returned by ``analogRead()`` will fluctuate due to a number of reasons +(like the values of the other analog inputs, how close your hand is to +the board, etc.) in a "random" way. + +Example +------- + +:: + + int analogPin = 3; // Potentiometer wiper (middle terminal) connected + // to analog pin 3. outside leads to ground and +3.3V. + // You may have to change this value if your board + // cannot perform ADC conversion on pin 3. + + int val = 0; // variable to store the value read + + void setup() { + pinMode(analogPin, INPUT_ANALOG); // set up pin for analog input + } + + void loop() { + val = analogRead(analogPin); // read the input pin + SerialUSB.println(val); // print the value, for debugging with + // a serial monitor + } + +Arduino Compatibility +--------------------- + +The Arduino board contains a 6 channel (8 channels on the Mini and +Nano, 16 on the Mega), 10-bit analog to digital converter with an +input voltage range of 0V--5V. This means that it will map input +voltages between 0 and 5 volts (which is **larger** than Maple's range +of 0V-3.3V) into integer values between 0 and 1023 (which is +**smaller** than the Maple's range of 0--4095). + +This yields a theoretical resolution between readings of: 5 volts / +1024 units or .0049 volts (4.9 mV) per unit on Arduino boards, which +is larger, and thus less precise, than Maple's 0.0008 volts (0.8 mV). + +If your program expects Arduino-style 10-bit ADC, you can :ref:`right +shift <lang-bitshift>` the value of a Maple readout by 2, like so:: + + // right shift means that the result will be between 0 and 1023; + // be aware that you're losing a lot of precision if you do this + int adc_reading = analogRead(pin) >> 2; + +.. FIXME [0.1.0] Mention that Native can do analogReference() + +On the Arduino, the input range and resolution can be changed using +the `analogReference() +<http://arduino.cc/en/Reference/AnalogReference>`_ function. Because +of hardware restrictions, this function is not available on the Maple +and Maple RET6 Edition. If your inputs lie in a different voltage +range than 0V--3.3V, you'll need to bring them into that range before +using ``analogRead()``. See the :ref:`ADC reference <adc-range>` for +more information. + +See Also +-------- + +- :ref:`ADC tutorial <adc>` +- `(Arduino) Tutorial: Analog Input Pins <http://arduino.cc/en/Tutorial/AnalogInputPins>`_ + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/analogwrite.rst b/docs/source/lang/api/analogwrite.rst new file mode 100644 index 0000000..0169976 --- /dev/null +++ b/docs/source/lang/api/analogwrite.rst @@ -0,0 +1,181 @@ +.. highlight:: cpp + +.. _lang-analogwrite: + +.. _lang-api-analogwrite: + + +analogWrite() +============= + +analogWrite() is used to create a :ref:`PWM <pwm>` wave on a pin. + +.. note:: + + On the Maple, calling analogWrite() is the same as calling + :ref:`lang-pwmwrite`. We recommend writing pwmWrite() instead of + analogWrite(). + + This is because PWM is not true analog output (it's not the output + of a `DAC + <http://en.wikipedia.org/wiki/Digital-to-analog_converter>`_\ ), so + the function is very badly named. For instance, **analogWrite() + has nothing to do with** :ref:`lang-analogread`\ , which can be + confusing. + + We provide analogWrite() for the sake of compatibility with Arduino + only. + +.. contents:: Contents + :local: + +.. _lang-analogwrite-compatibility: + +Arduino Compatibility +--------------------- + +There are a few important differences between Arduino's `analogWrite() +<http://arduino.cc/en/Reference/AnalogWrite>`_ and Maple's +:ref:`lang-pwmwrite` that you should keep in mind. In each case, we +have some recommendations you can use to help converting from Arduino +to Maple. + +Difference 1: Duty cycle range is different +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The first and most important difference is that the largest possible +value for the duty cycle is much bigger on the Maple. Using Arduino's +analogWrite(), the duty cycle ranges between 0--255 (always off -- +always on)\ [#fbytemax]_\ . Using Maple's pwmWrite(), the duty cycle +ranges from 0--65,535 by default\ [#fuint16max]_\ . + +This is a good thing! The greater range of values on the Maple gives +you much more precise control over the duty cycle of your PWM output. + +If you're porting code from the Arduino and want a quick-and-dirty +fix, one solution is to :ref:`map <lang-map>` the argument to +analogWrite() into the right range:: + + // Arduino code: + analogWrite(pin, duty); + + // Becomes Maple code: + analogWrite(pin, map(duty, 0, 255, 0, 65535)); + +This will convert values in the range 0-255 to values in the range +0--65,535, which is the correct default range for all of the timers +which control PWM output. See the :ref:`timers reference <timers>` +for more information. + +Another fix is to consult your board's :ref:`pin maps <gpio-pin-maps>` +to find the timer which controls PWM on the pin you're using, then set +that timer's overflow to 255. Subsequent calls to analogWrite() +should work as on the Arduino (with the same loss of precision). +Note, however, that that affects the overflow for the **entire +timer**, so other code relying on that timer (such as any +:ref:`interrupts <lang-hardwaretimer-interrupts>` the timer controls) +will likely need to be modified as well. + +Difference 2: You must use pinMode() to set up PWM +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The second difference is that on the Maple, you **must** set up the pin +for PWM output using :ref:`lang-pinmode`\ , with argument ``PWM``. +This should just be one extra line of code in your +:ref:`lang-setup` function. Example:: + + void setup() { + // set up pin 9 for PWM + pinMode(9, PWM); + } + +This also means that you can't later call :ref:`lang-digitalread` +or :ref:`lang-digitalwrite` on that pin (unless some time in +between, you use pinMode() to reconfigure that pin for ``INPUT`` or +``OUTPUT``; see the :ref:`lang-pinmode` page for more information). + +Difference 3: No PWM on pin 10 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, +9, 11, 12, 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. + +* **Older Arduino boards** with an ATmega8 only support analogWrite() + on pins 9, 10, and 11. Maple does not support PWM on pin 10. + +In all cases, Arduino boards support PWM on pin 10, unlike Maple. We +did our best to make PWM as pin-compatible as possible; however, +circuit layout constraints prevented us from achieving perfect +compatibility. + +The "safest" pins to use for PWM output are pins 9 and 11. These pins +work on any Arduino board and on Maple. The "safe" pins, which work +on most recent Arduino boards, the Arduino Mega and the Maple, are +pins 3, 5, 6, 9, and 11. Thus, if you want your project to be as +portable as possible between Maple and Arduino, we recommend using the +"safest" pins first, then the "safe" pins, then any other pins, as +necessary. + +Difference 4: PWM frequency +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The frequency of the PWM signal (i.e., the frequency of a complete +on/off cycle) on the Arduino is approximately 490 Hz. + +On the Maple, the frequency is configurable, defaulting to about 1100 +Hz, or 1.1 KHz. This is because the PWM frequency is the frequency of +the timer which controls PWM output on the particular pin (\ +:ref:`the PWM tutorial has the details <pwm>`\ ). + +If your application definitely requires Arduino's PWM frequency, then +the steps are: + +1. Figure out which :ref:`timer <lang-hardwaretimer>` controls PWM + output on your pin (\ :ref:`your board's Timer Pin Map + <gpio-pin-maps>` is your friend here). + +2. Let's say it's timer ``n``, where ``n`` is some number. You'll + then need to put "``HardwareTimer timer(n);``" with your variables, + as described in the :ref:`HardwareTimer + <lang-hardwaretimer-getting-started>` reference. + +3. In your :ref:`lang-setup`, put "``timer.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. The important examples are :ref:`timer interrupts +<lang-hardwaretimer-interrupts>` and :ref:`PWM +<timers-pwm-conflicts>`\ . + +See Also +-------- + +- :ref:`pwm` +- :ref:`lang-pwmwrite` +- :ref:`BOARD_NR_PWM_PINS <lang-board-values-nr-pwm-pins>` +- :ref:`boardPWMPins <lang-board-values-pwm-pins>` + +.. rubric:: Footnotes + +.. [#fbytemax] This is because the value for the duty cycle on Arduino + must fit in 1 byte of memory, and an unsigned (i.e., nonnegative) + integer with size 1 byte can hold the values between 0 and 255. + +.. [#fuint16max] This is because the value for the duty cycle on the + Maple uses 2 bytes of memory, and an unsigned (i.e., nonnegative) + integer with size 2 bytes can hold the values between 0 and 65,535. + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/assert.rst b/docs/source/lang/api/assert.rst new file mode 100644 index 0000000..76330b6 --- /dev/null +++ b/docs/source/lang/api/assert.rst @@ -0,0 +1,30 @@ +.. highlight:: cpp + +.. _lang-assert: + +``ASSERT(...)`` +=============== + +ASSERT() can be very useful for basic program debugging. It accepts a +boolean; for example:: + + ASSERT(state == WAIT); + +Zero is false and any other number is true. If the boolean is true, +the assertion passes and the program continues as usual. If it is +false, the assertion fails: the program is halted, debug information +is printed to USART2, and the status LED begins to throb (it's +noticeably different from blinking). The debug information is printed +at 9600 baud and consists of the filename and line number where the +ASSERT() failed. + +Including assertions in a program increases the program size. When +using libmaple **from the command line only**, they can be disabled by +making the definition :: + + #define DEBUG_LEVEL DEBUG_NONE + +before including either wirish.h or libmaple.h. In this case, all +assertions will pass without any lost clock cycles. Note that this +will **not work in the IDE**; even with this definition, assertions +will still be enabled. diff --git a/docs/source/lang/api/attachinterrupt.rst b/docs/source/lang/api/attachinterrupt.rst new file mode 100644 index 0000000..58e4764 --- /dev/null +++ b/docs/source/lang/api/attachinterrupt.rst @@ -0,0 +1,114 @@ +.. highlight:: cpp + +.. _lang-attachinterrupt: + +attachInterrupt() +================= + +Used to specify a function to call when an :ref:`external interrupt +<external-interrupts>` occurs. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. FIXME [doxygenfunction] once Breathe knows how to get the correct +.. attachInterupt (right now it's copying from HardwareTimer), replace +.. with a doxygenfunction directive + +.. cpp:function:: void attachInterrupt(uint8 pin, voidFuncPtr handler, ExtIntTriggerMode mode) + + Registers an interrupt handler on a pin. + + The interrupt will be triggered on a given transition on the pin, + as specified by the mode parameter. The handler runs in interrupt + context. The new handler will replace whatever handler is + currently registered for the pin, if any. + + *Parameters* + + - ``pin`` - Maple pin number + + - ``handler`` - Function to run upon external interrupt trigger. + The handler should take no arguments, and have void return type. + + - ``mode`` - Type of transition to trigger on, e.g. falling, + rising, etc. + +.. doxygenenum:: ExtIntTriggerMode + +.. doxygentypedef:: voidFuncPtr + +.. note:: + + You should set the :ref:`pin mode <lang-pinmode>` of your desired + pin to an input mode (e.g. ``INPUT``, ``INPUT_PULLUP``, + ``INPUT_PULLDOWN``). + +Discussion +---------- + +Because the function will run in interrupt context, inside of it, +:ref:`lang-delay` won't work, and the value returned by +:ref:`lang-millis` will not increment. Serial data received while in +the function may be lost. You should declare as ``volatile`` any +global variables that you modify within the attached function. + +There are some limits you should be aware of if you're using +``attachInterrupt()`` with more than one pin; the :ref:`External +Interrupts <external-interrupts-exti-line>` page has more information. + +Example +------- + +The following example blinks the LED any time pin 0 changes from +``HIGH`` to ``LOW`` or vice versa. :: + + volatile int state = LOW; // must declare volatile, since it's + // modified within the blink() handler + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); + pinMode(0, INPUT); + attachInterrupt(0, blink, CHANGE); + } + + void loop() { + digitalWrite(BOARD_LED_PIN, state); + } + + void blink() { + if (state == HIGH) { + state = LOW; + } else { // state must be LOW + state = HIGH; + } + } + +In this example, the function ``blink()`` is the interrupt handler. +Whenever the state on pin 0 changes, ``blink()`` gets called. It +reacts to the change by changing the ``state`` variable to ``LOW`` if +it is ``HIGH``, and to ``HIGH`` if it is ``LOW``. It then exits, +letting the board get back to calling ``loop()``. Since ``loop()`` +sets the LED pin to whatever ``state`` is, changing the voltage on pin +0 will toggle the LED. + +Arduino Compatibility +--------------------- + +Most Arduino boards have two external interrupts: numbers 0 (on +digital pin 2) and 1 (on digital pin 3). The Arduino Mega has an +additional four: numbers 2 (pin 21), 3 (pin 20), 4 (pin 19), and 5 +(pin 18). On the Maple, you don't have to remember which interrupt +number goes with which pin -- just tell ``attachInterrupt()`` the pin +you want. + +See Also +-------- + +- :ref:`lang-detachinterrupt` +- :ref:`external-interrupts` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/bit.rst b/docs/source/lang/api/bit.rst new file mode 100644 index 0000000..3df042c --- /dev/null +++ b/docs/source/lang/api/bit.rst @@ -0,0 +1,38 @@ +.. _lang-bit: + +bit() +===== + +(Macro) Computes the value of an (unsigned) integer with the specified +bit set (``bit(0)`` is 1, ``bit(1)`` is 2, ``bit(2)`` is 4, then 8, +16, 32, etc.). + +Syntax +------ + +``bit(n)`` + +Parameters +---------- + +* **n** the bit to set. + +Value +----- + +The value of an integer with the given bit set. + +Arduino Compatibility +--------------------- + +The Maple implementation of ``bit()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`lang-bitread` +- :ref:`lang-bitwrite` +- :ref:`lang-bitset` +- :ref:`lang-bitclear` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/bitclear.rst b/docs/source/lang/api/bitclear.rst new file mode 100644 index 0000000..f487059 --- /dev/null +++ b/docs/source/lang/api/bitclear.rst @@ -0,0 +1,39 @@ +.. _lang-bitclear: + +bitClear() +========== + +(Macro) Clears (writes a 0 to) a bit of a numeric variable. + +Syntax +------ + +``bitClear(x, n)`` + +Parameters +---------- + +* **x** the numeric variable whose bit to clear + +* **n** which bit to clear, starting at 0 for the least-significant + (rightmost) bit + +Returns +------- + +Nothing. + +Arduino Compatibility +--------------------- + +The Maple implementation of ``bitClear()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`bit <lang-bit>`\ () +- :ref:`bitRead <lang-bitread>`\ () +- :ref:`bitWrite <lang-bitwrite>`\ () +- :ref:`bitSet <lang-bitset>`\ () + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/bitread.rst b/docs/source/lang/api/bitread.rst new file mode 100644 index 0000000..fd9fbbe --- /dev/null +++ b/docs/source/lang/api/bitread.rst @@ -0,0 +1,39 @@ +.. _lang-bitread: + +bitRead() +========= + +(Macro) Gets the value of a bit in a number. + +Syntax +------ + +``bitRead(x, n)`` + +Parameters +---------- + +* **x** the number from which to read the bit. + +* **n** which bit to read, starting at 0 for the least-significant + (rightmost) bit + +Value +----- + +The value of the bit (0 or 1). + +Arduino Compatibility +--------------------- + +The Maple implementation of ``bitRead`` is compatible with Arduino. + +See Also +-------- + +- :ref:`lang-bit` +- :ref:`lang-bitwrite` +- :ref:`lang-bitset` +- :ref:`lang-bitclear` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/bitset.rst b/docs/source/lang/api/bitset.rst new file mode 100644 index 0000000..83ab5f8 --- /dev/null +++ b/docs/source/lang/api/bitset.rst @@ -0,0 +1,39 @@ +.. _lang-bitset: + +bitSet() +======== + +(Macro) Sets (writes a 1 to) a bit of a numeric variable. + +Syntax +------ + +``bitSet(x, n)`` + +Parameters +---------- + +* **x** the numeric variable whose bit to set + +* **n** which bit to set, starting at 0 for the least-significant + (rightmost) bit + +Value +----- + +None. + +Arduino Compatibility +--------------------- + +The Maple implementation of bitSet is compatible with Arduino. + +See Also +-------- + +- :ref:`lang-bit` +- :ref:`lang-bitread` +- :ref:`lang-bitwrite` +- :ref:`lang-bitclear` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/bitwrite.rst b/docs/source/lang/api/bitwrite.rst new file mode 100644 index 0000000..6106545 --- /dev/null +++ b/docs/source/lang/api/bitwrite.rst @@ -0,0 +1,45 @@ +.. highlight:: cpp + +.. _lang-bitwrite: + +bitWrite() +========== + +(Macro) Writes a bit of a numeric variable. + +Syntax +------ + +:: + + bitWrite(x, n, b) + +Parameters +---------- + +**x**: the numeric variable whose bit to write. + +**n**: which bit of the number to write, starting at 0 for the +least-significant (rightmost) bit. + +**b**: the value to write to the bit (0 or 1). + +Returns +------- + +Nothing. + +Arduino Compatibility +--------------------- + +Maple's implementation of ``bitWrite()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`bit() <lang-bit>` +- :ref:`bitRead() <lang-bitRead>` +- :ref:`bitSet() <lang-bitSet>` +- :ref:`bitClear() <lang-bitClear>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/board-values.rst b/docs/source/lang/api/board-values.rst new file mode 100644 index 0000000..d944c8d --- /dev/null +++ b/docs/source/lang/api/board-values.rst @@ -0,0 +1,189 @@ +.. highlight:: cpp + +.. _lang-board-values: + +Board-Specific Values +===================== + +There are a number of board-specific values: constants or variables +which are different depending on which LeafLabs board you have. The +exact values for each board are given in your :ref:`board's hardware +documentation <index-boards>`. + +This page lists and documents the board-specific values. You should +use these when appropriate in your own programs. This will help make +it easier to share your code with other people who have different +boards. Some example usages are given :ref:`below +<lang-board-values-examples>`. + +.. contents:: Contents + :local: + +Constants +--------- + +- ``CYCLES_PER_MICROSECOND``: Number of CPU cycles per microsecond on + your board. + +- ``CLOCK_SPEED_MHZ``: Clock speed of your board, in megahertz + (MHz). This is the same as ``CYCLES_PER_MICROSECOND``. + +- ``CLOCK_SPEED_HZ``: Clock speed of your board, in hertz (Hz). This + is the same as ``CLOCK_SPEED_MHZ`` × 1,000,000. + +- ``SYSTICK_RELOAD_VAL``: Value used when reloading the :ref:`systick` + timer's counter [#fmillis]_. + +.. _lang-board-values-but: + +- ``BOARD_BUTTON_PIN``: Pin connected to the built-in button (labeled + "BUT" on your board's silkscreen). + +.. _lang-board-values-led: + +- ``BOARD_LED_PIN``: Pin connected to the built-in LED. + +- ``BOARD_NR_GPIO_PINS``: Total number of :ref:`GPIO pins <gpio>` that + are broken out to headers. Some of these might already be connected + to external hardware (like the built-in LED and button). To find + out if a pin is in use, see :ref:`boardUsesPin() + <lang-boardusespin>` (and also :ref:`boardUsedPins + <lang-board-values-used-pins>`). + +.. _lang-board-values-nr-pwm-pins: + +- ``BOARD_NR_PWM_PINS``: Total *number* of GPIO pins that can be used + for :ref:`PWM <pwm>`. The actual *pins* that can do PWM are in the + :ref:`boardPWMPins <lang-board-values-pwm-pins>` array. + +.. _lang-board-values-nr-adc-pins: + +- ``BOARD_NR_ADC_PINS``: Total number of GPIO pins that can be used + for :ref:`analog-to-digital conversion <adc>`. The actual pins that + can do ADC conversion are in the :ref:`boardADCPins + <lang-board-values-adc-pins>` array. + +.. _lang-board-values-nr-used-pins: + +- ``BOARD_NR_USED_PINS``: Total number of GPIO pins that are already + connected to some external hardware (like a built-in LED) on the + board. The actual pins that that are already used are in the + :ref:`boardUsedPins <lang-board-values-used-pins>` array. To see if + a pin is already in use, use the :ref:`boardUsesPin() + <lang-boardusespin>` function. + +.. _lang-board-values-usart: + +- :ref:`USART <usart>` (serial port) related constants: + + * ``BOARD_USART1_TX_PIN``, ``BOARD_USART2_TX_PIN``, ``BOARD_USART3_TX_PIN``: + TX pins for the 3 USARTS. + + * ``BOARD_USART1_RX_PIN``, ``BOARD_USART2_RX_PIN``, ``BOARD_USART3_RX_PIN``: + RX pins for the 3 USARTS. + + * ``BOARD_UART4_TX_PIN``, ``BOARD_UART5_TX_PIN``: TX pins for + UARTs 4 and 5 (high-density boards like Maple Native only). + + * ``BOARD_UART4_RX_PIN``, ``BOARD_UART5_RX_PIN``: RX pins for + UARTs 4 and 5 (high-density boards like Maple Native only). + + * ``BOARD_NR_USARTS``: Number of serial ports on the board. This + number includes UARTs 4 and 5 if they are available. + +- :ref:`SPI <spi>` related constants: + + * ``BOARD_SPI1_NSS_PIN``, ``BOARD_SPI1_MOSI_PIN``, + ``BOARD_SPI1_MISO_PIN``, ``BOARD_SPI1_SCK_PIN``: SPI1 + peripheral's NSS, MOSI, MISO, and SCK pins, respectively. + + * ``BOARD_SPI2_NSS_PIN``, ``BOARD_SPI2_MOSI_PIN``, + ``BOARD_SPI2_MISO_PIN``, ``BOARD_SPI2_SCK_PIN``: SPI2 + peripheral's NSS, MOSI, MISO, and SCK pins, respectively. + + * ``BOARD_SPI3_NSS_PIN``, ``BOARD_SPI3_MOSI_PIN``, + ``BOARD_SPI3_MISO_PIN``, ``BOARD_SPI3_SCK_PIN``: SPI3 + peripheral's NSS, MOSI, MISO, and SCK pins, respectively + (available on high-density devices like Maple Native and Maple + RET6 edition only). + + * ``BOARD_NR_SPI``: Number of SPI peripherals on the board. + +.. _lang-board-values-debug: + +- Debug (JTAG, SW-Debug) related constants: ``BOARD_JTMS_SWDIO_PIN``, + ``BOARD_JTCK_SWCLK_PIN``, ``BOARD_JTDI_PIN``, ``BOARD_JTDO_PIN``, + and ``BOARD_NJTRST_PIN``. + + These constants are the pin numbers for :ref:`GPIOs <gpio>` used by + the :ref:`jtag` and Serial-Wire Debug peripherals. Except for the + Maple Mini, these pins are usually reserved for special purposes by + default (i.e., they are in :ref:`boardUsedPins + <lang-board-values-used-pins>`). However, they can be used as + ordinary GPIOs if you call the :ref:`lang-disabledebugports` + function. (Be careful with this on the Maple and Maple RET6 + Edition, as writing to ``BOARD_NJTRST_PIN`` :ref:`may cause your + board to reset <maple-nrst-pb4>`\ !). + +.. _lang-board-values-pwm-pins: + +.. _lang-board-values-adc-pins: + +.. _lang-board-values-used-pins: + +Pin Arrays +---------- + +Some :ref:`arrays <lang-array>` of pin numbers are available which you +can use to find out certain important information about a given pin. + +- ``boardPWMPins``: Pin numbers of each pin capable of :ref:`PWM + <pwm>` output, using :ref:`pwmWrite() <lang-pwmwrite>`. The total + number of these pins is :ref:`BOARD_NR_PWM_PINS + <lang-board-values-nr-pwm-pins>`. + +- ``boardADCPins``: Pin numbers of each pin capable of :ref:`ADC + <adc>` conversion, using :ref:`analogRead() <lang-analogread>`. The + total number of these pins is :ref:`BOARD_NR_ADC_PINS + <lang-board-values-nr-adc-pins>`. + +- ``boardUsedPins``: Pin numbers of each pin that, by default, is used + for some special purpose by the board. The total number of these + pins is :ref:`BOARD_NR_USED_PINS <lang-board-values-nr-used-pins>`. + To check if a pin is used for a special purpose, use + :ref:`boardUsesPin() <lang-boardusespin>`. + +.. _lang-board-values-examples: + +Examples +-------- + +:ref:`BOARD_LED_PIN <lang-board-values-led>` On the Maple, the +built-in LED is connected to pin 13. On the Maple Mini, however, it +is connected to pin 33. You can write a "blinky" program that works +on both boards using :ref:`this example <lang-toggleled-example>`. + +:ref:`BOARD_BUTTON_PIN <lang-board-values-but>`: On the Maple, the +built-in button is connected to pin 38. On the Maple Mini, however, +it is connected to pin 32. :ref:`This example +<lang-waitforbuttonpress-example>` shows how you can write a program +that prints a message whenever the button is pressed which will work +on all LeafLabs boards. + +See Also +-------- + +- :ref:`lang-boardusespin` +- :ref:`lang-isbuttonpressed` +- :ref:`lang-waitforbuttonpress` +- :ref:`lang-pinmode` +- :ref:`lang-toggleled` +- :ref:`lang-analogread` +- :ref:`lang-pwmwrite` +- :ref:`lang-enabledebugports` +- :ref:`lang-disabledebugports` + +.. rubric:: Footnotes + +.. [#fmillis] In order for :ref:`lang-millis` to work properly, this + must be ``CYCLES_PER_MICROSECOND`` × 1,000 - 1. diff --git a/docs/source/lang/api/boardusespin.rst b/docs/source/lang/api/boardusespin.rst new file mode 100644 index 0000000..126c4a0 --- /dev/null +++ b/docs/source/lang/api/boardusespin.rst @@ -0,0 +1,27 @@ +.. highlight:: cpp + +.. _lang-boardusespin: + +boardUsesPin() +============== + +Each LeafLabs board connects some pins to external hardware. The most +important examples of this are the pins connected to the built-in LED +and button. You can check if a board uses a particular pin using this +function. + +Library Documentation +--------------------- + +.. doxygenfunction:: boardUsesPin + +See Also +-------- + +- :ref:`Board-specific values <lang-board-values>` +- :ref:`boardUsedPins <lang-board-values-used-pins>` +- :ref:`BOARD_LED_PIN <lang-board-values-led>` +- :ref:`toggleLED() <lang-toggleled>` +- :ref:`BOARD_BUTTON_PIN <lang-board-values-but>` +- :ref:`isButtonPressed() <lang-isbuttonpressed>` +- :ref:`waitForButtonPress() <lang-waitforbuttonpress>` diff --git a/docs/source/lang/api/constants.rst b/docs/source/lang/api/constants.rst new file mode 100644 index 0000000..6f69dfe --- /dev/null +++ b/docs/source/lang/api/constants.rst @@ -0,0 +1,318 @@ +.. _lang-constants: + +Constants +========= + +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: + +.. _lang-constants-bool: + +Boolean Constants +----------------- + +There are two constants used to represent truth and falsity: ``true``, +and ``false``. + +.. _lang-constants-false: + +false +^^^^^ + +``false`` is the false ``bool`` value. An integer which is 0 evaluates +to ``false`` as a boolean. + +.. _lang-constants-true: + +true +^^^^ + +``true`` is the true ``bool`` value. As an integer, ``true`` is often +said to be 1. This is correct in the sense that ``true`` evaluates to +1 as an integer. However, any integer which is *non-zero* is ``true`` +as a :ref:`bool <lang-booleanvariables>`. So -1, 2 and -200 are all +"true", in the sense that these numbers are treated the same as +``true`` in a boolean context. + +Note that the ``true`` and ``false`` constants are typed in lowercase; +unlike e.g. ``HIGH``, ``LOW``, ``INPUT``, and ``OUTPUT`` (which are +described below). + +.. _lang-pin-levels: + +Pin Levels: 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 the pin is set to ``INPUT`` or ``OUTPUT``. When a +pin is configured as an ``INPUT`` (using :ref:`pinMode() +<lang-pinmode>`), and read with :ref:`digitalRead() +<lang-digitalread>`, the microcontroller will report ``HIGH`` if a +voltage of 3 volts or more is present at the pin. + +When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to +``HIGH`` with :ref:`digitalWrite() <lang-digitalwrite>`, the pin is at +3.3 volts. In this state it can *source* current, e.g. light an LED +that is connected through a series resistor to ground, or to another +pin configured as an output and set to ``LOW``. + +.. _lang-constants-low: + +LOW +^^^ + +The meaning of ``LOW`` also has a different meaning depending on +whether a pin is set to ``INPUT`` or ``OUTPUT``. When a pin is +configured as an ``INPUT`` with :ref:`pinMode() <lang-pinmode>`, and +read with :ref:`digitalRead() <lang-digitalread>`, the microcontroller +will report ``LOW`` if a voltage of 2 volts or less is present at the +pin. + +When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to +``LOW`` with :ref:`digitalWrite() <lang-digitalwrite>`, the +microcontroller will attempt to keep that pin's voltage at 0 V. In this +state it can *sink* current, e.g. light an LED that is connected +through a series resistor to +3.3 V, or to another pin configured as an +output, and set to ``HIGH``. + +Pin Modes +--------- + +Digital pins can be used in a variety of modes. The basic modes, +``INPUT`` and ``OUTPUT``, have been introduced above. Changing a pin +from ``INPUT`` TO ``OUTPUT`` with :ref:`pinMode() <lang-pinmode>` +drastically changes the electrical behavior of the pin. + +This section describes the basic digital pin modes (``INPUT`` and +``OUTPUT``) only. For a detailed description of all possible pin +modes, see the :ref:`pinMode() <lang-pinmode>` reference page. + +.. _lang-constants-input: + +INPUT +^^^^^ + +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 very few demans on circuit that they are connected +to. This makes them useful for reading a sensor, but not powering an +LED. + +.. _lang-constants-output: + +OUTPUT +^^^^^^ + +Pins configured as ``OUTPUT`` with :ref:`pinMode() <lang-pinmode>` are +said to be in a low-impedance state. This means that they can provide +a substantial amount of current to other circuits. 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. + +Pins configured as outputs can also be damaged or destroyed if short +circuited to either ground or power supplies. The amount of current +provided by a 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, an integer constant is treated as a (signed) +:ref:`int <lang-int>`, but you can change this with the U and L +modifiers (see :ref:`below <lang-constants-integers-u-l>`). You can +specify negative numbers by putting a minus sign in front, like +``-123``. + +Normally, integer constants are treated as base 10 (decimal) integers, +but special notation (formatters) may be used to enter numbers in +other bases. These are explained 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. You shouldn't use them +in new programs. + +.. _lang-constants-integers-dec: + +**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. + +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. Binary +literals are indicated by the prefix ``0b``. + +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 +literals are indicated by the prefix ``0``. + +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 + treat it as an octal number. + +.. _lang-constants-integers-hex: + +**Hexadecimal** (or "hex") is base sixteen. Valid characters are 0 +through 9 and letters A through F; A has the value 10, B is 11, up to +F, which is 15. Hex values are indicated by the prefix ``0x``. A-F +can be typed in upper or lower case (a-f). + +For example, the hexadecimal constant ``0x101`` is two hundred fifty +seven: 1×16\ :sup:`2` + 0×16\ :sup:`1` + 1×16\ :sup:`0` = 257. + +The hexadecimal constant ``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: + +U and L Suffixes +^^^^^^^^^^^^^^^^ + +By default, an integer constant is treated as an :ref:`int <lang-int>` +(and must be in the int type's :ref:`range limits +<lang-int-overflow>`). To specify an integer constant with another +data type, follow it with: + +- a ``u`` or ``U`` to interpret the constant as an unsigned value. + For example, ``33U`` is an :ref:`unsigned int <lang-unsignedint>`. + +- an ``l`` or ``L`` to interpret the constant as a long value. For + example, ``100000L`` is a :ref:`long <lang-long>`. On the Maple, + ``long`` is just a synonym for ``int``. + +- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an + :ref:`unsigned long <lang-unsignedlong>`. On the Maple, ``unsigned + long`` is just a synonym for ``unsigned int``. + +- an ``ll`` or ``LL`` to interpret the constant as a :ref:`long long + <lang-longlong>` value. + +- a ``ull`` or ``ULL`` to interpret the constant as an :ref:`unsigned + long long <lang-unsignedlonglong>`. + +.. _lang-constants-fp: + +Floating-Point Constants +------------------------ + +A floating point constant is any number which includes a decimal +point. For instance, ``3.0`` is a floating-point constant for the +number 3. By default, a floating-point constant is a :ref:`double +<lang-double>`. In order for the constant to be interpreted as a +:ref:`float <lang-float>`, you can write ``f`` directly after it. For +example, ``3.0f`` is a floating-point constant 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: + + +.. list-table:: + :header-rows: 1 + + * - Floating-point constant + - Evaluates to + - Alternate expression + + * - ``10.0`` + - 10 + - + + * - ``2.34E5`` + - 2.34×10\ :sup:`5` + - ``234000.0`` + + * - ``67e-12`` + - 67.0×10\ :sup:`-12` + - ``0.000000000067`` + +.. _lang-constants-board: + +Board-Specific Constants +------------------------ + +There are several :ref:`board-specific constants <lang-board-values>` +whose value depends on which LeafLabs board you have. If you use +them, it will help make sure that your code will work well on all +LeafLabs boards, not just the one you have. This will make it easier +to share your code with others. + +For example, the pin number connected to the board's built-in LED is +different on the different boards, but the board-specific constant +:ref:`BOARD_LED_PIN <lang-board-values-led>` will always be the +correct value for each board. + +See Also +-------- + +- :ref:`pinMode() <lang-pinmode>` +- :ref:`Boolean Variables <lang-booleanvariables>` +- :ref:`#define <lang-define>` +- :ref:`int <lang-int>` +- :ref:`unsigned int <lang-unsignedint>` +- :ref:`long <lang-long>` +- :ref:`unsigned long <lang-unsignedlong>` +- :ref:`long long <lang-longlong>` +- :ref:`unsigned long long <lang-unsignedlonglong>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` +- :ref:`Board-Specific Values <lang-board-values>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/constrain.rst b/docs/source/lang/api/constrain.rst new file mode 100644 index 0000000..28af1e3 --- /dev/null +++ b/docs/source/lang/api/constrain.rst @@ -0,0 +1,68 @@ +.. highlight:: cpp + +.. _lang-constrain: + +constrain() +=========== + +(Macro) Constrains a number to be within a range. + +Syntax +------ + +:: + + constrain(x, a, b) + + +Parameters +---------- + +**x**: the number to constrain + +**a**: the lower end of the range + +**b**: the upper end of the range + +Returns +------- + +**x**: if **x** is between **a** and **b** + +**a**: if **x** is less than **a** + +**b**: if **x** is greater than **b** + +Example +------- + +:: + + // limits range of sensor values to between 10 and 150: + sensVal = constrain(sensVal, 10, 150); + + +Warning +------- + +Because of the way ``constrain()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + constrain(x,a++,b); // avoid this - yields incorrect results + + constrain(x,a,b); // use this instead- + a++; // keep other math outside constrain() + +Arduino Compatibility +--------------------- + +Maple's implementation of ``constrain()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`min() <lang-min>` +- :ref:`max() <lang-max>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/cos.rst b/docs/source/lang/api/cos.rst new file mode 100644 index 0000000..c340f09 --- /dev/null +++ b/docs/source/lang/api/cos.rst @@ -0,0 +1,30 @@ +.. _lang-cos: + +cos() +===== + +Calculates the cosine of an angle. + +Library Documentation +--------------------- + +.. doxygenfunction:: cos + +Arduino Compatibility +--------------------- + +The Maple ``cos()`` implementation is compatible with Arduino. + +Note that the Maple implementation comes from `newlib +<http://sourceware.org/newlib/>`_\ , while Arduino's is that of +`avr-libc <http://avr-libc.nongnu.org/>`_\ . + +See Also +-------- + +- :ref:`sin() <lang-sin>` +- :ref:`tan() <lang-tan>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/delay.rst b/docs/source/lang/api/delay.rst new file mode 100644 index 0000000..30bd436 --- /dev/null +++ b/docs/source/lang/api/delay.rst @@ -0,0 +1,69 @@ +.. highlight:: cpp + +.. _lang-delay: + +delay() +======= + +Pauses the program for at least a given number of milliseconds. (There +are 1000 milliseconds in a second.) + +Library Documentation +--------------------- + +.. doxygenfunction:: delay + + +Discussion +---------- + +While it is easy to create a blinking LED with the ``delay()`` +function, and many sketches use short delays for such tasks as switch +debouncing, the use of ``delay()`` in a sketch has significant +drawbacks. No other reading of sensors, mathematical calculations, or +pin manipulation can go on during the delay function, so in effect, it +brings most other activity to a halt. For alternative approaches to +controlling timing see the :ref:`millis() <lang-millis>` function +and the "Blink Without Delay" sketch cited :ref:`below +<lang-delay-seealso>`\ . More knowledgeable programmers usually +avoid the use of ``delay()`` for timing of events longer than tens of +milliseconds, unless the sketch is very simple. + +Certain things *do* go on while the ``delay()`` function is +controlling the STM32 chip, however, because the delay function does +not disable interrupts. Serial communication that appears at the RX +pin is recorded, PWM (see :ref:`pwmWrite() <lang-pwmwrite>`\ ) values +and pin states are maintained, and :ref:`interrupts +<lang-attachinterrupt>` will work as they should. + + +Example +------- + +:: + + void setup() { + // set up the built-in LED pin for output: + pinMode(BOARD_LED_PIN, OUTPUT); + } + + void loop() { + digitalWrite(BOARD_LED_PIN, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(BOARD_LED_PIN, LOW); // sets the LED off + delay(1000); // waits for a second + } + +.. _lang-delay-seealso: + +See Also +-------- + +- :ref:`millis() <lang-millis>` +- :ref:`micros() <lang-micros>` +- :ref:`delayMicroseconds() <lang-delayMicroseconds>` +- (Arduino) `Blink Without Delay + <http://arduino.cc/en/Tutorial/BlinkWithoutDelay>`_ example (works + unmodified on Maple) + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/delaymicroseconds.rst b/docs/source/lang/api/delaymicroseconds.rst new file mode 100644 index 0000000..7078660 --- /dev/null +++ b/docs/source/lang/api/delaymicroseconds.rst @@ -0,0 +1,62 @@ +.. highlight:: cpp + +.. _lang-delaymicroseconds: + +delayMicroseconds() +=================== + +Pauses the program for the amount of time (in microseconds) +specified as parameter. There are a thousand microseconds in a +millisecond, and a million microseconds in a second. + +Library Documentation +--------------------- + +.. doxygenfunction:: delayMicroseconds + + +Example +------- + +The following example configures pin number 8 to work as an output +pin, and sends a train of pulses with a period of roughly 100 +microseconds:: + + int outPin = 8; + + void setup() { + pinMode(outPin, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(outPin, HIGH); // sets the pin on + delayMicroseconds(50); // pauses for 50 microseconds + digitalWrite(outPin, LOW); // sets the pin off + delayMicroseconds(50); // pauses for 50 microseconds + } + + +Caveats and Known Issues +------------------------ + +The longest time ``delayMicroseconds()`` can delay is bounded by its +argument type and the STM32 clock rate to be (2^32 - 1) / 12 +microseconds, or less than 6 minutes. For longer pauses, use of +:ref:`lang-delay` is possible. + +Arduino Compatibility +--------------------- + +While we have made every effort we could to ensure that the timing of +``delayMicroseconds()`` is as accurate as possible, we cannot +guarantee it will behave as the Arduino implementation down to the +microsecond, especially for smaller values of ``us``. + +See Also +-------- + +- :ref:`millis <lang-millis>` +- :ref:`micros <lang-micros>` +- :ref:`delay <lang-delay>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/detachinterrupt.rst b/docs/source/lang/api/detachinterrupt.rst new file mode 100644 index 0000000..6eb8e53 --- /dev/null +++ b/docs/source/lang/api/detachinterrupt.rst @@ -0,0 +1,43 @@ +.. _lang-detachinterrupt: + +detachInterrupt() +================= + +Used to disable an interrupt specified with +:ref:`lang-attachinterrupt`\ . + +Library Documentation +--------------------- + +.. FIXME [Breathe] once we can get the correct detachInterrupt(), +.. replace with doxygenfunction. + +.. cpp:function:: void detachInterrupt(uint8 pin) + + Disable any registered external interrupt on the given pin. + + *Parameters* + + - ``pin`` Maple pin number + +Arduino Compatibility +--------------------- + +There is one important difference between the Maple version of +detachInterrupt and the Arduino version. On the Maple, the argument +to ``detachInterrupt()`` is the *pin* on which the interrupt is +attached, while on the Arduino, the argument is the *interrupt +number*, which is different from the pin the interrupt is enabled on. + +If you're calling this function, you've already called +:ref:`lang-attachinterrupt` to set up your interrupt handler, so +just call ``detachInterrupt()`` with the same pin argument you gave to +``attachInterrupt()``. + +See Also +-------- + +- :ref:`attachInterrupt() <lang-attachInterrupt>` +- :ref:`external-interrupts` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/digitalread.rst b/docs/source/lang/api/digitalread.rst new file mode 100644 index 0000000..03ccd7f --- /dev/null +++ b/docs/source/lang/api/digitalread.rst @@ -0,0 +1,51 @@ +.. highlight:: cpp + +.. _lang-digitalread: + +digitalRead() +============= + +Reads the value from a specified digital pin, either :ref:`HIGH +<lang-constants-high>` or :ref:`LOW <lang-constants-low>`. + +Library Documentation +--------------------- + +.. doxygenfunction:: digitalRead + +Discussion +---------- + +If the pin isn't connected to anything, ``digitalRead()`` can return +either HIGH or LOW (and this will change in a way that seems random). + +Example +------- + +The following example turns the LED on or off when the button is pressed:: + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); + pinMode(BOARD_BUTTON_PIN, INPUT); + } + + void loop() { + int val = digitalRead(BOARD_BUTTON_PIN); // reads the input pin + togglePin(BOARD_LED_PIN); + } + +Arduino Compatibility +--------------------- + +The Maple version of ``digitalRead()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`BOARD_BUTTON_PIN <lang-board-values-but>` +- :ref:`lang-isButtonPressed` +- :ref:`lang-pinmode` +- :ref:`lang-digitalWrite` +- :ref:`lang-togglepin` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/digitalwrite.rst b/docs/source/lang/api/digitalwrite.rst new file mode 100644 index 0000000..bae8db9 --- /dev/null +++ b/docs/source/lang/api/digitalwrite.rst @@ -0,0 +1,56 @@ +.. highlight:: cpp + +.. _lang-digitalwrite: + +digitalWrite() +============== + +Write a :ref:`HIGH <lang-constants-high>` or a :ref:`LOW +<lang-constants-low>` value to a pin configured as :ref:`OUTPUT +<lang-constants-output>`. + +Library Documentation +--------------------- + +.. doxygenfunction:: digitalWrite + +Discussion +---------- + +If the pin has been configured as an ``OUTPUT`` with :ref:`pinMode() +<lang-pinmode>` its voltage will be set to the corresponding value: +3.3V for ``HIGH``, and 0V (ground) for ``LOW``. + +Because it is soldered to an LED and resistor in series, your board's +:ref:`BOARD_LED_PIN <lang-board-values-led>` will respond slightly +more slowly as an output than the other pins. + +Example +------- + +The following example sets the built-in LED pin to ``HIGH``, makes a +one-second-long delay, sets the pin back to ``LOW``, and delays again, +causing a blinking pattern (you could also use +:ref:`lang-toggleled`):: + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(BOARD_LED_PIN, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(BOARD_LED_PIN, LOW); // sets the LED off + delay(1000); // waits for a second + } + +See Also +-------- + +- :ref:`pinMode <lang-pinmode>` +- :ref:`digitalRead <lang-digitalread>` +- :ref:`BOARD_LED_PIN <lang-board-values-led>` +- :ref:`lang-toggleled` +- :ref:`lang-togglepin` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/disabledebugports.rst b/docs/source/lang/api/disabledebugports.rst new file mode 100644 index 0000000..283cdbf --- /dev/null +++ b/docs/source/lang/api/disabledebugports.rst @@ -0,0 +1,33 @@ +.. highlight:: cpp + +.. _lang-disabledebugports: + +disableDebugPorts() +=================== + +Used to disable the JTAG and Serial Wire debugging ports. + +Library Documentation +--------------------- + +.. doxygenfunction:: disableDebugPorts + +Example +------- + + :: + + void setup() { + disableDebugPorts(); + } + + void loop() { + // Now you can use the debug port pins (the pins on the JTAG + // header on the Maple) as ordinary pins. + } + +See Also +-------- + +- :ref:`lang-enabledebugports` +- :ref:`Important erratum on Maple pin 43 <maple-nrst-pb4>` diff --git a/docs/source/lang/api/enabledebugports.rst b/docs/source/lang/api/enabledebugports.rst new file mode 100644 index 0000000..bee2b0a --- /dev/null +++ b/docs/source/lang/api/enabledebugports.rst @@ -0,0 +1,31 @@ +.. highlight:: cpp + +.. _lang-enabledebugports: + +enableDebugPorts() +================== + +Used to enable the JTAG and Serial Wire debugging ports. + +Library Documentation +--------------------- + +.. doxygenfunction:: enableDebugPorts + +Example +------- + + :: + + void setup() { + enableDebugPorts(); + // Now you can debug using JTAG and SW-Debug + } + + void loop() { + } + +See Also +-------- + +* :ref:`lang-disabledebugports` diff --git a/docs/source/lang/api/hardwarespi.rst b/docs/source/lang/api/hardwarespi.rst new file mode 100644 index 0000000..a44a65f --- /dev/null +++ b/docs/source/lang/api/hardwarespi.rst @@ -0,0 +1,170 @@ +.. highlight:: cpp + +.. _lang-hardwarespi: + +HardwareSPI +=========== + +This page describes how to use the built-in SPI ports. It does not +describe the SPI protocol itself. For more information about SPI, see +the :ref:`SPI reference <spi>`. + +.. contents:: Contents + :local: + +Getting Started +--------------- + +In order to get started, you'll first need to define a ``HardwareSPI`` +variable, which you'll use to control the SPI port. Do this by +putting the line "``HardwareSPI spi(number);``" with your variables, +where ``number`` is the SPI port's number. + +Here's an example (we'll fill in :ref:`setup() <lang-setup>` and +:ref:`loop() <lang-loop>` later):: + + // Use SPI port number 1 + HardwareSPI spi(1); + + void setup() { + // Your setup code + } + + void loop() { + // Do stuff with SPI + } + +Turning the SPI Port On +----------------------- + +Now it's time to turn your SPI port on. Do this with the ``begin()`` +function (an example is given below). + +.. FIXME [Breathe] Output doesn't include the class; fix & submit pull req + +.. doxygenfunction:: HardwareSPI::begin + +.. note:: If you are using SPI port 3 (on a board that supports it; + not all do); you'll need to call :ref:`lang-disabledebugports` + before calling ``begin()``. + +The speed at which the SPI port communicates is configured using a +``SPIFrequency`` value: + +.. FIXME [0.1.0] Breathe's enum output is enormous; shrink & submit pull req + +.. doxygenenum:: SPIFrequency + +.. note:: Due to hardware issues, you can't use the frequency + ``SPI_140_625KHz`` with SPI port 1. + +The "mode" value determines the clock phase and polarity, like so: + +.. doxygenenum:: spi_mode + +You'll need to determine the correct values for ``frequency``, +``bitOrder``, and ``mode`` yourself, by consulting the datasheet for +the device you're communicating with. Continuing our example from +before, we'll add a call to ``begin()`` to our ``setup()``:: + + // Use SPI port number 1 + HardwareSPI spi(1); + + void setup() { + // Turn on the SPI port + spi.begin(SPI_18MHZ, MSBFIRST, 0); + } + + void loop() { + // Do stuff with SPI + } + +If you call ``begin()`` with no arguments (as in "``spi.begin();``"), +it's the same as if you wrote "``spi.begin(SPI_1_125MHZ, MSBFIRST, +0);``". + +Communicating Over SPI +---------------------- + +Now that you've got your SPI port set up, it's time to start +communicating. You can send data using ``HardwareSPI::write()``, +receive data using ``HardwareSPI::read()``, and do both using +``HardwareSPI::transfer()``. + +.. cpp:function:: void HardwareSPI::write(byte data) + + Send a single byte of data. + + **Parameters**: + + - ``data``: Byte to send + +.. cpp:function:: byte HardwareSPI::read() + + Get the next available, unread byte. If there aren't any unread + bytes, this function will wait until one is received. + +.. cpp:function:: byte HardwareSPI::transfer(byte data) + + Send a byte, then return the next byte received. + + **Parameters:** + + - ``data``: Byte to send + + **Returns:** Next unread byte + +Continuing our example from before, let's send a number over SPI and +print out whatever we get back over :ref:`lang-serialusb`:: + + // Use SPI port number 1 + HardwareSPI spi(1); + + void setup() { + // Turn on the SPI port + spi.begin(SPI_18MHZ, MSBFIRST, 0); + } + + void loop() { + // Send 245 over SPI, and wait for a response. + spi.write(245); + byte response = spi.read(); + // Print out the response received. + SerialUSB.print("response: "); + SerialUSB.println(response, DEC); + } + +HardwareSPI Class Reference +--------------------------- + +There are a number of other things you can accomplish with your +``spi`` object. A full function listing follows. + +.. doxygenclass:: HardwareSPI + :members: HardwareSPI, begin, beginSlave, end, read, write, transfer + +Deprecated Functions +-------------------- + +The following functions are defined for now, but they have been +deprecated, and will be removed in a future Maple IDE release. You +shouldn't use them in new programs, and you should change any of your +programs which do use them to the up-to-date functions discussed +above. + +.. 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. diff --git a/docs/source/lang/api/hardwaretimer.rst b/docs/source/lang/api/hardwaretimer.rst new file mode 100644 index 0000000..b919e52 --- /dev/null +++ b/docs/source/lang/api/hardwaretimer.rst @@ -0,0 +1,345 @@ +.. highlight:: cpp + +.. _lang-hardwaretimer: + +HardwareTimer +============= + +This page describes how to control the built-in timers. It does not +describe how the timers work on your board. For more information on +that, the :ref:`timers reference <timers>`. + +.. warning:: The timer interface is still taking shape, and is + expected to change significantly between releases. Because of + that, the functionality described in this page shouldn't be + considered stable. + + If you want a timer API that will be consistent between releases of + the Maple IDE, your best bet for now is to use the low-level + support in :ref:`libmaple-timer`. + +.. contents:: Contents + :local: + +.. _lang-hardwaretimer-getting-started: + +Getting Started +--------------- + +You'll first need to define a ``HardwareTimer`` variable, which you'll +use to control the timer. Do this by putting the line +"``HardwareTimer timer(number);``" with your variables, where +``number`` is the timer's number. + +Here's an example (we'll fill in :ref:`setup() <lang-setup>` and +:ref:`loop() <lang-loop>` later):: + + // Use timer 1 + HardwareTimer timer(1); + + void setup() { + // Your setup code + } + + void loop() { + // ... + } + +Configuring the Prescaler and Overflow +-------------------------------------- + +After defining your ``timer`` variable, you'll probably want to +configure how fast your timer's counter changes (using the prescaler) +and when it gets reset to zero (using the overflow value). You can do +that with the ``setPrescaleFactor()`` and ``setOverflow()`` functions. + +.. _lang-hardwaretimer-setprescalefactor: + +.. doxygenfunction:: HardwareTimer::setPrescaleFactor + :no-link: + +.. _lang-hardwaretimer-setoverflow: + +.. doxygenfunction:: HardwareTimer::setOverflow + :no-link: + +For example:: + + // Use timer 1 + HardwareTimer timer(1); + + void setup() { + timer.setPrescaleFactor(5); + timer.setOverflow(255); + } + + void loop() { + // ... + } + +You may also find the ``setPeriod()`` function useful: + +.. _lang-hardwaretimer-setperiod: + +.. doxygenfunction:: HardwareTimer::setPeriod + :no-link: + +For example:: + + // Use timer 1 + HardwareTimer timer(1); + + void setup() { + // Have the timer repeat every 20 milliseconds + int microseconds_per_millisecond = 1000; + timer.setPeriod(20 * microseconds_per_millisecond); + } + + void loop() { + // ... + } + +.. _lang-hardwaretimer-interrupts: + +Using Timer Interrupts +---------------------- + +.. TODO [0.2.0] Improve the interrupts section, here or in timers.rst + +In order to use timer interrupts, we recommend the following sequence: + +* Pause the timer. +* Configure the prescaler and overflow. +* Pick a timer channel to handle the interrupt and set the channel's + :ref:`mode <lang-hardwaretimer-timermode>` to ``TIMER_OUTPUT_COMPARE``. +* Set the channel compare value appropriately (this controls what counter value, + from 0 to overflow - 1). If you just want to make the interrupt fire once + every time the timer overflows, and you don't care what the timer count is, + the channel compare value can just be 1. +* Attach an interrupt handler to the channel. +* Refresh the timer. +* Resume the timer. + +Here are two complete examples. + +**LED blink**: This example blinks the built-in LED without doing +anything in ``loop()``. :: + + #define LED_RATE 500000 // in microseconds; should give 0.5Hz toggles + + // We'll use timer 2 + HardwareTimer timer(2); + + void setup() { + // Set up the LED to blink + pinMode(BOARD_LED_PIN, OUTPUT); + + // Pause the timer while we're configuring it + timer.pause(); + + // Set up period + timer.setPeriod(LED_RATE); // in microseconds + + // Set up an interrupt on channel 1 + timer.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE); + timer.setCompare(TIMER_CH1, 1); // Interrupt 1 count after each update + timer.attachInterrupt(1, handler_led); + + // Refresh the timer's count, prescale, and overflow + timer.refresh(); + + // Start the timer counting + timer.resume(); + } + + void loop() { + // Nothing! It's all in the handler_led() interrupt: + } + + void handler_led(void) { + toggleLED(); + } + +**Racing Counters**: This example shows how to use multiple timers at +the same time. :: + + int count3 = 0; + int count4 = 0; + + // We'll use timers 3 and 4 + HardwareTimer timer3(3); + HardwareTimer timer4(4); + + void setup() { + // Set up the button for input + pinMode(BOARD_BUTTON_PIN, INPUT_PULLUP); + + // Set up timers to add 1 to their counts each time + // their interrupts fire. + timer3.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE); + timer4.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE); + timer3.pause(); + timer4.pause(); + timer3.setCount(0); + timer4.setCount(0); + timer3.setOverflow(30000); + timer4.setOverflow(30000); + timer3.setCompare(TIMER_CH1, 1000); // somewhere in the middle + timer4.setCompare(TIMER_CH1, 1000); + timer3.attachCompare1Interrupt(handler3); + timer4.attachCompare1Interrupt(handler4); + timer3.refresh(); + timer4.refresh(); + timer3.resume(); + timer4.resume(); + } + + void loop() { + // Display the running counts + SerialUSB.print("Count 3: "); + SerialUSB.print(count3); + SerialUSB.print("\t\tCount 4: "); + SerialUSB.println(count4); + + // While the button is held down, pause timer 4 + for (int i = 0; i < 1000; i++) { + if (digitalRead(BOARD_BUTTON_PIN)) { + timer4.pause(); + } else { + timer4.resume(); + } + delay(1); + } + } + + void handler3(void) { + count3++; + } + + void handler4(void) { + count4++; + } + +``HardwareTimer`` Class Reference +--------------------------------- + +This section gives a full listing of the capabilities of a +``HardwareTimer``. + +.. doxygenclass:: HardwareTimer + :members: HardwareTimer, pause, resume, getPrescaleFactor, setPrescaleFactor, getOverflow, setOverflow, getCount, setCount, setPeriod, setMode, getCompare, setCompare, attachInterrupt, detachInterrupt, refresh + +.. _lang-hardwaretimer-timermode: + +.. doxygenenum:: timer_mode + +Deprecated Functionality +------------------------ + +The following functionality exists for now, but it has been +deprecated, and will be removed in a future Maple IDE release. You +shouldn't use it in new programs, and you should change any of your +programs which do use them to use the up-to-date features described +above. + +The ``TimerMode`` type from previous releases has been renamed +``timer_mode``. The mode ``TIMER_OUTPUTCOMPARE`` is still present, +but will be removed in a future release. Use ``TIMER_OUTPUT_COMPARE`` +instead. + +.. cpp:function:: void HardwareTimer::attachCompare1Interrupt(voidFuncPtr handler) + + Use ``attachInterrupt(1, handler)`` instead. + +.. cpp:function:: void HardwareTimer::attachCompare2Interrupt(voidFuncPtr handler) + + Use ``attachInterrupt(2, handler)`` instead. + +.. cpp:function:: void HardwareTimer::attachCompare3Interrupt(voidFuncPtr handler) + + Use ``attachInterrupt(3, handler)`` instead. + +.. cpp:function:: void HardwareTimer::attachCompare4Interrupt(voidFuncPtr handler) + + Use ``attachInterrupt(4, handler)`` instead. + +.. _lang-hardwaretimer-setchannelmode: + +.. cpp:function:: void HardwareTimer::setChannelMode(int channel, timer_mode mode) + + Use ``setMode(channel, mode)`` instead. + +.. cpp:function:: void HardwareTimer::setChannel1Mode(timer_mode mode) + + Use ``setMode(1, mode)`` instead. + +.. cpp:function:: void HardwareTimer::setChannel2Mode(timer_mode mode) + + Use ``setMode(2, mode)`` instead. + +.. cpp:function:: void HardwareTimer::setChannel3Mode(timer_mode mode) + + Use ``setMode(3, mode)`` instead. + +.. cpp:function:: void HardwareTimer::setChannel4Mode(timer_mode mode) + + Use ``setMode(4, mode)`` instead. + +.. cpp:function:: uint16 HardwareTimer::getCompare1() + + Use ``getCompare(1, mode)`` instead. + +.. cpp:function:: uint16 HardwareTimer::getCompare2() + + Use ``getCompare(2, mode)`` instead. + +.. cpp:function:: uint16 HardwareTimer::getCompare3() + + Use ``getCompare(3, mode)`` instead. + +.. cpp:function:: uint16 HardwareTimer::getCompare4() + + Use ``getCompare(4, mode)`` instead. + +.. cpp:function:: void HardwareTimer::setCompare1(uint16 compare) + + Use ``setCompare(1, compare)`` instead. + +.. cpp:function:: void HardwareTimer::setCompare2(uint16 compare) + + Use ``setCompare(2, compare)`` instead. + +.. cpp:function:: void HardwareTimer::setCompare3(uint16 compare) + + Use ``setCompare(3, compare)`` instead. + +.. cpp:function:: void HardwareTimer::setCompare4(uint16 compare) + + Use ``setCompare(4, compare)`` instead. + +.. cpp:function:: void HardwareTimer::detachCompare1Interrupt() + + Use ``detachInterrupt(1)`` instead. + +.. cpp:function:: void HardwareTimer::detachCompare2Interrupt() + + Use ``detachInterrupt(2)`` instead. + +.. cpp:function:: void HardwareTimer::detachCompare3Interrupt() + + Use ``detachInterrupt(3)`` instead. + +.. cpp:function:: void HardwareTimer::detachCompare4Interrupt() + + Use ``detachInterrupt(4)`` instead. + +.. cpp:function:: void HardwareTimer::generateUpdate() + + Use ``refresh()`` instead. + +In previous releases, to interact with a particular timers, you would +use one of the predefined ``HardwareTimer`` instances ``Timer1``, +``Timer2``, ``Timer3``, and ``Timer4``. These are still available for +now, but they are also deprecated, and will be removed in a future +release. As detailed in :ref:`lang-hardwaretimer-getting-started`, +you should define your own ``HardwareTimer`` variables. diff --git a/docs/source/lang/api/highbyte.rst b/docs/source/lang/api/highbyte.rst new file mode 100644 index 0000000..4cb6f9b --- /dev/null +++ b/docs/source/lang/api/highbyte.rst @@ -0,0 +1,55 @@ +.. highlight:: cpp + +.. _lang-highbyte: + +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 + value. It makes sense to call this the "high" byte on a 16-bit + ``int`` microcontroller like the Atmel chips on Arduinos, but it + makes no sense at all on a 32-bit microcontroller like the STM32s + in the Maple line. + + In short: we provide this so that existing Arduino code works as + expected, but **strongly discourage its use** in new programs. + +Syntax +------ + +:: + + highByte(x) + +Parameters +---------- + +**x**: a value of any integral type. + +Returns +------- + +Second lowest byte in **x**. + +Example +------- + +:: + + int x = 0xDEADBEEF; + SerialUSB.println(x, HEX); // prints "BE" + +Arduino Compatibility +--------------------- + +The Maple version of ``highByte()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`lowByte() <lang-lowbyte>` + +.. include:: /arduino-cc-attribution.txt 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() <lang-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() <lang-nointerrupts>` +- :ref:`attachInterrupt() <lang-attachinterrupt>` +- :ref:`detachInterrupt() <lang-detachinterrupt>` +- :ref:`Timers reference <timers>` +- :ref:`Timer API <lang-hardwaretimer>` +- :ref:`External interrupts <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..8c350b9 --- /dev/null +++ b/docs/source/lang/api/isbuttonpressed.rst @@ -0,0 +1,20 @@ +.. _lang-isbuttonpressed: + +isButtonPressed() +================= + +Check whether the board's built-in button (labeled BUT on the +silkscreen) is pressed. The pin number of the built-in button is +given by the constant ``BOARD_BUTTON_PIN``. + +Library Documentation +--------------------- + +.. doxygenfunction:: isButtonPressed + +See Also +-------- + +- :ref:`Board-specific values <lang-board-values>` +- :ref:`BOARD_BUTTON_PIN <lang-board-values-but>` +- :ref:`lang-waitforbuttonpress` diff --git a/docs/source/lang/api/loop.rst b/docs/source/lang/api/loop.rst new file mode 100644 index 0000000..c2a5097 --- /dev/null +++ b/docs/source/lang/api/loop.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-loop: + +loop() +====== + +After creating a :ref:`setup() <lang-setup>` function, which +initializes your sketch, the ``loop()`` function gets called +repeatedly, allowing your program to change and respond. Use it to +actively control your Maple board. + +Example +------- + +:: + + int buttonPin = 38; + + // setup initializes serial and the button pin + void setup() { + SerialUSB.begin(); + pinMode(buttonPin, INPUT); + } + + // loop() checks the button pin each time it executes, + // and will print 'H' if it is pressed, 'L' otherwise + void loop() { + if (digitalRead(buttonPin) == HIGH) { + SerialUSB.println('H'); + } else { + SerialUSB.println('L'); + } + + delay(1000); + } + +See Also +-------- + +- :ref:`setup() <lang-setup>` + + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/lowbyte.rst b/docs/source/lang/api/lowbyte.rst new file mode 100644 index 0000000..c513711 --- /dev/null +++ b/docs/source/lang/api/lowbyte.rst @@ -0,0 +1,25 @@ +.. _lang-lowbyte: + +lowByte() +========= + +Extracts the low-order (rightmost) byte of a variable (e.g. a +word). + +Syntax +------ + +lowByte(x) + +Parameters +---------- + +**x**: a value of any type. However, if a non-integral type is used, +the results will be strange. + +Returns +------- + +The low byte's value (this will be between 0 and 255). + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/map.rst b/docs/source/lang/api/map.rst new file mode 100644 index 0000000..69661a0 --- /dev/null +++ b/docs/source/lang/api/map.rst @@ -0,0 +1,68 @@ +.. highlight:: cpp + +.. _lang-map: + +map() +===== + +Re-maps a number from one range to another. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: map + +Discussion +---------- + +``map()`` does not constrain values to within the range, because +out-of-range values are sometimes intended and useful. The +:ref:`constrain() <lang-constrain>` macro may be used either before or +after this function, if limits to the ranges are desired. + +Note that the "lower bounds" of either range may be larger or smaller +than the "upper bounds" so that ``map()`` may be used to reverse a +range of numbers; for example:: + + y = map(x, 1, 50, 50, 1); + +The function also handles negative numbers well, so that this +example :: + + y = map(x, 1, 50, 50, -100); + +is also valid. + +The ``map()`` function uses integer math (its arguments and return +values all have type :ref:`long <lang-long>`), so it will not generate +fractions, when the math might indicate that it should do so. +Fractional remainders are truncated, and are not rounded or averaged. + +Example +------- + +:: + + /* Map an ADC reading (12 bits) to 16-bit PWM (0 to 65,535) */ + + void setup() { + pinMode(0, INPUT_ANALOG); + pinMode(9, PWM); + } + + void loop() { + int val = analogRead(0); + val = map(val, 0, 4095, 0, 65535); + analogWrite(9, val); + } + + +See Also +-------- + +- :ref:`constrain() <lang-constrain>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/max.rst b/docs/source/lang/api/max.rst new file mode 100644 index 0000000..d356f08 --- /dev/null +++ b/docs/source/lang/api/max.rst @@ -0,0 +1,64 @@ +.. highlight:: cpp + +.. _lang-max: + +max() +===== + +(Macro) Calculates the maximum of two numbers. + +Syntax +------ + +:: + + max(x, y) + +Parameters +---------- + +**x**: the first number; may be any number or numeric expression. + +**y**: the second number; may be any number or numeric expression. + + +Returns +------- + +The larger of the two parameter values. + +Example +------- + +:: + + sensVal = max(senVal, 20); // assigns sensVal to the larger of sensVal or 20 + // (effectively ensuring that it is at least 20) + +.. note:: Perhaps counter-intuitively, max() is often used to + constrain the lower end of a variable's range, while :ref:`min() + <lang-min>` is used to constrain the upper end of the range. + +Warning +------- + +Because of the way ``max()`` is implemented, avoid using other +functions inside the parentheses. It may lead to incorrect results:: + + max(a--, 0); // avoid this - yields incorrect results + + a--; // use this instead - + max(a, 0); // keep other operations outside max() + +Arduino Compatibility +--------------------- + +The Maple implementation of ``max()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`min() <lang-min>` +- :ref:`constrain() <lang-constrain>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/micros.rst b/docs/source/lang/api/micros.rst new file mode 100644 index 0000000..de85303 --- /dev/null +++ b/docs/source/lang/api/micros.rst @@ -0,0 +1,46 @@ +.. highlight:: cpp + +.. _lang-micros: + +micros() +======== + +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 +--------------------- + +.. doxygenfunction:: micros + +Example +------- + +:: + + unsigned int time; + + void setup() { + } + + void loop() { + SerialUSB.print("Time: "); + time = micros(); + // prints time since program started + SerialUSB.println(time); + // wait a second so as not to send massive amounts of data + delay(1000); + } + +See Also +-------- + +- :ref:`millis() <lang-millis>` +- :ref:`delay() <lang-delay>` +- :ref:`delayMicroseconds() <lang-delaymicroseconds>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/millis.rst b/docs/source/lang/api/millis.rst new file mode 100644 index 0000000..b6fbf55 --- /dev/null +++ b/docs/source/lang/api/millis.rst @@ -0,0 +1,52 @@ +.. highlight:: cpp + +.. _lang-millis: + +millis() +======== + +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 int time; + + void setup() { + } + + void loop() { + SerialUSB.print("Time: "); + time = millis(); + // prints time since program started + SerialUSB.println(time); + + // wait a second so as not to send massive amounts of data + delay(1000); + } + +Tip +--- + +Since the return value for ``millis()`` is an :ref:`unsigned long +<lang-unsignedlong>`, overflow errors may occur if you try to do math +with other data types, such as :ref:`chars <lang-char>`. + +See Also +-------- + +- :ref:`micros <lang-micros>` +- :ref:`delay <lang-delay>` +- :ref:`delayMicroseconds <lang-delaymicroseconds>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/min.rst b/docs/source/lang/api/min.rst new file mode 100644 index 0000000..3307105 --- /dev/null +++ b/docs/source/lang/api/min.rst @@ -0,0 +1,65 @@ +.. highlight:: cpp + +.. _lang-min: + +min() +===== + +(Macro) Calculates the minimum of two numbers. + +Syntax +------ + +:: + + min(x,y) + +Parameters +---------- + +**x**: the first number; may be any number or numeric expression. + +**y**: the second number; may be any number or numeric expression. + +Returns +------- + +The smaller of the two numbers. + +Example +------- + +:: + + sensVal = min(sensVal, 100); // assigns sensVal to the smaller of sensVal or 100 + // ensuring that it never gets above 100. + + +.. note:: Perhaps counter-intuitively, max() is often used to + constrain the lower end of a variable's range, while min() is used + to constrain the upper end of the range. + + +Warning +------- + +Because of the way ``min()`` is implemented, avoid using other +functions inside the parentheses. It may lead to incorrect results:: + + min(a++, 100); // avoid this - yields incorrect results + + a++; // use this instead - + min(a, 100); // keep other operations outside min() + +Arduino Compatibility +--------------------- + +The Maple version of ``min()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`max() <lang-max>` +- :ref:`constrain() <lang-constrain>` + +.. include:: /arduino-cc-attribution.txt 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() <lang-interrupts>` +- :ref:`attachInterrupt() <lang-attachinterrupt>` +- :ref:`detachInterrupt() <lang-detachinterrupt>` +- :ref:`Timers reference <timers>` +- :ref:`Timer API <lang-hardwaretimer>` +- :ref:`External interrupts <external-interrupts>` + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/api/pinmode.rst b/docs/source/lang/api/pinmode.rst new file mode 100644 index 0000000..643e26e --- /dev/null +++ b/docs/source/lang/api/pinmode.rst @@ -0,0 +1,80 @@ +.. highlight:: cpp + +.. _lang-pinmode: + +pinMode() +========= + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pinMode + +.. _lang-pinmode-wiringpinmode: + +.. doxygenenum:: WiringPinMode + +Discussion +---------- + +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 +------- + +This example uses pinMode() to set up the pin connected to the +built-in LED as an output. Once this is done, +:ref:`lang-digitalwrite` can be used to turn the pin ``HIGH`` and +``LOW``, which turn the LED on and off. + +:: + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); // sets the LED pin as output + } + + void loop() { + digitalWrite(BOARD_LED_PIN, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(BOARD_LED_PIN, LOW); // sets the LED off + delay(1000); // waits for a second + } + +Arduino Compatibility +--------------------- + +.. TODO check out Arduino vs. Maple static discilpline cutoffs to +.. ensure accuracy of following: + +On Maple, pinMode() supports the ``INPUT`` and ``OUTPUT`` modes in the +same way as Arduino (however, remember that the Maple, as a 3.3V +device, will only drive 3.3V to an ``OUTPUT`` pin that has been set +``HIGH``, instead of 5V like on Arduino). + +``INPUT_ANALOG`` and ``PWM`` modes were added because the Maple +doesn't separate the analog and digital pins the same way Arduino +does. Unlike on Arduino, you **must call** pinMode() to set up a pin +for these purposes before a call to, e.g., :ref:`lang-analogRead`. +This should only add a few lines to your :ref:`lang-setup` function. + +.. TODO [0.1.0] 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. + +See Also +-------- + +- :ref:`lang-board-values` +- :ref:`lang-constants` +- :ref:`lang-digitalwrite` +- :ref:`lang-digitalread` +- :ref:`gpio` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/pow.rst b/docs/source/lang/api/pow.rst new file mode 100644 index 0000000..219a866 --- /dev/null +++ b/docs/source/lang/api/pow.rst @@ -0,0 +1,20 @@ +.. _lang-pow: + +pow() +===== + +Calculates the value of a number raised to a power. + +Library Documentation +--------------------- + +.. doxygenfunction:: pow + +See Also +-------- + +- :ref:`sqrt() <lang-sqrt>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/pwmwrite.rst b/docs/source/lang/api/pwmwrite.rst new file mode 100644 index 0000000..5cc112e --- /dev/null +++ b/docs/source/lang/api/pwmwrite.rst @@ -0,0 +1,61 @@ +.. highlight:: cpp + +.. _lang-pwmwrite: + +pwmWrite() +========== + +Writes a :ref:`PWM wave <pwm>` to a pin. You can use this to make an +LED get brighter or dimmer, control a servomotor, etc. After a call to +pwmWrite(), the pin will output a steady square wave with the given +duty cycle. You can change the duty cycle later by calling pwmWrite() +again with the same pin and a different duty. + +The pins which support PWM have ``PWM`` listed underneath their number +on your board's silkscreen. These pin numbers are available to your +program in the :ref:`boardPWMPins <lang-board-values-pwm-pins>` +board-specific array. The number of pins which are capable of PWM on +your board is given by the ``BOARD_NR_PWM_PINS`` constant. These +values are documented for each board in the :ref:`Board Hardware +Documentation <index-boards>` pages. + +The Arduino function :ref:`analogWrite() <lang-analogwrite>` is an +alias for ``pwmWrite()``, but it is badly named, and its use is +discouraged. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pwmWrite + +Example +------- + +Sets the output to the LED proportional to the value read from the +potentiometer:: + + int analogPin = 3; // potentiometer connected to analog pin 3 + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); // sets the LED pin as output + + pinMode(analogPin, INPUT_ANALOG); // sets the potentiometer pin as + // analog input + } + + void loop() { + int val = analogRead(analogPin); // read the input pin + + pwmWrite(BOARD_LED_PIN, val * 16); // analogRead values go from 0 + // to 4095, pwmWrite values + // from 0 to 65535, so scale roughly + } + +See Also +-------- + +- :ref:`Maple PWM tutorial <pwm>` +- :ref:`boardPWMPins <lang-board-values-pwm-pins>` diff --git a/docs/source/lang/api/random.rst b/docs/source/lang/api/random.rst new file mode 100644 index 0000000..9875ee6 --- /dev/null +++ b/docs/source/lang/api/random.rst @@ -0,0 +1,71 @@ +.. highlight:: cpp + +.. _lang-random: + +random() +======== + +The ``random()`` function generates pseudo-random numbers. + +Library Documentation +--------------------- + +.. FIXME [Breathe] use doxygenfunction when possible + +.. cpp:function:: random(long max) + + Same as a call to ``random(0, max)``. + +.. cpp:function:: random(long min, long max) + + Generate a pseudo-random number with given lower and upper bounds. + + *Parameters* + + - ``min`` - Lower bound on the returned value, inclusive + - ``max`` - Upper bound on the returned value, exclusive + + *Returns*: A pseudo-random number in the range [min, max). + +Discussion +---------- + +If it is important for a sequence of values generated by +:ref:`random() <lang-random>` to differ, on subsequent executions of a +sketch, use :ref:`randomSeed() <lang-randomseed>` to initialize the +random number generator with a fairly random input, such as +:ref:`analogRead() <lang-analogread>` on an unconnected pin. + +Conversely, it can occasionally be useful to use pseudorandom +sequences that repeat exactly. This can be accomplished by calling +``randomSeed()`` with a fixed number, before starting the random +sequence. + +Example +------- + +The following sketch initializes the random seed based on an :ref:`ADC +<adc>` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +<ide-serial-monitor>` each time it is run:: + + long randNumber; + + void setup() { + pinMode(0, INPUT_ANALOG); + randomSeed(analogRead(0)); + } + + void loop() { + randNumber = random(300); + SerialUSB.println(randNumber); + + delay(50); + } + +See Also +-------- + +- :ref:`randomSeed() <lang-randomseed>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/randomseed.rst b/docs/source/lang/api/randomseed.rst new file mode 100644 index 0000000..ca7b75f --- /dev/null +++ b/docs/source/lang/api/randomseed.rst @@ -0,0 +1,60 @@ +.. highlight:: cpp + +.. _lang-randomseed: + +randomSeed() +============ + +``randomSeed()`` initializes the `pseudorandom number generator +<http://en.wikipedia.org/wiki/Pseudorandom_number_generator>`_, +causing it to start at an arbitrary point in its random sequence. +This sequence, while very long, and random, is always the same. + + +Library Documentation +--------------------- + +.. doxygenfunction:: randomSeed + +Discussion +---------- + +If it is important for a sequence of values generated by +:ref:`random() <lang-random>` to differ, on subsequent executions of a +sketch, use ``randomSeed()`` to initialize the random number generator +with a fairly random input, such as :ref:`analogRead() +<lang-analogread>` on an unconnected pin. + +Conversely, it can occasionally be useful to use pseudorandom +sequences that repeat exactly. This can be accomplished by calling +``randomSeed()`` with a fixed number, before starting the random +sequence. + +Example +------- + +The following sketch initializes the random seed based on an :ref:`ADC +<adc>` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +<ide-serial-monitor>` each time it is run:: + + long randNumber; + + void setup() { + pinMode(0, INPUT_ANALOG); + randomSeed(analogRead(0)); + } + + void loop() { + randNumber = random(300); + SerialUSB.println(randNumber); + + delay(50); + } + +See Also +-------- + +- :ref:`random() <lang-random>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/serial.rst b/docs/source/lang/api/serial.rst new file mode 100644 index 0000000..e287015 --- /dev/null +++ b/docs/source/lang/api/serial.rst @@ -0,0 +1,282 @@ +.. FIXME [0.0.13] This doesn't include UART4/5, or USART6 +.. highlight:: cpp + +.. _lang-serial: + +Serial Ports (``Serial1``, ``Serial2``, ``Serial3``) +==================================================== + +This page describes how to use the built-in serial ports (also known +as USARTs). For more information about serial ports, see +:ref:`usart`. + +.. contents:: Contents + :local: + +Getting Started +--------------- + +First, decide which serial port you wish to use, and :ref:`connect its +pins to the device you're communicating with <usart-circuit>`. (The TX +and RX pins for a serial port are labeled on your board's silkscreen; +for example, serial port 2 has pins labeled "TX2" and "RX2"). + +The variable for controlling a serial port is the word ``Serial``, +plus the serial port's number. For example, you can control serial +port 1 with the variable ``Serial1``, serial port 2 with ``Serial2``, +and so on. + +In order to get started using your serial port, you'll first need to +turn it on. Do this by calling your serial port's ``begin()`` +function, giving it the baud rate you wish it to communicate at. If +you're not sure what baud rate to use, 9600 is a safe (although slow) +value to try. Put this call to ``begin()`` in your :ref:`lang-setup`, +like in the following example:: + + void setup() { + // 9600 is the baud rate to use. The baud rate determines how + // fast the communication goes. + Serial2.begin(9600); + } + + void loop() { + // Communicate using Serial2 here + } + +Communicating Over Serial +------------------------- + +Now that your serial port is set up, it's time to start communicating. + +One common use for serial ports is to print strings and other +debugging information to a computer. You can print numbers or strings +using ``print()`` and ``println()``, like this:: + + void printSomeInformation() { + Serial2.print("First, print this string. Then print a number: "); + Serial2.print(42); + Serial2.print(". You can print floating point values, too: "); + Serial2.print(3.14); + Serial2.println(". Using println() instead of print() ends the line."); + Serial2.println("This sentence starts on a new line."); + } + +This sort of communication can go both ways: you can send characters +from a computer to a serial port as well. You can check how many +characters are waiting for you to read using the ``available()`` +function, and read them out one at a time using ``read()``. The +following example program uses these functions to "echo" back anything +sent to ``Serial2``:: + + void setup() { + Serial2.begin(9600); + } + + void echoCharacter() { + // Check to see if we have received any information. numUnread + // will hold the number of bytes we've received, but haven't + // looked at yet. + int numUnread = Serial2.available(); + + // numUnread > 0 means that there are some unread bytes waiting + if (numUnread > 0) { + // Read a single byte out: + byte b = Serial2.read(); + // And then print it back: + Serial2.print(b); + } + } + + void loop() { + echoCharacter(); + } + +Function Reference +------------------ + +This section gives a full listing of functions available for use with +serial ports. + +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:: void HardwareSerial::begin(unsigned int baud) + + Set up a ``HardwareSerial`` object for communications. This method + must be called before attempting to use the ``HardwareSerial`` + object (typically, you call this in your :ref:`setup() + <lang-setup>` function). + +.. cpp:function:: void HardwareSerial::end() + + Disables the USART associated with this object, allowing any + associated communication pins to be used for other purposes. + +.. cpp:function:: unsigned int HardwareSerial::available() + + Returns the number of bytes available for reading. + +.. cpp:function:: unsigned char HardwareSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + <HardwareSerial::available>`), the call will block until one + becomes available. + +.. cpp:function:: void HardwareSerial::flush() + + Throw away the contents of the serial port's receiver (RX) buffer. + That is, clears any buffered characters, so that the next character + read is guaranteed to be new. + +.. cpp:function:: void HardwareSerial::print(unsigned char b) + + Print the given byte over the USART. + +.. cpp:function:: void HardwareSerial::print(char c) + + Print the given character over the USART. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: void HardwareSerial::print(const char *str) + + Print the given null-terminated string over the USART. + +.. cpp:function:: void 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:: void HardwareSerial::print(unsigned int n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: void 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:: void HardwareSerial::print(unsigned long n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: void 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:: void HardwareSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. + +.. _lang-serial-println: + +.. cpp:function:: void HardwareSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: void HardwareSerial::println() + + Prints ``"\r\n"`` over the USART. + +.. cpp:function:: void HardwareSerial::write(unsigned char ch) + + Sends one character over the USART. This function is currently + blocking. + + 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:: void 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:: void HardwareSerial::write(void *buf, unsigned int size) + + 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. + +.. cpp:function:: int HardwareSerial::txPin() + + Return the number of the TX (transmit) pin. + +.. cpp:function:: int HardwareSerial::rxPin() + + Return the number of the RX (receive) pin. + +Arduino Compatibility Note +-------------------------- + +Unlike the Arduino, none of the Maple's serial ports is connected to +the USB port on the Maple board. If you want to communicate using the +built-in USB port, use :ref:`SerialUSB <lang-serialusb>` instead. You +will need an additional USB-to-serial adapter to communicate between a +USART and your computer. + +.. FIXME [0.1.0] port these examples over + +.. Examples +.. -------- + +.. - `ASCII Table <http://arduino.cc/en/Tutorial/ASCIITable>`_ +.. - `Dimmer <http://arduino.cc/en/Tutorial/Dimmer>`_ +.. - `Graph <http://arduino.cc/en/Tutorial/Graph>`_ +.. - `Physical Pixel <http://arduino.cc/en/Tutorial/PhysicalPixel>`_ +.. - `Virtual Color Mixer <http://arduino.cc/en/Tutorial/VirtualColorMixer>`_ +.. - `Serial Call Response <http://arduino.cc/en/Tutorial/SerialCallResponse>`_ +.. - `Serial Call Response ASCII <http://arduino.cc/en/Tutorial/SerialCallResponseASCII>`_ + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/serialusb.rst b/docs/source/lang/api/serialusb.rst new file mode 100644 index 0000000..ed466f2 --- /dev/null +++ b/docs/source/lang/api/serialusb.rst @@ -0,0 +1,242 @@ +.. highlight:: cpp + +.. _lang-serialusb: + +``SerialUSB`` +============= + +Used for communication between the Maple board and a computer. + +.. contents:: Contents + :local: + +Introduction +------------ + +In addition to three :ref:`serial ports <lang-serial>`, the Maple's +STM32 microprocessor includes a dedicated USB peripheral. This +peripheral is used to emulate a regular serial port for use as a +terminal. The emulated terminal is relatively slow; 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 ``SerialUSB`` on a computer, your + program will run much slower than if it is being monitored or + totally disconnected (run off of a battery). + + You can avoid this behavior by :ref:`deciphering the port status + using the DTR and RTS line status <lang-serialusb-safe-print>` (the + behavior of these control lines is platform dependent and we no + longer interpret them by default). + +Library Documentation +--------------------- + +The ``SerialUSB`` object is an instance of the ``USBSerial`` class, +which is documented in this section. This means that you can use any +of these functions by writing +``SerialUSB.functionName(arguments...)``. For example, to print the +message "hello, world!", you can write ``USBSerial.println("hello, +world!")``. + +.. cpp:class:: USBSerial + + Emulated serial-over-USB class. ``SerialUSB`` is the predefined + (singleton) instance. + +.. _lang-serialusb-begin: + +.. 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. 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 + <troubleshooting-perpetual-bootloader>`. + +.. cpp:function:: unsigned int USBSerial::available() + + Returns the number of bytes available for reading. + +.. _lang-serialusb-read: + +.. cpp:function:: unsigned char USBSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + <USBSerial::available>`), the call will block until one + becomes available. + +.. cpp:function:: USBSerial::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: + +.. 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 BOARD_LED_PIN + + void setup() { + /* Set up the LED to blink */ + pinMode(LED_PIN, OUTPUT); + } + + void loop() { + // LED will stay off if we are disconnected, and will blink + // quickly if USB is unplugged (battery power, 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() take a long time, + // 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 will be fast 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/api/setup.rst b/docs/source/lang/api/setup.rst new file mode 100644 index 0000000..1e8e3b8 --- /dev/null +++ b/docs/source/lang/api/setup.rst @@ -0,0 +1,29 @@ +.. highlight:: cpp + +.. _lang-setup: + +setup() +======= + +The ``setup()`` function is called when a sketch starts. Use it to +initialize :ref:`variables <lang-variables>`, :ref:`pin modes +<lang-pinmode>`, start using :ref:`libraries <libraries>`, etc. The +``setup()`` function will only run once, after each power-up or reset +of the Maple board. + +Example +------- + +:: + + int buttonPin = 38; + + void setup() { + pinMode(buttonPin, INPUT); + } + + void loop() { + // ... + } + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/shiftout.rst b/docs/source/lang/api/shiftout.rst new file mode 100644 index 0000000..1d9ba12 --- /dev/null +++ b/docs/source/lang/api/shiftout.rst @@ -0,0 +1,99 @@ +.. highlight:: cpp + +.. _lang-shiftout: + +shiftOut() +========== + +Shift out a byte of data, one bit at a time. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: shiftOut + +Discussion +---------- + +This is a software implementation. There is also a hardware :ref:`SPI +<spi>` library available which will be faster and consume less CPU +cycles than this function. + +Note that the ``dataPin`` and ``clockPin`` must already be configured +to :ref:`OUTPUT <lang-constants-output>` mode by a call to +:ref:`pinMode() <lang-pinmode>`. + +Also note that since shiftOut() outputs 1 byte (8 bits) at a time, it +requires multiple steps to output values larger than 255. + +Examples +-------- + +To use these examples, replace ``dataPin`` and ``clockPin`` with the +numbers of the pins you want to use:: + + /* MSBFIRST example */ + + uint16 data = 500; + // shift out high byte + shiftOut(dataPin, clockPin, MSBFIRST, (data >> 8)); + // shift out low byte + shiftOut(dataPin, clockPin, MSBFIRST, data); + + /* LSBFIRST serial */ + + data = 500; + // shift out low byte + shiftOut(dataPin, clockPin, LSBFIRST, data); + // shift out high byte + shiftOut(dataPin, clockPin, LSBFIRST, (data >> 8)); + +Arduino Tutorial Example +------------------------ + +This Arduino example runs unmodified on the Maple. For accompanying +circuit, see the `tutorial on controlling a 74HC595 shift register +<http://arduino.cc/en/Tutorial/ShiftOut>`_. + +:: + + //**************************************************************// + // 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/api/sin.rst b/docs/source/lang/api/sin.rst new file mode 100644 index 0000000..3e28c0b --- /dev/null +++ b/docs/source/lang/api/sin.rst @@ -0,0 +1,31 @@ +.. _lang-sin: + +sin() +===== + +Calculates the `sine <http://en.wikipedia.org/wiki/Sine>`_ of an +angle. + +Library Documentation +--------------------- + +.. doxygenfunction:: sin + +Arduino Compatibility +--------------------- + +The Maple version of ``sin()`` is compatible with Arduino. + +Note that the Maple implementation comes from `newlib +<http://sourceware.org/newlib/>`_\ , while Arduino's is that of +`avr-libc <http://avr-libc.nongnu.org/>`_\ . + +See Also +-------- + +- :ref:`cos <lang-cos>` +- :ref:`tan <lang-tan>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/sq.rst b/docs/source/lang/api/sq.rst new file mode 100644 index 0000000..96724d3 --- /dev/null +++ b/docs/source/lang/api/sq.rst @@ -0,0 +1,45 @@ +.. highlight:: cpp + +.. _lang-sq: + +sq() +==== + +(Macro) computes the square of a number. + +Syntax +------ + +:: + + sq(a) + +Parameters +---------- + +**a**: the number. + +Returns +------- + +**a** squared (**a** × **a**). + +Warning +------- + +Because of the way ``sq()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + b = sq(a++); // avoid this - yields incorrect results + + b = sq(a); // use this instead - + a++; // keep other operations outside sq() + + +Arduino Compatibility +--------------------- + +Maple's implementation of ``sq()`` is compatible with Arduino. + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/tan.rst b/docs/source/lang/api/tan.rst new file mode 100644 index 0000000..b1aed31 --- /dev/null +++ b/docs/source/lang/api/tan.rst @@ -0,0 +1,30 @@ +.. _lang-tan: + +tan() +===== + +Calculates the tangent of an angle. + +Library Documentation +--------------------- + +.. doxygenfunction:: tan + +Arduino Compatibility +--------------------- + +The Maple version of ``tan()`` is compatible with Arduino. + +Note that the Maple implementation comes from `newlib +<http://sourceware.org/newlib/>`_\ , while Arduino's is that of +`avr-libc <http://avr-libc.nongnu.org/>`_\ . + +See Also +-------- + +- :ref:`sin <lang-sin>` +- :ref:`cos <lang-cos>` +- :ref:`float <lang-float>` +- :ref:`double <lang-double>` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/toggleled.rst b/docs/source/lang/api/toggleled.rst new file mode 100644 index 0000000..cad347f --- /dev/null +++ b/docs/source/lang/api/toggleled.rst @@ -0,0 +1,37 @@ +.. highlight:: cpp + +.. _lang-toggleled: + +toggleLED() +=========== + +*Toggle* the built-in LED: switch it from off to on, or on to off. + +Library Documentation +--------------------- + +.. doxygenfunction:: toggleLED + +Example +------- + +.. _lang-toggleled-example: + +This example sets up the board's LED pin for output, then toggles the +LED every 100 milliseconds:: + + void setup() { + pinMode(BOARD_LED_PIN, OUTPUT); + } + + void loop() { + toggleLED(); + delay(100); + } + + +See Also +-------- + +- :ref:`BOARD_LED_PIN <lang-board-values-led>` +- :ref:`togglePin() <lang-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 <lang-constants-high>` +to :ref:`LOW <lang-constants-low>`, or from LOW to HIGH. + +Library Documentation +--------------------- + +.. doxygenfunction:: togglePin + +See Also +-------- + +- :ref:`toggleLED() <lang-toggleled>` diff --git a/docs/source/lang/api/volatile.rst b/docs/source/lang/api/volatile.rst new file mode 100644 index 0000000..1b72897 --- /dev/null +++ b/docs/source/lang/api/volatile.rst @@ -0,0 +1,65 @@ +.. highlight:: cpp + +.. _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. + +Declaring a variable ``volatile`` is a directive to the compiler. The +compiler is software which translates your C++ code into the machine +code, which are the real instructions for the STM32 chip in the +Maple. (The particular compiler we provide for use with the Maple is a +version of :ref:`GCC <arm-gcc>`). + +Specifically, it directs the compiler to read the variable's value +fresh every time it is used, rather than "backing up" the value and +reading from its backup copy. (Compilers often "back up" a variable's +value in RAM into a storage location called a *register*; this is done +for efficiency). + +A variable should be declared ``volatile`` whenever its value can be +changed by something beyond the control of the code section in which +it appears, such as an :ref:`external interrupt +<external-interrupts>`. (The only place that this is likely to occur +in most programs is inside of code called by interrupts). + +Example +------- + +:: + + // toggles LED when interrupt pin changes state + + int pin = 13; + volatile int state = LOW; + + void setup() { + pinMode(pin, OUTPUT); + attachInterrupt(0, blink, CHANGE); + } + + void loop() { + digitalWrite(pin, state); + } + + void blink() { + if (state == HIGH) { + state = LOW; + } else { + // state must be HIGH + state = HIGH; + } + } + +See Also +-------- + +- :ref:`External Interrupts <external-interrupts>` +- :ref:`lang-attachinterrupt` +- :ref:`lang-detachinterrupt` + +.. include:: /arduino-cc-attribution.txt diff --git a/docs/source/lang/api/waitforbuttonpress.rst b/docs/source/lang/api/waitforbuttonpress.rst new file mode 100644 index 0000000..0e0fbaf --- /dev/null +++ b/docs/source/lang/api/waitforbuttonpress.rst @@ -0,0 +1,43 @@ +.. highlight:: cpp + +.. _lang-waitforbuttonpress: + +waitForButtonPress() +==================== + +Wait for the board's built-in button to be pressed, possibly with +timeout. The button is labeled "BUT" on the board's silkscreen. Its +pin number is the constant :ref:`BOARD_BUTTON_PIN +<lang-board-values-but>`. + +Library Documentation +--------------------- + +.. doxygenfunction:: waitForButtonPress + + +Example +------- + +.. _lang-waitforbuttonpress-example: + +This example sets up the board's button pin as an input, then prints a +message very time the button is pressed. + +:: + + void setup() { + pinMode(BOARD_BUTTON_PIN, INPUT); + } + + void loop() { + waitForButtonPress(); + SerialUSB.println("You pressed the button!"); + } + +See Also +-------- + +- :ref:`Board-specific values <lang-board-values>` +- :ref:`BOARD_BUTTON_PIN <lang-board-values-but>` +- :ref:`lang-isbuttonpressed` |