From 5e587be27a7c3bd854b686952a5c9637a2432ff0 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Sun, 28 Nov 2010 11:23:33 -0500 Subject: reorganized all the arduino/ docs into a lang/ subdirectory since they're properly CC attributed now. --- docs/source/lang/abs.rst | 42 +++++ docs/source/lang/analogread.rst | 152 ++++++++++++++++ docs/source/lang/analogwrite.rst | 164 +++++++++++++++++ docs/source/lang/arithmetic.rst | 129 ++++++++++++++ docs/source/lang/arithmeticcompound.rst | 46 +++++ docs/source/lang/array.rst | 123 +++++++++++++ docs/source/lang/assignment.rst | 70 ++++++++ docs/source/lang/attachinterrupt.rst | 102 +++++++++++ docs/source/lang/bit.rst | 48 +++++ docs/source/lang/bitclear.rst | 47 +++++ docs/source/lang/bitread.rst | 49 ++++++ docs/source/lang/bitset.rst | 49 ++++++ docs/source/lang/bitshift.rst | 148 ++++++++++++++++ docs/source/lang/bitwisecompound.rst | 231 ++++++++++++++++++++++++ docs/source/lang/bitwisemath.rst | 186 ++++++++++++++++++++ docs/source/lang/bitwrite.rst | 40 +++++ docs/source/lang/boolean.rst | 91 ++++++++++ docs/source/lang/booleanvariables.rst | 55 ++++++ docs/source/lang/braces.rst | 109 ++++++++++++ docs/source/lang/break.rst | 35 ++++ docs/source/lang/byte.rst | 34 ++++ docs/source/lang/bytecast.rst | 53 ++++++ docs/source/lang/cc-attribution.txt | 9 + docs/source/lang/char.rst | 53 ++++++ docs/source/lang/charcast.rst | 39 +++++ docs/source/lang/comments.rst | 67 +++++++ docs/source/lang/comparison.rst | 87 +++++++++ docs/source/lang/const.rst | 52 ++++++ docs/source/lang/constants.rst | 302 ++++++++++++++++++++++++++++++++ docs/source/lang/constrain.rst | 65 +++++++ docs/source/lang/continue.rst | 34 ++++ docs/source/lang/cos.rst | 32 ++++ docs/source/lang/define.rst | 56 ++++++ docs/source/lang/delay.rst | 72 ++++++++ docs/source/lang/delaymicroseconds.rst | 65 +++++++ docs/source/lang/detachinterrupt.rst | 37 ++++ docs/source/lang/digitalread.rst | 61 +++++++ docs/source/lang/digitalwrite.rst | 116 ++++++++++++ docs/source/lang/double.rst | 51 ++++++ docs/source/lang/doublecast.rst | 30 ++++ docs/source/lang/dowhile.rst | 27 +++ docs/source/lang/else.rst | 54 ++++++ docs/source/lang/enum.rst | 8 + docs/source/lang/float.rst | 53 ++++++ docs/source/lang/floatcast.rst | 31 ++++ docs/source/lang/for.rst | 142 +++++++++++++++ docs/source/lang/goto.rst | 130 ++++++++++++++ docs/source/lang/highbyte.rst | 53 ++++++ docs/source/lang/if.rst | 81 +++++++++ docs/source/lang/include.rst | 71 ++++++++ docs/source/lang/increment.rst | 44 +++++ docs/source/lang/int.rst | 67 +++++++ docs/source/lang/intcast.rst | 32 ++++ docs/source/lang/interrupts.rst | 62 +++++++ docs/source/lang/keywords.rst | 11 ++ docs/source/lang/long.rst | 55 ++++++ docs/source/lang/longcast.rst | 30 ++++ docs/source/lang/loop.rst | 45 +++++ docs/source/lang/lowbyte.rst | 45 +++++ docs/source/lang/map.rst | 122 +++++++++++++ docs/source/lang/max.rst | 63 +++++++ docs/source/lang/micros.rst | 69 ++++++++ docs/source/lang/millis.rst | 70 ++++++++ docs/source/lang/min.rst | 66 +++++++ docs/source/lang/modulo.rst | 77 ++++++++ docs/source/lang/nointerrupts.rst | 59 +++++++ docs/source/lang/notone.rst | 50 ++++++ docs/source/lang/pinmode.rst | 76 ++++++++ docs/source/lang/pointer.rst | 28 +++ docs/source/lang/pow.rst | 29 +++ docs/source/lang/pulsein.rst | 82 +++++++++ docs/source/lang/pwmwrite.rst | 51 ++++++ docs/source/lang/random.rst | 95 ++++++++++ docs/source/lang/randomseed.rst | 73 ++++++++ docs/source/lang/return.rst | 61 +++++++ docs/source/lang/scope.rst | 120 +++++++++++++ docs/source/lang/semicolon.rst | 25 +++ docs/source/lang/serial.rst | 68 +++++++ docs/source/lang/serialusb.rst | 8 + docs/source/lang/setup.rst | 34 ++++ docs/source/lang/shiftout.rst | 136 ++++++++++++++ docs/source/lang/sin.rst | 32 ++++ docs/source/lang/sizeof.rst | 64 +++++++ docs/source/lang/sq.rst | 42 +++++ docs/source/lang/sqrt.rst | 25 +++ docs/source/lang/static.rst | 57 ++++++ docs/source/lang/string.rst | 131 ++++++++++++++ docs/source/lang/stringclass.rst | 9 + docs/source/lang/stringobject.rst | 91 ++++++++++ docs/source/lang/switchcase.rst | 117 +++++++++++++ docs/source/lang/tan.rst | 31 ++++ docs/source/lang/tone.rst | 81 +++++++++ docs/source/lang/types.rst | 7 + docs/source/lang/unsignedchar.rst | 36 ++++ docs/source/lang/unsignedint.rst | 58 ++++++ docs/source/lang/unsignedlong.rst | 44 +++++ docs/source/lang/variables.rst | 170 ++++++++++++++++++ docs/source/lang/void.rst | 40 +++++ docs/source/lang/volatile.rst | 73 ++++++++ docs/source/lang/while.rst | 49 ++++++ 100 files changed, 6891 insertions(+) create mode 100644 docs/source/lang/abs.rst create mode 100644 docs/source/lang/analogread.rst create mode 100644 docs/source/lang/analogwrite.rst create mode 100644 docs/source/lang/arithmetic.rst create mode 100644 docs/source/lang/arithmeticcompound.rst create mode 100644 docs/source/lang/array.rst create mode 100644 docs/source/lang/assignment.rst create mode 100644 docs/source/lang/attachinterrupt.rst create mode 100644 docs/source/lang/bit.rst create mode 100644 docs/source/lang/bitclear.rst create mode 100644 docs/source/lang/bitread.rst create mode 100644 docs/source/lang/bitset.rst create mode 100644 docs/source/lang/bitshift.rst create mode 100644 docs/source/lang/bitwisecompound.rst create mode 100644 docs/source/lang/bitwisemath.rst create mode 100644 docs/source/lang/bitwrite.rst create mode 100644 docs/source/lang/boolean.rst create mode 100644 docs/source/lang/booleanvariables.rst create mode 100644 docs/source/lang/braces.rst create mode 100644 docs/source/lang/break.rst create mode 100644 docs/source/lang/byte.rst create mode 100644 docs/source/lang/bytecast.rst create mode 100644 docs/source/lang/cc-attribution.txt create mode 100644 docs/source/lang/char.rst create mode 100644 docs/source/lang/charcast.rst create mode 100644 docs/source/lang/comments.rst create mode 100644 docs/source/lang/comparison.rst create mode 100644 docs/source/lang/const.rst create mode 100644 docs/source/lang/constants.rst create mode 100644 docs/source/lang/constrain.rst create mode 100644 docs/source/lang/continue.rst create mode 100644 docs/source/lang/cos.rst create mode 100644 docs/source/lang/define.rst create mode 100644 docs/source/lang/delay.rst create mode 100644 docs/source/lang/delaymicroseconds.rst create mode 100644 docs/source/lang/detachinterrupt.rst create mode 100644 docs/source/lang/digitalread.rst create mode 100644 docs/source/lang/digitalwrite.rst create mode 100644 docs/source/lang/double.rst create mode 100644 docs/source/lang/doublecast.rst create mode 100644 docs/source/lang/dowhile.rst create mode 100644 docs/source/lang/else.rst create mode 100644 docs/source/lang/enum.rst create mode 100644 docs/source/lang/float.rst create mode 100644 docs/source/lang/floatcast.rst create mode 100644 docs/source/lang/for.rst create mode 100644 docs/source/lang/goto.rst create mode 100644 docs/source/lang/highbyte.rst create mode 100644 docs/source/lang/if.rst create mode 100644 docs/source/lang/include.rst create mode 100644 docs/source/lang/increment.rst create mode 100644 docs/source/lang/int.rst create mode 100644 docs/source/lang/intcast.rst create mode 100644 docs/source/lang/interrupts.rst create mode 100644 docs/source/lang/keywords.rst create mode 100644 docs/source/lang/long.rst create mode 100644 docs/source/lang/longcast.rst create mode 100644 docs/source/lang/loop.rst create mode 100644 docs/source/lang/lowbyte.rst create mode 100644 docs/source/lang/map.rst create mode 100644 docs/source/lang/max.rst create mode 100644 docs/source/lang/micros.rst create mode 100644 docs/source/lang/millis.rst create mode 100644 docs/source/lang/min.rst create mode 100644 docs/source/lang/modulo.rst create mode 100644 docs/source/lang/nointerrupts.rst create mode 100644 docs/source/lang/notone.rst create mode 100644 docs/source/lang/pinmode.rst create mode 100644 docs/source/lang/pointer.rst create mode 100644 docs/source/lang/pow.rst create mode 100644 docs/source/lang/pulsein.rst create mode 100644 docs/source/lang/pwmwrite.rst create mode 100644 docs/source/lang/random.rst create mode 100644 docs/source/lang/randomseed.rst create mode 100644 docs/source/lang/return.rst create mode 100644 docs/source/lang/scope.rst create mode 100644 docs/source/lang/semicolon.rst create mode 100644 docs/source/lang/serial.rst create mode 100644 docs/source/lang/serialusb.rst create mode 100644 docs/source/lang/setup.rst create mode 100644 docs/source/lang/shiftout.rst create mode 100644 docs/source/lang/sin.rst create mode 100644 docs/source/lang/sizeof.rst create mode 100644 docs/source/lang/sq.rst create mode 100644 docs/source/lang/sqrt.rst create mode 100644 docs/source/lang/static.rst create mode 100644 docs/source/lang/string.rst create mode 100644 docs/source/lang/stringclass.rst create mode 100644 docs/source/lang/stringobject.rst create mode 100644 docs/source/lang/switchcase.rst create mode 100644 docs/source/lang/tan.rst create mode 100644 docs/source/lang/tone.rst create mode 100644 docs/source/lang/types.rst create mode 100644 docs/source/lang/unsignedchar.rst create mode 100644 docs/source/lang/unsignedint.rst create mode 100644 docs/source/lang/unsignedlong.rst create mode 100644 docs/source/lang/variables.rst create mode 100644 docs/source/lang/void.rst create mode 100644 docs/source/lang/volatile.rst create mode 100644 docs/source/lang/while.rst (limited to 'docs/source/lang') diff --git a/docs/source/lang/abs.rst b/docs/source/lang/abs.rst new file mode 100644 index 0000000..ed95e6f --- /dev/null +++ b/docs/source/lang/abs.rst @@ -0,0 +1,42 @@ +.. _lang-abs: + +abs(x) +====== + +Description +----------- + +(Macro) computes the absolute value of a number. + +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:: cc-attribution.txt diff --git a/docs/source/lang/analogread.rst b/docs/source/lang/analogread.rst new file mode 100644 index 0000000..0c93650 --- /dev/null +++ b/docs/source/lang/analogread.rst @@ -0,0 +1,152 @@ +.. highlight:: cpp + +.. _lang-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 board +contains a 16-channel, 12-bit analog to digital converter. This means +that it will map input voltages between 0 and 3.3 volts into integer +values between 0 and 4095. This yields a resolution between readings +of 3.3V / 4096 units, or 0.8 millivolts. 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`\ ). + +It takes about 0.8 microseconds (.0000008 seconds) to read an analog +input, so the maximum sample rate using this function is approximately +1.3 million samples per second\ [#fsamp]_. + + +Parameter Discussion +-------------------- + +The pin parameter is the number of the analog input pin to read from. +Header pins on the Maple with ADC functionality (marked as "AIN" on +the silkscreen) are: + + 0, 1, 2, 3, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 27, 28 + +Note that pins 3, 27, and 28 are not marked AIN on the silkscreen +for Maple revisions through Rev 5, however, they **do work** as +analog input pins. + +Note +---- + +If the analog input pin is not connected to anything, the value +returned by analogRead() will fluctuate based on a number of factors +(e.g. the values of the other analog inputs, how close your hand is to +the board, etc.) in a seemingly random way. + + +Example +------- + + :: + + + int analogPin = 3; // potentiometer wiper (middle terminal) connected + // to analog pin 3. outside leads to ground and +3.3V + int val = 0; // variable to store the value read + + void setup() { + pinMode(analogPin, INPUT_ANALOG); // set up pin for analog input + SerialUSB.begin(); // set up usb virtual COM port + } + + void loop() { + val = analogRead(analogPin); // read the input pin + SerialUSB.println(val); // 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 ` the value of a Maple readout by 2, like so:: + + // right shift means that the result will be between 0 and 1023; + // be aware that you're losing a lot of precision if you do this + int adc_reading = analogRead(pin) >> 2; + +On the Arduino, the input range and resolution can be changed using +their implementation of `analogReference() +`_\ . Because of the +way its hardware (as of Rev 5) was designed, it's not possible to +implement analogReference on the Maple, so this function doesn't +exist. If your inputs lie in a different voltage range than 0V--3.3V, +you'll need to bring them into that range before using analogRead. +Some basic tools to accomplish this are `resistor dividers +`_ and `Zener diodes +`_\ +. However, opamps and other powered components can also be used if +greater precision is required. + +Finally, On the Arduino, it takes significantly longer to read analog +input: about 100 microseconds (0.0001 s), so the maximum reading rate +is 10,000 times a second. + + +See also +-------- + +- :ref:`ADC note ` +- `(Arduino) Tutorial: Analog Input Pins `_ + + +.. rubric:: Footnotes + +.. [#fsamp] This is based on the current configuration of a 55.5 cycle + sample time, at 72 MHz. However, the minimum sample time *possible* + is 1.5 cycles, leading to a theoretical maximum of approximately 48 + million samples per second (of course, doing anything with the + readings also consumes cycles, so this maximum can't be reached in + practice). + + See the `STM32 Reference Manual `_, §§11.12.4--5 + (pp. 225--226), for more information on the low-level bit twiddling + currently necessary to change the sample time. For examples of how + the ADCs are configured in libmaple, see `adc.h + `_ + and `adc.c + `_\ + . Be aware that changing the sample time has important + consequences related to the impedance of the device connected to + the input pin. If you want to make changes, as a minimum, you + should first read ST's application notes on `ADC modes + `_ and `ADC oversampling + `_. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/analogwrite.rst b/docs/source/lang/analogwrite.rst new file mode 100644 index 0000000..d30d4d9 --- /dev/null +++ b/docs/source/lang/analogwrite.rst @@ -0,0 +1,164 @@ +.. highlight:: cpp + +.. _lang-analogwrite: + +analogWrite() +============= + +.. note:: + + On the Maple, calling analogWrite() is the same as calling + :ref:`lang-pwmwrite`\ ; see that function's documentation for more + information. + + This is because PWM is not true analog output (i.e., is not the + output of a `DAC + `_\ ), so + the function is badly named. For instance, **analogWrite() has + absolutely nothing to do with** :ref:`lang-analogread`\ , which is + potentially confusing. + + The alias of analogWrite() to pwmWrite() is provided (sigh) for the + sake of compatibility with Arduino, but we recommend using + :ref:`lang-pwmwrite` when writing new software, for clarity. + +.. contents:: Contents + :local: + +Arduino Compatibility +--------------------- + +There are a few important differences between Arduino's `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 ` the argument to +analogWrite into the right range:: + + // Arduino code: + analogWrite(pin, duty); + + // Becomes Maple code: + analogWrite(pin, map(duty, 0, 255, 0, 65535)); + +This will convert values in the range 0-255 to values in the range +0--65,635, which is the correct default range for all of the timers +which control PWM output. See the :ref:`timers reference ` +for more information. + +Another fix is to consult the :ref:`pin mapping mega table +` to find the timer which controls PWM on the +pin you're using, then set that Timer's overflow to 255. Subsequent +calls to analogWrite() should work as on the Arduino (with the same +loss of precision). Note, however, that that affects the overflow for +the **entire timer**, so other code relying on that timer (such as any +:ref:`interrupts ` 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, and 14, or twelve pins in total. That is at least as +*many* PWM pins as any Arduino board, but there are differences in +*which* pins support it. + +* On **most Arduino boards** (those with the ATmega168 or ATmega328; + this includes the **Arduino Uno**), this function works on pins 3, + 5, 6, 9, 10, and 11, or six pins total. Note that these boards + support PWM on pin 10, while Maple does not. + +* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins + total. Note that this board supports PWM on pins 4, 10, and 13, + while the Maple does not. Maple supports PWM on pins 0, 1, and 14, + which the Mega does not, making the total number of pins supporting + PWM equal on these boards. + +* **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, 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 `\ ). + +If your application absolutely requires Arduino's PWM frequency (it +probably doesn't), then the steps are: + +1. Figure out which timer controls PWM output on your pin (\ :ref:`this table ` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. + +2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. + +Be aware that this will change the period for the **entire timer**\ , +and will affect anything else in your program that depends on that +timer. One example is :ref:`interrupts `\ . +You've been :ref:`warned `\ . + +See also +-------- + +- :ref:`Maple PWM tutorial ` + +.. 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:: cc-attribution.txt diff --git a/docs/source/lang/arithmetic.rst b/docs/source/lang/arithmetic.rst new file mode 100644 index 0000000..9f21627 --- /dev/null +++ b/docs/source/lang/arithmetic.rst @@ -0,0 +1,129 @@ +.. highlight:: cpp + +.. _lang-arithmetic: + +Addition, Subtraction, Multiplication, & Division +================================================= + +.. contents:: Contents + :local: + +Description +----------- + +These operators return the sum, difference, product, or quotient +(respectively) of the two operands. The operation is conducted using +the data type of the operands, so, for example, ``9 / 4`` gives ``2`` +since 9 and 4 are :ref:`int variables `. + +This also means that the operation can overflow if the result is +larger than that which can be stored in the data type (e.g. adding 1 +to an :ref:`lang-int` with the value 2147483647 gives +-2147483648). If the operands are of different types, the "larger" +type is used for the calculation. + +.. _lang-arithmetic-typeconversion: + +.. note:: The specifics of these rules are beyond the scope of this + documentation; for more information, see `The C++ Programming + Language `_\ , by Bjarne + Stroustroup, Appendix C, especially §§C.4-C.6, or `this WikiBooks + entry on C++ type conversion + `_. + +.. note:: For more information on how computers represent integers, + see the Wikipedia page on `two's complement + `_. + +If one of the numbers (operands) are of the type **float** or of type +**double**, floating point math will be used for the +calculation. + +Examples +-------- + + :: + + y = y + 3; + x = x - 7; + i = j * 6; + r = r / 5; + + +Syntax +------ + + :: + + result = value1 + value2; + result = value1 - value2; + result = value1 * value2; + result = value1 / value2; + + +Parameters +---------- + +**value1**: any numeric variable or constant + +**value2**: any numeric variable or constant + +Programming Tips +---------------- + +- Know that :ref:`integer constants ` + default to :ref:`int `, so some constant calculations + may overflow (e.g., 200000 * 5000000 will yield a negative result). + +- Choose variable sizes that are large enough to hold the largest + results from your calculations. + +- Know at what point your variable will "roll over" and also what + happens in the other direction e.g. (0 - 1) for unsigned arithmetic, + or (0 - -2,147,483,648) for signed arithmetic. + +- For math that requires fractions, float variables may be used, but + be aware of their drawbacks: large size and slow computation speeds + (the STM32 has no floating point hardware, so all floating point + calculations have to be done in software). + +- Use cast operator, e.g. ``(int)myFloat`` to convert one variable type + to another on the fly. + +Arduino Compatibility +--------------------- + +Since the STM32 processor on the Maple is a 32-bit machine, the int +type overflows at a much higher value on Maple than on Arduino. In +particular, on Maple, ints do not overflow (become negative) until +they reach 2,147,483,648; on the Arduino, they overflow at 32,767. +Because of this, programs running on Maple are much less likely to run +into overflow issues. The following table summarizes the sizes and +ranges of integer datatypes on the Maple (the ranges of long long +types are approximate): + +.. _lang-arithmetic-int-sizes: + +.. csv-table:: + :header: Datatype, Unsigned range, Signed range, Size (bytes) + :widths: 8, 12, 17, 8 + + ``char``, 0 --- 255, -128 --- 127, 1 + ``short``, "0 --- 65,535", "-32,768 --- 32,767", 2 + ``int``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long long``, "0 --- 1.8*10\ :sup:`19`\ " (approx.), "-9.2*10\ :sup:`18` --- 9.2*10\ :sup:`18` (approx.)", 8 + + +See Also +-------- + +- The individual sizes (in bits) of various available types are + defined in `libmaple_types.h + `_\ + . + +- :ref:`sizeof `\ () + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/arithmeticcompound.rst b/docs/source/lang/arithmeticcompound.rst new file mode 100644 index 0000000..aa0dc18 --- /dev/null +++ b/docs/source/lang/arithmeticcompound.rst @@ -0,0 +1,46 @@ +.. highlight:: cpp + +.. _lang-arithmeticcompound: + +Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) +=============================================================== + +Description +----------- + +Perform a mathematical operation on a variable with another constant +or variable. These operators are just a convenient shorthand:: + + x += y; // equivalent to the expression x = x + y; + x -= y; // equivalent to the expression x = x - y; + x *= y; // equivalent to the expression x = x * y; + x /= y; // equivalent to the expression x = x / y; + +Here is an example:: + + int x = 2; + int y = 10; + + x += 4; // x now contains 6 + x -= 3; // x now contains 3 + x *= y; // x now contains 30 + x /= 2; // x now contains 15 + x += max(20, 6); // x now contains 35 + x -= sq(5); // x now contains 15 + +Parameters +---------- + +**x**: a numeric variable + +**y**: a numeric variable, number constant, or any other expression +that evaluates to a number (e.g. call to a function that returns a +number). + +See Also +-------- + +- :ref:`Arithmetic operators ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/array.rst b/docs/source/lang/array.rst new file mode 100644 index 0000000..30a818f --- /dev/null +++ b/docs/source/lang/array.rst @@ -0,0 +1,123 @@ +.. highlight:: cpp + +.. _lang-array: + +Arrays +====== + +An array is a collection of variables that are accessed with an index +number. Arrays in the C++ programming language, in which the Maple is +programmed, can be complicated, but using simple arrays is relatively +straightforward. + +.. contents:: Contents + :local: + +Creating (Declaring) an Array +----------------------------- + +All of the methods below are valid ways to create (declare) an +array. :: + + int myInts[6]; + int myPins[] = {2, 4, 8, 3, 6}; + int mySensVals[6] = {2, 4, -8, 3, 2}; + char message[6] = "hello"; + +You can declare an array without initializing it, as with myInts. In +the line referring to myPins, we declare an array without explicitly +choosing a size. The compiler counts the elements and creates an +array of the appropriate size. + +Finally, you can both initialize and size your array, as in +mySensVals. Note that when declaring an array with elements of type +char, one more element than your initialization is required, to hold +the required `null character `_. + + +Accessing an Array +------------------ + + +.. compound:: + + Arrays are **zero indexed**; that is, referring to the array + initialization above, the first element of the array is at index 0, + hence :: + + mySensVals[0] == 2; + mySensVals[1] == 4 + + and so forth. + +It also means that in an array with ten elements, index nine is the +last element. Hence:: + + int myArray[10]={9,3,2,4,3,2,7,8,9,11}; + // myArray[9] contains 11 + // myArray[10] is invalid and contains random information (other memory address) + +For this reason, you should be careful in accessing arrays. Accessing +past the end of an array (using an index number greater than your +declared array size - 1) is reading from memory that is in use for +other purposes. Reading from these locations is probably not going to +do much except yield invalid data. Writing to random memory locations +is definitely a bad idea, and can often lead to unhappy results such +as crashes or program malfunction. This can also be a difficult bug to +track down. + +Unlike Basic or Java, the C compiler does no checking to see if array +access is within legal bounds of the array size that you have +declared. + + +To assign a value to an array +----------------------------- + :: + + mySensVals[0] = 10; + + +To retrieve a value from an array +--------------------------------- + + :: + + x = mySensVals[4]; + + +Arrays and ``for`` Loops +------------------------ + +Arrays are often manipulated inside :ref:`for loops `, where +the loop counter is used as the index for each array element. For +example, to print the elements of an array over the serial port, you +could do something like this:: + + int i; + for (i = 0; i < 5; i = i + 1) { + SerialUSB.println(myPins[i]); + } + + +Example +------- + +For a complete program that demonstrates the use of arrays, see the +Arduino `Knight Rider example +`_\ (which will run +unmodified on the Maple). + +Arduino Compatibility +--------------------- + +Arrays on Maple are identical those on Arduino. + +See also +-------- + +- :ref:`Storing arrays in FLASH memory ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/assignment.rst b/docs/source/lang/assignment.rst new file mode 100644 index 0000000..16f0bf4 --- /dev/null +++ b/docs/source/lang/assignment.rst @@ -0,0 +1,70 @@ +.. highlight:: cpp + +.. _lang-assignment: + += assignment operator (single equal sign) +========================================= + +Stores the value to the right of the equal sign in the variable to +the left of the equal sign. + +The single equal sign in the C++ programming language is called the +assignment operator. It has a different meaning than in algebra +class, where it indicated an equation or equality. The assignment +operator tells the microcontroller to evaluate whatever value or +expression is on the right side of the equal sign, and store it in +the variable to the left of the equal sign [#fgross]_. + + + +Example +------- + +:: + + int sensVal; // declare an integer variable named sensVal + senVal = analogRead(0); // store the (digitized) input voltage at analog pin 0 in SensVal + + + +Programming Tips +---------------- + +The variable on the left side of the assignment operator ( = sign ) +needs to be able to hold the value stored in it. If it is not large +enough to hold a value, the value stored in the variable will be +incorrect. + +Don't confuse the assignment operator [ = ] (single equal sign) +with the comparison operator [ == ] (double equal signs), which +evaluates whether two expressions are equal. + + +Arduino Compatibility +--------------------- + +Assignments on the Maple are identical to those on Arduino. + + + +See Also +-------- + + +- `if (comparison operators) `_ +- `char `_ +- `int `_ +- `long `_ + + +.. rubric:: Footnotes + +.. [#fgross] Experienced C++ programmers know this to be an + oversimplification of what happens when the variable on the left + hand side is an object. See Richard Gillam's wonderful and scary + `The Anatomy of the Assignment Operator + `_ + for more information. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/attachinterrupt.rst b/docs/source/lang/attachinterrupt.rst new file mode 100644 index 0000000..0b8907f --- /dev/null +++ b/docs/source/lang/attachinterrupt.rst @@ -0,0 +1,102 @@ +.. highlight:: cpp + +.. _lang-attachinterrupt: + +attachInterrupt() +================= + +Used to specify a function to call when an external interrupt (like an +GPIO changing from LOW to HIGH, a button getting pressed, etc.) +occurs. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: attachInterrupt + +.. doxygenenum:: ExtIntTriggerMode + +.. doxygentypedef:: voidFuncPtr + +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 a few constraints you should be aware of if you're using +more than one interrupt at a time; the :ref:`external-interrupts` page +has the details. + + +Using Interrupts +---------------- + +Interrupts are useful for making things happen automatically in +microcontroller programs, and can help solve timing problems. A +good task for using an interrupt might be reading a rotary encoder, +or monitoring user input. + + +If you wanted to insure that a program always caught the pulses +from a rotary encoder, never missing a pulse, it would make it very +tricky to write a program to do anything else, because the program +would need to constantly poll the sensor lines for the encoder, in +order to catch pulses when they occurred. Other sensors have a +similar interface dynamic too, such as trying to read a sound +sensor that is trying to catch a click, or an infrared slot sensor +(photo-interrupter) trying to catch a coin drop. In all of these +situations, using an interrupt can free the microcontroller to get +some other work done while not missing the doorbell. + + +Example +------- + +:: + + int maple_led_pin = 13; + volatile int state = LOW; // must declare volatile, since it's + // modified within the blink handler + + void setup() { + pinMode(maple_led_pin, OUTPUT); + attachInterrupt(0, blink, CHANGE); + } + + void loop() { + digitalWrite(maple_led_pin, state); + } + + void blink() { + state = !state; + } + + +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:`detachInterrupt ` +- :ref:`external-interrupts` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bit.rst b/docs/source/lang/bit.rst new file mode 100644 index 0000000..c342fdd --- /dev/null +++ b/docs/source/lang/bit.rst @@ -0,0 +1,48 @@ +.. _lang-bit: + +bit() +===== + +Description +----------- + +(Macro) Computes the value of an (unsigned) integer with the specified +bit set (``bit(0)`` is 1, ``bit(1)`` is 2, ``bit(2)`` is 4, then 8, +16, 32, etc.). + + +Syntax +------ + +``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:: cc-attribution.txt diff --git a/docs/source/lang/bitclear.rst b/docs/source/lang/bitclear.rst new file mode 100644 index 0000000..5d1eb95 --- /dev/null +++ b/docs/source/lang/bitclear.rst @@ -0,0 +1,47 @@ +.. _lang-bitclear: + +bitClear() +========== + +Description +----------- + +(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 +------- + +None. + + +Arduino Compatibility +--------------------- + +This implementation is compatible with that of Arduino. + + +See also +-------- + +- :ref:`bit `\ () +- :ref:`bitRead `\ () +- :ref:`bitWrite `\ () +- :ref:`bitSet `\ () + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitread.rst b/docs/source/lang/bitread.rst new file mode 100644 index 0000000..9f885cf --- /dev/null +++ b/docs/source/lang/bitread.rst @@ -0,0 +1,49 @@ +.. _lang-bitread: + +bitRead() +========= + +Description +----------- + +(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:: cc-attribution.txt diff --git a/docs/source/lang/bitset.rst b/docs/source/lang/bitset.rst new file mode 100644 index 0000000..502c1b6 --- /dev/null +++ b/docs/source/lang/bitset.rst @@ -0,0 +1,49 @@ +.. _lang-bitset: + +bitSet() +======== + +Description +----------- + +(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:: cc-attribution.txt diff --git a/docs/source/lang/bitshift.rst b/docs/source/lang/bitshift.rst new file mode 100644 index 0000000..f05d49e --- /dev/null +++ b/docs/source/lang/bitshift.rst @@ -0,0 +1,148 @@ +.. highlight:: cpp + +.. _lang-bitshift: + +Bit shift left (``<<``), bit shift right (``>>``) +================================================= + +Description +----------- + +(Adapted from `The Bit Math Tutorial +`_ in `The Arduino +Playground `_\ ) + + +There are two bit shift operators in C++: the left shift operator +``<<`` and the right shift operator ``>>``. These operators cause the +bits in the left operand to be shifted left or right by the number of +positions specified by the right operand. + +More information on bitwise math can be obtained in the Wikipedia +article on `bitwise operations +`_\ , especially the +section on shifts in `C, C++, and Java +`_\ . + + +Syntax +------ + +``some_int << number_of_bits`` + +``some_int >> number_of_bits`` + + +Parameters +---------- + +* **some_int** An integer value or variable. + +* **number_of_bits** integer whose value is at most ``8 * + sizeof(variable)`` (so ``number_of_bits`` can be at most 32 for + ``int`` values, at most ``8`` for ``char`` values, etc.; the various + integer sizes are summarized :ref:`in this table + `\ ). + + + +Example: +-------- + +Here are some examples of bit shifting, with the binary representation of the number in comments:: + + int a = 5; // binary: 101 + int b = a << 3; // binary: 101000, or 40 in decimal + int c = b >> 3; // binary: 101, or back to 5 like we started with + + +When you left shift a value x by y bits (x << y), the leftmost y bits +in x are lost, literally shifted out of existence. We'll do this +example with ``char`` values (which are integers in the range 0-255, +and take up 8 bits of memory):: + + char a = 5; // binary (all 8 bits): 00000101 + char b = a << 7; // binary: 10000000 - the first 1 in 101 was discarded + + +If you are certain that none of the ones in a value are being shifted +into oblivion, a simple way to think of the left-shift operator is +that it multiplies the left operand by 2 raised to the right operand +power (in math notation, ``x << y`` equals x * 2\ :sup:`y`\ , as long +as none of the bits of x get shifted out). For example, to generate +powers of 2, the following expressions can be employed:: + + 1 << 0 == 1 + 1 << 1 == 2 + 1 << 2 == 4 + 1 << 3 == 8 + ... + 1 << 8 == 256 + 1 << 9 == 512 + 1 << 10 == 1024 + ... + +.. _lang-bitshift-signbit-gotcha: + +When you shift x right by y bits (``x >> y``), and the highest bit in +x is a 1, the behavior depends on the exact data type of x. If x is of +type ``int``, the highest bit is special, and determines whether x is +negative or not; the details are too complicated to explain here, but +they are thoroughly explained in the Wikipedia article on `two's +complement arithmetic +`_\ , which the +system most computers use to store integers. In that case, the sign +bit is copied into lower bits, for esoteric historical reasons:: + + int x = -16; // binary (all 32 bits): 11111111111111111111111111110000 + int y = x >> 3; // binary: 11111111111111111111111111111110 + + + +This behavior, called "sign extension", is often not what you +want. You probably wish zeros to be shifted in from the left. It +turns out that the right shift rules are different for ``unsigned +int`` values, so you can use a type cast to suppress ones being copied +from the left:: + + int x = -16; // binary: 11111111111111111111111111110000 + int y = (unsigned int)x >> 3; // binary: 00011111111111111111111111111110 + + + +If you are careful to avoid sign extension, you can use the +right-shift operator, ``>>``, as a way to divide by powers of 2. For +example:: + + int x = 1000; + int y = x >> 3; // integer division of 1000 by 8, causing y = 125. + + +Arduino Compatibility +--------------------- + +Since it's part of the C++ language, bit shifting on the Maple is +compatible with the Arduino; however, you should keep in mind that the +Maple has bigger integer types (as in, more bits) than the Arduino. + +Since the STM32 is a 32-bit processor, the ``int`` type takes up 32 +bits instead of 16, like on Arduino's 16-bit microcontroller. This +means that you can shift left, like ``x << y``, with bigger values of +``y`` on the Maple before ones in ``x`` start to get shifted out. + +To calculate the number of bits of an integer type on the Maple, +multiply its size in bytes (see :ref:`this table +` for these) by 8, since there are 8 +bits in 1 byte. For example, a ``short`` takes up 2 bytes of memory, +or 2 * 8 = 16 bits. + +See Also +-------- + +- :ref:`lang-bit` +- :ref:`lang-bitread` +- :ref:`lang-bitwrite` +- :ref:`lang-bitclear` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwisecompound.rst b/docs/source/lang/bitwisecompound.rst new file mode 100644 index 0000000..2b0fe2f --- /dev/null +++ b/docs/source/lang/bitwisecompound.rst @@ -0,0 +1,231 @@ +.. highlight:: cpp + +.. _lang-bitwisecompound: + +Compound bitwise and (&=), or (\|=), XOR (^=) +============================================= + +The compound bitwise operators perform their calculations at the +bit level of variables. They are often used to clear and set +specific bits of a variable. + +See the :ref:`bitwise math tutorial ` for more +information on bitwise operators. + +.. contents:: Contents + :local: + +.. _lang-bitwisecompound-and: + +Compound bitwise AND (&=) +------------------------- + +The compound bitwise AND operator ``&=`` is often used with a variable +and a constant to force particular bits in a variable to be zero. This +is often referred to in programming guides as "clearing" or +"resetting" bits. In a program, writing the line ``x &= y;`` is +equivalent to writing ``x = x & y;``. That is, the value of ``x`` +after the line will be equal to its old value bitwise ANDed with the +value of ``y``:: + + x &= y; // equivalent to x = x & y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any :ref:`integer value +` (like ``3`` or ``0x20``) for ``y``. + +Before doing an example of ``&=``, let's first review the Bitwise AND +(``&``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + +As shown above, bits that are "bitwise ANDed" with 0 become 0, while +bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` +is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & +B11111111`` equals ``b``. + +.. _lang-bitwisecompound-binconst: + +.. note:: The above uses :ref:`binary constants + `\ . The numbers are still the same + value in other representations, they just might not be as easy to + understand. + + Normally, in C and C++ code, :ref:`hexadecimal + ` or :ref:`octal + ` are used when we're interested in + an integer's bits, rather than its value as a number. + + While hexadecimal and octal literals might be harder to understand + at first, you should really take the time to learn them. They're + part of C, C++, and many other programming languages, while binary + constants are available only for compatibility with Arduino. + + Also, ``B00000000`` is shown for clarity, but zero in any number + format is zero. + +So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while +leaving the rest of the variable's bits unchanged, use the compound +bitwise AND operator ``&=`` with the constant ``B11111100`` +(hexadecimal ``0xFC``\ ):: + + 1 0 1 0 1 0 1 0 variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + 1 0 1 0 1 0 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +Here is the same representation with the variable's bits replaced +with the symbol ``x``\ :: + + x x x x x x x x variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + x x x x x x 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +So, using a byte variable ``b``\ , if we say:: + + b = B10101010; // B10101010 == 0xAA + b &= B11111100; // B11111100 == 0xFC + +then we will have :: + + b == B10101000; // B10101000 == 0xA8 + +.. _lang-bitwisecompound-or: + +Compound bitwise OR (\|=) +------------------------- + +The compound bitwise OR operator ``|=`` is often used with a variable +and a constant to "set" (set to 1) particular bits in a variable. In +a program, writing the line ``x |= y;`` is equivalent to writing ``x = +x | y;``. That is, the value of ``x`` after the line will be equal to +its old value bitwise ORed with the value of ``y``:: + + x |= y; // equivalent to x = x | y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`compound bitwise AND +`\ , ``&=``). + +Before doing an example of ``|=``, let's first review the Bitwise OR +(``|``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Bits that are "bitwise ORed" with 0 are unchanged, while bits that are +"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` +variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` +equals ``B11111111`` (here we've used binary constants; see the +:ref:`note ` above). + +So, to set bits 0 and 1 of a one-byte variable, while leaving the rest +of the variable unchanged, use the compound bitwise OR operator +(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +Here is the same representation with the variable's bits replaced with +the symbol ``x``:: + + x x x x x x x x variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + x x x x x x 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b |= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101011; // B10101011 == 0xAB + +.. _lang-bitwisecompound-xor: + +Compound bitwise XOR (\^=) +-------------------------- + +The compound bitwise XOR operator ``^=`` is used with a variable and a +constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a +variable. In a program, writing the line ``x ^= y;`` is equivalent to +writing ``x = x ^ y;``. That is, the value of ``x`` after the line +will be equal to its old value bitwise XORed with the value of ``y``:: + + x ^= y; // equivalent to x = x ^ y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`&= +` and :ref:`\|= +`; in fact, these three operators all +work the same in this way). + +Before doing an example of ``^=``, let's first review the Bitwise +XOR operator, ``^``:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + +One way to look at bitwise XOR is that each bit in the result is a 1 +if the input bits are different, or 0 if they are the same. Another +way to think about it is that the result bit will be 1 when *exactly* +one (no more, no less) of the input bits is 1; otherwise, it will be +zero. This means that if you XOR a bit with 1, it will change (or +toggle) its value, while if you XOR a bit with 0, it stays the same. + +So, to toggle bits 0 and 1 of a one-byte variable, while leaving the +rest of the variable unchanged, use the compound bitwise XOR operator +``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see +:ref:`note ` above):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged toggled + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b ^= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101001; // B10101001 == 0xA9 + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwisemath.rst b/docs/source/lang/bitwisemath.rst new file mode 100644 index 0000000..30e8873 --- /dev/null +++ b/docs/source/lang/bitwisemath.rst @@ -0,0 +1,186 @@ +.. highlight:: cpp + +.. _lang-bitwisemath: + +Bitwise AND (&), OR (\|), XOR (^), NOT (~) +========================================== + +The bitwise operators perform their calculations at the bit level of +variables. They help solve a wide range of common programming +problems. + +Much of the material here is adapted for Maple from an (Arduino) +`tutorial on bitwise math +`_\ . Another great +resource is the Wikipedia article on `bitwise operations +`_\ . + +Below are descriptions and syntax for all of the operators. + +.. contents:: Contents + :local: + +.. _lang-bitwisemath-and: + +Bitwise AND (&) +--------------- + +The bitwise AND operator in C++ is a single ampersand, ``&``, used +between two other integer expressions. Bitwise AND operates on each +bit position of the surrounding expressions independently, according +to this rule: if both input bits are 1, the resulting output is 1, +otherwise the output is 0. Another way of expressing this is:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + + +On the Maple, the type ``int`` is a 32-bit value, so using ``&`` +between two ``int`` expressions causes 32 simultaneous AND operations +to occur. In a code fragment like:: + + int a = 92; // in binary: 00000000000000000000000001011100 + int b = 101; // in binary: 00000000000000000000000001100101 + int c = a & b; // result: 00000000000000000000000001000100, + // (or 68 in decimal). + + +Each of the 32 bits in ``a`` and ``b`` are processed using bitwise +AND, and all 32 resulting bits are stored in ``c``, resulting in the +value 1000100 in binary, which is 68 in decimal. + + +.. _lang-bitwisemath-or: + +Bitwise OR (\|) +--------------- + +The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like +the ``&`` operator, ``|`` operates independently on each bit in its +two surrounding integer expressions, but what it does is +different. The bitwise OR of two bits is 1 if either or both of the +input bits is 1, otherwise it is 0. For example:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Here is an example of bitwise OR used in a snippet of C++ code (using +``char``, which takes up 8 bits of memory, instead of ``int``, which +uses 32):: + + char a = 92; // in binary: 01011100 + char b = 101; // in binary: 01100101 + char c = a | b; // result: 01111101, or 125 in decimal. + +.. _lang-bitwisemath-xor: + +Bitwise XOR (^) +--------------- + +There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE +OR, also known as bitwise XOR. (In English, this is usually pronounced +"zor" or "ex-or"). The bitwise XOR operator is written using the caret +symbol, ``^``. This operator is very similar to the bitwise OR +operator ``|``, except it evaluates to 0 for a given bit position when +both of the input bits for that position are 1:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + + +Another way to look at bitwise XOR is that each bit in the result +is a 1 if the input bits are different, or 0 if they are the same. + +Here is a simple example:: + + int x = 12; // binary (ignoring extra bits): 1100 + int y = 10; // binary: 1010 + int z = x ^ y; // binary: 0110, or decimal 6 + + + +The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 +to 0) some of the bits in an integer expression. In a bitwise OR +operation if there is a 1 in the mask bit, that bit is inverted; if +there is a 0, the bit is not inverted and stays the same. Below is a +program to blink digital pin 13 (the LED pin on Maple):: + + // Blink Maple LED pin + + int led_pin = 13; + int toggle = 0; + + // demo for Exclusive OR + void setup(){ + pinMode(led_pin, OUTPUT); + } + + void loop(){ + toggle = toggle ^ 1; + digitalWrite(led_pin, toggle); + delay(100); + } + +.. _lang-bitwisemath-not: + +Bitwise NOT (~) +--------------- + +The bitwise NOT operator in C++ is the tilde character ``~``. Unlike +``&`` and ``|``, the bitwise NOT operator is applied to a single +operand to its right. Bitwise NOT changes each bit to its opposite: 0 +becomes 1, and 1 becomes 0. For example:: + + 0 1 operand1 + ---- + 1 0 ~operand1 = result + +Another example:: + + char a = 103; // binary: 01100111 + char b = ~a; // binary: 10011000 = -104 + +You might be surprised to see a negative number like -104 as the +result of this operation. This is because the highest bit in an int +variable is the so-called "sign bit". If the highest bit is 1, the +number is interpreted as negative. This encoding of positive and +negative numbers is referred to as *two's complement*. For more +information, see the Wikipedia article on `two's +complement. `_ + +As an aside, it is interesting to note that (under two's complement +arithmetic) for any integer ``x``, ``~x`` is the same as ``-x-1``. + +At times, the sign bit in a signed integer expression can cause +some unwanted surprises. + + +Uses +---- + +One of the most common uses of bitwise operations is to select or +manipulate a particular bit (or bits) from an integer value, often +called `bit masking +`_\ . See the +linked Wikipedia article for more information and examples. + +If you really want to see bit-twiddling techniques in their full +glory, you could do much worse than to get yourself a copy of +`Hacker's Delight `_\ . + + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Compound bitwise operations ` (``&=``, + ``|=``, ``^=``). + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwrite.rst b/docs/source/lang/bitwrite.rst new file mode 100644 index 0000000..86df26e --- /dev/null +++ b/docs/source/lang/bitwrite.rst @@ -0,0 +1,40 @@ +.. _lang-bitwrite: + +bitWrite(x, n, b) +================= + +Description +----------- + +(Macro) Writes a bit of a numeric variable. + +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 version of ``bitWrite()`` is compatible with Arduino. + +See also +-------- + +- :ref:`bit() ` +- :ref:`bitRead() ` +- :ref:`bitSet() ` +- :ref:`bitClear() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/boolean.rst b/docs/source/lang/boolean.rst new file mode 100644 index 0000000..6ff4097 --- /dev/null +++ b/docs/source/lang/boolean.rst @@ -0,0 +1,91 @@ +.. highlight:: cpp + +.. _lang-boolean: + +Boolean Operators +================= + +These can be used inside the condition of an :ref:`if ` +statement. Evaluate to :ref:`true ` or +:ref:`false `. + +.. contents:: Contents + :local: + +.. _lang-boolean-and: + +&& (logical and) +---------------- + +True only if both operands are true. For example:: + + if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches + // ... + } + +is true only if both inputs are high. Another example:: + + if (a >= 10 && a <= 20){} // true if a is between 10 and 20 + +**Be careful** not to say ``10 <= a <= 20``! This won't work the way +you want. You have to separately test whether ``a`` is at least 10 +using ``a >= 10``, then test whether ``a`` is at most 20 using ``a <= +20``, then combine the results using ``&&``. + + +.. _lang-boolean-or: + +\|\| (logical or) +----------------- + +True if either operand is true. For example:: + + if (x > 0 || y > 0) { + // ... + } + +is true if either ``x`` or ``y`` is greater than 0. + +.. _lang-boolean-not: + +! (logical not) +--------------- + +True if the operand is false. For example:: + + if (!x) { + // ... + } + +is true if ``x`` is false (i.e. if ``x`` is zero). + +Some Advice +----------- + +.. warning:: + + Make sure you don't mistake the boolean AND operator ``&&`` + (double ampersand) for the :ref:`bitwise AND operator + ` ``&`` (single ampersand). They are + entirely different beasts. + + Similarly, do not confuse the boolean OR operator ``||`` (double + pipe) with the :ref:`bitwise OR operator ` + ``|`` (single pipe). + + The :ref:`bitwise NOT operator ` ``~`` + (tilde) looks much different than the boolean not operator ``!`` + (exclamation point, or "bang", as some programmers say), but you + still have to be sure which one you want. + + +See Also +-------- + +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) +- :ref:`Compound bitwise operators ` (``&=``, + ``|=``, ``^=``). +- :ref:`if statement ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/booleanvariables.rst b/docs/source/lang/booleanvariables.rst new file mode 100644 index 0000000..9d0e992 --- /dev/null +++ b/docs/source/lang/booleanvariables.rst @@ -0,0 +1,55 @@ +.. highlight:: cpp + +.. _lang-booleanvariables: + +Booleans +======== + +A **boolean** holds one of two values, :ref:`true +` or :ref:`false `. +On a Maple, each boolean variable occupies one byte of memory, and has +type ``bool``. + +.. warning:: + + On an Arduino, the type ``boolean`` is also provided. While the + Maple also has this type for compatibility, **its use is strongly + discouraged**. The ``bool`` type is a standard part of C++, while + ``boolean`` is a non-standard extension that serves no purpose. + +Example +------- + +:: + + int ledPin = 13; // LED on pin 13 + int switchPin = 12; // momentary switch on 12, other side connected to ground + + // running is a boolean variable: + bool running = false; + + void setup() { + pinMode(ledPin, OUTPUT); + pinMode(switchPin, INPUT); + digitalWrite(switchPin, HIGH); // turn on pullup resistor + } + + void loop() { + if (digitalRead(switchPin) == LOW) { + // switch is pressed - pullup keeps pin high normally + delay(100); // delay to debounce switch + running = !running; // toggle running variable + digitalWrite(ledPin, running) // indicate via LED + } + } + +See also +-------- + + +- :ref:`Boolean constants ` +- :ref:`Boolean operators ` +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/braces.rst b/docs/source/lang/braces.rst new file mode 100644 index 0000000..229ad8c --- /dev/null +++ b/docs/source/lang/braces.rst @@ -0,0 +1,109 @@ +.. highlight:: cpp + +.. _lang-braces: + +Curly Braces ({}) +================= + +.. contents:: Contents + :local: + +Introduction +------------ + +Curly braces (also referred to as just "braces" or as "curly +brackets") are a major part of the C and C++ programming +languages. They are used in several different constructs, outlined +below, and this can sometimes be confusing for beginners. + +An opening curly brace, ``{`` must always be followed by a closing +curly brace ``}``. This is a condition that is often referred to as +the braces being *balanced*. The Maple IDE (integrated development +environment) includes a convenient feature to check the balance of +curly braces. Just select a brace, or even click the insertion point +immediately following a brace, and its companion will be highlighted\ +[#fbug]_\ . + +Beginning programmers, and programmers coming to C++ from languages +without braces, often find using them confusing or daunting. + +Because the use of the curly brace is so varied, it is good +programming practice to type the closing brace immediately after +typing the opening brace when inserting a construct which requires +curly braces. Then insert some blank lines between your braces and +begin inserting statements. Your braces, and your attitude, will never +become unbalanced. + +Unbalanced braces can often lead to cryptic, impenetrable compiler +errors that can sometimes be hard to track down in a large program. +Because of their varied usages, braces are also incredibly important +to the syntax of a program and moving a brace one or two lines will +usually dramatically affect the meaning of a program. + +The main uses of curly braces +----------------------------- + +**Functions**:: + + // a function body needs braces around it + void myFunction(datatype argument) { + // ... function body goes in here ... + } + +**Loops** (see the :ref:`while `\ , :ref:`for +`\ , and :ref:`do/while ` loop reference +pages for more information):: + + // you should put braces around the body of a loop: + + while (boolean expression) { + // code inside the loop goes here + } + + for (initialisation; termination condition; incrementing expr) { + // code inside the loop goes here + } + + do { + // code inside the loop goes here + } while (boolean expression); + + +**Conditional statements** (see the :ref:`if statement ` +reference page for more information):: + + // you should put braces around the body of an "if", "else if", + // or "else": + + if (boolean expression) { + // code inside the "if" + } + else if (boolean expression) { + // code inside the "else if" + } + else { + // code inside the "else" + } + +**Switch statements** (see the :ref:`switch statement +` reference page for more information):: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + +.. rubric:: Footnotes + +.. TODO remove this once IDE 0.1.0 released + +.. [#fbug] At present this feature is slightly buggy as the IDE will + often find (incorrectly) a brace in text that has been commented + out. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/break.rst b/docs/source/lang/break.rst new file mode 100644 index 0000000..dc50b5f --- /dev/null +++ b/docs/source/lang/break.rst @@ -0,0 +1,35 @@ +.. highlight:: cpp + +.. _lang-break: + +break +===== + +``break`` is used to exit from a :ref:`while `\ , +:ref:`for `\ , or :ref:`do/while ` loop, +bypassing the normal loop condition. It is also used to exit from a +:ref:`switch ` statement. + + +Example +------- + +:: + + for (x = 0; x < 255; x ++) + { + digitalWrite(PWMpin, x); + sens = analogRead(sensorPin); + if (sens > threshold){ // bail out on sensor detect + x = 0; + // this line of code means that we'll immediately exit + // from the "for" loop: + break; + } + delay(50); + } + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/byte.rst b/docs/source/lang/byte.rst new file mode 100644 index 0000000..45c9d5f --- /dev/null +++ b/docs/source/lang/byte.rst @@ -0,0 +1,34 @@ +.. highlight:: cpp + +.. _lang-byte: + +byte +==== + +The ``byte`` type stores a 1-byte (8-bit) unsigned integer number, +from 0 to 255. + +.. warning:: + + The ``byte`` type is provided for compatibility with Arduino. + However, it is a non-standard extension. The standard C++ type for + storing an 8-bit unsigned integer is ``unsigned char``; we + recommend using that instead. (Your code will still work on an + Arduino). + + +Example +------- + +:: + + byte b = 134; + +See Also +-------- + +- :ref:`byte() ` (casting a value to a byte) +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/bytecast.rst b/docs/source/lang/bytecast.rst new file mode 100644 index 0000000..4ad2a89 --- /dev/null +++ b/docs/source/lang/bytecast.rst @@ -0,0 +1,53 @@ +.. highlight:: cpp + +.. _lang-bytecast: + +byte() (cast) +============= + +Description +----------- + +Converts a value to the :ref:`byte ` data type. + +.. note:: + + Casting to the byte type is provided for compatibility with + Arduino. However, the recommended Maple type for storing an 8-bit + unsigned integer is ``uint8``. (C and C++ programmers: ``stdint.h`` + is also available). + + In order to cast a variable ``x`` to a ``uint8``, the + following syntax can be used:: + + uint8(x); + +Syntax +------ + +``byte(x)`` + + +Parameters +---------- + +**x**: a value of any integer type + + +Returns +------- + +The value, converted to a ``byte``. Note, however, that if the value +is larger than the maximum value you can store in a byte (255), then +the results might be strange and unexpected. + + +See Also +-------- + +- :ref:`lang-byte` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cc-attribution.txt b/docs/source/lang/cc-attribution.txt new file mode 100644 index 0000000..e100140 --- /dev/null +++ b/docs/source/lang/cc-attribution.txt @@ -0,0 +1,9 @@ +.. Included in all this directory's files in order to satisfy the +.. Arduino CC Attribution-ShareAlike 3.0 License + +.. admonition:: License and Attribution + + This documentation page was adapted from the `Arduino Reference + Documentation `_\ , which + is released under a `Creative Commons Attribution-ShareAlike 3.0 + License `_. diff --git a/docs/source/lang/char.rst b/docs/source/lang/char.rst new file mode 100644 index 0000000..8c6dadf --- /dev/null +++ b/docs/source/lang/char.rst @@ -0,0 +1,53 @@ +.. highlight:: cpp + +.. _lang-char: + +char +==== + +Description +----------- + +The ``char`` type stores a 1-byte character value (or integer with +value from -128 to 127). Character literals are written in single +quotes, like this: ``'A'`` (for multiple characters - strings - use +double quotes: ``"ABC"``). + + +Just like everything else on a computer, characters are stored as +numbers. You can see the specific encoding in the `ASCII chart +`_\ +. This means that it is possible to do arithmetic on characters, in +which the ASCII value of the character is used (e.g. ``'A' + 1`` has the +decimal value 66, since the ASCII value of the capital letter A in +decimal is 65). See the :ref:`Serial.println() +` documentation for more information about how +characters are converted into numbers. + +The ``char`` datatype is a signed type, meaning that it encodes +numbers from -128 to 127. For an unsigned type, which stores values +from 0 to 255, just use the type ``unsigned char`` (two words). + + +Example +------- + +:: + + // the following two lines are equivalent, using the ASCII + // character encoding: + char c = 'A'; + char c = 65; + + +See also +-------- + + +- :ref:`lang-int` +- :ref:`lang-array` (a string is just an array of ``char``\ s) +- :ref:`Serial.println() ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/charcast.rst b/docs/source/lang/charcast.rst new file mode 100644 index 0000000..844dd58 --- /dev/null +++ b/docs/source/lang/charcast.rst @@ -0,0 +1,39 @@ +.. highlight:: cpp + +.. _lang-charcast: + +char() (cast) +============= + +Description +----------- + +Converts a value to the :ref:`char ` data type. + +Syntax +------ + +``char(x)`` + + +Parameters +---------- + +**x**: a value of any type + + +Returns +------- + +The value, converted to a ``char``. Note, however, that if the value +is outside the range of a ``char`` (-128 to 127), then the results +might be strange and unexpected. + + +See Also +-------- + +- :ref:`char ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/comments.rst b/docs/source/lang/comments.rst new file mode 100644 index 0000000..c5f118a --- /dev/null +++ b/docs/source/lang/comments.rst @@ -0,0 +1,67 @@ +.. highlight:: cpp + +.. _lang-comments: + +Comments +======== + +Comments are lines in the program that are used to inform yourself or +others about the way the program works. They are ignored by the +compiler, and not exported to the processor, so they don't take up any +space in RAM or Flash. + +One use for comments is to help you understand (or remember) how your +program works, or to inform others how your program works. There are +two different ways of making comments. + +.. _lang-comments-singleline: + +**Single line comment**: Anything following two slashes, ``//``, until +the end of the line, is a comment:: + + x = 5; // the rest of this line is a comment + +.. _lang-comments-multiline: + +**Multi-line comment**: Anything in between a pair of ``/*`` and ``*/`` +is a comment:: + + /* <-- a slash-star begins a multi-line comment + + all of this in the multi-line comment - you can use it to comment + out whole blocks of code + + if (gwb == 0){ // single line comment is OK inside a multi-line comment + x = 3; + } + + // don't forget the "closing" star-slash - they have to be balanced: + */ + +Note that it's okay to use single-line comments within a multi-line +comment, but you can't use multi-line comments within a multi-line +comment. Here's an example:: + + /* ok, i started a multi-line comment + + x = 3; /* this next star-slash ENDS the multi-line comment: */ + + x = 4; // this line is outside of the multi-line comment + + // next line is also outside of the comment, and causes a compile error: + */ + +Programming Tip +--------------- + +When experimenting with code, "commenting out" parts of your program +is a convenient way to remove lines that may be buggy. This leaves +the lines in the code, but turns them into comments, so the compiler +just ignores them. This can be especially useful when trying to locate +a problem, or when a program refuses to compile and the compiler error +is cryptic or unhelpful. + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/comparison.rst b/docs/source/lang/comparison.rst new file mode 100644 index 0000000..8873256 --- /dev/null +++ b/docs/source/lang/comparison.rst @@ -0,0 +1,87 @@ +.. highlight:: cpp + +.. _lang-comparison: + +Comparison Operators +==================== + +The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and +``>=`` are used to compare two numbers. They are :ref:`true +` when the comparison is true, and :ref:`false +` otherwise. They are based on the symbols +=, ≠, <, >, ≤, and ≥ from mathematics. + +Here are some examples, with their meaning in comments:: + + // "eq" is true when x is equal to y + bool eq = (x == y); + + // "neq" is true when x is different than y + bool neq = (x != y); + + // "lt" is true when x is less than, but NOT equal to, y + bool lt = (x < y); + + // "gt" is true when x is greater than, but NOT equal to, y + bool gt = (x > y); + + // "lte" is true when x is less than or equal to y + bool lte = (x <= y); + + // "gte" is true when x is greater than or equal to y + bool gte = (x >= y); + +The parentheses are optional; they are present only for clarity. For +example, the following two lines are the same:: + + bool eq = x == y; + + bool eq = (x == y); + +Uses +---- + +Comparison operators, along with :ref:`boolean operators +`, are useful inside the conditionals of :ref:`if +` statements. Here's one example:: + + if (x < 50) { + // only execute these lines if x is less than 50 + SerialUSB.println("delaying:"); + SerialUSB.println(x); + delay(x); + } + +.. warning:: + Beware of accidentally using the single equal sign (``=``) when you + meant to test if two numbers are equal (``==``). This is a common + mistake inside of ``if`` statement conditionals, e.g.:: + + // DON'T MAKE THIS MISTAKE + if (x = 10) { + // body + } + + The single equal sign is the assignment operator, and sets x to 10 + (puts the value 10 into the variable x). Instead use the double equal + sign (e.g. ``if (x == 10)``), which is the comparison operator, and + tests *whether* x is equal to 10 or not. The latter statement is only + true if x equals 10, but the former statement will always be true. + + This is because C evaluates the statement ``if (x=10)`` as follows: 10 + is assigned to x (remember that the single equal sign is the + :ref:`assignment operator `), so x now + contains 10. Then the 'if' conditional evaluates 10, which evaluates + to :ref:`true `, since any non-zero number + evaluates to ``true``. + + Consequently, the conditional of an ``if`` statement like ``if (x = + 10) {...}`` will always evaluate to ``true``, and the variable x + will be set to 10, which is probably not what you meant. + + (This sometimes has uses, though, so just because an assignment + appears within a conditional doesn't mean it's automatically wrong. + Be careful to know what you mean.) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/const.rst b/docs/source/lang/const.rst new file mode 100644 index 0000000..1658e6d --- /dev/null +++ b/docs/source/lang/const.rst @@ -0,0 +1,52 @@ +.. highlight:: cpp + +.. _lang-const: + +const Keyword +============= + +The ``const`` keyword stands for "constant". It is a variable +*qualifier* that modifies the behavior of the variable, making a +variable "*read-only*". This means that the variable can be used just +as any other variable of its type, but its value cannot be +changed. You will get a compiler error if you try to assign a value to +a ``const`` variable. + +Constants defined with the ``const`` keyword obey the same rules of +:ref:`variable scoping ` that govern other +variables. This, and the pitfalls of using :ref:`#define +`, often makes using the ``const`` keyword a superior +method for defining constants than ``#define``. + +Example +------- + +:: + + // this defines a variable called "pi", which cannot be changed: + const float pi = 3.14; + float x; + + // .... + + x = pi * 2; // it's fine to find the value of a const variable + + pi = 7; // illegal - you can't write to (modify) a constant + + +**#define** or **const** +------------------------ + +You can use either ``const`` or ``#define`` for creating numeric or +string constants. For :ref:`arrays `\ , you will need +to use ``const``. In general, ``const`` is preferred over ``#define`` +for defining constants. + +See Also +-------- + +- :ref:`#define ` +- :ref:`volatile ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/constants.rst b/docs/source/lang/constants.rst new file mode 100644 index 0000000..b7521ed --- /dev/null +++ b/docs/source/lang/constants.rst @@ -0,0 +1,302 @@ +.. _lang-constants: + +constants +========= + +Constants are predefined variables in the Arduino language. They +are used to make the programs easier to read. We classify constants +in groups. + +.. contents:: Contents + :local: + +.. _lang-constants-bool: + +Boolean Constants +----------------- + +There are two constants used to represent truth and falsity in the +Arduino language: **true**, and **false**. + +.. _lang-constants-false: + +false +^^^^^ + +false is the easier of the two to define. false is defined as 0 +(zero). + +.. _lang-constants-true: + +true +^^^^ + +true is often said to be defined as 1, which is correct, but true +has a wider definition. Any integer which is *non-zero* is TRUE, in +a Boolean sense. So -1, 2 and -200 are all defined as true, too, in +a Boolean sense. + + +Note that the *true* and *false* constants are typed in lowercase +unlike HIGH, LOW, INPUT, & OUTPUT. + + +Defining Pin Levels, HIGH and LOW +--------------------------------- + +When reading or writing to a digital pin there are only two +possible values a pin can take/be-set-to: **HIGH** and **LOW**. + +.. _lang-constants-high: + +**HIGH** + + + +The meaning of HIGH (in reference to a pin) is somewhat different +depending on whether a pin is set to an INPUT or OUTPUT. When a pin +is configured as an INPUT with pinMode, and read with digitalRead, +the microcontroller will report HIGH if a voltage of 3 volts or +more is present at the pin. + + + +A pin may also be configured as an INPUT with pinMode, and +subsequently made HIGH with digitalWrite, this will set the +internal 20K pullup resistors, which will *steer* the input pin to +a HIGH reading unless it is pulled LOW by external circuitry. + + + +When a pin is configured to OUTPUT with pinMode, and set to HIGH +with digitalWrite, the pin is at 5 volts. In this state it can +*source* current, e.g. light an LED that is connected through a +series resistor to ground, or to another pin configured as an +output, and set to LOW. + +.. _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 pinMode, and read with 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 digitalWrite, the pin is at 0 volts. In this state it can +*sink* current, e.g. light an LED that is connected through a +series resistor to, +5 volts, or to another pin configured as an +output, and set to HIGH. + + + +Defining Digital Pins, INPUT and OUTPUT +--------------------------------------- + +Digital pins can be used either as **INPUT** or **OUTPUT**. +Changing a pin from INPUT TO OUTPUT with pinMode() drastically +changes the electrical behavior of the pin. + +.. _lang-constants-input: + +Pins Configured as Inputs +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Arduino (Atmega) pins configured as **INPUT** with pinMode() are +said to be in a high-impedance state. One way of explaining this is +that pins configured as INPUT make extremely small demands on the +circuit that they are sampling, say equivalent to a series resistor +of 100 Megohms in front of the pin. This makes them useful for +reading a sensor, but not powering an LED. + +.. _lang-constants-output: + +Pins Configured as Outputs +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Pins configured as **OUTPUT** with pinMode() are said to be in a +low-impedance state. This means that they can provide a substantial +amount of current to other circuits. Atmega pins can source +(provide positive current) or sink (provide negative current) up to +40 mA (milliamps) of current to other devices/circuits. This makes +them useful for powering LED's but useless for reading sensors. +Pins configured as outputs can also be damaged or destroyed if +short circuited to either ground or 5 volt power rails. The amount +of current provided by an Atmega pin is also not enough to power +most relays or motors, and some interface circuitry will be +required. + +.. _lang-constants-fp: + +Floating-Point Constants +------------------------ + +Similar to integer constants, floating point constants are used to +make code more readable. Floating point constants are swapped at +compile time for the value to which the expression evaluates. + +.. TODO explain that floating point literals are doubles + +.. _lang-constants-fp-f: + +.. TODO f modifiers + +Examples: + +``n = .005;`` + +Floating point constants can also be expressed in a variety of +scientific notation. 'E' and 'e' are both accepted as valid +exponent indicators. + +:: + + + floating-point evaluates to: also evaluates to: + constant + + 10.0 10 + 2.34E5 2.34 * 10^5 234000 + 67e-12 67.0 * 10^-12 .000000000067 + +.. _lang-constants-integers: + +Integer Constants +----------------- + +Integer constants are numbers used directly in a sketch, like +``123``. By default, these numbers are treated as +`int `_'s but you can change +this with the U and L modifiers (see below). + + + +Normally, integer constants are treated as base 10 (decimal) +integers, but special notation (formatters) may be used to enter +numbers in other bases. + + + +:: + + Base Example Formatter Comment + + 10 (decimal) 123 none + + 2 (binary) B1111011 leading 'B' only works with 8 bit values (0 to 255) + characters 0-1 valid + + 8 (octal) 0173 leading "0" characters 0-7 valid + + 16 (hexadecimal) 0x7B leading "0x" characters 0-9, A-F, a-f valid + +.. _lang-constants-integers-dec: + +**Decimal** is base 10. This is the common-sense math with which +you are acquainted. Constants without other prefixes are assumed to +be in decimal format. + + + +Example: +:: + + 101 // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) + +.. _lang-constants-integers-bin: + +**Binary** is base two. Only characters 0 and 1 are valid. + + + +Example: +:: + + B101 // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) + +The binary formatter only works on bytes (8 bits) between 0 (B0) +and 255 (B11111111). If it is convenient to input an int (16 bits) +in binary form you can do it a two-step procedure such as: + + + +:: + + myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte + +.. _lang-constants-integers-oct: + +**Octal** is base eight. Only characters 0 through 7 are valid. Octal +values are indicated by the prefix "0". + +Example: + +:: + + 0101 // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) + +Warning +It is possible to generate a hard-to-find bug by (unintentionally) +including a leading zero before a constant and having the compiler +unintentionally interpret your constant as octal. + +.. _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". +Note that A-F may be syted in upper or lower case (a-f). + + + +Example: + +:: + + 0x101 // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) + +.. _lang-constants-integers-u-l: + +U & L formatters +^^^^^^^^^^^^^^^^ + +By default, an integer constant is treated as an +`int `_ with the attendant +limitations in values. To specify an integer constant with another +data type, follow it with: + + + + +- a 'u' or 'U' to force the constant into an unsigned data format. + Example: ``33u`` +- a 'l' or 'L' to force the constant into a long data format. + Example: ``100000L`` +- a 'ul' or 'UL' to force the constant into an unsigned long + constant. Example: ``32767ul`` + + + + +See also +-------- + + +- `pinMode() `_ +- `Integer Constants `_ +- `boolean variables `_ +- `#define `_ +- `byte `_ +- `int `_ +- `unsigned int `_ +- `long `_ +- `unsigned long `_ + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/constrain.rst b/docs/source/lang/constrain.rst new file mode 100644 index 0000000..297a2d4 --- /dev/null +++ b/docs/source/lang/constrain.rst @@ -0,0 +1,65 @@ +.. highlight:: cpp + +.. _lang-constrain: + +constrain(x, a, b) +================== + +Description +----------- + +(Macro) Constrains a number to be within a range. + + +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() ` +- :ref:`max() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/continue.rst b/docs/source/lang/continue.rst new file mode 100644 index 0000000..21b3984 --- /dev/null +++ b/docs/source/lang/continue.rst @@ -0,0 +1,34 @@ +.. highlight:: cpp + +.. _lang-continue: + +========== + continue +========== + +The ``continue`` keyword skips the rest of the current iteration of a +:ref:`while `\ , :ref:`for `\ , or +:ref:`do/while ` loop. It continues by checking the +conditional expression of the loop, and proceeding with any subsequent +iterations. + + +Example +======= + +:: + + + for (x = 0; x < 255; x ++) { + if (x > 40 && x < 120) { // create jump in values + continue; // skips the next two lines and goes to the + // beginning of the loop, with the next value of x + } + + digitalWrite(PWMpin, x); + delay(50); + } + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cos.rst b/docs/source/lang/cos.rst new file mode 100644 index 0000000..3fbb0af --- /dev/null +++ b/docs/source/lang/cos.rst @@ -0,0 +1,32 @@ +.. _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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See also +-------- + + +- :ref:`sin() ` +- :ref:`tan() ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/define.rst b/docs/source/lang/define.rst new file mode 100644 index 0000000..30738ec --- /dev/null +++ b/docs/source/lang/define.rst @@ -0,0 +1,56 @@ +.. highlight:: cpp + +.. _lang-define: + +#define +======= + +``#define`` is a useful C and C++ feature that allows the programmer +to give a name to a constant value before the program is compiled. +The compiler will replace references to these constants with the +defined value at compile time. + +This can have some unwanted side effects. In general, the :ref:`const +` keyword is preferred for defining constants. + + +Syntax +------ + +The following line would define the name ``MY_CONSTANT`` to have value +``value``:: + + #define MY_CONSTANT value + +Note that the ``#`` is necessary. It is usually good style for the +name to be capitalized, although this is not required. + +There is no semicolon after the #define statement. If you include one, +the compiler will likely throw cryptic errors in unrelated places. +That is, **don't do this**:: + + // DON'T DO THIS! THE SEMICOLON SHOULDN'T BE THERE! + #define NAME value; + +Similarly, including an equal sign after the ``#define`` line will +also generate a cryptic compiler error further down the page. That +is, **don't do this, either**:: + + // DON'T DO THIS, EITHER! THE EQUALS SIGN SHOULDN'T BE THERE! + #define NAME = value + +Example +------- + +:: + + #define LED_PIN 13 + // The compiler will replace any mention of LED_PIN with + // the value 3 at compile time. + +See Also +-------- +- :ref:`const ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/delay.rst b/docs/source/lang/delay.rst new file mode 100644 index 0000000..90ca268 --- /dev/null +++ b/docs/source/lang/delay.rst @@ -0,0 +1,72 @@ +.. 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() ` function +and the "Blink Without Delay" sketch cited :ref:`below +`\ . 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() `\ ) values +and pin states are maintained, and :ref:`interrupts +` will work as they should. + + +Example +------- + +:: + + int ledPin = 13; // LED connected to pin 13 + + void setup() { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + +.. _lang-delay-seealso: + +See also +-------- + + +- :ref:`millis() ` +- :ref:`micros() ` +- :ref:`delayMicroseconds() ` +- (Arduino) `Blink Without Delay + `_ example (works + unmodified on Maple) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/delaymicroseconds.rst b/docs/source/lang/delaymicroseconds.rst new file mode 100644 index 0000000..24a8286 --- /dev/null +++ b/docs/source/lang/delaymicroseconds.rst @@ -0,0 +1,65 @@ +.. 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 ` +- :ref:`micros ` +- :ref:`delay ` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/detachinterrupt.rst b/docs/source/lang/detachinterrupt.rst new file mode 100644 index 0000000..adb2439 --- /dev/null +++ b/docs/source/lang/detachinterrupt.rst @@ -0,0 +1,37 @@ +.. _lang-detachinterrupt: + +detachInterrupt() +================= + +Used to disable an interrupt specified with +:ref:`lang-attachinterrupt`\ . + + +Library Documentation +--------------------- + +.. doxygenfunction:: detachInterrupt + +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() ` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/digitalread.rst b/docs/source/lang/digitalread.rst new file mode 100644 index 0000000..71583ca --- /dev/null +++ b/docs/source/lang/digitalread.rst @@ -0,0 +1,61 @@ +.. highlight:: cpp + +.. _lang-digitalread: + +digitalRead() +============= + +Description +----------- + +Reads the value from a specified digital pin, either :ref:`HIGH +` or :ref:`LOW `. + + +Library Documentation +--------------------- + +.. doxygenfunction:: digitalRead + + +Example +------- + +The following example turns the LED on when the button is pressed:: + + int ledPin = 13; // LED connected to Maple pin 13 + int buttonPin = 38; // BUT connected to Maple pin 38 + + void setup() { + pinMode(ledPin, OUTPUT); + pinMode(buttonPin, INPUT); + } + + void loop() { + int val = digitalRead(buttonPin); // reads the input pin + digitalWrite(ledPin, val); + } + +Note +---- + +If the pin isn't connected to anything, ``digitalRead()`` can return +either HIGH or LOW (and this can change in a way that seems random). + +Arduino Compatibility +--------------------- + +The Maple version of ``digitalRead()`` is compatible with Arduino. + + +See Also +-------- + +- :ref:`pinMode ` +- :ref:`digitalWrite ` + + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/digitalwrite.rst b/docs/source/lang/digitalwrite.rst new file mode 100644 index 0000000..419ef3a --- /dev/null +++ b/docs/source/lang/digitalwrite.rst @@ -0,0 +1,116 @@ +.. _lang-digitalwrite: + +digitalWrite() +============== + +Description +----------- + +Write a `HIGH `_ or a +`LOW `_ value to a +digital pin. + + + +If the pin has been configured as an OUTPUT with +`pinMode `_\ (), its voltage +will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) +for HIGH, 0V (ground) for LOW. + + + +If the pin is configured as an INPUT, writing a HIGH value with +digitalWrite() will enable an internal 20K pullup resistor (see the +`tutorial on digital pins `_). +Writing LOW will disable the pullup. The pullup resistor is enough +to light an LED dimly, so if LEDs appear to work, but very dimly, +this is a likely cause. The remedy is to set the pin to an output +with the pinMode() function. + + + +**NOTE:** Digital pin 13 is harder to use as a digital input than +the other digital pins because it has an LED and resistor attached +to it that's soldered to the board on most boards. If you enable +its internal 20k pull-up resistor, it will hang at around 1.7 V +instead of the expected 5V because the onboard LED and series +resistor pull the voltage level down, meaning it always returns +LOW. If you must use pin 13 as a digital input, use an external +pull down resistor. + + + +Syntax +------ + +digitalWrite(pin, value) + + + +Parameters +---------- + +pin: the pin number + + + +value: `HIGH `_ or +`LOW `_ + + + +Returns +------- + +none + + + +Example +------- + +:: + + + int ledPin = 13; // LED connected to digital pin 13 + + void setup() + { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() + { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + + + +Sets pin 13 to HIGH, makes a one-second-long delay, and sets the +pin back to LOW. + + + +Note +---- + +The analog input pins can be used as digital pins, referred to as +A0, A1, etc. + + + +See also +-------- + + +- `pinMode `_\ () +- `digitalRead `_\ () +- `Tutorial: Digital Pins `_ + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/double.rst b/docs/source/lang/double.rst new file mode 100644 index 0000000..b4a1219 --- /dev/null +++ b/docs/source/lang/double.rst @@ -0,0 +1,51 @@ +.. _lang-double: + +double +====== + +Description +----------- + +Double precision floating point number. Occupies 8 bytes. On Maple, +the ``double`` type has a range of approximately -1.79769×10^308 to +1.79769×10^308; the ``double`` type subject to the same :ref:`overflow +issues ` as any numeric data type. + +Floating point numbers are not exact, and may yield strange results +when compared. For example ``6.0 / 3.0`` may not equal ``2.0``. You +should instead check that the absolute value of the difference between +the numbers is less than some small number. + +Floating point math is also much slower than integer math in +performing calculations, so should be avoided if, for example, a loop +has to run at top speed for a critical timing function. Programmers +often go to some lengths to convert floating point calculations to +integer math to increase speed. + +For more information, see the `Wikipedia article on floating point +math `_\ . + +Floating-point numbers represent numbers with "decimal point", unlike +integral types, which always represent whole numbers. Floating-point +numbers are often used to approximate analog and continuous values +because they have greater resolution than integers. + +The double implementation on the Maple uses twice the number of bytes +as a :ref:`float `, with the corresponding gains in +precision. + +Tip +--- + +Users who borrow code from other sources that includes ``double`` +variables may wish to examine the code to see if the implied range and +precision are different from that actually achieved on the Maple. + +See Also +-------- + +- :ref:`float ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/doublecast.rst b/docs/source/lang/doublecast.rst new file mode 100644 index 0000000..4ea1776 --- /dev/null +++ b/docs/source/lang/doublecast.rst @@ -0,0 +1,30 @@ +.. highlight:: cpp + +.. _lang-doublecast: + +double() (cast) +=============== + +Description +----------- + +Converts a value to the :ref:`double ` floating point +data type. Here is an example:: + + int x = 2; + double d = double(x); // d now holds 2.0, a double value + +The value ``x`` can be of any type. However, if ``x`` is not a number +(like an ``int`` or ``long``), you will get strange results. + +See the :ref:`double ` reference for details about the +precision and limitations of ``double`` values on the Maple. + +See Also +-------- + +- :ref:`double ` +- :ref:`float ` +- :ref:`float() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/dowhile.rst b/docs/source/lang/dowhile.rst new file mode 100644 index 0000000..77e02a3 --- /dev/null +++ b/docs/source/lang/dowhile.rst @@ -0,0 +1,27 @@ +.. highlight:: cpp + +.. _lang-dowhile: + +do/while Loop +============= + +A ``do`` loop works in the same manner as a :ref:`while +` loop, with the exception that the condition is tested +at the end of the loop, so the ``do`` loop will *always* run at least +once. + +This is the basic syntax:: + + do { + // statement block + } while (test condition); + +Example:: + + do { + delay(50); // wait for sensors to stabilize + x = readSensors(); // check the sensors + } while (x < 100); + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/else.rst b/docs/source/lang/else.rst new file mode 100644 index 0000000..863f21b --- /dev/null +++ b/docs/source/lang/else.rst @@ -0,0 +1,54 @@ +.. highlight:: cpp + +.. _lang-else: + +if/else +======= + +``if``/\ ``else`` allows greater control over the flow of code than +the basic :ref:`if ` statement, by allowing multiple tests +to be grouped together. For example, an :ref:`analog input +` could be tested, with one action taken if the +input was less than 500, and another action taken if the input was 500 +or greater. The code would look like this:: + + if (pinFiveInput < 500) { + // action A + } else { + // action B + } + +``else`` can precede another ``if`` test, so that multiple, mutually +exclusive tests can be run at the same time. + +Each test will proceed to the next one until a true test is +encountered. When a true test is found, its associated block of code +is run, and the program then skips to the line following the entire +if/else construction. If no test proves to be true, the default +``else`` block is executed, if one is present, and sets the default +behavior. + + +Note that an ``else if`` block may be used with or without a +terminating ``else`` block, and vice-versa. An unlimited number of +such ``else if`` branches is allowed. Here is a code example:: + + if (pinFiveInput < 500) { + // do Thing A + } else if (pinFiveInput >= 1000) { + // do Thing B + } else { + // do Thing C + } + +Another way to express branching, mutually exclusive tests, is with a +:ref:`switch/case ` statement. + +See Also +-------- + +- :ref:`if ` +- :ref:`switch/case ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/enum.rst b/docs/source/lang/enum.rst new file mode 100644 index 0000000..5ecd99c --- /dev/null +++ b/docs/source/lang/enum.rst @@ -0,0 +1,8 @@ +.. _lang-enum: + +enum +==== + +Stub. + +Reference this from language.rst diff --git a/docs/source/lang/float.rst b/docs/source/lang/float.rst new file mode 100644 index 0000000..ef1a339 --- /dev/null +++ b/docs/source/lang/float.rst @@ -0,0 +1,53 @@ +.. highlight:: cpp + +.. _lang-float: + +float +===== + +Description +----------- + +Single-precision floating point number. Occupies 4 bytes. On Maple, +the ``float`` type has a range of approximately -3.40282×10^38 to +3.40282×10^38; the ``float`` type is subject to the same +:ref:`overflow issues ` as any numeric data +type. + +``float``\ s have only 6-7 decimal digits of precision. That means the +total number of digits, not the number to the right of the decimal +point. You can get more precision by using a :ref:`double +` (which has a precision of about 16 decimal digits). + +The following example declares a ``float`` value named ``myfloat``:: + + float myfloat; + +This example declares a ``float`` value named ``sensorCalibrate``, +with value 1.117:: + + float sensorCalibrate = 1.117; + +The general syntax for declaring a float named ``var`` with value +``val`` is:: + + float var = val; + +Here is a more extended example involving a :ref:`float cast +`:: + + int x; + int y; + float z; + + x = 1; + y = x / 2; // y now contains 0, ints can't hold fractions + z = float(x) / 2; // z now contains .5 + +See Also +-------- + +- :ref:`double ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/floatcast.rst b/docs/source/lang/floatcast.rst new file mode 100644 index 0000000..7476188 --- /dev/null +++ b/docs/source/lang/floatcast.rst @@ -0,0 +1,31 @@ +.. highlight:: cpp + +.. _lang-floatcast: + +float() (cast) +============== + +Description +----------- + +Converts a value to the :ref:`float ` data type. Here +is an example (see the :ref:`constants reference +` for an explanation of the "2.0f"):: + + int x = 2; + float f = float(x); // f now holds 2.0f, a float value + +The value ``x`` can be of any type. However, if ``x`` is not a number +(like an ``int``), you will get strange results. + +See the :ref:`float ` reference for details about the +precision and limitations of ``float`` values on the Maple. + +See Also +-------- + +- :ref:`float ` +- :ref:`double ` +- :ref:`double() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/for.rst b/docs/source/lang/for.rst new file mode 100644 index 0000000..6b00d7a --- /dev/null +++ b/docs/source/lang/for.rst @@ -0,0 +1,142 @@ +.. highlight:: cpp + +.. _lang-for: + +for Loops +========= + +.. contents:: Contents + :local: + +Description +----------- + +A ``for`` loop is used to repeat a block of statements enclosed in +curly braces. ``for`` loops are useful for performing repetitive +operations, and are often used in combination with :ref:`arrays +` to operate on collections of data or multiple +:ref:`pins `. A ``for`` loop is composed of two parts: first, a +*header*, which sets up the for loop, and then a *body*, which is made +up of lines of code enclosed in curly braces. + +There are three parts to the ``for`` loop header: an *initialization* +expression, *loop condition* expression, and a *post-loop* +expression. The general syntax looks like this:: + + for (initialization; condition; post-loop) { + // all of these lines inside the curly braces are part + // of the loop body. + statement 1; + statement 2; + ... + } + +(Note that there is no semicolon after the post-loop). The +initialization happens first and exactly once, before the loop begins. +Each time through the loop, the condition is tested. The condition is +a :ref:`boolean ` expression. If it is true, then the +list of statements inside the curly braces are executed. Next, the +post-loop is executed. The loop then begins again by evaluating the +condition again, entering the loop body if it is true. This proceeds +until the condition becomes false. + +Examples +-------- + +Here's an example:: + + // Dim an LED using a PWM pin + int pwmPin = 9; // LED in series with 470 ohm resistor on pin 9 + + void setup() { + pinMode(pwmPin, PWM); + } + + void loop() { + for (int i=0; i <= 65535; i++) { + pwmWrite(pwmPin, i); + delay(1); + } + } + +There is a ``for`` loop In the :ref:`loop() ` function of +the above example. This loop starts by declaring an ``int`` variable +named ``i``, whose value starts out at zero. The loop proceeds by +checking if ``i`` is less than or equal to 65535. Since ``i`` is +zero, this is true, and so the calls to :ref:`pwmWrite() +` and :ref:`delay() ` happen next. At this +point, the post-loop expression ``i++`` is evaluated, which +:ref:`increments ` ``i``, so that ``i`` becomes one. +That concludes the first time through the loop. Each "time through +the loop" is referred to as an *iteration*. + +The loop then jumps back to the beginning, checking the condition as +the beginning of its second iteration (initialization is skipped, +since this only happens once, before the first iteration). One is +less than 65535, so the loop statements are executed again. This +proceeds over and over until the iteration when ``i`` finally +reaches 65536. At that point, the condition is no longer true, so the +loop stops executing, and the ``loop()`` function returns. + +Here's another example, using a ``for`` loop to brighten and fade an +LED (see the :ref:`pwmWrite() ` reference for more +information):: + + int pwmPin = 9; // hook up the LED to pin 9 + void loop() { + int x = 1; + for (int i = 0; i >= 0; i += x) { + analogWrite(pwmPin, i); // controls the brightness of the LED + if (i == 65535) { + x = -1; // switch direction, so i starts decreasing + } + delay(1); + } + } + +Coding Tips +----------- + +The C ``for`` loop is more flexible than ``for`` loops found in some +other computer languages, including BASIC. Any or all of the three +header elements may be left blank, although the semicolons are +required. Also the statements for initialization, condition, and +post-loop can be any valid C statements, and use any C datatypes, +including :ref:`floating point numbers `. These types +of unusual ``for`` loops sometimes provide solutions to less-common +programming problems. + +For example, using a multiplication in the post-loop line will +generate a `geometric progression +`_:: + + for(int x = 1; x <= 100; x = x * 2) { + SerialUSB.println(x); + } + + +This loop prints out the numbers 1, 2, 4, 8, ..., 64. Check +your understanding of ``for`` loops by answering the following two +questions (answers are in footnote [#fanswers]_\ ): + +1. How many iterations occur before the loop finishes? + +2. Why does it stop at 64? + +See also +-------- + +- :ref:`while ` loops +- :ref:`do ` loops + +.. rubric:: Footnotes + +.. [#fanswers] + 1. Seven. + + 2. After the seventh iteration, the post-loop causes ``x`` to + equal 128. This is larger than 100, so the loop condition is + false, and the loop stops. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/goto.rst b/docs/source/lang/goto.rst new file mode 100644 index 0000000..96a6262 --- /dev/null +++ b/docs/source/lang/goto.rst @@ -0,0 +1,130 @@ +.. highlight:: cpp + +.. _lang-goto: + +Labels and goto +=============== + +A *label* gives a name to a line of code within a function. You can +label a line by writing a name for it, then a colon (``:``), before +the line starts. The ``goto`` keyword allows program flow to transfer +to a labeled line from anywhere within the same function. + +.. warning:: The use of ``goto`` is discouraged in C and C++ + programming. It is *never necessary* to use ``goto`` to write a + program. + + Unless you know what you're doing, using ``goto`` tends to + encourage code which is harder to debug and understand than + programs without ``goto`` that do the same thing. That said, + however, it's sometimes useful; :ref:`see below ` + for a concrete example. + +Using Labels and goto +--------------------- + +Labels and ``goto`` are probably best explained through example. +Let's start with an example of how to label lines. The first line +(``int x = analogRead(some_pin);``) in the :ref:`loop ` +function below has label ``readpin``. The third line (``delay(x);``) +has label ``startdelay``. The second line (``SerialUSB.println(x);``) +does not have a label:: + + void loop() { + readpin: + int x = analogRead(some_pin); + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +Anything which can be a :ref:`variable ` name can +be a label. + +Let's say that we wanted to print ``x`` only if it was very large, say +at least 2000. We might want to do this just so anybody watching on a +:ref:`serial monitor ` would know they were in for +a longer wait than usual. We can accomplish this through the use of a +``goto`` statement that skips the printing if ``x`` is less than +2000:: + + void loop() { + readpin: + int x = analogRead(some_pin); + if (x < 2000) { + goto startdelay; + } + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +In this modified program, whenever ``x`` is less than 2000, the body +of the :ref:`if ` statement in the second line is +executed. The ``goto`` statement inside the ``if`` body skips +straight to the line labeled ``startdelay``, passing over the line +doing the printing. + +A ``goto`` does not have to "move forwards"; it can go "backwards", +too. For example, the following program prints "5" forever (why?):: + + void loop() { + printfive: + SerialUSB.println(5); + goto printfive; + SerialUSB.println(6); + } + +.. _goto-when-to-use: + +When to Use goto +---------------- + +As mentioned above, use of ``goto`` is `generally discouraged +`_. However, +when used with care, ``goto`` can simplify certain programs. One +important use case for ``goto`` is breaking out of deeply nested +:ref:`for ` loops or :ref:`if ` logic blocks. +Here's an example:: + + for(int r = 0; r < 255; r++) { + for(int g = 255; g > -1; g--) { + for(int b = 0; b < 255; b++) { + if (analogRead(0) > 250) { + goto bailout; + } + // more statements ... + } + // innermost loop ends here + } + } + bailout: + // more code here + +In the above example, whenever the :ref:`analog reading +` on pin 0 was greater than 250, the program would +jump to the line labeled ``bailout``, exiting all three loops at once. + +While there is already a :ref:`break ` keyword for +breaking out of a loop, it will only break out of the *innermost* +loop. So, if instead of saying "``goto bailout;``", there was a +"``break;``" instead, the program would only exit from the loop with +header "``for(int b = 0; b < 255; b++)``". The program would continue +at the line which reads "``// innermost loop ends here``", which is +clearly undesirable if you wanted to leave all three loops at once. + +More examples of when ``goto`` is a good choice are given in Donald +Knuth's paper, "Structured Programming with go to Statements"; see +below for a link. + +See Also +-------- + +- Dijkstra, Edsger W. `Go To Statement Considered Harmful `_ (PDF) + +- Knuth, Donald. `Structured Programming with go to Statements `_ (PDF) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/highbyte.rst b/docs/source/lang/highbyte.rst new file mode 100644 index 0000000..af0bfcd --- /dev/null +++ b/docs/source/lang/highbyte.rst @@ -0,0 +1,53 @@ +.. _lang-highbyte: + +highByte(x) +=========== + +.. 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. + +Description +----------- + +(Macro) Extracts the second lowest byte of an integral data type. + +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() ` + + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/if.rst b/docs/source/lang/if.rst new file mode 100644 index 0000000..02ba1e7 --- /dev/null +++ b/docs/source/lang/if.rst @@ -0,0 +1,81 @@ +.. highlight:: cpp + +.. _lang-if: + +if Statements +============= + +An ``if`` statement is used to execute code when certain conditions +are met. The general syntax for an ``if`` statement is:: + + if (condition) { + body + } + +An ``if`` statement first tests whether its *condition* is true (such +as an input being above a certain number). If the condition is true, +the ``if`` statement executes its *body*, which is made up of lines of +code inside :ref:`curly braces `. If the condition is +false, the body is not executed. Here's a more concrete example:: + + if (someVariable > 50) { + // do something here + } + +The program tests to see if ``someVariable`` is greater than 50. If it +is, the program executes every line in the curly braces (which in the +above example does nothing, since the body is just the :ref:`comment +` line "``// do something here``"). + +Put another way, if the statement in parentheses is true, the +statements inside the braces are run. If not, the program skips over +the code. + +An ``if`` statement's condition (which is inside the parentheses after +``if``) often uses one or more :ref:`boolean ` or +:ref:`comparison ` operators. + +Writing the if Body +------------------- + +The brackets may be omitted after an ``if`` statement's +conditional. If this is done, the next line (which ends in a +semicolon) becomes the only line in the body. The following three +``if`` statements all do the same thing:: + + if (x > 120) digitalWrite(ledPin, HIGH); + + if (x > 120) + digitalWrite(ledPin, HIGH); + + if (x > 120) { + digitalWrite(ledPin, HIGH); + } + +However, the following two examples are different:: + + // example 1: two lines of code in the if body + if (x > 120) { + digitalWrite(ledPin1, HIGH); + digitalWrite(ledPin2, HIGH); + } + + // example 2: one line of code in the if body, and + // another line of code after the if statement + if (x > 120) + digitalWrite(ledPin1, HIGH); // this is in the if body + digitalWrite(ledPin2, HIGH); // this is NOT in the if body + +In the first example, since the body is enclosed in curly braces, both +lines are included. In the second example, since the curly braces are +missing, only the first line is in the ``if`` body. + +See Also +-------- + +- :ref:`boolean operators ` +- :ref:`comparison operators ` +- :ref:`else ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/include.rst b/docs/source/lang/include.rst new file mode 100644 index 0000000..a8bc74c --- /dev/null +++ b/docs/source/lang/include.rst @@ -0,0 +1,71 @@ +.. highlight:: cpp + +.. _lang-include: + +#include +======== + +``#include`` is used to include outside libraries in your sketch. +This gives the programmer access to a large group of standard C +libraries (groups of pre-made functions and data types), and also +libraries written especially for Maple. + +Example +------- + +This example (from the `Arduino LiquidCrystal Tutorial +`_) includes a library +that is used to control :ref:`LCD displays `:: + + // include the library code: + #include + + // initialize the library with the numbers of the interface pins + LiquidCrystal lcd(12, 11, 5, 4, 3, 2); + + void setup() { + // set up the LCD's number of columns and rows: + lcd.begin(16, 2); + // Print a message to the LCD. + lcd.print("hello, world!"); + } + + void loop() { + // set the cursor to column 0, line 1 + // (note: line 1 is the second row, since counting begins with 0): + lcd.setCursor(0, 1); + // print the number of seconds since reset: + lcd.print(millis()/1000); + } + +Note that a ``#include`` line, like :ref:`#define `, +has **no semicolon**. The compiler will print strange error messages +if you add one. + +C Standard Library +------------------ + +The standard C library that comes with Maple is called `newlib +`_. Its main sources of documentation +are its `main reference `_ +page and its `math functions +`_ reference page. Here's an +example that imports the math.h library in order to take the `cube +root `_ of a number:: + + #include + + void setup() { + // no setup necessary + } + + void loop() { + // "cbrt" stands for "cube root" + double cubeRootOf3 = cbrt(3.0); + // prints a number that is approximately the cube root of 3: + SerialUSB.println(cubeRootOf3); + } + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/increment.rst b/docs/source/lang/increment.rst new file mode 100644 index 0000000..5536a0a --- /dev/null +++ b/docs/source/lang/increment.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-increment: + +Increment (``++``) and Decrement (``--``) +========================================= + +These operators increment (add one to) or decrement (subtract one +from) a variable. If they come before the variable, they return its +new value; otherwise, they return its old value. + +Some quick examples:: + + x++; // adds one to x, and returns the old value of x + ++x; // adds one to x, and returns the new value of x + + x--; // decrement x by one and returns the old value of x + --x; // decrement x by one and returns the new value of x + +A more extended example:: + + x = 2; + y = ++x; // x now contains 3, y contains 3 + y = x--; // x contains 2 again, y still contains 3 + +.. warning:: Be careful! You cannot put a space in between the two + ``+`` or ``-`` signs. This example is broken:: + + // this line won't compile (notice the extra space): + int y = x+ +; + +Parameters +---------- + +**x**: an integer value (like an ``int``, ``long``, ``unsigned int``, +etc.). + +See also +-------- + +- :ref:`Compound arithmetic operators ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/int.rst b/docs/source/lang/int.rst new file mode 100644 index 0000000..ac2f16a --- /dev/null +++ b/docs/source/lang/int.rst @@ -0,0 +1,67 @@ +.. highlight:: cpp + +.. _lang-int: + +int +=== + +Description +----------- + +The ``int`` data type represents integers. Integers are your primary +data type for number storage, and store a 4 byte value. This yields a +range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a +maximum value of (2^31) - 1; that's about negative 2 billion to +positive 2 billion). + +An ``int`` stores a negative number with a technique called `two's +complement math +`_\ . +The highest bit in an ``int``, sometimes refered to as the "sign" bit, +flags the number as a negative number. (See the linked article on +two's complement for more information). + +The Maple takes care of dealing with negative numbers for you, so that +arithmetic operations work mostly as you'd expect. There can be an +:ref:`unexpected complication ` in +dealing with the :ref:`bitshift right operator (>>) +`, however. + +Here is an example of declaring an ``int`` variable named ``ledPin``, +then giving it value 13:: + + int ledPin = 13; + +The general syntax for declaring an ``int`` variable named ``var``, +then giving it value ``val``, looks like:: + + int var = val; + +.. _lang-int-overflow: + +Integer Overflow +---------------- + +When ``int`` variables leave the range specified above, they +:ref:`roll over ` in the other direction. +Here are some examples:: + + int x; + x = -2,147,483,648; + x--; // x now contains 2,147,483,647; rolled over "left to right" + + x = 2,147,483,647; + x++; // x now contains -2,147,483,648; rolled over "right to left" + +See Also +-------- + +- :ref:`unsigned int ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/intcast.rst b/docs/source/lang/intcast.rst new file mode 100644 index 0000000..03c0c07 --- /dev/null +++ b/docs/source/lang/intcast.rst @@ -0,0 +1,32 @@ +.. highlight:: cpp + +.. _lang-intcast: + +int() +===== + +Description +----------- + +Converts a value to the :ref:`int ` data type. Here is +an example:: + + double d = 2.5; + int i = int(d); // i holds "2", an int value + +The value inside of the parentheses (``int(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. + +See the :ref:`int ` reference for details about the +precision and limitations of ``int`` variables on the Maple. + +See Also +-------- + +- :ref:`int ` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/interrupts.rst b/docs/source/lang/interrupts.rst new file mode 100644 index 0000000..5ca7041 --- /dev/null +++ b/docs/source/lang/interrupts.rst @@ -0,0 +1,62 @@ +.. _lang-interrupts: + +interrupts() +============ + +Description +----------- + +Re-enables interrupts (after they've been disabled by +`noInterrupts `_\ ()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None + + + +Returns +------- + +None + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `noInterrupts `_\ () +- `attachInterrupt `_\ () +- `detachInterrupt `_\ () + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/keywords.rst b/docs/source/lang/keywords.rst new file mode 100644 index 0000000..451701e --- /dev/null +++ b/docs/source/lang/keywords.rst @@ -0,0 +1,11 @@ +.. _lang-keywords: + +Keywords +======== + +Stub. + +Include list of all C++ keywords, with links to internal documentation +as appropriate. + +Reference this page from language.rst diff --git a/docs/source/lang/long.rst b/docs/source/lang/long.rst new file mode 100644 index 0000000..8a19b2b --- /dev/null +++ b/docs/source/lang/long.rst @@ -0,0 +1,55 @@ +.. highlight:: cpp + +.. _lang-long: + +long +==== + +Description +----------- + +The ``long`` data type stores extended size integer values. You can +use a ``long`` when your values are too large to fit into an :ref:`int +`. A ``long`` occupies 8 bytes of memory. This yields a +range of approximately -9.2×10^18 to 9.2×10^18 (that's 9.2 billion +billion, or about 92 million times the number of stars in the Milky +Way galaxy). The exact range of a ``long`` on the Maple is from +-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, or -2^63 to +(2^63-1). A ``long`` it is subject to the same :ref:`overflow issues +` as any numeric data type. + +Here's an example of declaring a long (see :ref:`integer constants +` for an explanation of the "L" at the end of the +number):: + + // Speed of light in nanometers per second (approximate). + long c = 299792458000000000L; + +The general syntax for declaring an ``long`` variable named ``var``, +then giving it value ``val``, looks like:: + + long var = val; + +This is identical to the ``int`` syntax, with ``long`` replacing +``int``. + +Note that ``long`` values will still :ref:`overflow +`, just like ``int`` values, but their much +larger range makes this less likely to happen. + +The downside to using a ``long`` instead of an ``int`` (besides the +extra storage) is that :ref:`arithmetic ` operations +on ``long``\ s will take slightly longer than on ``int``\ s. + +See Also +-------- + +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`int ` +- :ref:`unsigned int ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/longcast.rst b/docs/source/lang/longcast.rst new file mode 100644 index 0000000..16d7582 --- /dev/null +++ b/docs/source/lang/longcast.rst @@ -0,0 +1,30 @@ +.. highlight:: cpp + +.. _lang-longcast: + +long() +====== + +Description +----------- + +Converts a value to the :ref:`long ` data type. Here is +an example:: + + double d = 2.5; + long i = long(d); // i holds "2L", an long value + +The value inside of the parentheses (``long(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. + +See the :ref:`long ` reference for details about the +precision and limitations of ``long`` variables on the Maple. + +See Also +-------- + +- :ref:`long ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/loop.rst b/docs/source/lang/loop.rst new file mode 100644 index 0000000..d8f6183 --- /dev/null +++ b/docs/source/lang/loop.rst @@ -0,0 +1,45 @@ +.. highlight:: cpp + +.. _lang-loop: + +loop() +====== + +After creating a :ref:`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() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/lowbyte.rst b/docs/source/lang/lowbyte.rst new file mode 100644 index 0000000..f9fb711 --- /dev/null +++ b/docs/source/lang/lowbyte.rst @@ -0,0 +1,45 @@ +.. _lang-lowbyte: + +lowByte() +========= + +Description +----------- + +Extracts the low-order (rightmost) byte of a variable (e.g. a +word). + + + +Syntax +------ + +lowByte(x) + + + +Parameters +---------- + +x: a value of any type + + + +Returns +------- + +byte + + + +See also +-------- + + +- `highByte `_\ () +- `word `_\ () + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/map.rst b/docs/source/lang/map.rst new file mode 100644 index 0000000..40b12a8 --- /dev/null +++ b/docs/source/lang/map.rst @@ -0,0 +1,122 @@ +.. _lang-map: + +map(value, fromLow, fromHigh, toLow, toHigh) +============================================ + +Description +----------- + +Re-maps a number from one range to another. That is, a **value** of +**fromLow** would get mapped to **toLow**, a value of **fromHigh** +to **toHigh**, values in-between to values in-between, etc. + + + +Does not constrain values to within the range, because out-of-range +values are sometimes intended and useful. The constrain() function +may be used either before or after this function, if limits to the +ranges are desired. + + + +Note that the "lower bounds" of either range may be larger or +smaller than the "upper bounds" so the map() function may be used +to reverse a range of numbers, for example + + + +``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 and works well. + + + +The map() function uses integer math so will not generate +fractions, when the math might indicate that it should do so. +Fractional remainders are truncated, and are not rounded or +averaged. + + + +Parameters +---------- + +value: the number to map + + + +fromLow: the lower bound of the value's current range + + + +fromHigh: the upper bound of the value's current range + + + +toLow: the lower bound of the value's target range + + + +toHigh: the upper bound of the value's target range + + + +Returns +------- + +The mapped value. + + + +Example +------- + +:: + + /* Map an analog value to 8 bits (0 to 255) */ + void setup() {} + + void loop() + { + int val = analogRead(0); + val = map(val, 0, 1023, 0, 255); + analogWrite(9, val); + } + + + +Appendix +~~~~~~~~ + +For the mathematically inclined, here's the whole function + + + +:: + + long map(long x, long in_min, long in_max, long out_min, long out_max) + { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + } + + + +See Also +-------- + + +- `constrain `_\ () + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/max.rst b/docs/source/lang/max.rst new file mode 100644 index 0000000..7dbf6a7 --- /dev/null +++ b/docs/source/lang/max.rst @@ -0,0 +1,63 @@ +.. highlight:: cpp + +.. _lang-max: + +max(x, y) +========= + +Description +----------- + +(Macro) Calculates the maximum of two numbers. + + + +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() + ` 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 version of ``max()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`min() ` +- :ref:`constrain() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/micros.rst b/docs/source/lang/micros.rst new file mode 100644 index 0000000..711c013 --- /dev/null +++ b/docs/source/lang/micros.rst @@ -0,0 +1,69 @@ +.. _lang-micros: + +micros() +======== + +Description +----------- + +Returns the number of microseconds since the Arduino board began +running the current program. This number will overflow (go back to +zero), after approximately 70 minutes. On 16 MHz Arduino boards +(e.g. Duemilanove and Nano), this function has a resolution of four +microseconds (i.e. the value returned is always a multiple of +four). On 8 MHz Arduino boards (e.g. the LilyPad), this function +has a resolution of eight microseconds. + + + +*Note*: there are 1,000 microseconds in a millisecond and 1,000,000 +microseconds in a second. + + + +Parameters +---------- + +None + + + +Returns +------- + +Number of microseconds since the program started (*unsigned long*) + + + +Example +------- + +:: + + unsigned long time; + + void setup(){ + Serial.begin(9600); + } + void loop(){ + Serial.print("Time: "); + time = micros(); + //prints time since program started + Serial.println(time); + // wait a second so as not to send massive amounts of data + delay(1000); + } + + + +See also +-------- + + +- `millis `_\ () +- `delay `_\ () +- `delayMicroseconds `_\ () + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/millis.rst b/docs/source/lang/millis.rst new file mode 100644 index 0000000..6ebfff5 --- /dev/null +++ b/docs/source/lang/millis.rst @@ -0,0 +1,70 @@ +.. _lang-millis: + +millis() +======== + +Description +----------- + +Returns the number of milliseconds since the Arduino board began +running the current program. This number will overflow (go back to +zero), after approximately 50 days. + + + +Parameters +---------- + +None + + + +Returns +------- + +Number of milliseconds since the program started (*unsigned long*) + + + +Example +------- + +:: + + unsigned long time; + + void setup(){ + Serial.begin(9600); + } + void loop(){ + Serial.print("Time: "); + time = millis(); + //prints time since program started + Serial.println(time); + // wait a second so as not to send massive amounts of data + delay(1000); + } + + + +Tip: +---- + +Note that the parameter for millis is an unsigned long, errors may +be generated if a programmer tries to do math with other datatypes +such as ints. + + + +See also +-------- + + +- `micros `_\ () +- `delay `_\ () +- `delayMicroseconds `_\ () +- `Tutorial: Blink Without Delay `_ + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/min.rst b/docs/source/lang/min.rst new file mode 100644 index 0000000..ffbf1ee --- /dev/null +++ b/docs/source/lang/min.rst @@ -0,0 +1,66 @@ +.. highlight:: cpp + +.. _lang-min: + +min(x, y) +========= + +Description +----------- + +(Macro) Calculates the minimum of two numbers. + + + +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() ` +- :ref:`constrain() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/modulo.rst b/docs/source/lang/modulo.rst new file mode 100644 index 0000000..9e0dabd --- /dev/null +++ b/docs/source/lang/modulo.rst @@ -0,0 +1,77 @@ +.. highlight:: cpp + +.. _lang-modulo: + +% (modulo) +========== + +Description +----------- + +Calculates the `remainder `_ +when one integer is divided by another. It is useful for keeping a +variable within a particular range (e.g. the size of an array). + +Syntax +------ + +:: + + result = dividend % divisor + + + +Parameters +---------- + +**dividend**: the number to be divided + +**divisor**: the number to divide by + +Returns +------- + +The remainder of **dividend**\ /\ **divisor**\ . + +Examples +-------- + +:: + + int x; + x = 7 % 5; // x now contains 2 + x = 9 % 5; // x now contains 4 + x = 5 % 5; // x now contains 0 + x = 4 % 5; // x now contains 4 + +:: + + /* update one value in an array each time through a loop */ + + int values[10]; + int i = 0; + + void setup() { + // no setup necessary + } + + void loop() { + values[i] = analogRead(0); + i = (i + 1) % 10; // modulo operator makes sure i stays between 0 and 9 + } + +Tip +--- + +The modulo operator does not work on floats. For that, you can use +the C standard library function `fmod() +`_. + + +See Also +-------- + +- :ref:`Arithmetic ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/nointerrupts.rst b/docs/source/lang/nointerrupts.rst new file mode 100644 index 0000000..2043c91 --- /dev/null +++ b/docs/source/lang/nointerrupts.rst @@ -0,0 +1,59 @@ +.. _lang-nointerrupts: + +noInterrupts() +============== + +Description +----------- + +Disables interrupts (you can re-enable them with interrupts()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None. + + + +Returns +------- + +None. + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `interrupts `_\ () + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/notone.rst b/docs/source/lang/notone.rst new file mode 100644 index 0000000..22432e2 --- /dev/null +++ b/docs/source/lang/notone.rst @@ -0,0 +1,50 @@ +.. _lang-notone: + +noTone() +======== + +Description +----------- + +Stops the generation of a square wave triggered by +`tone `_\ (). Has no effect if +no tone is being generated. + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +noTone(pin) + + + +Parameters +---------- + +pin: the pin on which to stop generating the tone + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `tone `_ () + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/pinmode.rst b/docs/source/lang/pinmode.rst new file mode 100644 index 0000000..aed23d6 --- /dev/null +++ b/docs/source/lang/pinmode.rst @@ -0,0 +1,76 @@ +.. highlight:: cpp + +.. _lang-pinmode: + +pinMode() +========= + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pinMode + +.. 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 +------- + + :: + + + int ledPin = 13; // LED connected to digital pin 13 + + void setup() + { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() + { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + + + +Arduino Compatibility +--------------------- + +The libmaple implementation of pinMode() supports OUTPUT and INPUT +modes with a meaning identical to that of the Arduino function. + +INPUT_ANALOG and PWM modes were added because the Maple does not +distinguish between analog and digital pins the same way the Arduino +does. Unlike the Arduino, you **must call pinMode**\ () to set up a pin +for these purposes before a call to, e.g., :ref:`lang-analogRead`. +In practice, this should only add a few lines of pinMode() calls to +your :ref:`lang-setup` function. + +OUTPUT_OPEN_DRAIN, INPUT_PULLUP, INPUT_PULLDOWN, and PWM_OPEN_DRAIN +modes represent functionality not currently available on Arduino +boards. + +See also +-------- + +- :ref:`lang-constants` +- :ref:`lang-digitalwrite` +- :ref:`lang-digitalread` +- Maple :ref:`GPIO ` reference page + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/pointer.rst b/docs/source/lang/pointer.rst new file mode 100644 index 0000000..bc48d7d --- /dev/null +++ b/docs/source/lang/pointer.rst @@ -0,0 +1,28 @@ +.. _lang-pointer: + +The pointer operators: & (reference) and \* (dereference) +========================================================= + + +Pointers are one of the more complicated subjects for beginners in +learning C, and it is possible to write the vast majority of +Arduino sketches without ever encountering pointers. However for +manipulating certain data structures, the use of pointers can +simplify the code, and and knowledge of manipulating pointers is +handy to have in one's toolkit. + +Introducing pointers is somewhat outside the scope of this +documentation. However, a good `pointer tutorial +`_ is available. +Also see the `Wikipedia article on pointers +`_, especially +the section on `pointers in C +`_. + +See Also +======== + +- http://xkcd.com/138/ + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/pow.rst b/docs/source/lang/pow.rst new file mode 100644 index 0000000..dbe89b6 --- /dev/null +++ b/docs/source/lang/pow.rst @@ -0,0 +1,29 @@ +.. _lang-pow: + +pow(base, exponent) +=================== + +Calculates the value of a number raised to a power. + +Library Documentation +--------------------- + +.. doxygenfunction:: pow + +Example +------- + +``pow()`` can be used to raise a number to a fractional power. This +is useful for e.g. generating exponential mapping of values or +curves. See the `fscale `_ +function in the Arduino playground for more on this. + +See Also +-------- + +- :ref:`sqrt() ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/pulsein.rst b/docs/source/lang/pulsein.rst new file mode 100644 index 0000000..7bbe84c --- /dev/null +++ b/docs/source/lang/pulsein.rst @@ -0,0 +1,82 @@ +.. _lang-pulsein: + +pulseIn() +========= + +Description +----------- + +Reads a pulse (either HIGH or LOW) on a pin. For example, if +**value** is **HIGH**, **pulseIn()** waits for the pin to go +**HIGH**, starts timing, then waits for the pin to go **LOW** and +stops timing. Returns the length of the pulse in microseconds. +Gives up and returns 0 if no pulse starts within a specified time +out. + + + +The timing of this function has been determined empirically and +will probably show errors in longer pulses. Works on pulses from 10 +microseconds to 3 minutes in length. + + + +Syntax +------ + +pulseIn(pin, value) +pulseIn(pin, value, timeout) + + + +Parameters +---------- + +pin: the number of the pin on which you want to read the pulse. +(*int*) + + + +value: type of pulse to read: either +`HIGH `_ or +`LOW `_. (*int*) + + + +timeout (optional): the number of microseconds to wait for the +pulse to start; default is one second (*unsigned long*) + + + +Returns +------- + +the length of the pulse (in microseconds) or 0 if no pulse started +before the timeout (*unsigned long*) + + + +Example +------- + +:: + + + + int pin = 7; + unsigned long duration; + + void setup() + { + pinMode(pin, INPUT); + } + + void loop() + { + duration = pulseIn(pin, HIGH); + } + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/pwmwrite.rst b/docs/source/lang/pwmwrite.rst new file mode 100644 index 0000000..acc0240 --- /dev/null +++ b/docs/source/lang/pwmwrite.rst @@ -0,0 +1,51 @@ +.. highlight:: cpp + +.. _lang-pwmwrite: + +pwmWrite() +========== + +Writes a :ref:`PWM wave ` to a pin. You can use this to make an +LED get brighter or dimmer, control a servomotor, etc. After a call to +pwmWrite(), the pin will output a steady square wave with the given +duty cycle. You can change the duty cycle later by calling pwmWrite() +again with the same pin and a different duty. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pwmWrite + +Example +------- + +Sets the output to the LED proportional to the value read from the +potentiometer (adapted for Maple from the Arduino `analogWrite() +reference `_):: + + + int ledPin = 13; // LED connected to pin 13 (Maple) + int analogPin = 3; // potentiometer connected to analog pin 3 + int val = 0; // variable to store the read value + + void setup() { + pinMode(ledPin, OUTPUT); // sets the LED pin as output + + pinMode(analogPin, PWM); // sets the potentiometer pin as PWM + // output + } + + void loop() { + val = analogRead(analogPin); // read the input pin + + analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, + // analogWrite values from 0 to 65535 + } + +See Also +-------- + +- :ref:`Maple PWM tutorial ` diff --git a/docs/source/lang/random.rst b/docs/source/lang/random.rst new file mode 100644 index 0000000..51bee67 --- /dev/null +++ b/docs/source/lang/random.rst @@ -0,0 +1,95 @@ +.. _lang-random: + +random() +======== + +Description +----------- + +The random function generates pseudo-random numbers. + + + +Syntax +------ + +random(max) +random(min, max) + + + +Parameters +---------- + +min - lower bound of the random value, inclusive *(optional)* + + + +max - upper bound of the random value, exclusive + + + +Returns +------- + +a random number between min and max-1 (*long*) + + + +Note: +----- + +If it is important for a sequence of values generated by random() +to differ, on subsequent executions of a sketch, use randomSeed() +to initialize the random number generator with a fairly random +input, such as analogRead() on an unconnected pin. + + + +Conversely, it can occasionally be useful to use pseudo-random +sequences that repeat exactly. This can be accomplished by calling +randomSeed() with a fixed number, before starting the random +sequence. + + + +Example +------- + +:: + + long randNumber; + + void setup(){ + Serial.begin(9600); + + // if analog input pin 0 is unconnected, random analog + // noise will cause the call to randomSeed() to generate + // different seed numbers each time the sketch runs. + // randomSeed() will then shuffle the random function. + randomSeed(analogRead(0)); + } + + void loop() { + // print a random number from 0 to 299 + randNumber = random(300); + Serial.println(randNumber); + + // print a random number from 10 to 19 + randNumber = random(10, 20); + Serial.println(randNumber); + + delay(50); + } + + + +See also +-------- + + +- `randomSeed `_\ () + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/randomseed.rst b/docs/source/lang/randomseed.rst new file mode 100644 index 0000000..3dcf4db --- /dev/null +++ b/docs/source/lang/randomseed.rst @@ -0,0 +1,73 @@ +.. _lang-randomseed: + +randomSeed(seed) +================ + +Description +----------- + +randomSeed() initializes the pseudo-random 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. + + + +If it is important for a sequence of values generated by random() +to differ, on subsequent executions of a sketch, use randomSeed() +to initialize the random number generator with a fairly random +input, such as analogRead() on an unconnected pin. + + + +Conversely, it can occasionally be useful to use pseudo-random +sequences that repeat exactly. This can be accomplished by calling +randomSeed() with a fixed number, before starting the random +sequence. + + + +Parameters +---------- + +long, int - pass a number to generate the seed. + + + +Returns +------- + +no returns + + + +Example +------- + +:: + + long randNumber; + + void setup(){ + Serial.begin(9600); + randomSeed(analogRead(0)); + } + + void loop(){ + randNumber = random(300); + Serial.println(randNumber); + + delay(50); + } + + + +See also +-------- + + +- `random `_ + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/return.rst b/docs/source/lang/return.rst new file mode 100644 index 0000000..e1b2924 --- /dev/null +++ b/docs/source/lang/return.rst @@ -0,0 +1,61 @@ +.. highlight:: cpp + +.. _lang-return: + +return +====== + +(Keyword) Terminates a function and return a value from a function to +the calling function, if the function has non-``void`` return type. + +Syntax: +------- + +:: + + // from within a "void" function: + return; + + // from within a non-"void" function: + return value; + +In the second case, ``value`` should have a type which is the same as +the return type of the function, or be convertible to it (like an +``int`` to a ``long``, etc.; see :ref:`this note +` for some references). + +Examples: +--------- + +A function to compare a sensor input to a threshold:: + + // converts analog readings between 0 and 400 to 0, and 400 up to 1. + int checkSensor() { + if (analogRead(0) > 400) { + return 1; + else { + return 0; + } + } + +An early ``return`` is also useful when testing a section of code +without having to "comment out" large sections of possibly buggy code, +like so:: + + void loop() { + + // brilliant code idea to test here + + return; + + // the rest of a dysfunctional sketch here + // this code will never be executed + } + +See Also +-------- + +- :ref:`comments ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/scope.rst b/docs/source/lang/scope.rst new file mode 100644 index 0000000..8e8bb13 --- /dev/null +++ b/docs/source/lang/scope.rst @@ -0,0 +1,120 @@ +.. highlight:: cpp + +.. _lang-scope: + +Variable Scope +============== + +Variables in the C++ programming language, which Maple uses (all of +your sketches are C++ programs in disguise), have a property called +*scope*. Simply put, a variable's scope is made up of all of the +lines where the variable can be used. + +Scope in C++ is a fairly complex topic, so we won't try to describe it +in full here. Instead, we present a simplified view, describing two +different kinds of scopes, *global* and *local*. For more detailed +information, consult a C++ reference. + +Global and Local Variables +-------------------------- + +A global variable is one that can be "seen" by every function in a +program. In the :ref:`Maple IDE `, any variable declared outside +of a function (like :ref:`setup() ` and :ref:`loop() +`) is a global variable. + +A local variable can only be "seen" inside of a particular function. +You can declare a variable to be local to a function by declaring it +inside of the :ref:`curly braces ` which enclose that +function. + +When programs start to get larger and more complex, local variables +are a useful way to ensure that a function has exclusive access to its +own variables. This prevents programming errors when one function +mistakenly modifies variables used by another function. + +It is also sometimes useful to declare and initialize a variable +inside a :ref:`for ` loop. This creates a variable that +can only be accessed from inside the loop body. + +Example +------- + +Here is an example sketch (which you can copy into the Maple IDE and +run on your Maple) that illustrates the use of global and local +variables, as well as declaring variables inside of a ``for`` loop. +Be sure to open a :ref:`serial monitor ` after you +:ref:`verify ` and :ref:`upload ` the sketch:: + + int globalVar; // any function will see this variable + + void setup() { + // since "globalVar" is declared outside of any function, + // every function can "see" and use it: + globalVar = 50; + + // the variables "i" and "d" declared inside the "loop" function + // can't be seen here. see what happens when you uncomment the + // following lines, and try to Verify (compile) the sketch: + // + // i = 16; + // SerialUSB.print("i = "); + // SerialUSB.println(i); + // d = 26.5; + // SerialUSB.print("d = "); + // SerialUSB.println(d); + } + + void loop() { + // since "i" and "d" are declared inside of the "loop" function, + // they can only be seen and used from inside of it: + int i; + double d; + + for (int j = 0; j < 5; j++) { + // variable i can be used anywhere inside the "loop" function; + // variable j can only be accessed inside the for-loop brackets: + i = j * j; + SerialUSB.print("i = "); + SerialUSB.println(i); + } + + // globalVar can be accessed from anywhere. note how even + // though we set globalVar = 50 in the "setup" function, we can + // see that value here: + SerialUSB.print("globalVar = "); + SerialUSB.println(globalVar); + + // d can be accessed from anywhere inside the "loop" function: + d = 26.5; + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (before separateFunction())"); + + separateFunction(); + + // notice how even though separateFunction() has a variable + // named "d", it didn't touch our (local) variable which has + // the same name: + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (after separateFunction())"); + } + + void separateFunction() { + // variable "d" here has the same name as variable "d" inside of + // the "loop" function, but since they're both _local_ + // variables, they don't affect each other: + double d = 30.5; + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (inside of separateFunction())"); + } + +See Also +-------- + +- `C++ programming Wikibook `_. +- Wikipedia article on `scope `_ + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/semicolon.rst b/docs/source/lang/semicolon.rst new file mode 100644 index 0000000..4cf7b9f --- /dev/null +++ b/docs/source/lang/semicolon.rst @@ -0,0 +1,25 @@ +.. highlight:: cpp + +.. _lang-semicolon: + +Semicolon (;) +============= + +Used to end a line of code. Example:: + + int a = 13; + +Tip +--- + +Forgetting to end a line in a semicolon will result in a compiler +error. The error text may be obvious, and refer to a missing +semicolon, or it may not. If an impenetrable or seemingly illogical +compiler error comes up, one of the first things to check is a +missing semicolon, in the immediate vicinity, preceding the line at +which the compiler complained. + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/serial.rst b/docs/source/lang/serial.rst new file mode 100644 index 0000000..743f921 --- /dev/null +++ b/docs/source/lang/serial.rst @@ -0,0 +1,68 @@ +.. _lang-serial: + +Serial +====== + +Used for communication between the Arduino board and a computer or +other devices. All Arduino boards have at least one serial port +(also known as a UART or USART): **Serial**. It communicates on +digital pins 0 (RX) and 1 (TX) as well as with the computer via +USB. Thus, if you use these functions, you cannot also use pins 0 +and 1 for digital input or output. + + + +You can use the Arduino environment's built-in serial monitor to +communicate with an Arduino board. Click the serial monitor button +in the toolbar and select the same baud rate used in the call to +begin(). + + + +The Arduino Mega has three additional serial ports: **Serial1** on +pins 19 (RX) and 18 (TX), **Serial2** on pins 17 (RX) and 16 (TX), +**Serial3** on pins 15 (RX) and 14 (TX). To use these pins to +communicate with your personal computer, you will need an +additional USB-to-serial adaptor, as they are not connected to the +Mega's USB-to-serial adaptor. To use them to communicate with an +external TTL serial device, connect the TX pin to your device's RX +pin, the RX to your device's TX pin, and the ground of your Mega to +your device's ground. (Don't connect these pins directly to an +RS232 serial port; they operate at +/- 12V and can damage your +Arduino board.) + + + +Functions +--------- + + +- `begin `_\ () +- `end `_\ () +- `available `_\ () +- `read `_\ () +- `flush `_\ () +- `print `_\ () + +.. _lang-serial-println: + +- `println `_\ () +- `write `_\ () + + + +Examples +-------- + + +- `ASCII Table `_ +- `Dimmer `_ +- `Graph `_ +- `Physical Pixel `_ +- `Virtual Color Mixer `_ +- `Serial Call Response `_ +- `Serial Call Response ASCII `_ + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/serialusb.rst b/docs/source/lang/serialusb.rst new file mode 100644 index 0000000..730fb07 --- /dev/null +++ b/docs/source/lang/serialusb.rst @@ -0,0 +1,8 @@ +.. _lang-serialusb: + +Serial over USB Communications +============================== + +.. _lang-serialusb-println: + +Stub. diff --git a/docs/source/lang/setup.rst b/docs/source/lang/setup.rst new file mode 100644 index 0000000..6b142d2 --- /dev/null +++ b/docs/source/lang/setup.rst @@ -0,0 +1,34 @@ +.. _lang-setup: + +setup() +======= + +The setup() function is called when a sketch starts. Use it to +initialize variables, pin modes, start using libraries, etc. The +setup function will only run once, after each powerup or reset of +the Arduino board. + + + +Example +~~~~~~~ + +:: + + + int buttonPin = 3; + + void setup() + { + Serial.begin(9600); + pinMode(buttonPin, INPUT); + } + + void loop() + { + // ... + } + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/shiftout.rst b/docs/source/lang/shiftout.rst new file mode 100644 index 0000000..e76cc01 --- /dev/null +++ b/docs/source/lang/shiftout.rst @@ -0,0 +1,136 @@ +.. _lang-shiftout: + +shiftOut() +========== + +Description +----------- + +Shifts out a byte of data one bit at a time. Starts from either the +most (i.e. the leftmost) or least (rightmost) significant bit. Each +bit is written in turn to a data pin, after which a clock pin is +pulsed to indicate that the bit is available. + + + +This is a software implementation; Arduino (as of 0019) also +provides an `SPI library `_ +that uses the hardware implementation. + + + +Syntax +------ + +shiftOut(dataPin, clockPin, bitOrder, value) + + + +Parameters +---------- + +dataPin: the pin on which to output each bit (*int*) + + + +clockPin: the pin to toggle once the **dataPin** has been set to +the correct value (*int*) + + + +bitOrder: which order to shift out the bits; either **MSBFIRST** or +**LSBFIRST**. +(Most Significant Bit First, or, Least Significant Bit First) + + + +value: the data to shift out. (*byte*) + + + +Returns +------- + +None + + + +Note +---- + +The **dataPin** and **clockPin** must already be configured as +outputs by a call to +`pinMode `_\ (). + + + +**shiftOut** is currently written to output 1 byte (8 bits) so it +requires a two step operation to output values larger than 255. + +:: + + // Do this for MSBFIRST serial + int data = 500; + // shift out highbyte + shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); + // shift out lowbyte + shiftOut(data, clock, MSBFIRST, data); + + // Or do this for LSBFIRST serial + data = 500; + // shift out lowbyte + shiftOut(dataPin, clock, LSBFIRST, data); + // shift out highbyte + shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); + + + +Example +------- + +*For accompanying circuit, see the `tutorial on controlling a 74HC595 shift register `_.* + + + +:: + + //**************************************************************// + // Name : shiftOutCode, Hello World // + // Author : Carlyn Maw,Tom Igoe // + // Date : 25 Oct, 2006 // + // Version : 1.0 // + // Notes : Code for using a 74HC595 Shift Register // + // : to count from 0 to 255 // + //**************************************************************** + + //Pin connected to ST_CP of 74HC595 + int latchPin = 8; + //Pin connected to SH_CP of 74HC595 + int clockPin = 12; + ////Pin connected to DS of 74HC595 + int dataPin = 11; + + void setup() { + //set pins to output because they are addressed in the main loop + pinMode(latchPin, OUTPUT); + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + } + + void loop() { + //count up routine + for (int j = 0; j < 256; j++) { + //ground latchPin and hold low for as long as you are transmitting + digitalWrite(latchPin, LOW); + shiftOut(dataPin, clockPin, LSBFIRST, j); + //return the latch pin high to signal chip that it + //no longer needs to listen for information + digitalWrite(latchPin, HIGH); + delay(1000); + } + } + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/sin.rst b/docs/source/lang/sin.rst new file mode 100644 index 0000000..398b8f3 --- /dev/null +++ b/docs/source/lang/sin.rst @@ -0,0 +1,32 @@ +.. _lang-sin: + +sin() +===== + +Calculates the `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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See Also +-------- + +- :ref:`cos ` +- :ref:`tan ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/sizeof.rst b/docs/source/lang/sizeof.rst new file mode 100644 index 0000000..409a6d7 --- /dev/null +++ b/docs/source/lang/sizeof.rst @@ -0,0 +1,64 @@ +.. highlight:: cpp + +.. _lang-sizeof: + +sizeof() +======== + +The ``sizeof`` operator on the Maple returns the number of bytes +needed to store a value of a given type\ [#fcharsize]_. This can be +an ordinary numeric type, like ``int``. It can be something more +complicated, like a ``struct`` or ``union``. If the argument to +``sizeof`` is an array, it returns the total number of bytes occupied +by the array. + +The general syntax looks like this:: + + sizeof(type) + sizeof(var) + +Example +------- + +The ``sizeof`` operator is useful for dealing with arrays (such as +strings) where it is convenient to be able to change the size of the +array without breaking other parts of the program. + +This program prints out a text string one character at a time. Try +changing the text phrase:: + + char myStr[] = "this is a test"; + int i; + + void setup() { + Serial.begin(9600); + } + + void loop() { + for (i = 0; i < sizeof(myStr) - 1; i++) { + Serial.print(i, DEC); + Serial.print(" = "); + Serial.println(myStr[i], BYTE); + } + } + + +Note that ``sizeof`` returns the total number of bytes. So for larger +variable types such as ``int``, the :ref:`for loop ` +would look something like this:: + + for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { + // do something with myInts[i] + } + +.. rubric:: Footnotes + +.. [#fcharsize] Technically (and pedantically) speaking, ``sizeof`` + returns a multiple of the number of bits a ``char`` occupies in + memory. However, on the Maple (this goes for most C++ + implementations), a ``char`` occupies 8 bits = 1 byte. All the C++ + standard guarantees, however, is that a ``char`` occupies at + *least* 8 bits. + +.. include:: cc-attribution.txt + diff --git a/docs/source/lang/sq.rst b/docs/source/lang/sq.rst new file mode 100644 index 0000000..a14817f --- /dev/null +++ b/docs/source/lang/sq.rst @@ -0,0 +1,42 @@ +.. highlight:: cpp + +.. _lang-sq: + +sq(a) +===== + +Description +----------- + +(Macro) computes the square of a number. + +Parameters +---------- + +**a**: the number. + +Returns +------- + +**a** squared (**a** × **a**). + +Warning +------- + +Because of the way ``sq()`` is implemented, avoid using other +functions or causing side effects inside the parentheses, as it may +lead to incorrect results:: + + b = sq(a++); // avoid this - yields incorrect results + + b = sq(a); // use this instead - + a++; // keep other operations outside sq() + + +Arduino Compatibility +--------------------- + +Maple's implementation of ``sq()`` is compatible with Arduino. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/sqrt.rst b/docs/source/lang/sqrt.rst new file mode 100644 index 0000000..956a754 --- /dev/null +++ b/docs/source/lang/sqrt.rst @@ -0,0 +1,25 @@ +.. _lang-sqrt: + +sqrt() +====== + +Calculates the square root of a number. + +Library Documentation +--------------------- + +.. doxygenfunction:: sqrt + +Arduino Compatibility +--------------------- + +The Maple versino of ``sqrt()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`pow ` +- :ref:`sq ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/static.rst b/docs/source/lang/static.rst new file mode 100644 index 0000000..4646db1 --- /dev/null +++ b/docs/source/lang/static.rst @@ -0,0 +1,57 @@ +.. highlight:: cpp + +.. _lang-static: + +Static +====== + +The ``static`` keyword can be used to create variables that are +visible to only one function. However, unlike local variables that get +created and destroyed every time a function is called, ``static`` +variables persist beyond the function call, preserving their data +between function calls. + +Variables declared as ``static`` will only be created and initialized +the first time a function is called. + +.. note:: This is only one use of the ``static`` keyword in C++. It + has some other important uses that are not documented here; consult + a reliable C++ reference for details. + +Example +------- + +One use case for ``static`` variables is implementing counters that +last longer than the functions which need them, but shouldn't be +shared to other functions. Here's an example:: + + void setup() { + SerialUSB.begin(); + } + + void loop() { + int reading; + if (timeToReadSensors()) { + reading = readSensors(); + } + // do something with reading + } + + int readSensors() { + static int numSensorReadings = 0; + numSensorReadings++; + if (numSensorReadings % 100 == 0) { + SerialUSB.print("just got to another 100 sensor readings"); + } + return analogRead(...); + } + +In this example, the static variable ``numSensorReadings`` is +initialized to zero the first time ``readSensors()`` is called, and +then incremented, so it starts out at one. Subsequent calls to +``readSensors()`` won't reset ``numSensorReadings`` to zero, because +it was declared ``static``. Thus, ``numSensorReadings`` is a count of +the number of times that ``readSensors()`` has been called. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/string.rst b/docs/source/lang/string.rst new file mode 100644 index 0000000..92c3f69 --- /dev/null +++ b/docs/source/lang/string.rst @@ -0,0 +1,131 @@ +.. highlight:: cpp + +.. _lang-string: + +Strings +======= + +Description +----------- + +Text strings can be represented in two ways. You can + +1. Use the :ref:`String ` data type, which is +part of the core as of version 0.0.9, or + +2. You can make a string out of an array of type :ref:`char +` and null-terminate it. + +This page describes the second method. + +Examples +-------- + +All of the following are valid declarations for strings:: + + char str1[15]; + char str2[6] = {'m', 'a', 'p', 'l', 'e'}; + char str3[6] = {'m', 'a', 'p', 'l', 'e', '\0'}; + char str4[ ] = "maple"; + char str5[6] = "maple"; + char str6[15] = "maple"; + +As you can see, there are several methods available for declaring and +initializing strings: + +- Declare an array of ``char`` without initializing it, as with ``str1``. + +- Declare an array of ``char`` (with one extra ``char``) and the + compiler will add the required null character, as with ``str2``. + +- Explicitly add the null character (``'\0'``), as with ``str3``. + +- Initialize with a string constant in quotation marks (``"..."``); + the compiler will size the array to fit the string constant and a + terminating null character (``str4``). + +- Initialize the array with an explicit size and string constant, + (``str5``). + +- Initialize the array, leaving extra space for a larger string + (``str6``). + +Null Termination +---------------- + +Generally, strings are terminated with a null character (`ASCII +`_ code 0). This allows functions +(like ``SerialUSB.print()``) to tell where the end of a string is. +Otherwise, they would continue reading subsequent bytes of memory that +aren't actually part of the string. + +This means that your string needs to have space for one more character +than the text you want it to contain. That is why ``str2`` and +``str5`` need to be six characters, even though "maple" is only five +-- the last position is automatically filled with a NULL +character. ``str4`` will be automatically sized to six characters, one +for the extra null. In the case of ``str3``, we've explicitly included +the null character (written ``'\0'``) ourselves. + +Note that it's possible to have a string without a final null +character (e.g. if you had specified the length of ``str2`` as five +instead of six). This will break most functions that use strings, so +you shouldn't do it intentionally. If you notice something behaving +strangely (operating on characters not in the string), however, this +could be the problem. + +Single quotes or double quotes? +------------------------------- + +Strings are always defined inside double quotes (``"Abc"``) and +characters are always defined inside single quotes (``'A'``). + +Wrapping long strings +--------------------- + +You can wrap long strings like this:: + + char myString[] = "This is the first line" + " this is the second line" + " etcetera"; + +Arrays of Strings +----------------- + +It is often convenient, when working with large amounts of text, +such as a project with an LCD display, to setup an array of +strings. Because strings themselves are arrays, this is in actually +an example of a two-dimensional array. + +In the code below, the asterisk after the datatype char ``char *`` +indicates that this is an array of "pointers". All array names are +actually pointers, so this is required to make an array of arrays. +Pointers are one of the more esoteric parts of C for beginners to +understand, but it isn't necessary to understand pointers in detail to +use them effectively here:: + + char* myStrings[] = {"This is string 1", "This is string 2", + "This is string 3", "This is string 4", + "This is string 5", "This is string 6"}; + + void setup() { + SerialUSB.begin(); + } + + void loop() { + for (int i = 0; i < 6; i++) { + SerialUSB.println(myStrings[i]); + delay(500); + } + } + + +See Also +-------- + +- :ref:`array ` +- :ref:`__attribute__ ` +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/stringclass.rst b/docs/source/lang/stringclass.rst new file mode 100644 index 0000000..5e53f08 --- /dev/null +++ b/docs/source/lang/stringclass.rst @@ -0,0 +1,9 @@ +.. _lang-stringclass: + +String Class +============ + +Stub. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/stringobject.rst b/docs/source/lang/stringobject.rst new file mode 100644 index 0000000..d7f287c --- /dev/null +++ b/docs/source/lang/stringobject.rst @@ -0,0 +1,91 @@ +.. _lang-stringobject: + +String +====== + +Description +----------- + +The String class, part of the core as of version 0019, allows you +to use and manipulate strings of text in more complex ways than +`character arrays `_ do. You +can concatenate Strings, append to them, search for and replace +substrings, and more. It takes more memory than a simple character +array, but it is also more useful. + + + +For reference, character arrays are referred to as strings with a +small s, and instances of the String class are referred to as +Strings with a capital S. Note that constant strings, specified in +"double quotes" are treated as char arrays, not instances of the +String class. + + + +Functions +--------- + + +- `String `_\ () +- `charAt `_\ () +- `compareTo `_\ () +- `concat `_\ () +- `endsWith `_\ () +- `equals `_\ () +- `equalsIgnoreCase `_\ () +- `getBytes `_\ () +- `indexOf `_\ () +- `lastIndexOf `_\ () +- `length `_\ () +- `replace `_\ () +- `setCharAt `_\ () +- `startsWith `_\ () +- `substring `_\ () +- `toCharArray `_\ () +- `toLowerCase `_\ () +- `toUpperCase `_\ () +- `trim `_\ () + + + +Operators +--------- + + +- `[] (element access) `_ +- `+ (concatenation) `_ +- `== (comparison) `_ + + + +Examples +-------- + + +- `StringConstructors `_ +- `StringAdditionOperator `_ +- `StringIndexOf `_ +- `StringAppendOperator `_ +- `StringLengthTrim `_ +- `StringCaseChanges `_ +- `StringReplace `_ +- `StringCharacters `_ +- `StringStartsWithEndsWith `_ +- `StringComparisonOperators `_ +- `StringSubstring `_ + + + +See Also +-------- + + +- `string `_: character + arrays +- `Variable Declaration `_ + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/switchcase.rst b/docs/source/lang/switchcase.rst new file mode 100644 index 0000000..46c47d8 --- /dev/null +++ b/docs/source/lang/switchcase.rst @@ -0,0 +1,117 @@ +.. highlight:: cpp + +.. _lang-switchcase: + +switch / case statements +======================== + +Like :ref:`if/else ` blocks, A ``switch`` statement +controls program flow by allowing you to specify different code that +should be executed under various cases. + +The general syntax looks like this:: + + switch (var) { + case val1: + // statements + break; + case val2: + // statements + break; + ... + default: + // statements + } + +Where ``var`` is a variable whose value to investigate, and the +``val1``, ``val2`` after each ``case`` are constant values that +``var`` might be. + + +Description +----------- + +A ``switch`` statement compares the value of a variable to the values +specified in ``case`` statements. When a ``case`` statement is found +whose value matches that of the variable, the code in that case +statement is run. + +Here's a more concrete example:: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + afterTheSwitch(); + +In the above example, if ``var == 1``, then the code beginning on the +line after ``case 1`` gets executed. That is, if ``var`` is one, +``doThing1()`` gets called first, and then the ``break`` statement is +executed. + +The ``break`` keyword exits the ``switch`` statement, and is typically +used at the end of each ``case``. Since there is a ``break`` at the +end of ``case 1``, the ``switch`` statement exits, and the next line +to be run is the one which calls ``afterTheSwitch()``. + +Without a ``break``, the ``switch`` statement will continue executing +the following ``case`` expressions ("falling-through") until a +``break`` (or the end of the switch statement) is reached. Let's +pretend the ``switch`` looked like this instead:: + + switch (var) { + case 1: + doThing1(); + // no break statement anymore + case 2: + doThing2(); + break; + } + afterTheSwitch(); + +Now, if ``var`` is one, ``doThing1()`` gets executed like before. +However, without a ``break``, the code would continue to be executed +line-by-line, so ``doThing2()`` would be called next. At this point, +a ``break`` has been reached, so the program continues by calling +``afterTheSwitch()``. This is usually not what you want, which is why +each ``case`` usually has a ``break`` at the end. + +Writing "``default:``" instead of a ``case`` statement allows you to +specify what to do if none of the ``case`` statements matches. Having +a ``default`` is optional (you can leave it out), but if you have one, +it must appear after all of the ``case`` statements. Let's add a +``default`` to the ``switch`` we've been discussing:: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + default: + doSomethingElse(); + } + afterTheSwitch(); + +If ``var`` is one, then ``doThing1()`` gets called. If ``var`` is +two, ``doThing2()`` gets called. If ``var`` is anything else, +``doSomethingElse()`` gets called. As stated above, a ``default`` is +optional. If you're missing one and none of the ``case`` statements +match, the ``switch`` does nothing at all, as if it weren't there. + +``switch`` statements are often used with an ``enum`` value as the +variable to compare. In this case, you can write down all of the +values the ``enum`` takes as ``case`` statements, and be sure you've +covered all the possibilities. + +See also: +--------- + +- :ref:`if...else ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/tan.rst b/docs/source/lang/tan.rst new file mode 100644 index 0000000..4bbe0db --- /dev/null +++ b/docs/source/lang/tan.rst @@ -0,0 +1,31 @@ +.. _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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See Also +-------- + + +- :ref:`sin ` +- :ref:`cos ` +- :ref:`float ` +- :ref:`double ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/tone.rst b/docs/source/lang/tone.rst new file mode 100644 index 0000000..96f0a7c --- /dev/null +++ b/docs/source/lang/tone.rst @@ -0,0 +1,81 @@ +.. _lang-tone: + +tone() +====== + +Description +----------- + +Generates a square wave of the specified frequency (and 50% duty +cycle) on a pin. A duration can be specified, otherwise the wave +continues until a call to +`noTone `_\ (). The pin can be +connected to a piezo buzzer or other speaker to play tones. + + + +Only one tone can be generated at a time. If a tone is already +playing on a different pin, the call to tone() will have no effect. +If the tone is playing on the same pin, the call will set its +frequency. + + + +Use of the tone() function will interfere with PWM output on pins 3 +and 11 (on boards other than the Mega). + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +tone(pin, frequency) +tone(pin, frequency, duration) + + + +Parameters +---------- + +pin: the pin on which to generate the tone + + + +frequency: the frequency of the tone in hertz + + + +duration: the duration of the tone in milliseconds (optional) + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `noTone `_\ () +- `analogWrite `_\ () +- `Tutorial:Tone `_ +- `Tutorial:Pitch follower `_ +- `Tutorial:Simple Keyboard `_ +- `Tutorial: multiple tones `_ + + +- `Tutorial: PWM `_ + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/types.rst b/docs/source/lang/types.rst new file mode 100644 index 0000000..d095da1 --- /dev/null +++ b/docs/source/lang/types.rst @@ -0,0 +1,7 @@ +.. _lang-types: + +Built-in types +============== + +Stub. (explain all built-in integral and floating-point types, +including ``uint8`` style ones). diff --git a/docs/source/lang/unsignedchar.rst b/docs/source/lang/unsignedchar.rst new file mode 100644 index 0000000..c49690d --- /dev/null +++ b/docs/source/lang/unsignedchar.rst @@ -0,0 +1,36 @@ +.. highlight:: cpp + +.. _lang-unsignedchar: + +unsigned char +============= + +Description +----------- + +An unsigned version of the :ref:`char ` data type. An +``unsigned char`` occupies 1 byte of memory; it stores an integer from +0 to 255. + +Like an :ref:`unsigned int `, an ``unsigned char`` +won't store negative numbers; it is also subject to the same +:ref:`overflow issues ` as any integral data type. + +Example +------- + +:: + + unsigned char c = 240; + +See Also +-------- + + +- :ref:`byte ` +- :ref:`int ` +- :ref:`array ` +- :ref:`SerialUSB.println() ` +- :ref:`Serial.println() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/unsignedint.rst b/docs/source/lang/unsignedint.rst new file mode 100644 index 0000000..aa5cc1b --- /dev/null +++ b/docs/source/lang/unsignedint.rst @@ -0,0 +1,58 @@ +.. highlight:: cpp + +.. _lang-unsignedint: + +unsigned int +============ + +Description +----------- + +An ``unsigned int`` (unsigned integer) is the same as an :ref:`int +` in that it stores a 4 byte integer value. However, +Instead of storing both negative and positive numbers, an ``unsigned +int`` can only store nonnegative values, yielding a range of 0 to +4,294,967,295 (the positive value is 2^32 - 1). + +The difference between an ``unsigned int`` and a (signed) ``int`` lies +in the way the highest bit, sometimes referred to as the "sign" bit, +is interpreted. In the case of the Maple ``int`` type (which is +signed), if the high bit is a "1", the number is interpreted as a +negative number, using a technique known as `two's complement math +`_. The +bits in an an ``unsigned int`` are interpreted according to the usual +rules for converting `binary to decimal +`_. + +An ``unsigned int`` is subject to the same :ref:`overflow issues +` as a regular ``int``; the only difference is +that an ``unsigned int`` will "underflow" at 0, and "overflow" at +4,294,967,295. Here is some example code which illustrates this:: + + unsigned int x; + x = 0; + x--; // x now contains 4,294,967,295; rolled over "left to right" + x++; // x now contains 0; rolled over "right to left" + +Here is an example of declaring an ``unsigned int`` variable named +``ledPin``, then giving it value 13:: + + unsigned int ledPin = 13; + +The general syntax for declaring an ``unsigned int`` variable named +``var``, then giving it value ``val``, looks like:: + + unsigned int var = val; + +See Also +-------- + +- :ref:`int ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/unsignedlong.rst b/docs/source/lang/unsignedlong.rst new file mode 100644 index 0000000..2ca49f8 --- /dev/null +++ b/docs/source/lang/unsignedlong.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-unsignedlong: + +unsigned long +============= + +Description +----------- + +An unsigned version of the :ref:`long ` data type. An +``unsigned long`` occupies 8 bytes of memory; it stores an integer +from 0 to 2^64-1, which is approximately 1.8×10^19 (18 quintillion, or +18 billion billion). + +Like an :ref:`unsigned int `, an ``unsigned long`` +won't store negative numbers; it is also subject to the same +:ref:`overflow issues ` as any integral data type. + +Here is an example of declaring an ``unsigned long`` variable named +``c``, then giving it value 299,792,458,000,000,000 (see :ref:`integer +constants ` for an explanation of the "L" at the +end of the number):: + + // Speed of light in nanometers per second (approximate). + unsigned long c = 299792458000000000L; + +The general syntax for declaring an ``unsigned long`` variable named +``var``, then giving it value ``val``, looks like:: + + unsigned long var = val; + +See Also +-------- + +- :ref:`long ` +- :ref:`int ` +- :ref:`unsigned ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/variables.rst b/docs/source/lang/variables.rst new file mode 100644 index 0000000..05a4f96 --- /dev/null +++ b/docs/source/lang/variables.rst @@ -0,0 +1,170 @@ +.. highlight:: cpp + +.. _lang-variables: + +Variables +========= + +A variable is a way of naming and storing a value for later use by +the program, such as data from a sensor or an intermediate value +used in a calculation. + +.. contents:: Contents + :local: + +.. _lang-variables-declaring: + +Declaring Variables +------------------- + +Before they are used, all variables have to be *declared*. Declaring a +variable means defining its type, giving it a name, and (optionally) +giving it an initial value (this is often referred to as +*initializing* the variable). Variables do not have to be initialized +(given a value) when they are declared, but it is good style to give +them an initial value whenever possible. + +Here is an example of declaring a variable named ``inputVariable1`` +with type :ref:`int ` (the ``int`` type is used to store +integers, like -2, -1, 0, 1, etc.):: + + int inputVariable1; + +In the above declaration, we did not give the variable an initial +value. Here is another example, where we declare an ``int`` variable +named ``inputVariable2``, with an initial value of ``0``:: + + int inputVariable2 = 0; + +The Maple environment comes ready to use with many useful types of +variables. See the :ref:`built-in types ` page for more +information. + +Here are a few examples of declaring variables of different types:: + + int lightSensVal; + char currentLetter; + unsigned long speedOfLight = 186000UL; + char errorMessage = {"choose another option"}; // see string + +Naming Variables +---------------- + +The rules for naming a variable are simple. Names for variables can +contain letters, numbers, and underscores (the underscore is the +:kbd:`_` character), and cannot begin with a number. So +``temperature_reading``, ``tempReading``, ``tempReading1``, and +``tempReading2`` are all valid variable names, but ``4_temp_readings`` +is not, because it begins with a number. + +You cannot choose a name for a variable that is one of the C++ +:ref:`keywords `. + +Variable names are case-sensitive, so "tempreading" and "tempReading" +are different variables. However, it is very bad style to write code +that chooses variables which are the same up to case. + +You should give your variables descriptive names, so as to make your +code more readable. Variable names like ``tiltSensor`` or +``pushButton`` help you (and anyone else reading your code) understand +what the variable represents. Variable names like ``var`` or +``value``, on the other hand, do little to make your code readable. + +.. _lang-variables-scope: + +Variable Scope +-------------- + +An important choice that programmers face is where (in the program +text) to declare variables. The specific place that variables are +declared influences how various functions in a program will "see" the +variable. This is called variable *scope*. See the :ref:`scope +reference ` for more information. + +.. _lang-variables-initializing: + +Initializing Variables +---------------------- + +Variables may be *initialized* (assigned a starting value) when they +are declared or not. It is always good programming practice however to +double check that a variable has valid data in it before it is used. +Using a variable before you give it a value is a common source of +bugs. + +.. _lang-variables-rollover: + +Variable Rollover +----------------- + +Every (numeric) type has a valid *range*. The range of a type is the +smallest and largest value that a variable of that type can store. +For example, the :ref:`int ` type has a range of +-2,147,483,648 to 2,147,483,647 [#frange]_. + +When variables are made to exceed their range's maximum value, they +"roll over" back to their minimum value. Note that this happens in +both directions. It's like in the game *Pac-Man* -- when Pac-Man goes +past the right edge of the screen, he reappears on the left, and when +he goes past the left side of the screen, he reappears on the right:: + + int x; + x = -2,147,483,648; + x = x - 1; // x now contains -2,147,483,647; rolled over "left to right" + + x = 2,147,483,647; + x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" + +Each numeric type's reference page includes its range. See the +:ref:`built-in types ` reference for links to each type's +reference page. + +Using Variables +--------------- + +Once variables have been declared, they are given values using the +:ref:`assignment operator `, which is a single equals +sign, ``=``. The assignment operator tells the program to store the +value on the right side of the equals sign into the variable on the +left side:: + + inputVariable1 = 7; // sets variable named inputVariable1 to 7 + inputVariable2 = analogRead(2); // sets variable named inputVariable2 to + // the (digitized) input voltage read from + // analog pin #2 + +Once a variable has been set (assigned a value), you can test its +value to see if it meets certain conditions, or you can use its value +directly. For instance, the following code tests whether the +inputVariable2 is less than 100, then sets a delay based on +inputVariable2 (which, at that point, is at least 100):: + + if (inputVariable2 < 100) { + inputVariable2 = 100; + } + + delay(inputVariable2); + +See Also +-------- + +- :ref:`lang-scope` +- :ref:`lang-types` + +.. rubric:: Footnotes + +.. [#frange] This range might seem a little weird at first. The + reasons for this range of values have to do with the fact that an + ``int`` occupies 32 bits of memory, and the facts :: + + 2^31 = -2,147,483,648 + 2^31 - 1 = 2,147,483,647 + + + Why 2^31 instead of 2^32? Well, that has to do with `how ints are + (usually) stored + `_ on computers. + + +.. include:: cc-attribution.txt + diff --git a/docs/source/lang/void.rst b/docs/source/lang/void.rst new file mode 100644 index 0000000..bc7a3dc --- /dev/null +++ b/docs/source/lang/void.rst @@ -0,0 +1,40 @@ +.. _lang-void: + +void +==== + +The void keyword is used only in function declarations. It +indicates that the function is expected to return no information to +the function from which it was called. + + + +Example: +-------- + +:: + + // actions are performed in the functions "setup" and "loop" + // but no information is reported to the larger program + + void setup() + { + // ... + } + + void loop() + { + // ... + } + + + + +See also +-------- + +`function declaration `_ + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/volatile.rst b/docs/source/lang/volatile.rst new file mode 100644 index 0000000..a0ef671 --- /dev/null +++ b/docs/source/lang/volatile.rst @@ -0,0 +1,73 @@ +.. _lang-volatile: + +volatile keyword +================ + +volatile is a keyword known as a variable *qualifier*, it is +usually used before the datatype of a variable, to modify the way +in which the compiler and subsequent program treats the variable. + + + +Declaring a variable volatile is a directive to the compiler. The +compiler is software which translates your C/C++ code into the +machine code, which are the real instructions for the Atmega chip +in the Arduino. + + + +Specifically, it directs the compiler to load the variable from RAM +and not from a storage register, which is a temporary memory +location where program variables are stored and manipulated. Under +certain conditions, the value for a variable stored in registers +can be inaccurate. + + + +A variable should be declared volatile whenever its value can be +changed by something beyond the control of the code section in +which it appears, such as a concurrently executing thread. In the +Arduino, the only place that this is likely to occur is in sections +of code associated with interrupts, called an interrupt service +routine. + + + +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() + { + state = !state; + } + + + +See also +-------- + + +- `AttachInterrupt `_ + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/while.rst b/docs/source/lang/while.rst new file mode 100644 index 0000000..be1ea14 --- /dev/null +++ b/docs/source/lang/while.rst @@ -0,0 +1,49 @@ +.. _lang-while: + +while Loops +=========== + +Description +----------- + +**while** loops will loop continuously, and infinitely, until the +expression inside the parenthesis, () becomes false. Something must +change the tested variable, or the **while** loop will never exit. +This could be in your code, such as an incremented variable, or an +external condition, such as testing a sensor. + + + +Syntax +------ + +:: + + while(expression){ + // statement(s) + } + + + +Parameters +---------- + +expression - a (boolean) C statement that evaluates to true or +false + + + +Example +------- + +:: + + var = 0; + while(var < 200){ + // do something repetitive 200 times + var++; + } + + + +.. include:: cc-attribution.txt -- cgit v1.2.3 From 078edc158da7906ba72e7e6528e1a811e07270e7 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Mon, 29 Nov 2010 01:49:26 -0500 Subject: Finished converting the Arduino docs --- docs/README | 83 +++-- docs/source/bootloader.rst | 7 + docs/source/compatibility.rst | 35 +- docs/source/conf.py | 4 +- docs/source/lang/abs.rst | 14 +- docs/source/lang/analogwrite.rst | 2 +- docs/source/lang/arithmetic.rst | 32 +- docs/source/lang/arithmeticcompound.rst | 46 --- docs/source/lang/assignment.rst | 4 +- docs/source/lang/bit.rst | 4 - docs/source/lang/bitclear.rst | 3 - docs/source/lang/bitread.rst | 3 - docs/source/lang/bitset.rst | 3 - docs/source/lang/bitshift.rst | 8 +- docs/source/lang/bitwisecompound.rst | 231 ------------ docs/source/lang/bitwisemath.rst | 22 +- docs/source/lang/bitwrite.rst | 16 +- docs/source/lang/boolean.rst | 2 +- docs/source/lang/booleanvariables.rst | 5 +- docs/source/lang/braces.rst | 109 ------ docs/source/lang/break.rst | 4 +- docs/source/lang/bytecast.rst | 3 - docs/source/lang/char.rst | 7 +- docs/source/lang/charcast.rst | 7 +- docs/source/lang/comparison.rst | 4 +- docs/source/lang/compoundarithmetic.rst | 44 +++ docs/source/lang/compoundbitwise.rst | 231 ++++++++++++ docs/source/lang/const.rst | 4 +- docs/source/lang/constants.rst | 410 ++++++++++----------- docs/source/lang/constrain.rst | 14 +- docs/source/lang/continue.rst | 8 +- docs/source/lang/curly-braces.rst | 109 ++++++ docs/source/lang/define.rst | 4 +- docs/source/lang/digitalread.rst | 3 - docs/source/lang/digitalwrite.rst | 116 ++---- docs/source/lang/double.rst | 11 +- docs/source/lang/doublecast.rst | 7 +- docs/source/lang/dowhile.rst | 4 +- docs/source/lang/else.rst | 54 --- docs/source/lang/enum.rst | 53 ++- docs/source/lang/float.rst | 7 +- docs/source/lang/floatcast.rst | 13 +- docs/source/lang/for.rst | 16 +- docs/source/lang/goto.rst | 4 +- docs/source/lang/highbyte.rst | 16 +- docs/source/lang/if.rst | 52 ++- docs/source/lang/include.rst | 7 +- docs/source/lang/increment.rst | 15 +- docs/source/lang/int.rst | 9 +- docs/source/lang/intcast.rst | 7 +- docs/source/lang/interrupts.rst | 62 ---- docs/source/lang/keywords.rst | 202 +++++++++- docs/source/lang/long.rst | 9 +- docs/source/lang/longcast.rst | 7 +- docs/source/lang/lowbyte.rst | 26 +- docs/source/lang/map.rst | 124 ++----- docs/source/lang/max.rst | 12 +- docs/source/lang/micros.rst | 65 ++-- docs/source/lang/millis.rst | 70 ++-- docs/source/lang/min.rst | 14 +- docs/source/lang/modulo.rst | 13 +- docs/source/lang/nointerrupts.rst | 59 --- docs/source/lang/notone.rst | 50 --- docs/source/lang/numeric-types.rst | 79 ++++ docs/source/lang/pinmode.rst | 43 +-- docs/source/lang/pointer.rst | 21 +- docs/source/lang/pow.rst | 12 +- docs/source/lang/pulsein.rst | 82 ----- docs/source/lang/pwmwrite.rst | 4 +- docs/source/lang/random.rst | 90 ++--- docs/source/lang/randomseed.rst | 69 ++-- docs/source/lang/return.rst | 8 +- docs/source/lang/scope.rst | 8 +- docs/source/lang/semicolon.rst | 4 +- docs/source/lang/serial.rst | 235 +++++++++--- docs/source/lang/serialusb.rst | 238 +++++++++++- docs/source/lang/setup.rst | 27 +- docs/source/lang/shiftout.rst | 136 ------- docs/source/lang/sizeof.rst | 4 +- docs/source/lang/sq.rst | 14 +- docs/source/lang/static.rst | 4 +- docs/source/lang/string.rst | 3 - docs/source/lang/stringclass.rst | 9 - docs/source/lang/stringobject.rst | 91 ----- docs/source/lang/switchcase.rst | 23 +- docs/source/lang/tone.rst | 81 ---- docs/source/lang/types.rst | 7 - docs/source/lang/unimplemented/interrupts.rst | 59 +++ docs/source/lang/unimplemented/nointerrupts.rst | 59 +++ docs/source/lang/unimplemented/notone.rst | 50 +++ docs/source/lang/unimplemented/pulsein.rst | 82 +++++ docs/source/lang/unimplemented/shiftout.rst | 136 +++++++ docs/source/lang/unimplemented/stringclass.rst | 9 + docs/source/lang/unimplemented/stringobject.rst | 89 +++++ docs/source/lang/unimplemented/tone.rst | 81 ++++ docs/source/lang/unsignedchar.rst | 7 +- docs/source/lang/unsignedint.rst | 7 +- docs/source/lang/unsignedlong.rst | 11 +- docs/source/lang/variables.rst | 10 +- docs/source/lang/void.rst | 33 +- docs/source/lang/volatile.rst | 76 ++-- docs/source/lang/while.rst | 41 +-- docs/source/language-index.rst | 127 +------ docs/source/language.rst | 204 ++++++----- docs/source/libraries.rst | 4 +- docs/source/spi.rst | 2 +- docs/source/timers.rst | 25 +- docs/source/troubleshooting.rst | 20 +- docs/source/unix-toolchain.rst | 31 +- docs/source/usb.rst | 162 +------- libmaple/usb/usb_callbacks.c | 468 ++++++++++++------------ wirish/comm/HardwareSerial.h | 9 +- wirish/io.h | 6 +- 113 files changed, 2937 insertions(+), 2752 deletions(-) delete mode 100644 docs/source/lang/arithmeticcompound.rst delete mode 100644 docs/source/lang/bitwisecompound.rst delete mode 100644 docs/source/lang/braces.rst create mode 100644 docs/source/lang/compoundarithmetic.rst create mode 100644 docs/source/lang/compoundbitwise.rst create mode 100644 docs/source/lang/curly-braces.rst delete mode 100644 docs/source/lang/else.rst delete mode 100644 docs/source/lang/interrupts.rst delete mode 100644 docs/source/lang/nointerrupts.rst delete mode 100644 docs/source/lang/notone.rst create mode 100644 docs/source/lang/numeric-types.rst delete mode 100644 docs/source/lang/pulsein.rst delete mode 100644 docs/source/lang/shiftout.rst delete mode 100644 docs/source/lang/stringclass.rst delete mode 100644 docs/source/lang/stringobject.rst delete mode 100644 docs/source/lang/tone.rst delete mode 100644 docs/source/lang/types.rst create mode 100644 docs/source/lang/unimplemented/interrupts.rst create mode 100644 docs/source/lang/unimplemented/nointerrupts.rst create mode 100644 docs/source/lang/unimplemented/notone.rst create mode 100644 docs/source/lang/unimplemented/pulsein.rst create mode 100644 docs/source/lang/unimplemented/shiftout.rst create mode 100644 docs/source/lang/unimplemented/stringclass.rst create mode 100644 docs/source/lang/unimplemented/stringobject.rst create mode 100644 docs/source/lang/unimplemented/tone.rst (limited to 'docs/source/lang') diff --git a/docs/README b/docs/README index b467d2d..326d278 100644 --- a/docs/README +++ b/docs/README @@ -3,46 +3,81 @@ as a Doxygen configuration file; we turn Doxygen XML output into Sphinx documentation. You can generate HTML documentation using the Makefile if you have make, or using make.bat from Windows. -You need a recent-ish version of doxygen in your PATH: +Documentation Build Steps +------------------------- - http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc +1. You need a recent-ish version of Doxygen in your PATH: -For the Doxygen-to-Sphinx bridge, we rely on a project called Breathe, -by Michael Jones. + http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc -***** You must clone the LEAFLABS VERSION OF THE breathe repository ****** +2. Install breathe, which does Doxygen-to-Sphinx conversion: - ... and then set an environment variable BREATHE_HOME to be able to -build the documentation. Something like this on bash: + Read/write version (for LeafLabs developers): $ git clone git@github.com:leaflabs/breathe.git + + Read-only version (for non-LeafLabs developers): + + $ git clone git://github.com/leaflabs/breathe.git + + After that's done, set an environment variable BREATHE_HOME to + point to where you downloaded it. Something like this on bash: + $ export BREATHE_HOME=/path/to/breathe/repo/ -You can now build the HTML docs with (on Unix): + (You'll want to put this in your shell startup script). + +3. Install Sphinx. + + From source or .egg: + + http://pypi.python.org/pypi/Sphinx#downloads + + Via easy_install: $ sudo easy_install -U Sphinx + +4. Before the first time you run Sphinx (and any time the Doxygen + comments in the libmaple source code are changed), you'll need to + rebuild the Doxygen XML output: + + $ cd libmaple/docs/source + $ doxygen + +5. Finally, you can build the documentation: + $ make html -Which will produce Doxygen documentation in doxygen/xml, and HTML -documentation (this is what you want to look at) in build/html. + (Read the Makefile for more targets). -All of the documentation itself lives in source/. The directory -source/_static is for static content like style sheets; -source/_templates contains Sphinx templates (or, it would if we had -any). +Reading and Modifying the Documentation +--------------------------------------- -The docs are written in reStructuredText (reST); it's a Python thing -that they use to produce the docs at python.org (which are beautiful, -if you've never seen them). You can read more about Sphinx here: +The net effect of the above is to produce Doxygen XML output (ignore +this) in libmaple/docs/doxygen/xml, and HTML documentation (this is +what you want) in libmaple/docs/build/html. - http://sphinx.pocoo.org/tutorial.html +Just point your web browser at the file + + libmaple/docs/build/html/index.html -Specific information on documenting C and C++ is available here: +it corresponds to the Sphinx file - http://sphinx.pocoo.org/domains.html + libmaple/docs/source/index.rst + +All of the documentation itself lives in libmaple/docs/source/. The +directory source/_static/ is for static content (like style sheets); +source/_templates/ contains Sphinx templates (or, it would, if we had +any). + +The docs are written in Sphinx's version of reStructuredText (reST); +it's a Python thing that they use to produce the docs at +http://python.org. You can read more about Sphinx here: + + http://sphinx.pocoo.org/tutorial.html -You can view the reST source for any generated page of documentation -by clicking the "Show Source" link in the sidebar. +You can view the source for any generated page of documentation by +clicking the "Show Source" link in the sidebar. -The file source/conf.py is the Sphinx configuration file; you can go -read it for more information about our setup. +The file libmaple/docs/source/conf.py is the Sphinx configuration +file; you can go read it for more information about our setup. diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index 6cb9ece..1cfd17f 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -574,3 +574,10 @@ SOFT_RESET response: - 1 - Either 0 or 1 (FAILED and OK, respectively). Will end this bootloader session and reset the processor. + +.. _bootloader-reflashing: + +Flashing A Custom Bootloader +---------------------------- + +Stub (flashing a custom bootloader) diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index cf4c2b3..7eb0a8f 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -83,34 +83,32 @@ differences, most of which are improvements: full 32-bit (4 byte) integer values instead of the regular 16-bit (2 byte) Arduino values. -* `pinMode()`_ types: any :ref:`GPIO ` (including analog pins) - can be configured into one of the following modes with a single call - to `pinMode()`_: ``OUTPUT``, ``OUTPUT_OPEN_DRAIN``, - ``INPUT_FLOATING``, ``INPUT_PULLUP``, +* :ref:`pinMode() ` types: any :ref:`GPIO ` + (including analog pins) can be configured into one of the following + modes with a single call to ```pinMode()``: ``OUTPUT``, + ``OUTPUT_OPEN_DRAIN``, ``INPUT_FLOATING``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``. Additionally, the PWM and Analog Input pins can be configured as ``INPUT_ANALOG`` and ``PWM`` respectively. See the :ref:`GPIO documentation ` for more information. - .. TODO: reference libmaple docs above when they're done - -* Serial1 syntax: like the `Arduino Mega +* ``Serial1`` syntax: like the `Arduino Mega `_, the Maple has - multiple USART ports. By default, Serial is not mapped to any of - them, use ``Serial1`` through ``Serial3`` instead. - - .. TODO: reference libmaple docs for Serial[n] above when they're done + multiple :ref:`USART ports `. By default, ``Serial`` + is not mapped to any of them, use ``Serial1`` through ``Serial3`` + instead. * 16-bit :ref:`PWM `: Arduino boards support 8-bit PWM, which - means that calls to `analogWrite()`_ take values between 0 (always - off) and 255 (always on). The Maple supports 16-bit PWM, so the - corresponding values should be between 0 (always off) and 65535 - (always on). + means that calls to :ref:`analogWrite() ` take + values between 0 (always off) and 255 (always on). The Maple + supports 16-bit PWM, so the corresponding values should be between 0 + (always off) and 65535 (always on). * 12-bit :ref:`ADC `: Arduino boards support 10-bit ADC, which - means that calls to `analogRead()`_ will return values between 0 and - 1023. The Maple supports 12-bit ADC, so the same call will instead - return values between 0 and 4095. + means that calls to :ref:`analogRead() ` will + return values between 0 and 1023. The Maple supports 12-bit ADC, so + the same call will instead return values between 0 and 4095. +Stub (unfinished) .. class:: ported-feature @@ -130,5 +128,4 @@ I sorta work And I am also ordinary -Stub (unfinished) diff --git a/docs/source/conf.py b/docs/source/conf.py index 288efad..74090f6 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -88,7 +88,7 @@ with open('prolog.rst', 'r') as pr: #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). @@ -105,7 +105,7 @@ pygments_style = 'sphinx' #modindex_common_prefix = [] # Warn about all references where the target cannot be found. -#nitpicky = True +nitpicky = True # -- Options for HTML output -------------------------------------------------- diff --git a/docs/source/lang/abs.rst b/docs/source/lang/abs.rst index ed95e6f..0f71d9b 100644 --- a/docs/source/lang/abs.rst +++ b/docs/source/lang/abs.rst @@ -1,13 +1,19 @@ +.. highlight:: cpp + .. _lang-abs: -abs(x) +abs() ====== -Description ------------ - (Macro) computes the absolute value of a number. +Syntax +------ + +:: + + abs(x) + Parameters ---------- diff --git a/docs/source/lang/analogwrite.rst b/docs/source/lang/analogwrite.rst index d30d4d9..3d05f44 100644 --- a/docs/source/lang/analogwrite.rst +++ b/docs/source/lang/analogwrite.rst @@ -62,7 +62,7 @@ which control PWM output. See the :ref:`timers reference ` for more information. Another fix is to consult the :ref:`pin mapping mega table -` to find the timer which controls PWM on the +` to find the timer which controls PWM on the pin you're using, then set that Timer's overflow to 255. Subsequent calls to analogWrite() should work as on the Arduino (with the same loss of precision). Note, however, that that affects the overflow for diff --git a/docs/source/lang/arithmetic.rst b/docs/source/lang/arithmetic.rst index 9f21627..91fe22e 100644 --- a/docs/source/lang/arithmetic.rst +++ b/docs/source/lang/arithmetic.rst @@ -2,28 +2,27 @@ .. _lang-arithmetic: -Addition, Subtraction, Multiplication, & Division +Arithmetic Operators (``+``, ``-``, ``*``, ``/``) ================================================= -.. contents:: Contents - :local: - -Description ------------ - -These operators return the sum, difference, product, or quotient -(respectively) of the two operands. The operation is conducted using -the data type of the operands, so, for example, ``9 / 4`` gives ``2`` -since 9 and 4 are :ref:`int variables `. +The operators ``+``, ``-``, ``*``, and ``/`` respectively evaluate to +the sum, difference, product, or quotient (respectively) of the two +operands. The operation is conducted using the data type of the +operands, so, for example, ``9 / 4`` gives ``2`` since 9 and 4 are +:ref:`int variables `. This also means that the operation can overflow if the result is larger than that which can be stored in the data type (e.g. adding 1 -to an :ref:`lang-int` with the value 2147483647 gives --2147483648). If the operands are of different types, the "larger" -type is used for the calculation. +to an :ref:`lang-int` with the value 2,147,483,647 gives +-2,147,483,648). .. _lang-arithmetic-typeconversion: +If the operands are of different types, the "larger" type is used for +the calculation. If one of the numbers (operands) are of the type +**float** or of type **double**, floating point math will be used for +the calculation. + .. note:: The specifics of these rules are beyond the scope of this documentation; for more information, see `The C++ Programming Language `_\ , by Bjarne @@ -35,9 +34,8 @@ type is used for the calculation. see the Wikipedia page on `two's complement `_. -If one of the numbers (operands) are of the type **float** or of type -**double**, floating point math will be used for the -calculation. +.. contents:: Contents + :local: Examples -------- diff --git a/docs/source/lang/arithmeticcompound.rst b/docs/source/lang/arithmeticcompound.rst deleted file mode 100644 index aa0dc18..0000000 --- a/docs/source/lang/arithmeticcompound.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. highlight:: cpp - -.. _lang-arithmeticcompound: - -Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) -=============================================================== - -Description ------------ - -Perform a mathematical operation on a variable with another constant -or variable. These operators are just a convenient shorthand:: - - x += y; // equivalent to the expression x = x + y; - x -= y; // equivalent to the expression x = x - y; - x *= y; // equivalent to the expression x = x * y; - x /= y; // equivalent to the expression x = x / y; - -Here is an example:: - - int x = 2; - int y = 10; - - x += 4; // x now contains 6 - x -= 3; // x now contains 3 - x *= y; // x now contains 30 - x /= 2; // x now contains 15 - x += max(20, 6); // x now contains 35 - x -= sq(5); // x now contains 15 - -Parameters ----------- - -**x**: a numeric variable - -**y**: a numeric variable, number constant, or any other expression -that evaluates to a number (e.g. call to a function that returns a -number). - -See Also --------- - -- :ref:`Arithmetic operators ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/assignment.rst b/docs/source/lang/assignment.rst index 16f0bf4..b6ad4d5 100644 --- a/docs/source/lang/assignment.rst +++ b/docs/source/lang/assignment.rst @@ -2,8 +2,8 @@ .. _lang-assignment: -= assignment operator (single equal sign) -========================================= +Assignment Operator (``=``) +=========================== Stores the value to the right of the equal sign in the variable to the left of the equal sign. diff --git a/docs/source/lang/bit.rst b/docs/source/lang/bit.rst index c342fdd..dd5c050 100644 --- a/docs/source/lang/bit.rst +++ b/docs/source/lang/bit.rst @@ -3,14 +3,10 @@ bit() ===== -Description ------------ - (Macro) Computes the value of an (unsigned) integer with the specified bit set (``bit(0)`` is 1, ``bit(1)`` is 2, ``bit(2)`` is 4, then 8, 16, 32, etc.). - Syntax ------ diff --git a/docs/source/lang/bitclear.rst b/docs/source/lang/bitclear.rst index 5d1eb95..941f912 100644 --- a/docs/source/lang/bitclear.rst +++ b/docs/source/lang/bitclear.rst @@ -3,9 +3,6 @@ bitClear() ========== -Description ------------ - (Macro) Clears (writes a 0 to) a bit of a numeric variable. Syntax diff --git a/docs/source/lang/bitread.rst b/docs/source/lang/bitread.rst index 9f885cf..46b4478 100644 --- a/docs/source/lang/bitread.rst +++ b/docs/source/lang/bitread.rst @@ -3,9 +3,6 @@ bitRead() ========= -Description ------------ - (Macro) Gets the value of a bit in a number. diff --git a/docs/source/lang/bitset.rst b/docs/source/lang/bitset.rst index 502c1b6..ccd76de 100644 --- a/docs/source/lang/bitset.rst +++ b/docs/source/lang/bitset.rst @@ -3,9 +3,6 @@ bitSet() ======== -Description ------------ - (Macro) Sets (writes a 1 to) a bit of a numeric variable. diff --git a/docs/source/lang/bitshift.rst b/docs/source/lang/bitshift.rst index f05d49e..e1c8de0 100644 --- a/docs/source/lang/bitshift.rst +++ b/docs/source/lang/bitshift.rst @@ -2,17 +2,13 @@ .. _lang-bitshift: -Bit shift left (``<<``), bit shift right (``>>``) -================================================= - -Description ------------ +Bit Shift Operators (``<<``, ``>>``) +==================================== (Adapted from `The Bit Math Tutorial `_ in `The Arduino Playground `_\ ) - There are two bit shift operators in C++: the left shift operator ``<<`` and the right shift operator ``>>``. These operators cause the bits in the left operand to be shifted left or right by the number of diff --git a/docs/source/lang/bitwisecompound.rst b/docs/source/lang/bitwisecompound.rst deleted file mode 100644 index 2b0fe2f..0000000 --- a/docs/source/lang/bitwisecompound.rst +++ /dev/null @@ -1,231 +0,0 @@ -.. highlight:: cpp - -.. _lang-bitwisecompound: - -Compound bitwise and (&=), or (\|=), XOR (^=) -============================================= - -The compound bitwise operators perform their calculations at the -bit level of variables. They are often used to clear and set -specific bits of a variable. - -See the :ref:`bitwise math tutorial ` for more -information on bitwise operators. - -.. contents:: Contents - :local: - -.. _lang-bitwisecompound-and: - -Compound bitwise AND (&=) -------------------------- - -The compound bitwise AND operator ``&=`` is often used with a variable -and a constant to force particular bits in a variable to be zero. This -is often referred to in programming guides as "clearing" or -"resetting" bits. In a program, writing the line ``x &= y;`` is -equivalent to writing ``x = x & y;``. That is, the value of ``x`` -after the line will be equal to its old value bitwise ANDed with the -value of ``y``:: - - x &= y; // equivalent to x = x & y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any :ref:`integer value -` (like ``3`` or ``0x20``) for ``y``. - -Before doing an example of ``&=``, let's first review the Bitwise AND -(``&``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 0 0 1 (operand1 & operand2) = result - -As shown above, bits that are "bitwise ANDed" with 0 become 0, while -bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` -is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & -B11111111`` equals ``b``. - -.. _lang-bitwisecompound-binconst: - -.. note:: The above uses :ref:`binary constants - `\ . The numbers are still the same - value in other representations, they just might not be as easy to - understand. - - Normally, in C and C++ code, :ref:`hexadecimal - ` or :ref:`octal - ` are used when we're interested in - an integer's bits, rather than its value as a number. - - While hexadecimal and octal literals might be harder to understand - at first, you should really take the time to learn them. They're - part of C, C++, and many other programming languages, while binary - constants are available only for compatibility with Arduino. - - Also, ``B00000000`` is shown for clarity, but zero in any number - format is zero. - -So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while -leaving the rest of the variable's bits unchanged, use the compound -bitwise AND operator ``&=`` with the constant ``B11111100`` -(hexadecimal ``0xFC``\ ):: - - 1 0 1 0 1 0 1 0 variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - 1 0 1 0 1 0 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -Here is the same representation with the variable's bits replaced -with the symbol ``x``\ :: - - x x x x x x x x variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - x x x x x x 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -So, using a byte variable ``b``\ , if we say:: - - b = B10101010; // B10101010 == 0xAA - b &= B11111100; // B11111100 == 0xFC - -then we will have :: - - b == B10101000; // B10101000 == 0xA8 - -.. _lang-bitwisecompound-or: - -Compound bitwise OR (\|=) -------------------------- - -The compound bitwise OR operator ``|=`` is often used with a variable -and a constant to "set" (set to 1) particular bits in a variable. In -a program, writing the line ``x |= y;`` is equivalent to writing ``x = -x | y;``. That is, the value of ``x`` after the line will be equal to -its old value bitwise ORed with the value of ``y``:: - - x |= y; // equivalent to x = x | y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any integer value (like ``3`` or ``0x20``) for -``y``. (This works the same way as :ref:`compound bitwise AND -`\ , ``&=``). - -Before doing an example of ``|=``, let's first review the Bitwise OR -(``|``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) = result - -Bits that are "bitwise ORed" with 0 are unchanged, while bits that are -"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` -variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` -equals ``B11111111`` (here we've used binary constants; see the -:ref:`note ` above). - -So, to set bits 0 and 1 of a one-byte variable, while leaving the rest -of the variable unchanged, use the compound bitwise OR operator -(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -Here is the same representation with the variable's bits replaced with -the symbol ``x``:: - - x x x x x x x x variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - x x x x x x 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b |= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101011; // B10101011 == 0xAB - -.. _lang-bitwisecompound-xor: - -Compound bitwise XOR (\^=) --------------------------- - -The compound bitwise XOR operator ``^=`` is used with a variable and a -constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a -variable. In a program, writing the line ``x ^= y;`` is equivalent to -writing ``x = x ^ y;``. That is, the value of ``x`` after the line -will be equal to its old value bitwise XORed with the value of ``y``:: - - x ^= y; // equivalent to x = x ^ y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any integer value (like ``3`` or ``0x20``) for -``y``. (This works the same way as :ref:`&= -` and :ref:`\|= -`; in fact, these three operators all -work the same in this way). - -Before doing an example of ``^=``, let's first review the Bitwise -XOR operator, ``^``:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 0 (operand1 ^ operand2) = result - -One way to look at bitwise XOR is that each bit in the result is a 1 -if the input bits are different, or 0 if they are the same. Another -way to think about it is that the result bit will be 1 when *exactly* -one (no more, no less) of the input bits is 1; otherwise, it will be -zero. This means that if you XOR a bit with 1, it will change (or -toggle) its value, while if you XOR a bit with 0, it stays the same. - -So, to toggle bits 0 and 1 of a one-byte variable, while leaving the -rest of the variable unchanged, use the compound bitwise XOR operator -``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see -:ref:`note ` above):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged toggled - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b ^= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101001; // B10101001 == 0xA9 - -See Also --------- - -- :ref:`Boolean operations ` (``&&``, ``||``) -- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwisemath.rst b/docs/source/lang/bitwisemath.rst index 30e8873..28fe6bf 100644 --- a/docs/source/lang/bitwisemath.rst +++ b/docs/source/lang/bitwisemath.rst @@ -2,8 +2,8 @@ .. _lang-bitwisemath: -Bitwise AND (&), OR (\|), XOR (^), NOT (~) -========================================== +Bitwise Operators (``&``, ``|``, ``^``, ``~``) +============================================== The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming @@ -22,8 +22,8 @@ Below are descriptions and syntax for all of the operators. .. _lang-bitwisemath-and: -Bitwise AND (&) ---------------- +Bitwise AND (``&``) +------------------- The bitwise AND operator in C++ is a single ampersand, ``&``, used between two other integer expressions. Bitwise AND operates on each @@ -54,8 +54,8 @@ value 1000100 in binary, which is 68 in decimal. .. _lang-bitwisemath-or: -Bitwise OR (\|) ---------------- +Bitwise OR (``|``) +------------------ The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like the ``&`` operator, ``|`` operates independently on each bit in its @@ -78,8 +78,8 @@ uses 32):: .. _lang-bitwisemath-xor: -Bitwise XOR (^) ---------------- +Bitwise XOR (``^``) +------------------- There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English, this is usually pronounced @@ -129,8 +129,8 @@ program to blink digital pin 13 (the LED pin on Maple):: .. _lang-bitwisemath-not: -Bitwise NOT (~) ---------------- +Bitwise NOT (``~``) +------------------- The bitwise NOT operator in C++ is the tilde character ``~``. Unlike ``&`` and ``|``, the bitwise NOT operator is applied to a single @@ -179,7 +179,7 @@ See Also -------- - :ref:`Boolean operations ` (``&&``, ``||``) -- :ref:`Compound bitwise operations ` (``&=``, +- :ref:`Compound bitwise operations ` (``&=``, ``|=``, ``^=``). diff --git a/docs/source/lang/bitwrite.rst b/docs/source/lang/bitwrite.rst index 86df26e..b3feff2 100644 --- a/docs/source/lang/bitwrite.rst +++ b/docs/source/lang/bitwrite.rst @@ -1,13 +1,19 @@ -.. _lang-bitwrite: +.. highlight:: cpp -bitWrite(x, n, b) -================= +.. _lang-bitwrite: -Description ------------ +bitWrite() +========== (Macro) Writes a bit of a numeric variable. +Syntax +------ + +:: + + bitWrite(x, n, b) + Parameters ---------- diff --git a/docs/source/lang/boolean.rst b/docs/source/lang/boolean.rst index 6ff4097..8d6aa5c 100644 --- a/docs/source/lang/boolean.rst +++ b/docs/source/lang/boolean.rst @@ -83,7 +83,7 @@ See Also -------- - :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) -- :ref:`Compound bitwise operators ` (``&=``, +- :ref:`Compound bitwise operators ` (``&=``, ``|=``, ``^=``). - :ref:`if statement ` diff --git a/docs/source/lang/booleanvariables.rst b/docs/source/lang/booleanvariables.rst index 9d0e992..6051b8c 100644 --- a/docs/source/lang/booleanvariables.rst +++ b/docs/source/lang/booleanvariables.rst @@ -6,9 +6,8 @@ Booleans ======== A **boolean** holds one of two values, :ref:`true -` or :ref:`false `. -On a Maple, each boolean variable occupies one byte of memory, and has -type ``bool``. +` or :ref:`false `. On a +Maple, each boolean variable has type ``bool``. .. warning:: diff --git a/docs/source/lang/braces.rst b/docs/source/lang/braces.rst deleted file mode 100644 index 229ad8c..0000000 --- a/docs/source/lang/braces.rst +++ /dev/null @@ -1,109 +0,0 @@ -.. highlight:: cpp - -.. _lang-braces: - -Curly Braces ({}) -================= - -.. contents:: Contents - :local: - -Introduction ------------- - -Curly braces (also referred to as just "braces" or as "curly -brackets") are a major part of the C and C++ programming -languages. They are used in several different constructs, outlined -below, and this can sometimes be confusing for beginners. - -An opening curly brace, ``{`` must always be followed by a closing -curly brace ``}``. This is a condition that is often referred to as -the braces being *balanced*. The Maple IDE (integrated development -environment) includes a convenient feature to check the balance of -curly braces. Just select a brace, or even click the insertion point -immediately following a brace, and its companion will be highlighted\ -[#fbug]_\ . - -Beginning programmers, and programmers coming to C++ from languages -without braces, often find using them confusing or daunting. - -Because the use of the curly brace is so varied, it is good -programming practice to type the closing brace immediately after -typing the opening brace when inserting a construct which requires -curly braces. Then insert some blank lines between your braces and -begin inserting statements. Your braces, and your attitude, will never -become unbalanced. - -Unbalanced braces can often lead to cryptic, impenetrable compiler -errors that can sometimes be hard to track down in a large program. -Because of their varied usages, braces are also incredibly important -to the syntax of a program and moving a brace one or two lines will -usually dramatically affect the meaning of a program. - -The main uses of curly braces ------------------------------ - -**Functions**:: - - // a function body needs braces around it - void myFunction(datatype argument) { - // ... function body goes in here ... - } - -**Loops** (see the :ref:`while `\ , :ref:`for -`\ , and :ref:`do/while ` loop reference -pages for more information):: - - // you should put braces around the body of a loop: - - while (boolean expression) { - // code inside the loop goes here - } - - for (initialisation; termination condition; incrementing expr) { - // code inside the loop goes here - } - - do { - // code inside the loop goes here - } while (boolean expression); - - -**Conditional statements** (see the :ref:`if statement ` -reference page for more information):: - - // you should put braces around the body of an "if", "else if", - // or "else": - - if (boolean expression) { - // code inside the "if" - } - else if (boolean expression) { - // code inside the "else if" - } - else { - // code inside the "else" - } - -**Switch statements** (see the :ref:`switch statement -` reference page for more information):: - - switch (var) { - case 1: - doThing1(); - break; - case 2: - doThing2(); - break; - } - -.. rubric:: Footnotes - -.. TODO remove this once IDE 0.1.0 released - -.. [#fbug] At present this feature is slightly buggy as the IDE will - often find (incorrectly) a brace in text that has been commented - out. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/break.rst b/docs/source/lang/break.rst index dc50b5f..ce8ac17 100644 --- a/docs/source/lang/break.rst +++ b/docs/source/lang/break.rst @@ -2,8 +2,8 @@ .. _lang-break: -break -===== +``break`` +========= ``break`` is used to exit from a :ref:`while `\ , :ref:`for `\ , or :ref:`do/while ` loop, diff --git a/docs/source/lang/bytecast.rst b/docs/source/lang/bytecast.rst index 4ad2a89..b3f0de2 100644 --- a/docs/source/lang/bytecast.rst +++ b/docs/source/lang/bytecast.rst @@ -5,9 +5,6 @@ byte() (cast) ============= -Description ------------ - Converts a value to the :ref:`byte ` data type. .. note:: diff --git a/docs/source/lang/char.rst b/docs/source/lang/char.rst index 8c6dadf..b8747f3 100644 --- a/docs/source/lang/char.rst +++ b/docs/source/lang/char.rst @@ -2,11 +2,8 @@ .. _lang-char: -char -==== - -Description ------------ +``char`` +======== The ``char`` type stores a 1-byte character value (or integer with value from -128 to 127). Character literals are written in single diff --git a/docs/source/lang/charcast.rst b/docs/source/lang/charcast.rst index 844dd58..a480dec 100644 --- a/docs/source/lang/charcast.rst +++ b/docs/source/lang/charcast.rst @@ -2,11 +2,8 @@ .. _lang-charcast: -char() (cast) -============= - -Description ------------ +``char()`` (cast) +================= Converts a value to the :ref:`char ` data type. diff --git a/docs/source/lang/comparison.rst b/docs/source/lang/comparison.rst index 8873256..b24355f 100644 --- a/docs/source/lang/comparison.rst +++ b/docs/source/lang/comparison.rst @@ -2,8 +2,8 @@ .. _lang-comparison: -Comparison Operators -==================== +Comparison Operators (``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``) +=================================================================== The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and ``>=`` are used to compare two numbers. They are :ref:`true diff --git a/docs/source/lang/compoundarithmetic.rst b/docs/source/lang/compoundarithmetic.rst new file mode 100644 index 0000000..420f1db --- /dev/null +++ b/docs/source/lang/compoundarithmetic.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-compoundarithmetic: + +Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) +=============================================================== + +These oparators perform a mathematical operation on a variable with +another constant or variable. These operators are just a convenient +shorthand:: + + x += y; // equivalent to the expression x = x + y; + x -= y; // equivalent to the expression x = x - y; + x *= y; // equivalent to the expression x = x * y; + x /= y; // equivalent to the expression x = x / y; + +Here is an example:: + + int x = 2; + int y = 10; + + x += 4; // x now contains 6 + x -= 3; // x now contains 3 + x *= y; // x now contains 30 + x /= 2; // x now contains 15 + x += max(20, 6); // x now contains 35 + x -= sq(5); // x now contains 15 + +Parameters +---------- + +**x**: a numeric variable + +**y**: a numeric variable, number constant, or any other expression +that evaluates to a number (e.g. call to a function that returns a +number). + +See Also +-------- + +- :ref:`Arithmetic operators ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/compoundbitwise.rst b/docs/source/lang/compoundbitwise.rst new file mode 100644 index 0000000..a4bbb24 --- /dev/null +++ b/docs/source/lang/compoundbitwise.rst @@ -0,0 +1,231 @@ +.. highlight:: cpp + +.. _lang-compoundbitwise: + +Compound Bitwise Operators (``&=``, ``|=``, ``^=``) +=================================================== + +The compound bitwise operators perform their calculations at the +bit level of variables. They are often used to clear and set +specific bits of a variable. + +See the :ref:`bitwise math tutorial ` for more +information on bitwise operators. + +.. contents:: Contents + :local: + +.. _lang-compoundbitwise-and: + +Compound bitwise AND (``&=``) +----------------------------- + +The compound bitwise AND operator ``&=`` is often used with a variable +and a constant to force particular bits in a variable to be zero. This +is often referred to in programming guides as "clearing" or +"resetting" bits. In a program, writing the line ``x &= y;`` is +equivalent to writing ``x = x & y;``. That is, the value of ``x`` +after the line will be equal to its old value bitwise ANDed with the +value of ``y``:: + + x &= y; // equivalent to x = x & y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any :ref:`integer value +` (like ``3`` or ``0x20``) for ``y``. + +Before doing an example of ``&=``, let's first review the Bitwise AND +(``&``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + +As shown above, bits that are "bitwise ANDed" with 0 become 0, while +bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` +is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & +B11111111`` equals ``b``. + +.. _lang-compoundbitwise-binconst: + +.. note:: The above uses :ref:`binary constants + `\ . The numbers are still the same + value in other representations, they just might not be as easy to + understand. + + Normally, in C and C++ code, :ref:`hexadecimal + ` or :ref:`octal + ` are used when we're interested in + an integer's bits, rather than its value as a number. + + While hexadecimal and octal literals might be harder to understand + at first, you should really take the time to learn them. They're + part of C, C++, and many other programming languages, while binary + constants are available only for compatibility with Arduino. + + Also, ``B00000000`` is shown for clarity, but zero in any number + format is zero. + +So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while +leaving the rest of the variable's bits unchanged, use the compound +bitwise AND operator ``&=`` with the constant ``B11111100`` +(hexadecimal ``0xFC``\ ):: + + 1 0 1 0 1 0 1 0 variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + 1 0 1 0 1 0 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +Here is the same representation with the variable's bits replaced +with the symbol ``x``\ :: + + x x x x x x x x variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + x x x x x x 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +So, using a byte variable ``b``\ , if we say:: + + b = B10101010; // B10101010 == 0xAA + b &= B11111100; // B11111100 == 0xFC + +then we will have :: + + b == B10101000; // B10101000 == 0xA8 + +.. _lang-compoundbitwise-or: + +Compound bitwise OR (``|=``) +---------------------------- + +The compound bitwise OR operator ``|=`` is often used with a variable +and a constant to "set" (set to 1) particular bits in a variable. In +a program, writing the line ``x |= y;`` is equivalent to writing ``x = +x | y;``. That is, the value of ``x`` after the line will be equal to +its old value bitwise ORed with the value of ``y``:: + + x |= y; // equivalent to x = x | y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`compound bitwise AND +`\ , ``&=``). + +Before doing an example of ``|=``, let's first review the Bitwise OR +(``|``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Bits that are "bitwise ORed" with 0 are unchanged, while bits that are +"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` +variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` +equals ``B11111111`` (here we've used binary constants; see the +:ref:`note ` above). + +So, to set bits 0 and 1 of a one-byte variable, while leaving the rest +of the variable unchanged, use the compound bitwise OR operator +(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +Here is the same representation with the variable's bits replaced with +the symbol ``x``:: + + x x x x x x x x variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + x x x x x x 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b |= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101011; // B10101011 == 0xAB + +.. _lang-compoundbitwise-xor: + +Compound bitwise XOR (``^=``) +----------------------------- + +The compound bitwise XOR operator ``^=`` is used with a variable and a +constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a +variable. In a program, writing the line ``x ^= y;`` is equivalent to +writing ``x = x ^ y;``. That is, the value of ``x`` after the line +will be equal to its old value bitwise XORed with the value of ``y``:: + + x ^= y; // equivalent to x = x ^ y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`&= +` and :ref:`\|= +`; in fact, these three operators all +work the same in this way). + +Before doing an example of ``^=``, let's first review the Bitwise +XOR operator, ``^``:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + +One way to look at bitwise XOR is that each bit in the result is a 1 +if the input bits are different, or 0 if they are the same. Another +way to think about it is that the result bit will be 1 when *exactly* +one (no more, no less) of the input bits is 1; otherwise, it will be +zero. This means that if you XOR a bit with 1, it will change (or +toggle) its value, while if you XOR a bit with 0, it stays the same. + +So, to toggle bits 0 and 1 of a one-byte variable, while leaving the +rest of the variable unchanged, use the compound bitwise XOR operator +``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see +:ref:`note ` above):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged toggled + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b ^= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101001; // B10101001 == 0xA9 + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/const.rst b/docs/source/lang/const.rst index 1658e6d..52de85f 100644 --- a/docs/source/lang/const.rst +++ b/docs/source/lang/const.rst @@ -2,8 +2,8 @@ .. _lang-const: -const Keyword -============= +``const`` +========= The ``const`` keyword stands for "constant". It is a variable *qualifier* that modifies the behavior of the variable, making a diff --git a/docs/source/lang/constants.rst b/docs/source/lang/constants.rst index b7521ed..bc5c894 100644 --- a/docs/source/lang/constants.rst +++ b/docs/source/lang/constants.rst @@ -1,11 +1,11 @@ .. _lang-constants: -constants +Constants ========= -Constants are predefined variables in the Arduino language. They -are used to make the programs easier to read. We classify constants -in groups. +Constants are like predefined variables, whose values can't +change. They are used to make the programs easier to read and modify. +This page describes the most commonly used constants. .. contents:: Contents :local: @@ -15,288 +15,290 @@ in groups. Boolean Constants ----------------- -There are two constants used to represent truth and falsity in the -Arduino language: **true**, and **false**. +There are two constants used to represent truth and falsity: ``true``, +and ``false``. .. _lang-constants-false: false ^^^^^ -false is the easier of the two to define. false is defined as 0 -(zero). +``false`` is the false ``bool`` value. An integer which is 0 evaluates +to ``false`` as a boolean. .. _lang-constants-true: true ^^^^ -true is often said to be defined as 1, which is correct, but true -has a wider definition. Any integer which is *non-zero* is TRUE, in -a Boolean sense. So -1, 2 and -200 are all defined as true, too, in -a Boolean sense. +``true`` is the true ``bool`` value. As an integer, ``true`` is often +said to be 1. This is correct in the sense that ``true`` evaluates to +1 as an integer. However, any integer which is *non-zero* is ``true`` +as a :ref:`bool `. So -1, 2 and -200 are all +"true", in the sense that these numbers are treated the same as +``true`` in a boolean context. +Note that the ``true`` and ``false`` constants are typed in lowercase; +unlike e.g. ``HIGH``, ``LOW``, ``INPUT``, and ``OUTPUT`` (which are +described below). -Note that the *true* and *false* constants are typed in lowercase -unlike HIGH, LOW, INPUT, & OUTPUT. +Pin Levels: HIGH and LOW +------------------------ -Defining Pin Levels, HIGH and LOW ---------------------------------- - -When reading or writing to a digital pin there are only two -possible values a pin can take/be-set-to: **HIGH** and **LOW**. +When reading or writing to a digital pin there are only two possible +values a pin can be set to: ``HIGH`` and ``LOW``. .. _lang-constants-high: -**HIGH** - - - -The meaning of HIGH (in reference to a pin) is somewhat different -depending on whether a pin is set to an INPUT or OUTPUT. When a pin -is configured as an INPUT with pinMode, and read with digitalRead, -the microcontroller will report HIGH if a voltage of 3 volts or -more is present at the pin. - - +HIGH +^^^^ -A pin may also be configured as an INPUT with pinMode, and -subsequently made HIGH with digitalWrite, this will set the -internal 20K pullup resistors, which will *steer* the input pin to -a HIGH reading unless it is pulled LOW by external circuitry. +The meaning of ``HIGH`` (in reference to a pin) is somewhat different +depending on whether the pin is set to ``INPUT`` or ``OUTPUT``. When a +pin is configured as an ``INPUT`` (using :ref:`pinMode() +`), and read with :ref:`digitalRead() +`, the microcontroller will report ``HIGH`` if a +voltage of 3 volts or more is present at the pin. +.. TODO? Following seems false; check it out sometime, leave out for now: +.. A pin may also be configured as an ``INPUT`` with ``pinMode()``, and +.. subsequently made ``HIGH`` with :ref:`digitalWrite() +.. `, this will set the internal pullup resistors, +.. which will *steer* the input pin to a HIGH reading unless it is pulled +.. LOW by external circuitry. -When a pin is configured to OUTPUT with pinMode, and set to HIGH -with digitalWrite, the pin is at 5 volts. In this state it can -*source* current, e.g. light an LED that is connected through a -series resistor to ground, or to another pin configured as an -output, and set to LOW. +When a pin is configured to ``OUTPUT`` with pinMode, and set to +``HIGH`` with :ref:`digitalWrite() `, the pin is at +3.3 volts. In this state it can *source* current, e.g. light an LED +that is connected through a series resistor to ground, or to another +pin configured as an output and set to ``LOW``. .. _lang-constants-low: -**LOW** +LOW +^^^ +The meaning of ``LOW`` also has a different meaning depending on +whether a pin is set to ``INPUT`` or ``OUTPUT``. When a pin is +configured as an ``INPUT`` with :ref:`pinMode() `, and +read with :ref:`digitalRead() `, the microcontroller +will report ``LOW`` if a voltage of 2 volts or less is present at the +pin. +When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to +``LOW`` with :ref:`digitalWrite() `, the +microcontroller will attempt to keep that pin's voltage at 0V. In this +state it can *sink* current, e.g. light an LED that is connected +through a series resistor to +3.3V, or to another pin configured as an +output, and set to ``HIGH``. -The meaning of LOW also has a different meaning depending on -whether a pin is set to INPUT or OUTPUT. When a pin is configured -as an INPUT with pinMode, and read with digitalRead, the -microcontroller will report LOW if a voltage of 2 volts or less is -present at the pin. +Pin Modes +--------- +Digital pins can be used in a variety of modes. The basic modes, +``INPUT`` and ``OUTPUT``, have been introduced above. Changing a pin +from ``INPUT`` TO ``OUTPUT`` with :ref:`pinMode() ` +drastically changes the electrical behavior of the pin. - -When a pin is configured to OUTPUT with pinMode, and set to LOW -with digitalWrite, the pin is at 0 volts. In this state it can -*sink* current, e.g. light an LED that is connected through a -series resistor to, +5 volts, or to another pin configured as an -output, and set to HIGH. - - - -Defining Digital Pins, INPUT and OUTPUT ---------------------------------------- - -Digital pins can be used either as **INPUT** or **OUTPUT**. -Changing a pin from INPUT TO OUTPUT with pinMode() drastically -changes the electrical behavior of the pin. +This section describes the basic digital pin modes (``INPUT`` and +``OUTPUT``) only. For a detailed description of all possible pin +modes, see the :ref:`pinMode() ` reference page. .. _lang-constants-input: -Pins Configured as Inputs -^^^^^^^^^^^^^^^^^^^^^^^^^ +INPUT +^^^^^ -Arduino (Atmega) pins configured as **INPUT** with pinMode() are -said to be in a high-impedance state. One way of explaining this is -that pins configured as INPUT make extremely small demands on the -circuit that they are sampling, say equivalent to a series resistor -of 100 Megohms in front of the pin. This makes them useful for -reading a sensor, but not powering an LED. +Maple (STM32) pins configured as ``INPUT`` are said to be in a +high-impedance state. One way of explaining this is that pins +configured as ``INPUT`` make extremely small demands on the circuit +that they are sampling. This makes them useful for reading a sensor, +but not powering an LED. .. _lang-constants-output: -Pins Configured as Outputs -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Pins configured as **OUTPUT** with pinMode() are said to be in a -low-impedance state. This means that they can provide a substantial -amount of current to other circuits. Atmega pins can source -(provide positive current) or sink (provide negative current) up to -40 mA (milliamps) of current to other devices/circuits. This makes -them useful for powering LED's but useless for reading sensors. -Pins configured as outputs can also be damaged or destroyed if -short circuited to either ground or 5 volt power rails. The amount -of current provided by an Atmega pin is also not enough to power -most relays or motors, and some interface circuitry will be -required. - -.. _lang-constants-fp: - -Floating-Point Constants ------------------------- - -Similar to integer constants, floating point constants are used to -make code more readable. Floating point constants are swapped at -compile time for the value to which the expression evaluates. - -.. TODO explain that floating point literals are doubles - -.. _lang-constants-fp-f: - -.. TODO f modifiers - -Examples: +OUTPUT +^^^^^^ -``n = .005;`` +Pins configured as ``OUTPUT`` with :ref:`pinMode() ` are +said to be in a low-impedance state. This means that they can provide +a substantial amount of current to other circuits. STM32 pins can +source (provide positive current) or sink (provide negative current) +up to 50 mA (milliamps) of current to other devices/circuits. This +makes them useful for powering LEDs, but useless for reading sensors. -Floating point constants can also be expressed in a variety of -scientific notation. 'E' and 'e' are both accepted as valid -exponent indicators. - -:: - - - floating-point evaluates to: also evaluates to: - constant - - 10.0 10 - 2.34E5 2.34 * 10^5 234000 - 67e-12 67.0 * 10^-12 .000000000067 +Pins configured as outputs can also be damaged or destroyed if short +circuited to either ground or 3.3V power rails. The amount of current +provided by an STM32 pin is also not enough to power most relays or +motors, and some interface circuitry will be required. .. _lang-constants-integers: Integer Constants ----------------- -Integer constants are numbers used directly in a sketch, like -``123``. By default, these numbers are treated as -`int `_'s but you can change -this with the U and L modifiers (see below). - - - -Normally, integer constants are treated as base 10 (decimal) -integers, but special notation (formatters) may be used to enter -numbers in other bases. - - - -:: - - Base Example Formatter Comment - - 10 (decimal) 123 none - - 2 (binary) B1111011 leading 'B' only works with 8 bit values (0 to 255) - characters 0-1 valid - - 8 (octal) 0173 leading "0" characters 0-7 valid - - 16 (hexadecimal) 0x7B leading "0x" characters 0-9, A-F, a-f valid +Integer constants (or more properly speaking, integer *literals*) are +numbers used directly in a sketch, like ``123``. By default, an +integer literal is treated as a (signed) :ref:`int `, but +you can change this with the U and L modifiers (see :ref:`below +`). You can specify negative numbers by +putting a minus sign in front, like ``-123``. + +Normally, integer literals are treated as base 10 (decimal) integers, +but special notation (formatters) may be used to enter numbers in +other bases. These are summarized in the following table: + +.. list-table:: + :header-rows: 1 + + * - Base + - Example + - Formatter + - Comment + + * - 10 (decimal) + - ``123`` + - None + - + + * - 2 (binary) + - ``0b1111011`` + - Leading "0b" + - GCC extension; not standard C++ + + * - 8 (octal) + - ``0173`` + - Leading "0" + - Characters 0-7 valid + + * - 16 (hexadecimal) + - ``0x7B`` + - Leading "0x" + - Characters 0-9, A-F (or a-f) valid + +Binary constants (like ``B1111011``) for values between 0 and 255 are +supported for compatibility with Arduino only. Their use in new +programs is discouraged. .. _lang-constants-integers-dec: -**Decimal** is base 10. This is the common-sense math with which -you are acquainted. Constants without other prefixes are assumed to -be in decimal format. +**Decimal** is base 10. This is the common number system we learn in +school. Integer literals without other prefixes are assumed to be in +decimal format. - - -Example: -:: - - 101 // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1) +For example, the decimal literal ``101`` is one hundred and one: 1×10\ +:sup:`2` + 0×10\ :sup:`1` + 1×10\ :sup:`0` = 101. .. _lang-constants-integers-bin: -**Binary** is base two. Only characters 0 and 1 are valid. - - - -Example: -:: - - B101 // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) - -The binary formatter only works on bytes (8 bits) between 0 (B0) -and 255 (B11111111). If it is convenient to input an int (16 bits) -in binary form you can do it a two-step procedure such as: +**Binary** is base two. Only characters 0 and 1 are valid. Binary +literals are indicated by the prefix ``0b`` (this is a :ref:`GCC +` extension; it's not standard C++). - - -:: - - myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte +For example, the binary literal ``0b101`` is five: 1×2\ :sup:`2` + +0×2\ :sup:`1` + 1×2\ :sup:`0` = 5. .. _lang-constants-integers-oct: **Octal** is base eight. Only characters 0 through 7 are valid. Octal -values are indicated by the prefix "0". +literals are indicated by the prefix ``0``. -Example: +For example, the octal literal ``0101`` is sixty five: 1×8\ :sup:`2` + +0×8\ :sup:`1` + 1×8\ :sup:`0` = 65. -:: +.. warning:: Bugs sometimes result by (unintentionally) including a + leading "0" before an integer literal, which makes the compiler + interpret it in octal. - 0101 // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1) +.. _lang-constants-integers-hex: -Warning -It is possible to generate a hard-to-find bug by (unintentionally) -including a leading zero before a constant and having the compiler -unintentionally interpret your constant as octal. +**Hexadecimal** (or "hex") is base sixteen. Valid characters are 0 +through 9 and letters A through F; A has the value 10, B is 11, up to +F, which is 15. Hex values are indicated by the prefix ``0x``. A-F +may be typed in upper or lower case (a-f). -.. _lang-constants-integers-hex: +For example, the hexadecimal literal ``0x101`` is two hundred fifty +seven: 1×16\ :sup:`2` + 0×16\ :sup:`1` + 1×16\ :sup:`0` = 257. -**Hexadecimal (or hex)** is base sixteen. Valid characters are 0 -through 9 and letters A through F; A has the value 10, B is 11, up -to F, which is 15. Hex values are indicated by the prefix "0x". -Note that A-F may be syted in upper or lower case (a-f). +The hexadecimal literal ``0xCF2`` is three thousand, three hundred +fourteen: 12×16\ :sup:`2` + 15×16\ :sup:`1` + 2×16\ :sup:`0` = 3314. +(Remember that in hex, ``A`` means 10, and counting up, ``B``\ =11, so +``C``\ =12 and ``F``\ =15). +.. _lang-constants-integers-u-l: -Example: +U and L Suffixes +^^^^^^^^^^^^^^^^ -:: +By default, an integer constant is treated as an :ref:`int +`, with the attendant :ref:`limitations in values +`. To specify an integer constant with another data +type, follow it with: - 0x101 // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1) +- a ``u`` or ``U`` to interpret the constant as an unsigned value. + For example, ``33U`` is an :ref:`unsigned int `. -.. _lang-constants-integers-u-l: +- an ``l`` or ``L`` to interpret the constant as a long value. For + example, ``100000L`` is a :ref:`long `. -U & L formatters -^^^^^^^^^^^^^^^^ +- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an + :ref:`unsigned long `. + +.. _lang-constants-fp: -By default, an integer constant is treated as an -`int `_ with the attendant -limitations in values. To specify an integer constant with another -data type, follow it with: +Floating-Point Constants +------------------------ +Similar to integer literals, floating point constants (properly: +floating-point *literals*) are used to make code more readable. +Floating point literals are swapped at compile time for the value to +which the expression evaluates. +A floating point literal is any number which includes a decimal point. +For instance, ``3.0`` is a floating-point literal for the number 3. +By default, a floating-point literal is a :ref:`double `. +In order for the literal to be interpreted as a :ref:`float +`, you can write ``f`` directly after it. For example, +``3.0f`` is a floating-point literal with type ``float``. +Floating point constants can also be expressed in a variety of +scientific notation. ``E`` and ``e`` are both accepted as valid +exponent indicators. Some examples are given in the following table: -- a 'u' or 'U' to force the constant into an unsigned data format. - Example: ``33u`` -- a 'l' or 'L' to force the constant into a long data format. - Example: ``100000L`` -- a 'ul' or 'UL' to force the constant into an unsigned long - constant. Example: ``32767ul`` +.. list-table:: + :header-rows: 1 + * - Floating-point literal + - Evaluates to + - Alternate expression + * - ``10.0`` + - 10 + - -See also --------- + * - ``2.34E5`` + - 2.34×10\ :sup:`5` + - ``234000.0`` + * - ``67e-12`` + - 67.0×10\ :sup:`-12` + - ``0.000000000067`` -- `pinMode() `_ -- `Integer Constants `_ -- `boolean variables `_ -- `#define `_ -- `byte `_ -- `int `_ -- `unsigned int `_ -- `long `_ -- `unsigned long `_ +See Also +-------- +- :ref:`pinMode() ` +- :ref:`Boolean Variables ` +- :ref:`#define ` +- :ref:`int ` +- :ref:`unsigned int ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`float ` +- :ref:`double ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/constrain.rst b/docs/source/lang/constrain.rst index 297a2d4..d19b61c 100644 --- a/docs/source/lang/constrain.rst +++ b/docs/source/lang/constrain.rst @@ -2,14 +2,18 @@ .. _lang-constrain: -constrain(x, a, b) -================== - -Description ------------ +constrain() +=========== (Macro) Constrains a number to be within a range. +Syntax +------ + +:: + + constrain(x, a, b) + Parameters ---------- diff --git a/docs/source/lang/continue.rst b/docs/source/lang/continue.rst index 21b3984..13d1815 100644 --- a/docs/source/lang/continue.rst +++ b/docs/source/lang/continue.rst @@ -2,9 +2,8 @@ .. _lang-continue: -========== - continue -========== +``continue`` +============ The ``continue`` keyword skips the rest of the current iteration of a :ref:`while `\ , :ref:`for `\ , or @@ -12,9 +11,8 @@ The ``continue`` keyword skips the rest of the current iteration of a conditional expression of the loop, and proceeding with any subsequent iterations. - Example -======= +------- :: diff --git a/docs/source/lang/curly-braces.rst b/docs/source/lang/curly-braces.rst new file mode 100644 index 0000000..a4bd3dc --- /dev/null +++ b/docs/source/lang/curly-braces.rst @@ -0,0 +1,109 @@ +.. highlight:: cpp + +.. _lang-curly-braces: + +Curly Braces (``{``, ``}``) +=========================== + +.. contents:: Contents + :local: + +Introduction +------------ + +Curly braces (also referred to as just "braces" or as "curly +brackets") are a major part of the C and C++ programming +languages. They are used in several different constructs, outlined +below, and this can sometimes be confusing for beginners. + +An opening curly brace, ``{`` must always be followed by a closing +curly brace ``}``. This is a condition that is often referred to as +the braces being *balanced*. The Maple IDE (integrated development +environment) includes a convenient feature to check the balance of +curly braces. Just select a brace, or even click the insertion point +immediately following a brace, and its companion will be highlighted\ +[#fbug]_\ . + +Beginning programmers, and programmers coming to C++ from languages +without braces, often find using them confusing or daunting. + +Because the use of the curly brace is so varied, it is good +programming practice to type the closing brace immediately after +typing the opening brace when inserting a construct which requires +curly braces. Then insert some blank lines between your braces and +begin inserting statements. Your braces, and your attitude, will never +become unbalanced. + +Unbalanced braces can often lead to cryptic, impenetrable compiler +errors that can sometimes be hard to track down in a large program. +Because of their varied usages, braces are also incredibly important +to the syntax of a program and moving a brace one or two lines will +usually dramatically affect the meaning of a program. + +The main uses of curly braces +----------------------------- + +**Functions**:: + + // a function body needs braces around it + void myFunction(datatype argument) { + // ... function body goes in here ... + } + +**Loops** (see the :ref:`while `\ , :ref:`for +`\ , and :ref:`do/while ` loop reference +pages for more information):: + + // you should put braces around the body of a loop: + + while (boolean expression) { + // code inside the loop goes here + } + + for (initialisation; termination condition; incrementing expr) { + // code inside the loop goes here + } + + do { + // code inside the loop goes here + } while (boolean expression); + + +**Conditional statements** (see the :ref:`if statement ` +reference page for more information):: + + // you should put braces around the body of an "if", "else if", + // or "else": + + if (boolean expression) { + // code inside the "if" + } + else if (boolean expression) { + // code inside the "else if" + } + else { + // code inside the "else" + } + +**Switch statements** (see the :ref:`switch statement +` reference page for more information):: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + +.. rubric:: Footnotes + +.. TODO remove this once IDE 0.1.0 released + +.. [#fbug] At present this feature is slightly buggy as the IDE will + often find (incorrectly) a brace in text that has been commented + out. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/define.rst b/docs/source/lang/define.rst index 30738ec..677390d 100644 --- a/docs/source/lang/define.rst +++ b/docs/source/lang/define.rst @@ -2,8 +2,8 @@ .. _lang-define: -#define -======= +``#define`` +=========== ``#define`` is a useful C and C++ feature that allows the programmer to give a name to a constant value before the program is compiled. diff --git a/docs/source/lang/digitalread.rst b/docs/source/lang/digitalread.rst index 71583ca..3502587 100644 --- a/docs/source/lang/digitalread.rst +++ b/docs/source/lang/digitalread.rst @@ -5,9 +5,6 @@ digitalRead() ============= -Description ------------ - Reads the value from a specified digital pin, either :ref:`HIGH ` or :ref:`LOW `. diff --git a/docs/source/lang/digitalwrite.rst b/docs/source/lang/digitalwrite.rst index 419ef3a..6124d5f 100644 --- a/docs/source/lang/digitalwrite.rst +++ b/docs/source/lang/digitalwrite.rst @@ -1,116 +1,68 @@ +.. highlight:: cpp + .. _lang-digitalwrite: digitalWrite() ============== -Description ------------ - -Write a `HIGH `_ or a -`LOW `_ value to a -digital pin. - - - -If the pin has been configured as an OUTPUT with -`pinMode `_\ (), its voltage -will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) -for HIGH, 0V (ground) for LOW. - - - -If the pin is configured as an INPUT, writing a HIGH value with -digitalWrite() will enable an internal 20K pullup resistor (see the -`tutorial on digital pins `_). -Writing LOW will disable the pullup. The pullup resistor is enough -to light an LED dimly, so if LEDs appear to work, but very dimly, -this is a likely cause. The remedy is to set the pin to an output -with the pinMode() function. - +Write a :ref:`HIGH ` or a :ref:`LOW +` value to a pin configured as :ref:`OUTPUT +`. +Library Documentation +--------------------- -**NOTE:** Digital pin 13 is harder to use as a digital input than -the other digital pins because it has an LED and resistor attached -to it that's soldered to the board on most boards. If you enable -its internal 20k pull-up resistor, it will hang at around 1.7 V -instead of the expected 5V because the onboard LED and series -resistor pull the voltage level down, meaning it always returns -LOW. If you must use pin 13 as a digital input, use an external -pull down resistor. +.. doxygenfunction:: digitalWrite - - -Syntax ------- - -digitalWrite(pin, value) - - - -Parameters +Discussion ---------- -pin: the pin number - +If the pin has been configured as an ``OUTPUT`` with :ref:`pinMode() +` its voltage will be set to the corresponding value: +3.3V for ``HIGH``, and 0V (ground) for ``LOW``. +.. TODO make the following paragraphs true, but refer the reader to +.. INPUT_PULLUP and INPUT_PULLDOWN: -value: `HIGH `_ or -`LOW `_ - - - -Returns -------- - -none - +If the pin is configured as an ``INPUT``, writing a ``HIGH`` value +with ``digitalWrite()`` will enable an internal pullup resistor. +Writing ``LOW`` will disable the pullup. The pullup resistor is enough +to light an LED dimly, so if LEDs appear to work, but very dimly, this +is a likely cause. The remedy is to set the pin to an output with the +:ref:`pinMode() ` function. +.. note:: Pin 13 is harder to use as an input than the other pins + because it has an LED and resistor soldered to it in series. If you + enable its internal pull-up resistor, it will likely hang at around + 1.1V instead of the expected 3.3V because the onboard LED and + series resistor pull the voltage level down. If you must use pin 13 + as a digital input, use an external pull-down resistor. Example ------- -:: +The following example sets pin 13 to ``HIGH``, makes a one-second-long +delay, sets the pin back to ``LOW``, and delays again, causing a +blinking pattern:: int ledPin = 13; // LED connected to digital pin 13 - void setup() - { + void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } - void loop() - { + void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second } - - -Sets pin 13 to HIGH, makes a one-second-long delay, and sets the -pin back to LOW. - - - -Note ----- - -The analog input pins can be used as digital pins, referred to as -A0, A1, etc. - - - -See also +See Also -------- - -- `pinMode `_\ () -- `digitalRead `_\ () -- `Tutorial: Digital Pins `_ - - - +- :ref:`pinMode ` +- :ref:`digitalRead ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/double.rst b/docs/source/lang/double.rst index b4a1219..1527778 100644 --- a/docs/source/lang/double.rst +++ b/docs/source/lang/double.rst @@ -1,13 +1,10 @@ .. _lang-double: -double -====== +``double`` +========== -Description ------------ - -Double precision floating point number. Occupies 8 bytes. On Maple, -the ``double`` type has a range of approximately -1.79769×10^308 to +Double precision floating point type. Occupies 8 bytes. On Maple, the +``double`` type has a range of approximately -1.79769×10^308 to 1.79769×10^308; the ``double`` type subject to the same :ref:`overflow issues ` as any numeric data type. diff --git a/docs/source/lang/doublecast.rst b/docs/source/lang/doublecast.rst index 4ea1776..511fe24 100644 --- a/docs/source/lang/doublecast.rst +++ b/docs/source/lang/doublecast.rst @@ -2,11 +2,8 @@ .. _lang-doublecast: -double() (cast) -=============== - -Description ------------ +``double()`` (cast) +=================== Converts a value to the :ref:`double ` floating point data type. Here is an example:: diff --git a/docs/source/lang/dowhile.rst b/docs/source/lang/dowhile.rst index 77e02a3..fe92226 100644 --- a/docs/source/lang/dowhile.rst +++ b/docs/source/lang/dowhile.rst @@ -2,8 +2,8 @@ .. _lang-dowhile: -do/while Loop -============= +``do``/``while`` +================ A ``do`` loop works in the same manner as a :ref:`while ` loop, with the exception that the condition is tested diff --git a/docs/source/lang/else.rst b/docs/source/lang/else.rst deleted file mode 100644 index 863f21b..0000000 --- a/docs/source/lang/else.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. highlight:: cpp - -.. _lang-else: - -if/else -======= - -``if``/\ ``else`` allows greater control over the flow of code than -the basic :ref:`if ` statement, by allowing multiple tests -to be grouped together. For example, an :ref:`analog input -` could be tested, with one action taken if the -input was less than 500, and another action taken if the input was 500 -or greater. The code would look like this:: - - if (pinFiveInput < 500) { - // action A - } else { - // action B - } - -``else`` can precede another ``if`` test, so that multiple, mutually -exclusive tests can be run at the same time. - -Each test will proceed to the next one until a true test is -encountered. When a true test is found, its associated block of code -is run, and the program then skips to the line following the entire -if/else construction. If no test proves to be true, the default -``else`` block is executed, if one is present, and sets the default -behavior. - - -Note that an ``else if`` block may be used with or without a -terminating ``else`` block, and vice-versa. An unlimited number of -such ``else if`` branches is allowed. Here is a code example:: - - if (pinFiveInput < 500) { - // do Thing A - } else if (pinFiveInput >= 1000) { - // do Thing B - } else { - // do Thing C - } - -Another way to express branching, mutually exclusive tests, is with a -:ref:`switch/case ` statement. - -See Also --------- - -- :ref:`if ` -- :ref:`switch/case ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/enum.rst b/docs/source/lang/enum.rst index 5ecd99c..ba82383 100644 --- a/docs/source/lang/enum.rst +++ b/docs/source/lang/enum.rst @@ -1,8 +1,53 @@ +.. highlight:: cpp + .. _lang-enum: -enum -==== +``enum`` +======== + +The ``enum`` keyword is used to specify an enumeration type. An +enumeration type is a type whose values are taken from a specified, +fixed list of constant values. + +Example +------- + +Here's an example defining an enumeration type called ``weather``, +which has values ``HOT``, ``COMFY``, and ``COLD``:: + + enum weather {HOT, COMFY, COLD}; + +Once you've defined this type, you can create variables of type +``weather``, in the same way you would with an :ref:`int ` +or a :ref:`long `:: + + // create a weather variable named theWeather, with value COMFY: + weather theWeather = COMFY; + +Enumeration types are useful within :ref:`switch statements +`. If you know that an argument is of an enumeration +type, you can make ``case`` statements for all of that type's possible +values, so you know you won't miss anything:: + + void describeWeather(weather currentWeather) { + switch(currentWeather) { + case HOT: + SerialUSB.println("it's hot out"); + break; + case COMFY: + SerialUSB.println("it's nice today"); + break; + case COLD: + SerialUSB.println("it's freezing!"); + break; + } + } + +Such a ``switch`` statement would need no :ref:`default +`, since we know that ``currentWeather`` must +be either ``HOT``, ``COMFY``, or ``COLD``. -Stub. +See Also +-------- -Reference this from language.rst +- :ref:`lang-switchcase` diff --git a/docs/source/lang/float.rst b/docs/source/lang/float.rst index ef1a339..6937c8c 100644 --- a/docs/source/lang/float.rst +++ b/docs/source/lang/float.rst @@ -2,11 +2,8 @@ .. _lang-float: -float -===== - -Description ------------ +``float`` +========= Single-precision floating point number. Occupies 4 bytes. On Maple, the ``float`` type has a range of approximately -3.40282×10^38 to diff --git a/docs/source/lang/floatcast.rst b/docs/source/lang/floatcast.rst index 7476188..4766478 100644 --- a/docs/source/lang/floatcast.rst +++ b/docs/source/lang/floatcast.rst @@ -2,15 +2,12 @@ .. _lang-floatcast: -float() (cast) -============== +``float()`` (cast) +================== -Description ------------ - -Converts a value to the :ref:`float ` data type. Here -is an example (see the :ref:`constants reference -` for an explanation of the "2.0f"):: +Converts a value to the :ref:`float ` data type. Here is +an example (see the :ref:`constants reference ` for +an explanation of the "2.0f"):: int x = 2; float f = float(x); // f now holds 2.0f, a float value diff --git a/docs/source/lang/for.rst b/docs/source/lang/for.rst index 6b00d7a..71c5aca 100644 --- a/docs/source/lang/for.rst +++ b/docs/source/lang/for.rst @@ -2,14 +2,8 @@ .. _lang-for: -for Loops -========= - -.. contents:: Contents - :local: - -Description ------------ +``for`` +======= A ``for`` loop is used to repeat a block of statements enclosed in curly braces. ``for`` loops are useful for performing repetitive @@ -19,6 +13,12 @@ operations, and are often used in combination with :ref:`arrays *header*, which sets up the for loop, and then a *body*, which is made up of lines of code enclosed in curly braces. +.. contents:: Contents + :local: + +Syntax +------ + There are three parts to the ``for`` loop header: an *initialization* expression, *loop condition* expression, and a *post-loop* expression. The general syntax looks like this:: diff --git a/docs/source/lang/goto.rst b/docs/source/lang/goto.rst index 96a6262..ff2f248 100644 --- a/docs/source/lang/goto.rst +++ b/docs/source/lang/goto.rst @@ -2,8 +2,8 @@ .. _lang-goto: -Labels and goto -=============== +Labels and ``goto`` +=================== A *label* gives a name to a line of code within a function. You can label a line by writing a name for it, then a colon (``:``), before diff --git a/docs/source/lang/highbyte.rst b/docs/source/lang/highbyte.rst index af0bfcd..50a1fa6 100644 --- a/docs/source/lang/highbyte.rst +++ b/docs/source/lang/highbyte.rst @@ -1,7 +1,11 @@ +.. highlight:: cpp + .. _lang-highbyte: -highByte(x) -=========== +highByte() +========== + +(Macro) Extracts the second lowest byte of an integral data type. .. warning:: This macro is provided for compatibility with Arduino only. It returns the second-least significant byte in an integral @@ -13,10 +17,12 @@ highByte(x) In short: we provide this so that existing Arduino code works as expected, but **strongly discourage its use** in new programs. -Description ------------ +Syntax +------ -(Macro) Extracts the second lowest byte of an integral data type. +:: + + highByte(x) Parameters ---------- diff --git a/docs/source/lang/if.rst b/docs/source/lang/if.rst index 02ba1e7..bef89e2 100644 --- a/docs/source/lang/if.rst +++ b/docs/source/lang/if.rst @@ -2,8 +2,8 @@ .. _lang-if: -if Statements -============= +``if``/``else`` +=============== An ``if`` statement is used to execute code when certain conditions are met. The general syntax for an ``if`` statement is:: @@ -15,8 +15,8 @@ are met. The general syntax for an ``if`` statement is:: An ``if`` statement first tests whether its *condition* is true (such as an input being above a certain number). If the condition is true, the ``if`` statement executes its *body*, which is made up of lines of -code inside :ref:`curly braces `. If the condition is -false, the body is not executed. Here's a more concrete example:: +code inside :ref:`curly braces `. If the condition +is false, the body is not executed. Here's a more concrete example:: if (someVariable > 50) { // do something here @@ -70,12 +70,52 @@ In the first example, since the body is enclosed in curly braces, both lines are included. In the second example, since the curly braces are missing, only the first line is in the ``if`` body. +``else`` +-------- + +``if``/\ ``else`` allows greater control over the flow of code than +the basic :ref:`if ` statement, by allowing multiple tests to +be grouped together. For example, an :ref:`analog input +` could be tested, with one action taken if the input +was less than 500, and another action taken if the input was 500 or +greater. The code would look like this:: + + if (pinFiveInput < 500) { + // action A + } else { + // action B + } + +``else`` can precede another ``if`` test, so that multiple, mutually +exclusive tests can be run at the same time. + +Each test will proceed to the next one until a true test is +encountered. When a true test is found, its associated block of code +is run, and the program then skips to the line following the entire +if/else construction. If no test proves to be true, the default +``else`` block is executed, if one is present, and sets the default +behavior. + +Note that an ``else if`` block may be used with or without a +terminating ``else`` block, and vice-versa. An unlimited number of +such ``else if`` branches is allowed. Here is a code example:: + + if (pinFiveInput < 500) { + // do Thing A + } else if (pinFiveInput >= 1000) { + // do Thing B + } else { + // do Thing C + } + +Another way to express branching, mutually exclusive tests, is with a +:ref:`switch/case ` statement. + + See Also -------- - :ref:`boolean operators ` - :ref:`comparison operators ` -- :ref:`else ` - .. include:: cc-attribution.txt diff --git a/docs/source/lang/include.rst b/docs/source/lang/include.rst index a8bc74c..74fe7af 100644 --- a/docs/source/lang/include.rst +++ b/docs/source/lang/include.rst @@ -2,8 +2,8 @@ .. _lang-include: -#include -======== +``#include`` +============ ``#include`` is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C @@ -15,7 +15,8 @@ Example This example (from the `Arduino LiquidCrystal Tutorial `_) includes a library -that is used to control :ref:`LCD displays `:: +that is used to control :ref:`LCD displays +`:: // include the library code: #include diff --git a/docs/source/lang/increment.rst b/docs/source/lang/increment.rst index 5536a0a..6dffa80 100644 --- a/docs/source/lang/increment.rst +++ b/docs/source/lang/increment.rst @@ -2,8 +2,8 @@ .. _lang-increment: -Increment (``++``) and Decrement (``--``) -========================================= +Increment and Decrement Operators (``++``, ``--``) +================================================== These operators increment (add one to) or decrement (subtract one from) a variable. If they come before the variable, they return its @@ -29,16 +29,9 @@ A more extended example:: // this line won't compile (notice the extra space): int y = x+ +; -Parameters ----------- - -**x**: an integer value (like an ``int``, ``long``, ``unsigned int``, -etc.). - -See also +See Also -------- -- :ref:`Compound arithmetic operators ` - +- :ref:`lang-compoundarithmetic` .. include:: cc-attribution.txt diff --git a/docs/source/lang/int.rst b/docs/source/lang/int.rst index ac2f16a..ca75f75 100644 --- a/docs/source/lang/int.rst +++ b/docs/source/lang/int.rst @@ -2,11 +2,8 @@ .. _lang-int: -int -=== - -Description ------------ +``int`` +======= The ``int`` data type represents integers. Integers are your primary data type for number storage, and store a 4 byte value. This yields a @@ -43,7 +40,7 @@ Integer Overflow ---------------- When ``int`` variables leave the range specified above, they -:ref:`roll over ` in the other direction. +:ref:`roll over ` in the other direction. Here are some examples:: int x; diff --git a/docs/source/lang/intcast.rst b/docs/source/lang/intcast.rst index 03c0c07..386fe14 100644 --- a/docs/source/lang/intcast.rst +++ b/docs/source/lang/intcast.rst @@ -2,11 +2,8 @@ .. _lang-intcast: -int() -===== - -Description ------------ +``int()`` (cast) +================ Converts a value to the :ref:`int ` data type. Here is an example:: diff --git a/docs/source/lang/interrupts.rst b/docs/source/lang/interrupts.rst deleted file mode 100644 index 5ca7041..0000000 --- a/docs/source/lang/interrupts.rst +++ /dev/null @@ -1,62 +0,0 @@ -.. _lang-interrupts: - -interrupts() -============ - -Description ------------ - -Re-enables interrupts (after they've been disabled by -`noInterrupts `_\ ()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None - - - -Returns -------- - -None - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `noInterrupts `_\ () -- `attachInterrupt `_\ () -- `detachInterrupt `_\ () - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/keywords.rst b/docs/source/lang/keywords.rst index 451701e..e4ebe99 100644 --- a/docs/source/lang/keywords.rst +++ b/docs/source/lang/keywords.rst @@ -3,9 +3,203 @@ Keywords ======== -Stub. +This page lists all of the C++ keywords, and either links to a +reference page explaining their use, or provides a brief description. -Include list of all C++ keywords, with links to internal documentation -as appropriate. +List of Keywords +---------------- -Reference this page from language.rst +The C++ keywords are: + +``and``, ``and_eq``, ``asm``, ``auto``, ``bitand``, ``bitor``, +``bool``, ``break``, ``case``, ``catch``, ``char``, ``class``, +``compl``, ``const``, ``const_cast``, ``continue``, ``default``, +``delete``, ``do``, ``double``, ``dynamic_cast``, ``else``, ``enum``, +``explicit``, ``export``, ``extern``, ``false``, ``float``, ``for``, +``friend``, ``goto``, ``if``, ``inline``, ``int``, ``long``, +``mutable``, ``namespace``, ``new``, ``not``, ``not_eq``, +``operator``, ``or``, ``or_eq``, ``private``, ``protected``, +``public``, ``register``, ``reinterpret_cast``, ``return``, ``short``, +``signed``, ``sizeof``, ``static``, ``static_cast``, ``struct``, +``switch``, ``template``, ``this``, ``throw``, ``true``, ``try``, +``typedef``, ``typeid``, ``typename``, ``union``, ``unsigned``, +``using``, ``virtual``, ``void``, ``volatile``, ``wchar_t``, +``while``, ``xor``, ``xor_eq`` + +Boolean Operator Synonyms +------------------------- + +- ``and`` is a synonym for :ref:`&& `. +- ``not`` is a synonym for :ref:`\! `. +- ``not_eq`` is a synonym for :ref:`\!= `. +- ``or`` is a synonym for :ref:`|| `. + +Bitwise Operator Synonyms +------------------------- + +- ``and_eq`` is a synonym for :ref:`&= `. +- ``bitand`` is a synonym for (bitwise) :ref:`& `. +- ``bitor`` is a synonym for :ref:`\| `. +- ``compl`` is a synonym for :ref:`~ `. +- ``or_eq`` is a synonym for :ref:`|= `. +- ``xor`` is a synonym for :ref:`^ `. +- ``xor_eq`` is a synonym for :ref:`^= `. + +Constants +--------- + +- ``true`` and ``false`` are the :ref:`boolean constants + `. + +Control Flow +------------ + +- ``break`` can exit out of a :ref:`switch statement + ` or a :ref:`for `, :ref:`do + `, or :ref:`while ` loop. + +- ``case`` defines alternatives in a :ref:`switch statement `. + +- ``continue`` will move control flow to the next iteration of the + enclosing :ref:`for `, :ref:`do `, or + :ref:`while ` loop. + +- ``default`` defines the default alternative in a :ref:`switch + statement `. + +- ``do`` introduces a :ref:`do ` loop. + +- ``else`` is used in :ref:`if statements `. + +- ``for`` introduces a :ref:`for ` loop. + +- ``goto`` :ref:`jumps ` to a label. + +- ``if`` introduces an :ref:`if statement `. + +- ``return`` :ref:`transfers flow to a function's caller `. + +- ``switch`` introduces a :ref:`switch statement `. + +- ``while`` introduces a :ref:`while ` loop. + +Types +----- + +The following keywords are used for built-in types. + +- :ref:`bool ` +- :ref:`lang-char` +- :ref:`lang-double` +- :ref:`lang-float` +- :ref:`lang-int` +- :ref:`lang-long` +- :ref:`short ` +- :ref:`void ` (not really a type, but used in the absence + of one) + +The following keywords are used to introduce new types. + +- :ref:`enum ` + +Qualifiers +---------- + +- :ref:`static ` can be used to declare persistent local + variables; it has other uses not documented here. + +- ``unsigned`` is used to specify an unsigned integral type. + Examples: :ref:`lang-unsignedint`, :ref:`lang-unsignedchar`, + :ref:`lang-unsignedlong`. + +- :ref:`volatile ` is useful when declaring variables + that may be modified by external interrupts. + +- :ref:`const ` is used to define constants. + +Other +----- + +These keywords are not described in the Maple documentation. For more +information, consult a C++ reference. + +- ``asm`` is used to insert literal assembly language. + +- ``auto`` is used to declare that a variable has automatic storage. + +- ``catch`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``class`` is used to define classes. + +- ``const_cast`` is used in typecasting. + +- ``delete`` is used to free ``new``\ -allocated storage. Note that + dynamic memory allocation is not available by default on the Maple, + so you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``dynamic_cast`` is used in typecasting. + +- ``explicit`` is used to declare constructors that can be called only + explicitly. + +- ``export`` declares a template definition accessible to other + compilation units. + +- ``extern`` can mark a declaration as a declaration and not a + definition, and also grant external linkage to a ``const`` or + ``typedef``. + +- ``friend`` is used to declare that certain functions have access to + a class's private variables. + +- ``inline`` is a compiler hint to inline a function. + +- ``mutable`` specifies that a member can be updated, even when a + member of a ``const`` object. + +- ``namespace`` declares a new namespace. + +- ``new`` dynamically allocates space for a value. Note that dynamic + memory allocation is not available by default on the Maple, so + you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``operator`` is used to define type-specific operator overrides. + +- ``private`` declares a private class member. + +- ``protected`` declares a protected class member. + +- ``public`` declares a public class member. + +- ``register`` is a compiler hint to store a variable in a register. + +- ``reinterpret_cast`` is used in typecasting. + +- ``signed`` is the opposite of ``unsigned``. + +- ``static_cast`` is used in typecasting. + +- ``struct`` declares a new struct. + +- ``template`` introduces a template class, function, etc. + +- ``this`` is a pointer to the receiver object. + +- ``throw`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``try`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``typedef`` defines a type synonym. + +- ``union`` defines an untagged union. + +- ``using`` is a directive related to namespaces. + +- ``virtual`` declares a method which may be overridden. + +- ``wchar_t`` is the wide character type. diff --git a/docs/source/lang/long.rst b/docs/source/lang/long.rst index 8a19b2b..d8498c0 100644 --- a/docs/source/lang/long.rst +++ b/docs/source/lang/long.rst @@ -2,11 +2,8 @@ .. _lang-long: -long -==== - -Description ------------ +``long`` +======== The ``long`` data type stores extended size integer values. You can use a ``long`` when your values are too large to fit into an :ref:`int @@ -19,7 +16,7 @@ Way galaxy). The exact range of a ``long`` on the Maple is from ` as any numeric data type. Here's an example of declaring a long (see :ref:`integer constants -` for an explanation of the "L" at the end of the +` for an explanation of the "L" at the end of the number):: // Speed of light in nanometers per second (approximate). diff --git a/docs/source/lang/longcast.rst b/docs/source/lang/longcast.rst index 16d7582..2b92345 100644 --- a/docs/source/lang/longcast.rst +++ b/docs/source/lang/longcast.rst @@ -2,11 +2,8 @@ .. _lang-longcast: -long() -====== - -Description ------------ +``long()`` (cast) +================= Converts a value to the :ref:`long ` data type. Here is an example:: diff --git a/docs/source/lang/lowbyte.rst b/docs/source/lang/lowbyte.rst index f9fb711..58e622f 100644 --- a/docs/source/lang/lowbyte.rst +++ b/docs/source/lang/lowbyte.rst @@ -3,43 +3,23 @@ lowByte() ========= -Description ------------ - Extracts the low-order (rightmost) byte of a variable (e.g. a word). - - Syntax ------ lowByte(x) - - Parameters ---------- -x: a value of any type - - +**x**: a value of any type. However, if a non-integral type is used, +the results will be strange. Returns ------- -byte - - - -See also --------- - - -- `highByte `_\ () -- `word `_\ () - - - +The low byte's value (this will be between 0 and 255). .. include:: cc-attribution.txt diff --git a/docs/source/lang/map.rst b/docs/source/lang/map.rst index 40b12a8..79122b3 100644 --- a/docs/source/lang/map.rst +++ b/docs/source/lang/map.rst @@ -1,122 +1,68 @@ -.. _lang-map: - -map(value, fromLow, fromHigh, toLow, toHigh) -============================================ - -Description ------------ - -Re-maps a number from one range to another. That is, a **value** of -**fromLow** would get mapped to **toLow**, a value of **fromHigh** -to **toHigh**, values in-between to values in-between, etc. - +.. highlight:: cpp +.. _lang-map: -Does not constrain values to within the range, because out-of-range -values are sometimes intended and useful. The constrain() function -may be used either before or after this function, if limits to the -ranges are desired. +map() +===== +Re-maps a number from one range to another. +.. contents:: Contents + :local: -Note that the "lower bounds" of either range may be larger or -smaller than the "upper bounds" so the map() function may be used -to reverse a range of numbers, for example +Library Documentation +--------------------- +.. doxygenfunction:: map +Discussion +---------- -``y = map(x, 1, 50, 50, 1);`` +``map()`` does not constrain values to within the range, because +out-of-range values are sometimes intended and useful. The +:ref:`constrain() ` macro may be used either before or +after this function, if limits to the ranges are desired. +Note that the "lower bounds" of either range may be larger or smaller +than the "upper bounds" so that ``map()`` may be used to reverse a +range of numbers; for example:: + y = map(x, 1, 50, 50, 1); The function also handles negative numbers well, so that this -example - - - -``y = map(x, 1, 50, 50, -100);`` - - +example :: -is also valid and works well. + y = map(x, 1, 50, 50, -100); +is also valid. - -The map() function uses integer math so will not generate +The ``map()`` function uses integer math (its arguments and return +values all have type :ref:`long `), so it will not generate fractions, when the math might indicate that it should do so. -Fractional remainders are truncated, and are not rounded or -averaged. - - - -Parameters ----------- - -value: the number to map - - - -fromLow: the lower bound of the value's current range - - - -fromHigh: the upper bound of the value's current range - - - -toLow: the lower bound of the value's target range - - - -toHigh: the upper bound of the value's target range - - - -Returns -------- - -The mapped value. - - +Fractional remainders are truncated, and are not rounded or averaged. Example ------- :: - /* Map an analog value to 8 bits (0 to 255) */ - void setup() {} + /* Map an ADC reading (12 bits) to 16-bit PWM (0 to 65,535) */ - void loop() - { - int val = analogRead(0); - val = map(val, 0, 1023, 0, 255); - analogWrite(9, val); + void setup() { + pinMode(0, INPUT_ANALOG); + pinMode(9, PWM); } - - -Appendix -~~~~~~~~ - -For the mathematically inclined, here's the whole function - - - -:: - - long map(long x, long in_min, long in_max, long out_min, long out_max) - { - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; + void loop() { + int val = analogRead(0); + val = map(val, 0, 4095, 0, 65535); + analogWrite(9, val); } - See Also -------- - -- `constrain `_\ () - +- :ref:`constrain() ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/max.rst b/docs/source/lang/max.rst index 7dbf6a7..d38eebe 100644 --- a/docs/source/lang/max.rst +++ b/docs/source/lang/max.rst @@ -2,15 +2,17 @@ .. _lang-max: -max(x, y) -========= - -Description ------------ +max() +===== (Macro) Calculates the maximum of two numbers. +Syntax +------ + +:: + max(x, y) Parameters ---------- diff --git a/docs/source/lang/micros.rst b/docs/source/lang/micros.rst index 711c013..f12976b 100644 --- a/docs/source/lang/micros.rst +++ b/docs/source/lang/micros.rst @@ -1,69 +1,46 @@ +.. highlight:: cpp + .. _lang-micros: micros() ======== -Description ------------ - -Returns the number of microseconds since the Arduino board began -running the current program. This number will overflow (go back to -zero), after approximately 70 minutes. On 16 MHz Arduino boards -(e.g. Duemilanove and Nano), this function has a resolution of four -microseconds (i.e. the value returned is always a multiple of -four). On 8 MHz Arduino boards (e.g. the LilyPad), this function -has a resolution of eight microseconds. - - - -*Note*: there are 1,000 microseconds in a millisecond and 1,000,000 -microseconds in a second. +Returns the number of microseconds since the Maple board began running +the current program. This number will overflow (go back to zero), +after approximately 70 minutes. +.. note:: There are 1,000 microseconds in a millisecond, and 1,000,000 + microseconds in a second. +Library Documentation +--------------------- -Parameters ----------- - -None - - - -Returns -------- - -Number of microseconds since the program started (*unsigned long*) - - +.. doxygenfunction:: micros Example ------- :: - unsigned long time; + unsigned int time; - void setup(){ - Serial.begin(9600); + void setup() { } - void loop(){ - Serial.print("Time: "); + + void loop() { + SerialUSB.print("Time: "); time = micros(); - //prints time since program started - Serial.println(time); + // prints time since program started + SerialUSB.println(time); // wait a second so as not to send massive amounts of data delay(1000); } - - -See also +See Also -------- - -- `millis `_\ () -- `delay `_\ () -- `delayMicroseconds `_\ () - - +- :ref:`millis() ` +- :ref:`delay() ` +- :ref:`delayMicroseconds() ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/millis.rst b/docs/source/lang/millis.rst index 6ebfff5..54e4507 100644 --- a/docs/source/lang/millis.rst +++ b/docs/source/lang/millis.rst @@ -1,70 +1,52 @@ +.. highlight:: cpp + .. _lang-millis: millis() ======== -Description ------------ - -Returns the number of milliseconds since the Arduino board began -running the current program. This number will overflow (go back to -zero), after approximately 50 days. - - - -Parameters ----------- - -None - - - -Returns -------- - -Number of milliseconds since the program started (*unsigned long*) +Returns the number of milliseconds since the Maple board began running +the current program. This number will overflow (go back to zero) after +approximately 50 days. +Library Documentation +--------------------- +.. doxygenfunction:: millis Example ------- -:: +The following time prints the value returned by ``millis()`` roughly +once per second:: - unsigned long time; + unsigned int time; - void setup(){ - Serial.begin(9600); + void setup() { } - void loop(){ - Serial.print("Time: "); + + void loop() { + SerialUSB.print("Time: "); time = millis(); - //prints time since program started + // prints time since program started Serial.println(time); + // wait a second so as not to send massive amounts of data delay(1000); } +Tip +--- +Since the return value for ``millis()`` is an :ref:`unsigned long +`, overflow errors may occur if you try to do math +with other data types, such as :ref:`ints `. -Tip: ----- - -Note that the parameter for millis is an unsigned long, errors may -be generated if a programmer tries to do math with other datatypes -such as ints. - - - -See also +See Also -------- - -- `micros `_\ () -- `delay `_\ () -- `delayMicroseconds `_\ () -- `Tutorial: Blink Without Delay `_ - - +- :ref:`micros ` +- :ref:`delay ` +- :ref:`delayMicroseconds ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/min.rst b/docs/source/lang/min.rst index ffbf1ee..1245f6f 100644 --- a/docs/source/lang/min.rst +++ b/docs/source/lang/min.rst @@ -2,15 +2,17 @@ .. _lang-min: -min(x, y) -========= - -Description ------------ +min() +===== (Macro) Calculates the minimum of two numbers. +Syntax +------ + +:: + min(x,y) Parameters ---------- @@ -19,13 +21,11 @@ Parameters **y**: the second number; may be any number or numeric expression. - Returns ------- The smaller of the two numbers. - Example ------- diff --git a/docs/source/lang/modulo.rst b/docs/source/lang/modulo.rst index 9e0dabd..289fba0 100644 --- a/docs/source/lang/modulo.rst +++ b/docs/source/lang/modulo.rst @@ -2,11 +2,8 @@ .. _lang-modulo: -% (modulo) -========== - -Description ------------ +Modulo Operator (``%``) +======================= Calculates the `remainder `_ when one integer is divided by another. It is useful for keeping a @@ -17,9 +14,7 @@ Syntax :: - result = dividend % divisor - - + dividend % divisor Parameters ---------- @@ -67,11 +62,9 @@ The modulo operator does not work on floats. For that, you can use the C standard library function `fmod() `_. - See Also -------- - :ref:`Arithmetic ` - .. include:: cc-attribution.txt diff --git a/docs/source/lang/nointerrupts.rst b/docs/source/lang/nointerrupts.rst deleted file mode 100644 index 2043c91..0000000 --- a/docs/source/lang/nointerrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-nointerrupts: - -noInterrupts() -============== - -Description ------------ - -Disables interrupts (you can re-enable them with interrupts()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None. - - - -Returns -------- - -None. - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `interrupts `_\ () - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/notone.rst b/docs/source/lang/notone.rst deleted file mode 100644 index 22432e2..0000000 --- a/docs/source/lang/notone.rst +++ /dev/null @@ -1,50 +0,0 @@ -.. _lang-notone: - -noTone() -======== - -Description ------------ - -Stops the generation of a square wave triggered by -`tone `_\ (). Has no effect if -no tone is being generated. - - - -**NOTE:** if you want to play different pitches on multiple pins, -you need to call noTone() on one pin before calling tone() on the -next pin. - - - -Syntax ------- - -noTone(pin) - - - -Parameters ----------- - -pin: the pin on which to stop generating the tone - - - -Returns -------- - -nothing - - - -See also --------- - - -- `tone `_ () - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/numeric-types.rst b/docs/source/lang/numeric-types.rst new file mode 100644 index 0000000..9d2be48 --- /dev/null +++ b/docs/source/lang/numeric-types.rst @@ -0,0 +1,79 @@ +.. _lang-numeric-types: + +Numeric types +============= + +This document serves as a reference for all of the built-in numeric +types which are available when programming in the IDE. Programmers +using the :ref:`command-line tools ` will have access +to these types as long as they have imported ``wirish.h``; several are +defined in in `libmaple_types.h +`_. + +.. _lang-numeric-types-integral: + +Integral types +-------------- + +.. cpp:type:: char + + 8-bit integer value. + +.. cpp:type:: short + + 16-bit integer value. + +.. cpp:type:: int + + 32-bit integer value. + +.. cpp:type:: long + + 64-bit integer value. + +.. cpp:type:: long long + + 64-bit integer value. + +.. cpp:type:: int8 + + Synonym for ``char``. + +.. cpp:type:: uint8 + + Synonym for ``unsigned char``. + +.. cpp:type:: int16 + + Synonym for ``short``. + +.. cpp:type:: uint16 + + Synonym for ``unsigned short``. + +.. cpp:type:: int32 + + Synonym for ``int``. + +.. cpp:type:: uint32 + + Synonym for ``unsigned int`` + +.. cpp:type:: int64 + + Synonym for ``long long`` + +.. cpp:type:: uint64 + + Synonym for ``unsigned long long``. + +Floating-Point Types +-------------------- + +.. cpp:type:: float + + 32-bit, IEEE 754 single-precision floating-point type. + +.. cpp:type:: double + + 64-bit, IEEE 754 double-precision floating-point type. diff --git a/docs/source/lang/pinmode.rst b/docs/source/lang/pinmode.rst index aed23d6..b9095da 100644 --- a/docs/source/lang/pinmode.rst +++ b/docs/source/lang/pinmode.rst @@ -18,50 +18,51 @@ Library Documentation Discussion ---------- -pinMode() is usually called within :ref:`lang-setup` in order to +``pinMode()`` is usually called within :ref:`lang-setup` in order to configure a pin for a certain usage (although it may be called anywhere). - Example ------- - :: - +:: int ledPin = 13; // LED connected to digital pin 13 - void setup() - { + void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } - void loop() - { + void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second } - - Arduino Compatibility --------------------- -The libmaple implementation of pinMode() supports OUTPUT and INPUT -modes with a meaning identical to that of the Arduino function. +.. TODO check out Arduino vs. Maple static discilpline cutoffs to +.. ensure accuracy of following: + +The libmaple implementation of ``pinMode()`` supports the ``INPUT`` +and ``OUTPUT`` modes with semantics identical to that of the Arduino +function (however, be advised that the Maple, as a 3.3V device, will +only drive 3.3V to an ``OUTPUT`` pin that has been set ``HIGH``). + +``INPUT_ANALOG`` and ``PWM`` modes were added because the Maple does +not distinguish between analog and digital pins the same way the +Arduino does. Unlike the Arduino, you **must call** ``pinMode()`` to +set up a pin for these purposes before a call to, e.g., +:ref:`lang-analogRead`. In practice, this should only add a few lines +to your :ref:`lang-setup` function. -INPUT_ANALOG and PWM modes were added because the Maple does not -distinguish between analog and digital pins the same way the Arduino -does. Unlike the Arduino, you **must call pinMode**\ () to set up a pin -for these purposes before a call to, e.g., :ref:`lang-analogRead`. -In practice, this should only add a few lines of pinMode() calls to -your :ref:`lang-setup` function. +.. TODO verify following before putting it in: -OUTPUT_OPEN_DRAIN, INPUT_PULLUP, INPUT_PULLDOWN, and PWM_OPEN_DRAIN -modes represent functionality not currently available on Arduino -boards. +.. ``OUTPUT_OPEN_DRAIN``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``, and +.. ``PWM_OPEN_DRAIN`` modes represent functionality not currently +.. available on Arduino boards. See also -------- diff --git a/docs/source/lang/pointer.rst b/docs/source/lang/pointer.rst index bc48d7d..0a42270 100644 --- a/docs/source/lang/pointer.rst +++ b/docs/source/lang/pointer.rst @@ -1,15 +1,19 @@ .. _lang-pointer: -The pointer operators: & (reference) and \* (dereference) -========================================================= +Pointer Operators (``&``, ``*``) +================================ +The pointer operators ``&`` (reference) and ``*`` (dereference) are +different from the bitwise math operator :ref:`& +` and the arithmetic operator :ref:`* +`. Pointers are one of the more complicated subjects for beginners in -learning C, and it is possible to write the vast majority of -Arduino sketches without ever encountering pointers. However for -manipulating certain data structures, the use of pointers can -simplify the code, and and knowledge of manipulating pointers is -handy to have in one's toolkit. +learning C, and it is possible to write many useful Arduino sketches +without ever encountering pointers. However, for manipulating certain +data structures, the use of pointers can simplify the code, improve +its efficiency, and generally provide many benefits that would be +difficult to achieve without the use of pointers. Introducing pointers is somewhat outside the scope of this documentation. However, a good `pointer tutorial @@ -20,9 +24,8 @@ the section on `pointers in C `_. See Also -======== +-------- - http://xkcd.com/138/ - .. include:: cc-attribution.txt diff --git a/docs/source/lang/pow.rst b/docs/source/lang/pow.rst index dbe89b6..4280400 100644 --- a/docs/source/lang/pow.rst +++ b/docs/source/lang/pow.rst @@ -1,7 +1,7 @@ .. _lang-pow: -pow(base, exponent) -=================== +pow() +===== Calculates the value of a number raised to a power. @@ -10,13 +10,7 @@ Library Documentation .. doxygenfunction:: pow -Example -------- - -``pow()`` can be used to raise a number to a fractional power. This -is useful for e.g. generating exponential mapping of values or -curves. See the `fscale `_ -function in the Arduino playground for more on this. +.. TODO LATER some examples See Also -------- diff --git a/docs/source/lang/pulsein.rst b/docs/source/lang/pulsein.rst deleted file mode 100644 index 7bbe84c..0000000 --- a/docs/source/lang/pulsein.rst +++ /dev/null @@ -1,82 +0,0 @@ -.. _lang-pulsein: - -pulseIn() -========= - -Description ------------ - -Reads a pulse (either HIGH or LOW) on a pin. For example, if -**value** is **HIGH**, **pulseIn()** waits for the pin to go -**HIGH**, starts timing, then waits for the pin to go **LOW** and -stops timing. Returns the length of the pulse in microseconds. -Gives up and returns 0 if no pulse starts within a specified time -out. - - - -The timing of this function has been determined empirically and -will probably show errors in longer pulses. Works on pulses from 10 -microseconds to 3 minutes in length. - - - -Syntax ------- - -pulseIn(pin, value) -pulseIn(pin, value, timeout) - - - -Parameters ----------- - -pin: the number of the pin on which you want to read the pulse. -(*int*) - - - -value: type of pulse to read: either -`HIGH `_ or -`LOW `_. (*int*) - - - -timeout (optional): the number of microseconds to wait for the -pulse to start; default is one second (*unsigned long*) - - - -Returns -------- - -the length of the pulse (in microseconds) or 0 if no pulse started -before the timeout (*unsigned long*) - - - -Example -------- - -:: - - - - int pin = 7; - unsigned long duration; - - void setup() - { - pinMode(pin, INPUT); - } - - void loop() - { - duration = pulseIn(pin, HIGH); - } - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/pwmwrite.rst b/docs/source/lang/pwmwrite.rst index acc0240..7a1d51f 100644 --- a/docs/source/lang/pwmwrite.rst +++ b/docs/source/lang/pwmwrite.rst @@ -23,9 +23,7 @@ Example ------- Sets the output to the LED proportional to the value read from the -potentiometer (adapted for Maple from the Arduino `analogWrite() -reference `_):: - +potentiometer:: int ledPin = 13; // LED connected to pin 13 (Maple) int analogPin = 3; // potentiometer connected to analog pin 3 diff --git a/docs/source/lang/random.rst b/docs/source/lang/random.rst index 51bee67..f2a9762 100644 --- a/docs/source/lang/random.rst +++ b/docs/source/lang/random.rst @@ -1,95 +1,73 @@ +.. highlight:: cpp + .. _lang-random: random() ======== -Description ------------ - -The random function generates pseudo-random numbers. - - - -Syntax ------- - -random(max) -random(min, max) - - - -Parameters ----------- - -min - lower bound of the random value, inclusive *(optional)* - +The ``random()`` function generates pseudo-random numbers. +.. TODO keep tracking Sphinx/Breathe's ability to reference overloaded +.. functions so we can use doxygenfunction instead of manually +.. documenting this. -max - upper bound of the random value, exclusive +Library Documentation +--------------------- +.. cpp:function:: random(long max) + Same as a call to ``random(0, max)``. -Returns -------- - -a random number between min and max-1 (*long*) +.. cpp:function:: random(long min, long max) + Generate a pseudo-random number with given lower and upper bounds. + *Parameters* -Note: ------ + - ``min`` - Lower bound on the returned value, inclusive + - ``max`` - Upper bound on the returned value, exclusive -If it is important for a sequence of values generated by random() -to differ, on subsequent executions of a sketch, use randomSeed() -to initialize the random number generator with a fairly random -input, such as analogRead() on an unconnected pin. + *Returns*: A pseudo-random number in the range [min, max). +Discussion +---------- +If it is important for a sequence of values generated by +:ref:`random() ` to differ, on subsequent executions of a +sketch, use :ref:`randomSeed() ` to initialize the +random number generator with a fairly random input, such as +:ref:`analogRead() ` on an unconnected pin. -Conversely, it can occasionally be useful to use pseudo-random +Conversely, it can occasionally be useful to use pseudorandom sequences that repeat exactly. This can be accomplished by calling -randomSeed() with a fixed number, before starting the random +``randomSeed()`` with a fixed number, before starting the random sequence. - - Example ------- -:: +The following sketch initializes the random seed based on an :ref:`ADC +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +` each time it is run:: long randNumber; - void setup(){ - Serial.begin(9600); - - // if analog input pin 0 is unconnected, random analog - // noise will cause the call to randomSeed() to generate - // different seed numbers each time the sketch runs. - // randomSeed() will then shuffle the random function. + void setup() { + pinMode(0, INPUT_ANALOG); randomSeed(analogRead(0)); } void loop() { - // print a random number from 0 to 299 randNumber = random(300); - Serial.println(randNumber); - - // print a random number from 10 to 19 - randNumber = random(10, 20); - Serial.println(randNumber); + SerialUSB.println(randNumber); delay(50); } - - -See also +See Also -------- - -- `randomSeed `_\ () - - +- :ref:`randomSeed() ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/randomseed.rst b/docs/source/lang/randomseed.rst index 3dcf4db..d0a15b7 100644 --- a/docs/source/lang/randomseed.rst +++ b/docs/source/lang/randomseed.rst @@ -1,73 +1,60 @@ -.. _lang-randomseed: +.. highlight:: cpp -randomSeed(seed) -================ +.. _lang-randomseed: -Description ------------ +randomSeed() +============ -randomSeed() initializes the pseudo-random number generator, +``randomSeed()`` initializes the `pseudorandom number generator +`_, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same. +Library Documentation +--------------------- -If it is important for a sequence of values generated by random() -to differ, on subsequent executions of a sketch, use randomSeed() -to initialize the random number generator with a fairly random -input, such as analogRead() on an unconnected pin. +.. doxygenfunction:: randomSeed +Discussion +---------- +If it is important for a sequence of values generated by +:ref:`random() ` to differ, on subsequent executions of a +sketch, use ``randomSeed()`` to initialize the random number generator +with a fairly random input, such as :ref:`analogRead() +` on an unconnected pin. -Conversely, it can occasionally be useful to use pseudo-random +Conversely, it can occasionally be useful to use pseudorandom sequences that repeat exactly. This can be accomplished by calling -randomSeed() with a fixed number, before starting the random +``randomSeed()`` with a fixed number, before starting the random sequence. - - -Parameters ----------- - -long, int - pass a number to generate the seed. - - - -Returns -------- - -no returns - - - Example ------- -:: +The following sketch initializes the random seed based on an :ref:`ADC +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +` each time it is run:: long randNumber; - void setup(){ - Serial.begin(9600); + void setup() { + pinMode(0, INPUT_ANALOG); randomSeed(analogRead(0)); } - void loop(){ + void loop() { randNumber = random(300); - Serial.println(randNumber); + SerialUSB.println(randNumber); delay(50); } - - -See also +See Also -------- - -- `random `_ - - - +- :ref:`random() ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/return.rst b/docs/source/lang/return.rst index e1b2924..7b5039e 100644 --- a/docs/source/lang/return.rst +++ b/docs/source/lang/return.rst @@ -2,11 +2,11 @@ .. _lang-return: -return -====== +``return`` +========== -(Keyword) Terminates a function and return a value from a function to -the calling function, if the function has non-``void`` return type. +Terminates a function and return a value from a function to the +calling function, if the function has non-``void`` return type. Syntax: ------- diff --git a/docs/source/lang/scope.rst b/docs/source/lang/scope.rst index 8e8bb13..7b65bab 100644 --- a/docs/source/lang/scope.rst +++ b/docs/source/lang/scope.rst @@ -2,8 +2,8 @@ .. _lang-scope: -Variable Scope -============== +Scope +===== Variables in the C++ programming language, which Maple uses (all of your sketches are C++ programs in disguise), have a property called @@ -25,8 +25,8 @@ of a function (like :ref:`setup() ` and :ref:`loop() A local variable can only be "seen" inside of a particular function. You can declare a variable to be local to a function by declaring it -inside of the :ref:`curly braces ` which enclose that -function. +inside of the :ref:`curly braces ` which enclose +that function. When programs start to get larger and more complex, local variables are a useful way to ensure that a function has exclusive access to its diff --git a/docs/source/lang/semicolon.rst b/docs/source/lang/semicolon.rst index 4cf7b9f..8164616 100644 --- a/docs/source/lang/semicolon.rst +++ b/docs/source/lang/semicolon.rst @@ -2,8 +2,8 @@ .. _lang-semicolon: -Semicolon (;) -============= +Semicolon (``;``) +================= Used to end a line of code. Example:: diff --git a/docs/source/lang/serial.rst b/docs/source/lang/serial.rst index 743f921..f96547d 100644 --- a/docs/source/lang/serial.rst +++ b/docs/source/lang/serial.rst @@ -1,68 +1,219 @@ .. _lang-serial: -Serial -====== +Serial Ports (``Serial1``, ``Serial2``, ``Serial3``) +==================================================== -Used for communication between the Arduino board and a computer or -other devices. All Arduino boards have at least one serial port -(also known as a UART or USART): **Serial**. It communicates on -digital pins 0 (RX) and 1 (TX) as well as with the computer via -USB. Thus, if you use these functions, you cannot also use pins 0 -and 1 for digital input or output. +Used for communication between the Maple board and a computer or other +devices. +.. contents:: Contents + :local: +Introduction +------------ -You can use the Arduino environment's built-in serial monitor to -communicate with an Arduino board. Click the serial monitor button -in the toolbar and select the same baud rate used in the call to -begin(). +The Maple has three serial ports (also known as a UARTs or USARTs): +``Serial1``, ``Serial2``, and ``Serial3``. They communicate using the +pins summarized in the following table: +.. list-table:: + :header-rows: 1 + * - Serial port + - Pins (TX, RX) -The Arduino Mega has three additional serial ports: **Serial1** on -pins 19 (RX) and 18 (TX), **Serial2** on pins 17 (RX) and 16 (TX), -**Serial3** on pins 15 (RX) and 14 (TX). To use these pins to -communicate with your personal computer, you will need an -additional USB-to-serial adaptor, as they are not connected to the -Mega's USB-to-serial adaptor. To use them to communicate with an -external TTL serial device, connect the TX pin to your device's RX -pin, the RX to your device's TX pin, and the ground of your Mega to -your device's ground. (Don't connect these pins directly to an -RS232 serial port; they operate at +/- 12V and can damage your -Arduino board.) + * - ``Serial1`` + - 7, 8 + * - ``Serial2`` + - 1, 0 + * - ``Serial3`` + - 29, 30 -Functions ---------- +Thus, if you use a particular serial port, you cannot also use its +communication pins for other purposes at the same time. +Unlike the Arduino, none of these serial ports is connected to the USB +port on the Maple board. Thus, to use these pins to communicate with +your personal computer, you will need an additional USB-to-serial +adaptor. -- `begin `_\ () -- `end `_\ () -- `available `_\ () -- `read `_\ () -- `flush `_\ () -- `print `_\ () +If you want to communicate with the Maple using the provided USB port, +use :ref:`SerialUSB ` instead. + +To use them to communicate with an external TTL serial device, connect +the TX pin to your device's RX pin, the RX to your device's TX pin, +and the ground of your Maple to your device's ground. + +.. warning:: Don't connect these pins directly to an RS232 serial + port; they operate at +/- 12V and can damage your board. + + +Library Documentation +--------------------- + +All of the ``Serial[1,2,3]`` objects are instances of the +``HardwareSerial`` class, which is documented in this section. (This +means that you can use any of these functions on any of ``Serial1``, +``Serial2``, and ``Serial3``). + +.. cpp:class:: HardwareSerial + + Serial port class. Predefined instances are Serial1, Serial2, and + Serial3. + +.. cpp:function:: HardwareSerial::begin(unsigned int baud) + + Set up a ``HardwareSerial`` object for communications. This method + must be called before attempting to use the ``HardwareSerial`` + object (typically, you call this in your :ref:`setup() + ` function). + +.. cpp:function:: HardwareSerial::end() + + Disables the USART associated with this object, allowing any + associated TX and RX pins to be used for other purposes. + +.. cpp:function:: unsigned int HardwareSerial::available() + + Returns the number of bytes available for reading. + +.. cpp:function:: unsigned char HardwareSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + `), the call will block until one + becomes available. + +.. cpp:function:: HardwareSerial::flush() + + Removes the contents of the Serial's associated USART RX FIFO. + That is, clears any buffered characters, so that the next character + read is guaranteed to be new. + +.. cpp:function:: HardwareSerial::print(unsigned char b) + + Print the given byte over the USART. + +.. cpp:function:: HardwareSerial::print(char c) + + Print the given character over the USART. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: HardwareSerial::print(const char *str) + + Print the given null-terminated string over the USART. + +.. cpp:function:: HardwareSerial::print(int n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned int n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned long n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n, int base) + + Print the digits of ``n`` over the USART, in base ``base`` (which + may be between 2 and 16). The ``base`` value 2 corresponds to + binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. Negative + values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. .. _lang-serial-println: -- `println `_\ () -- `write `_\ () +.. cpp:function:: HardwareSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println() + + Prints ``"\r\n"`` over the USART. + +.. cpp:function:: HardwareSerial::write(unsigned char ch) + + Sends one character over the USART. This function is currently + blocking, although nonblocking writes are a planned future + extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: HardwareSerial::write(const char* str) + + Send the given null-terminated character string over the USART. + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. +.. cpp:function:: HardwareSerial::write(void *buf, unsigned int size) -Examples --------- + Writes the first ``size`` bytes of ``buf`` over the USART. Each + byte is transmitted as an individual character. + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. -- `ASCII Table `_ -- `Dimmer `_ -- `Graph `_ -- `Physical Pixel `_ -- `Virtual Color Mixer `_ -- `Serial Call Response `_ -- `Serial Call Response ASCII `_ +.. TODO LATER port these examples over +.. Examples +.. -------- +.. - `ASCII Table `_ +.. - `Dimmer `_ +.. - `Graph `_ +.. - `Physical Pixel `_ +.. - `Virtual Color Mixer `_ +.. - `Serial Call Response `_ +.. - `Serial Call Response ASCII `_ .. include:: cc-attribution.txt diff --git a/docs/source/lang/serialusb.rst b/docs/source/lang/serialusb.rst index 730fb07..9beee82 100644 --- a/docs/source/lang/serialusb.rst +++ b/docs/source/lang/serialusb.rst @@ -1,8 +1,240 @@ +.. highlight:: cpp + .. _lang-serialusb: -Serial over USB Communications -============================== +``SerialUSB`` +============= + +Used for communication between the Maple board and a computer. + +.. contents:: Contents + :local: + +Introduction +------------ + +In addition to three :ref:`serial ports `, the Maple's +STM32 microprocessor includes a dedicated USB peripheral. This +peripheral is used to emulate a regular serial port for use as a +terminal (text read/write). The emulated terminal is relatively slow +and inefficient; it is best for transferring data at regular serial +speeds (kilobaud). + +Library access to the emulated serial port is provided through the +``SerialUSB`` object. You can mostly use ``SerialUSB`` as a drop-in +replacement for ``Serial1``, ``Serial2``, and ``Serial3``. + +.. warning:: The ``SerialUSB`` functionality includes a 50 millisecond + timeout for writes, and does not try to detect if the USB host is + "really" connected, or just enumerated and initialized. + + This means that if you have a number of calls to one of the + ``SerialUSB`` ``write()`` or ``print()`` functions in your code, + and you are not monitoring the emulated on a computer, your program + will run much, much slower than if it is being monitored or totally + disconnected (run off of a battery). + + You can avoid this behavior by :ref:`deciphering the port status + using the DTR and RTS line status `; the + behavior of these control lines is platform dependent and we no + longer interpret them by default. + +Library Documentation +--------------------- + +The ``SerialUSB`` object is an instance of the ``USBSerial`` class, +which is documented in this section. This means that you can use any +of these functions by writing +``SerialUSB.functionName(arguments...)``. For example, to print the +message "hello, world!", you can write ``USBSerial.println("hello, +world!")``. + +.. cpp:class:: USBSerial + + Emulated serial-over-USB class. ``SerialUSB`` is the predefined + instance. + +.. cpp:function:: USBSerial::begin() + + Set up the USB peripheral for emulated serial communication. The + peripheral is configured this way by default; calling this function + should only be necessary if you have disabled the peripheral using + ``SerialUSB.end()``. + +.. _lang-serialusb-end: + +.. cpp:function:: USBSerial::end() + + Disables the USB peripheral. + +.. cpp:function:: unsigned int USBSerial::available() + + Returns the number of bytes available for reading. + +.. cpp:function:: unsigned char USBSerial::read() + + Returns the next available, unread character. If there are no + available characters (you can check this with :cpp:func:`available + `), the call will block until one + becomes available. + +.. cpp:function:: USBSerial::flush() + + Removes the contents of the Serial's associated input buffer. That + is, clears any buffered characters, so that the next character read + is guaranteed to be new. + +.. cpp:function:: USBSerial::print(unsigned char b) + + Print the given byte over the USB connection. + +.. cpp:function:: USBSerial::print(char c) + + Print the given character over the USB connection. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: USBSerial::print(const char *str) + + Print the given null-terminated string over the USB connection. + +.. cpp:function:: USBSerial::print(int n) + + Print the argument's digits over the USB connection, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned int n) + + Print the argument's digits over the USB connection, in decimal format. + +.. cpp:function:: USBSerial::print(long n) + + Print the argument's digits over the USB connection, in decimal + format. Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned long n) + + Print the argument's digits over the USB connection, in decimal + format. + +.. cpp:function:: USBSerial::print(long n, int base) + + Print the digits of ``n`` over the USB connection, in base ``base`` + (which may be between 2 and 16). The ``base`` value 2 corresponds + to binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. .. _lang-serialusb-println: -Stub. +.. cpp:function:: USBSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println() + + Prints ``"\r\n"`` over the USB connection. + +.. cpp:function:: USBSerial::write(unsigned char ch) + + Sends one character over the USB connection. This function is + currently blocking, although nonblocking writes are a planned + future extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(const char* str) + + Send the given null-terminated character string over the USB + connection. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(void *buf, unsigned int size) + + Writes the first ``size`` bytes of ``buf`` over the USB connection. + Each byte is transmitted as an individual character. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +Examples +-------- + +.. _lang-serialusb-safe-print: + +**Safe print**: This function should run smoothly and not block; the +LED should blink at roughly the same speed whether being monitored, +running from battery, or connected but not monitored. You may need to +experiment with the DTR/RTS logic for your platform and device +configuration. :: + + #define LED_PIN 13 + + void setup() { + /* Set up the LED to blink */ + pinMode(LED_PIN, OUTPUT); + } + + void loop() { + // LED will stay off if we are disconnected; + // will blink quickly if USB is unplugged (battery etc) + if(SerialUSB.isConnected()) { + digitalWrite(LED_PIN, 1); + } + delay(100); + + // If this logic fails to detect if bytes are going to + // be read by the USB host, then the println() will fully + // many times, causing a very slow LED blink. + // If the characters are printed and read, the blink will + // only slow a small amount when "really" connected, and fast + // when the virtual port is only configured. + if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { + for(int i=0; i<10; i++) { + SerialUSB.println(123456,BIN); + } + } + digitalWrite(LED_PIN, 0); + delay(100); + } + diff --git a/docs/source/lang/setup.rst b/docs/source/lang/setup.rst index 6b142d2..837ddd6 100644 --- a/docs/source/lang/setup.rst +++ b/docs/source/lang/setup.rst @@ -1,34 +1,29 @@ +.. highlight:: cpp + .. _lang-setup: setup() ======= -The setup() function is called when a sketch starts. Use it to -initialize variables, pin modes, start using libraries, etc. The -setup function will only run once, after each powerup or reset of -the Arduino board. - - +The ``setup()`` function is called when a sketch starts. Use it to +initialize :ref:`variables `, :ref:`pin modes +`, start using :ref:`libraries `, etc. The +``setup()`` function will only run once, after each power-up or reset +of the Maple board. Example -~~~~~~~ +------- :: + int buttonPin = 38; - int buttonPin = 3; - - void setup() - { - Serial.begin(9600); + void setup() { pinMode(buttonPin, INPUT); } - void loop() - { + void loop() { // ... } - - .. include:: cc-attribution.txt diff --git a/docs/source/lang/shiftout.rst b/docs/source/lang/shiftout.rst deleted file mode 100644 index e76cc01..0000000 --- a/docs/source/lang/shiftout.rst +++ /dev/null @@ -1,136 +0,0 @@ -.. _lang-shiftout: - -shiftOut() -========== - -Description ------------ - -Shifts out a byte of data one bit at a time. Starts from either the -most (i.e. the leftmost) or least (rightmost) significant bit. Each -bit is written in turn to a data pin, after which a clock pin is -pulsed to indicate that the bit is available. - - - -This is a software implementation; Arduino (as of 0019) also -provides an `SPI library `_ -that uses the hardware implementation. - - - -Syntax ------- - -shiftOut(dataPin, clockPin, bitOrder, value) - - - -Parameters ----------- - -dataPin: the pin on which to output each bit (*int*) - - - -clockPin: the pin to toggle once the **dataPin** has been set to -the correct value (*int*) - - - -bitOrder: which order to shift out the bits; either **MSBFIRST** or -**LSBFIRST**. -(Most Significant Bit First, or, Least Significant Bit First) - - - -value: the data to shift out. (*byte*) - - - -Returns -------- - -None - - - -Note ----- - -The **dataPin** and **clockPin** must already be configured as -outputs by a call to -`pinMode `_\ (). - - - -**shiftOut** is currently written to output 1 byte (8 bits) so it -requires a two step operation to output values larger than 255. - -:: - - // Do this for MSBFIRST serial - int data = 500; - // shift out highbyte - shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); - // shift out lowbyte - shiftOut(data, clock, MSBFIRST, data); - - // Or do this for LSBFIRST serial - data = 500; - // shift out lowbyte - shiftOut(dataPin, clock, LSBFIRST, data); - // shift out highbyte - shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); - - - -Example -------- - -*For accompanying circuit, see the `tutorial on controlling a 74HC595 shift register `_.* - - - -:: - - //**************************************************************// - // Name : shiftOutCode, Hello World // - // Author : Carlyn Maw,Tom Igoe // - // Date : 25 Oct, 2006 // - // Version : 1.0 // - // Notes : Code for using a 74HC595 Shift Register // - // : to count from 0 to 255 // - //**************************************************************** - - //Pin connected to ST_CP of 74HC595 - int latchPin = 8; - //Pin connected to SH_CP of 74HC595 - int clockPin = 12; - ////Pin connected to DS of 74HC595 - int dataPin = 11; - - void setup() { - //set pins to output because they are addressed in the main loop - pinMode(latchPin, OUTPUT); - pinMode(clockPin, OUTPUT); - pinMode(dataPin, OUTPUT); - } - - void loop() { - //count up routine - for (int j = 0; j < 256; j++) { - //ground latchPin and hold low for as long as you are transmitting - digitalWrite(latchPin, LOW); - shiftOut(dataPin, clockPin, LSBFIRST, j); - //return the latch pin high to signal chip that it - //no longer needs to listen for information - digitalWrite(latchPin, HIGH); - delay(1000); - } - } - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/sizeof.rst b/docs/source/lang/sizeof.rst index 409a6d7..eae509c 100644 --- a/docs/source/lang/sizeof.rst +++ b/docs/source/lang/sizeof.rst @@ -2,8 +2,8 @@ .. _lang-sizeof: -sizeof() -======== +``sizeof()`` +============ The ``sizeof`` operator on the Maple returns the number of bytes needed to store a value of a given type\ [#fcharsize]_. This can be diff --git a/docs/source/lang/sq.rst b/docs/source/lang/sq.rst index a14817f..bd32648 100644 --- a/docs/source/lang/sq.rst +++ b/docs/source/lang/sq.rst @@ -2,14 +2,18 @@ .. _lang-sq: -sq(a) -===== - -Description ------------ +sq() +==== (Macro) computes the square of a number. +Syntax +------ + +:: + + sq(a) + Parameters ---------- diff --git a/docs/source/lang/static.rst b/docs/source/lang/static.rst index 4646db1..5d1802e 100644 --- a/docs/source/lang/static.rst +++ b/docs/source/lang/static.rst @@ -2,8 +2,8 @@ .. _lang-static: -Static -====== +``static`` +========== The ``static`` keyword can be used to create variables that are visible to only one function. However, unlike local variables that get diff --git a/docs/source/lang/string.rst b/docs/source/lang/string.rst index 92c3f69..0a270da 100644 --- a/docs/source/lang/string.rst +++ b/docs/source/lang/string.rst @@ -5,9 +5,6 @@ Strings ======= -Description ------------ - Text strings can be represented in two ways. You can 1. Use the :ref:`String ` data type, which is diff --git a/docs/source/lang/stringclass.rst b/docs/source/lang/stringclass.rst deleted file mode 100644 index 5e53f08..0000000 --- a/docs/source/lang/stringclass.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _lang-stringclass: - -String Class -============ - -Stub. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/stringobject.rst b/docs/source/lang/stringobject.rst deleted file mode 100644 index d7f287c..0000000 --- a/docs/source/lang/stringobject.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. _lang-stringobject: - -String -====== - -Description ------------ - -The String class, part of the core as of version 0019, allows you -to use and manipulate strings of text in more complex ways than -`character arrays `_ do. You -can concatenate Strings, append to them, search for and replace -substrings, and more. It takes more memory than a simple character -array, but it is also more useful. - - - -For reference, character arrays are referred to as strings with a -small s, and instances of the String class are referred to as -Strings with a capital S. Note that constant strings, specified in -"double quotes" are treated as char arrays, not instances of the -String class. - - - -Functions ---------- - - -- `String `_\ () -- `charAt `_\ () -- `compareTo `_\ () -- `concat `_\ () -- `endsWith `_\ () -- `equals `_\ () -- `equalsIgnoreCase `_\ () -- `getBytes `_\ () -- `indexOf `_\ () -- `lastIndexOf `_\ () -- `length `_\ () -- `replace `_\ () -- `setCharAt `_\ () -- `startsWith `_\ () -- `substring `_\ () -- `toCharArray `_\ () -- `toLowerCase `_\ () -- `toUpperCase `_\ () -- `trim `_\ () - - - -Operators ---------- - - -- `[] (element access) `_ -- `+ (concatenation) `_ -- `== (comparison) `_ - - - -Examples --------- - - -- `StringConstructors `_ -- `StringAdditionOperator `_ -- `StringIndexOf `_ -- `StringAppendOperator `_ -- `StringLengthTrim `_ -- `StringCaseChanges `_ -- `StringReplace `_ -- `StringCharacters `_ -- `StringStartsWithEndsWith `_ -- `StringComparisonOperators `_ -- `StringSubstring `_ - - - -See Also --------- - - -- `string `_: character - arrays -- `Variable Declaration `_ - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/switchcase.rst b/docs/source/lang/switchcase.rst index 46c47d8..b484bc5 100644 --- a/docs/source/lang/switchcase.rst +++ b/docs/source/lang/switchcase.rst @@ -2,12 +2,12 @@ .. _lang-switchcase: -switch / case statements -======================== +``switch``\ /\ ``case`` +======================= -Like :ref:`if/else ` blocks, A ``switch`` statement -controls program flow by allowing you to specify different code that -should be executed under various cases. +Like :ref:`if ` statements, A ``switch`` statement controls +program flow by allowing you to specify different code that should be +executed under various cases. The general syntax looks like this:: @@ -27,7 +27,6 @@ Where ``var`` is a variable whose value to investigate, and the ``val1``, ``val2`` after each ``case`` are constant values that ``var`` might be. - Description ----------- @@ -80,6 +79,8 @@ a ``break`` has been reached, so the program continues by calling ``afterTheSwitch()``. This is usually not what you want, which is why each ``case`` usually has a ``break`` at the end. +.. _lang-switchcase-default: + Writing "``default:``" instead of a ``case`` statement allows you to specify what to do if none of the ``case`` statements matches. Having a ``default`` is optional (you can leave it out), but if you have one, @@ -104,14 +105,14 @@ two, ``doThing2()`` gets called. If ``var`` is anything else, optional. If you're missing one and none of the ``case`` statements match, the ``switch`` does nothing at all, as if it weren't there. -``switch`` statements are often used with an ``enum`` value as the -variable to compare. In this case, you can write down all of the -values the ``enum`` takes as ``case`` statements, and be sure you've -covered all the possibilities. +``switch`` statements are often used with an :ref:`enum ` +value as the variable to compare. In this case, you can write down +all of the values the ``enum`` takes as ``case`` statements, and be +sure you've covered all the possibilities. See also: --------- -- :ref:`if...else ` +- :ref:`if/else ` .. include:: cc-attribution.txt diff --git a/docs/source/lang/tone.rst b/docs/source/lang/tone.rst deleted file mode 100644 index 96f0a7c..0000000 --- a/docs/source/lang/tone.rst +++ /dev/null @@ -1,81 +0,0 @@ -.. _lang-tone: - -tone() -====== - -Description ------------ - -Generates a square wave of the specified frequency (and 50% duty -cycle) on a pin. A duration can be specified, otherwise the wave -continues until a call to -`noTone `_\ (). The pin can be -connected to a piezo buzzer or other speaker to play tones. - - - -Only one tone can be generated at a time. If a tone is already -playing on a different pin, the call to tone() will have no effect. -If the tone is playing on the same pin, the call will set its -frequency. - - - -Use of the tone() function will interfere with PWM output on pins 3 -and 11 (on boards other than the Mega). - - - -**NOTE:** if you want to play different pitches on multiple pins, -you need to call noTone() on one pin before calling tone() on the -next pin. - - - -Syntax ------- - -tone(pin, frequency) -tone(pin, frequency, duration) - - - -Parameters ----------- - -pin: the pin on which to generate the tone - - - -frequency: the frequency of the tone in hertz - - - -duration: the duration of the tone in milliseconds (optional) - - - -Returns -------- - -nothing - - - -See also --------- - - -- `noTone `_\ () -- `analogWrite `_\ () -- `Tutorial:Tone `_ -- `Tutorial:Pitch follower `_ -- `Tutorial:Simple Keyboard `_ -- `Tutorial: multiple tones `_ - - -- `Tutorial: PWM `_ - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/types.rst b/docs/source/lang/types.rst deleted file mode 100644 index d095da1..0000000 --- a/docs/source/lang/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _lang-types: - -Built-in types -============== - -Stub. (explain all built-in integral and floating-point types, -including ``uint8`` style ones). diff --git a/docs/source/lang/unimplemented/interrupts.rst b/docs/source/lang/unimplemented/interrupts.rst new file mode 100644 index 0000000..55b8e93 --- /dev/null +++ b/docs/source/lang/unimplemented/interrupts.rst @@ -0,0 +1,59 @@ +.. _lang-interrupts: + +interrupts() +============ + +Re-enables interrupts (after they've been disabled by +`noInterrupts `_\ ()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None + + + +Returns +------- + +None + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `noInterrupts `_\ () +- `attachInterrupt `_\ () +- `detachInterrupt `_\ () + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/nointerrupts.rst b/docs/source/lang/unimplemented/nointerrupts.rst new file mode 100644 index 0000000..fb2e5f9 --- /dev/null +++ b/docs/source/lang/unimplemented/nointerrupts.rst @@ -0,0 +1,59 @@ +.. _lang-nointerrupts: + +noInterrupts() +============== + +Description +----------- + +Disables interrupts (you can re-enable them with interrupts()). +Interrupts allow certain important tasks to happen in the +background and are enabled by default. Some functions will not work +while interrupts are disabled, and incoming communication may be +ignored. Interrupts can slightly disrupt the timing of code, +however, and may be disabled for particularly critical sections of +code. + + + +Parameters +---------- + +None. + + + +Returns +------- + +None. + + + +Example +------- + +:: + + void setup() {} + + void loop() + { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + + + +See Also +-------- + + +- `interrupts `_\ () + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/notone.rst b/docs/source/lang/unimplemented/notone.rst new file mode 100644 index 0000000..485c9c5 --- /dev/null +++ b/docs/source/lang/unimplemented/notone.rst @@ -0,0 +1,50 @@ +.. _lang-notone: + +noTone() +======== + +Description +----------- + +Stops the generation of a square wave triggered by +`tone `_\ (). Has no effect if +no tone is being generated. + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +noTone(pin) + + + +Parameters +---------- + +pin: the pin on which to stop generating the tone + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `tone `_ () + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/pulsein.rst b/docs/source/lang/unimplemented/pulsein.rst new file mode 100644 index 0000000..2b52428 --- /dev/null +++ b/docs/source/lang/unimplemented/pulsein.rst @@ -0,0 +1,82 @@ +.. _lang-pulsein: + +pulseIn() +========= + +Description +----------- + +Reads a pulse (either HIGH or LOW) on a pin. For example, if +**value** is **HIGH**, **pulseIn()** waits for the pin to go +**HIGH**, starts timing, then waits for the pin to go **LOW** and +stops timing. Returns the length of the pulse in microseconds. +Gives up and returns 0 if no pulse starts within a specified time +out. + + + +The timing of this function has been determined empirically and +will probably show errors in longer pulses. Works on pulses from 10 +microseconds to 3 minutes in length. + + + +Syntax +------ + +pulseIn(pin, value) +pulseIn(pin, value, timeout) + + + +Parameters +---------- + +pin: the number of the pin on which you want to read the pulse. +(*int*) + + + +value: type of pulse to read: either +`HIGH `_ or +`LOW `_. (*int*) + + + +timeout (optional): the number of microseconds to wait for the +pulse to start; default is one second (*unsigned long*) + + + +Returns +------- + +the length of the pulse (in microseconds) or 0 if no pulse started +before the timeout (*unsigned long*) + + + +Example +------- + +:: + + + + int pin = 7; + unsigned long duration; + + void setup() + { + pinMode(pin, INPUT); + } + + void loop() + { + duration = pulseIn(pin, HIGH); + } + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/shiftout.rst b/docs/source/lang/unimplemented/shiftout.rst new file mode 100644 index 0000000..ff3852f --- /dev/null +++ b/docs/source/lang/unimplemented/shiftout.rst @@ -0,0 +1,136 @@ +.. _lang-shiftout: + +shiftOut() +========== + +Description +----------- + +Shifts out a byte of data one bit at a time. Starts from either the +most (i.e. the leftmost) or least (rightmost) significant bit. Each +bit is written in turn to a data pin, after which a clock pin is +pulsed to indicate that the bit is available. + + + +This is a software implementation; Arduino (as of 0019) also +provides an `SPI library `_ +that uses the hardware implementation. + + + +Syntax +------ + +shiftOut(dataPin, clockPin, bitOrder, value) + + + +Parameters +---------- + +dataPin: the pin on which to output each bit (*int*) + + + +clockPin: the pin to toggle once the **dataPin** has been set to +the correct value (*int*) + + + +bitOrder: which order to shift out the bits; either **MSBFIRST** or +**LSBFIRST**. +(Most Significant Bit First, or, Least Significant Bit First) + + + +value: the data to shift out. (*byte*) + + + +Returns +------- + +None + + + +Note +---- + +The **dataPin** and **clockPin** must already be configured as +outputs by a call to +`pinMode `_\ (). + + + +**shiftOut** is currently written to output 1 byte (8 bits) so it +requires a two step operation to output values larger than 255. + +:: + + // Do this for MSBFIRST serial + int data = 500; + // shift out highbyte + shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); + // shift out lowbyte + shiftOut(data, clock, MSBFIRST, data); + + // Or do this for LSBFIRST serial + data = 500; + // shift out lowbyte + shiftOut(dataPin, clock, LSBFIRST, data); + // shift out highbyte + shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); + + + +Example +------- + +*For accompanying circuit, see the `tutorial on controlling a 74HC595 shift register `_.* + + + +:: + + //**************************************************************// + // Name : shiftOutCode, Hello World // + // Author : Carlyn Maw,Tom Igoe // + // Date : 25 Oct, 2006 // + // Version : 1.0 // + // Notes : Code for using a 74HC595 Shift Register // + // : to count from 0 to 255 // + //**************************************************************** + + //Pin connected to ST_CP of 74HC595 + int latchPin = 8; + //Pin connected to SH_CP of 74HC595 + int clockPin = 12; + ////Pin connected to DS of 74HC595 + int dataPin = 11; + + void setup() { + //set pins to output because they are addressed in the main loop + pinMode(latchPin, OUTPUT); + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + } + + void loop() { + //count up routine + for (int j = 0; j < 256; j++) { + //ground latchPin and hold low for as long as you are transmitting + digitalWrite(latchPin, LOW); + shiftOut(dataPin, clockPin, LSBFIRST, j); + //return the latch pin high to signal chip that it + //no longer needs to listen for information + digitalWrite(latchPin, HIGH); + delay(1000); + } + } + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/stringclass.rst b/docs/source/lang/unimplemented/stringclass.rst new file mode 100644 index 0000000..cdd385d --- /dev/null +++ b/docs/source/lang/unimplemented/stringclass.rst @@ -0,0 +1,9 @@ +.. _lang-stringclass: + +String Class +============ + +Stub. + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/stringobject.rst b/docs/source/lang/unimplemented/stringobject.rst new file mode 100644 index 0000000..e47ed7e --- /dev/null +++ b/docs/source/lang/unimplemented/stringobject.rst @@ -0,0 +1,89 @@ +.. _lang-stringobject: + +String +====== + +Description +----------- + +The String class, part of the core as of version 0019, allows you to +use and manipulate strings of text in more complex ways than character +arrays do. You can concatenate Strings, append to them, search for and +replace substrings, and more. It takes more memory than a simple +character array, but it is also more useful. + + + +For reference, character arrays are referred to as strings with a +small s, and instances of the String class are referred to as +Strings with a capital S. Note that constant strings, specified in +"double quotes" are treated as char arrays, not instances of the +String class. + + + +Functions +--------- + + +- `String `_\ () +- `charAt `_\ () +- `compareTo `_\ () +- `concat `_\ () +- `endsWith `_\ () +- `equals `_\ () +- `equalsIgnoreCase `_\ () +- `getBytes `_\ () +- `indexOf `_\ () +- `lastIndexOf `_\ () +- `length `_\ () +- `replace `_\ () +- `setCharAt `_\ () +- `startsWith `_\ () +- `substring `_\ () +- `toCharArray `_\ () +- `toLowerCase `_\ () +- `toUpperCase `_\ () +- `trim `_\ () + + + +Operators +--------- + + +- `[] (element access) `_ +- `+ (concatenation) `_ +- `== (comparison) `_ + + + +Examples +-------- + + +- `StringConstructors `_ +- `StringAdditionOperator `_ +- `StringIndexOf `_ +- `StringAppendOperator `_ +- `StringLengthTrim `_ +- `StringCaseChanges `_ +- `StringReplace `_ +- `StringCharacters `_ +- `StringStartsWithEndsWith `_ +- `StringComparisonOperators `_ +- `StringSubstring `_ + + + +See Also +-------- + + +- `Character array strings `_ +- `Variable Declaration `_ + + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/tone.rst b/docs/source/lang/unimplemented/tone.rst new file mode 100644 index 0000000..f83bf6b --- /dev/null +++ b/docs/source/lang/unimplemented/tone.rst @@ -0,0 +1,81 @@ +.. _lang-tone: + +tone() +====== + +Description +----------- + +Generates a square wave of the specified frequency (and 50% duty +cycle) on a pin. A duration can be specified, otherwise the wave +continues until a call to +`noTone `_\ (). The pin can be +connected to a piezo buzzer or other speaker to play tones. + + + +Only one tone can be generated at a time. If a tone is already +playing on a different pin, the call to tone() will have no effect. +If the tone is playing on the same pin, the call will set its +frequency. + + + +Use of the tone() function will interfere with PWM output on pins 3 +and 11 (on boards other than the Mega). + + + +**NOTE:** if you want to play different pitches on multiple pins, +you need to call noTone() on one pin before calling tone() on the +next pin. + + + +Syntax +------ + +tone(pin, frequency) +tone(pin, frequency, duration) + + + +Parameters +---------- + +pin: the pin on which to generate the tone + + + +frequency: the frequency of the tone in hertz + + + +duration: the duration of the tone in milliseconds (optional) + + + +Returns +------- + +nothing + + + +See also +-------- + + +- `noTone `_\ () +- `analogWrite `_\ () +- `Tutorial:Tone `_ +- `Tutorial:Pitch follower `_ +- `Tutorial:Simple Keyboard `_ +- `Tutorial: multiple tones `_ + + +- `Tutorial: PWM `_ + + + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unsignedchar.rst b/docs/source/lang/unsignedchar.rst index c49690d..5b946ed 100644 --- a/docs/source/lang/unsignedchar.rst +++ b/docs/source/lang/unsignedchar.rst @@ -2,11 +2,8 @@ .. _lang-unsignedchar: -unsigned char -============= - -Description ------------ +``unsigned char`` +================= An unsigned version of the :ref:`char ` data type. An ``unsigned char`` occupies 1 byte of memory; it stores an integer from diff --git a/docs/source/lang/unsignedint.rst b/docs/source/lang/unsignedint.rst index aa5cc1b..f6311da 100644 --- a/docs/source/lang/unsignedint.rst +++ b/docs/source/lang/unsignedint.rst @@ -2,11 +2,8 @@ .. _lang-unsignedint: -unsigned int -============ - -Description ------------ +``unsigned int`` +================ An ``unsigned int`` (unsigned integer) is the same as an :ref:`int ` in that it stores a 4 byte integer value. However, diff --git a/docs/source/lang/unsignedlong.rst b/docs/source/lang/unsignedlong.rst index 2ca49f8..14a4fc3 100644 --- a/docs/source/lang/unsignedlong.rst +++ b/docs/source/lang/unsignedlong.rst @@ -2,11 +2,8 @@ .. _lang-unsignedlong: -unsigned long -============= - -Description ------------ +``unsigned long`` +================= An unsigned version of the :ref:`long ` data type. An ``unsigned long`` occupies 8 bytes of memory; it stores an integer @@ -19,8 +16,8 @@ won't store negative numbers; it is also subject to the same Here is an example of declaring an ``unsigned long`` variable named ``c``, then giving it value 299,792,458,000,000,000 (see :ref:`integer -constants ` for an explanation of the "L" at the -end of the number):: +constants ` for an explanation of the "L" +at the end of the number):: // Speed of light in nanometers per second (approximate). unsigned long c = 299792458000000000L; diff --git a/docs/source/lang/variables.rst b/docs/source/lang/variables.rst index 05a4f96..9094cd5 100644 --- a/docs/source/lang/variables.rst +++ b/docs/source/lang/variables.rst @@ -37,8 +37,8 @@ named ``inputVariable2``, with an initial value of ``0``:: int inputVariable2 = 0; The Maple environment comes ready to use with many useful types of -variables. See the :ref:`built-in types ` page for more -information. +variables. See the :ref:`built-in types ` page +for more information. Here are a few examples of declaring variables of different types:: @@ -116,8 +116,8 @@ he goes past the left side of the screen, he reappears on the right:: x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" Each numeric type's reference page includes its range. See the -:ref:`built-in types ` reference for links to each type's -reference page. +:ref:`built-in types ` reference for links to each +type's reference page. Using Variables --------------- @@ -149,7 +149,7 @@ See Also -------- - :ref:`lang-scope` -- :ref:`lang-types` +- :ref:`lang-numeric-types` .. rubric:: Footnotes diff --git a/docs/source/lang/void.rst b/docs/source/lang/void.rst index bc7a3dc..88bd448 100644 --- a/docs/source/lang/void.rst +++ b/docs/source/lang/void.rst @@ -1,40 +1,31 @@ +.. highlight:: cpp + .. _lang-void: -void -==== +``void`` +======== -The void keyword is used only in function declarations. It +The ``void`` keyword is used only in function declarations. It indicates that the function is expected to return no information to -the function from which it was called. - - +the function from which it was called, or that it expects no arguments +from its caller. -Example: --------- +Example +------- :: // actions are performed in the functions "setup" and "loop" // but no information is reported to the larger program - void setup() - { + void setup() { // ... } - void loop() - { + void loop() { // ... } - - - -See also --------- - -`function declaration `_ - - +.. TODO doc page on function declaration? .. include:: cc-attribution.txt diff --git a/docs/source/lang/volatile.rst b/docs/source/lang/volatile.rst index a0ef671..276bb6a 100644 --- a/docs/source/lang/volatile.rst +++ b/docs/source/lang/volatile.rst @@ -1,37 +1,31 @@ -.. _lang-volatile: - -volatile keyword -================ - -volatile is a keyword known as a variable *qualifier*, it is -usually used before the datatype of a variable, to modify the way -in which the compiler and subsequent program treats the variable. - - - -Declaring a variable volatile is a directive to the compiler. The -compiler is software which translates your C/C++ code into the -machine code, which are the real instructions for the Atmega chip -in the Arduino. - - +.. highlight:: cpp -Specifically, it directs the compiler to load the variable from RAM -and not from a storage register, which is a temporary memory -location where program variables are stored and manipulated. Under -certain conditions, the value for a variable stored in registers -can be inaccurate. +.. _lang-volatile: +``volatile`` +============ +The ``volatile`` keyword known is a variable *qualifier*. It is +usually used before the datatype of a variable, to modify the way in +which the compiler treats the variable. -A variable should be declared volatile whenever its value can be -changed by something beyond the control of the code section in -which it appears, such as a concurrently executing thread. In the -Arduino, the only place that this is likely to occur is in sections -of code associated with interrupts, called an interrupt service -routine. +Declaring a variable ``volatile`` is a directive to the compiler. The +compiler is software which translates your C++ code into the machine +code, which are the real instructions for the STM32 chip in the +Maple. (The particular compiler we provide for use with the Maple is a +version of :ref:`GCC `). +Specifically, it directs the compiler to read the variable's value +fresh every time it is used, rather than "backing up" the value and +reading from its backup copy. (Compilers often "back up" a variable's +value in RAM into a storage location called a *register*; this is done +for efficiency). +A variable should be declared ``volatile`` whenever its value can be +changed by something beyond the control of the code section in which +it appears, such as an :ref:`external interrupt +`. On the Maple, the only place that this is +likely to occur is in sections of code associated with interrupts. Example ------- @@ -43,31 +37,29 @@ Example int pin = 13; volatile int state = LOW; - void setup() - { + void setup() { pinMode(pin, OUTPUT); attachInterrupt(0, blink, CHANGE); } - void loop() - { + void loop() { digitalWrite(pin, state); } - void blink() - { - state = !state; + void blink() { + if (state == HIGH) { + state = LOW; + } else { + // state must be HIGH + state = HIGH; + } } - - See also -------- - -- `AttachInterrupt `_ - - - +- :ref:`External Interrupts ` +- :ref:`lang-attachinterrupt` +- :ref:`lang-detachinterrupt` .. include:: cc-attribution.txt diff --git a/docs/source/lang/while.rst b/docs/source/lang/while.rst index be1ea14..9047d05 100644 --- a/docs/source/lang/while.rst +++ b/docs/source/lang/while.rst @@ -1,37 +1,28 @@ -.. _lang-while: - -while Loops -=========== - -Description ------------ - -**while** loops will loop continuously, and infinitely, until the -expression inside the parenthesis, () becomes false. Something must -change the tested variable, or the **while** loop will never exit. -This could be in your code, such as an incremented variable, or an -external condition, such as testing a sensor. +.. highlight:: cpp +.. _lang-while: +``while`` +========= Syntax ------ :: - while(expression){ - // statement(s) + while (expression) { + // block of code } +Description +----------- - -Parameters ----------- - -expression - a (boolean) C statement that evaluates to true or -false - - +``while`` loops will repeat the statements inside their associated +block of code until the expression inside the parentheses becomes +:ref:`false `. Something must change the tested +expressions' value, or the ``while`` loop will never exit. This could +be in your code, such as an incremented variable, or an external +condition, such as testing a sensor. Example ------- @@ -39,11 +30,9 @@ Example :: var = 0; - while(var < 200){ + while(var < 200) { // do something repetitive 200 times var++; } - - .. include:: cc-attribution.txt diff --git a/docs/source/language-index.rst b/docs/source/language-index.rst index 90b3d79..ddc7849 100644 --- a/docs/source/language-index.rst +++ b/docs/source/language-index.rst @@ -6,126 +6,23 @@ Language Reference Index This is the index of the :ref:`language reference ` documentation. -Not converted Arduino docs: - .. toctree:: :maxdepth: 1 + :glob: - lang/pwmwrite - lang/types - lang/serialusb + lang/* -Finished: +.. Unfinished, unimplemented in libmaple: .. toctree:: - :maxdepth: 1 - - lang/abs - lang/analogread - lang/pinmode - lang/arithmetic - lang/array - lang/assignment - lang/attachinterrupt - lang/bit - lang/bitclear - lang/bitread - lang/bitset - lang/bitshift - lang/analogwrite - lang/bitwisemath - lang/bitwisecompound - lang/bitwrite - lang/boolean - lang/booleanvariables - lang/braces - lang/break - lang/byte - lang/bytecast - lang/char - lang/charcast - lang/comments - lang/const - lang/constrain - lang/continue - lang/cos - lang/define - lang/delay - lang/delaymicroseconds - lang/detachinterrupt - lang/digitalread - lang/double - lang/doublecast - lang/dowhile - lang/else - lang/float - lang/floatcast - lang/for - lang/goto - lang/highbyte - lang/if - lang/comparison - lang/include - lang/increment - lang/arithmeticcompound - lang/int - lang/intcast - lang/long - lang/longcast - lang/loop - lang/max - lang/min - lang/modulo - lang/pointer - lang/pow - lang/return - lang/scope - lang/semicolon - lang/sin - lang/sizeof - lang/sqrt - lang/sq - lang/static - lang/string - lang/switchcase - lang/tan - lang/unsignedchar - lang/unsignedint - lang/unsignedlong - lang/variables + :hidden: -Unfinished; straightforward to convert: - -.. toctree:: - :maxdepth: 1 - - lang/void - lang/volatile - lang/while - lang/keywords - lang/enum - -Unfinished, requires libmaple/Arduino knowledge: - -.. toctree:: - :maxdepth: 1 + lang/unimplemented/interrupts.rst + lang/unimplemented/nointerrupts.rst + lang/unimplemented/notone.rst + lang/unimplemented/pulsein.rst + lang/unimplemented/shiftout.rst + lang/unimplemented/stringclass.rst + lang/unimplemented/stringobject.rst + lang/unimplemented/tone.rst - lang/constants - lang/digitalwrite - lang/notone - lang/serial - lang/interrupts - lang/analogwrite - lang/nointerrupts - lang/pulsein - lang/stringobject - lang/tone - lang/random - lang/randomseed - lang/setup - lang/map - lang/shiftout - lang/micros - lang/millis - lang/lowbyte - lang/stringclass diff --git a/docs/source/language.rst b/docs/source/language.rst index 0a79fb0..350b0c3 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -52,6 +52,9 @@ Unique Maple Additions Maple Language Reference ------------------------ +The following table summarizes the available language features. A +more exhaustive index is available at the :ref:`language-index`. + +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ | Structure | Variables | Functions | | | | | @@ -63,151 +66,154 @@ Maple Language Reference | | |* :ref:`digitalWrite() ` | |**Control Structures** |* :ref:`INPUT ` | | | | | :ref:`OUTPUT ` |* :ref:`digitalRead() ` | -|* :ref:`if ` | | | +|* :ref:`if/else ` | | | | |* :ref:`true ` | | | -|* :ref:`if...else ` | :ref:`false ` |**Analog I/O** | -| | | | -|* :ref:`for ` |* :ref:`integer constants |* :ref:`analogRead() ` | -| | ` | | -|* :ref:`switch/case ` | |* :ref:`pwmWrite() ` | -| |* :ref:`floating point constants | (:ref:`analogWrite() ` is | -|* :ref:`while ` | ` | also available, though its use is discouraged) | +|* :ref:`for ` | :ref:`false ` |**Analog I/O** | | | | | -|* :ref:`do...while ` | | | -| |**Data Types** |**Advanced I/O** | +|* :ref:`switch/case ` |* :ref:`Constants |* :ref:`analogRead() ` | +| | ` (:ref:`integers | | +|* :ref:`while ` | `, :ref:`floating |* :ref:`pwmWrite() ` | +| | point `) | (:ref:`analogWrite() ` is | +|* :ref:`do...while ` | | also available, though its use is discouraged) | +| |**Data Types** | | |* :ref:`break ` | | | -| | The size of each datatype, in bytes, is |* tone(): TODO | +| | The size of each datatype, in bytes, is |**Advanced I/O** | |* :ref:`continue ` | given in parentheses where appropriate. | | -| | |* noTone(): TODO | +| | |* tone(): TODO | |* :ref:`return ` | *Note*: The ``word`` type is (deliberately) | | -| | :ref:`not supported `. |* shiftOut(): TODO | +| | :ref:`not supported `. |* noTone(): TODO | |* :ref:`goto ` | | | -| |* :ref:`void ` |* pulseIn(): TODO | +| |* :ref:`void ` |* shiftOut(): TODO | +| | | | +|**Further syntax** |* :ref:`boolean ` (1 byte) |* pulseIn(): TODO | | | | | -|**Further syntax** |* :ref:`boolean ` (1 byte) | | -| | |**Time** | |* :ref:`; (semicolon) ` |* :ref:`char ` (1 byte) | | -| | |* :ref:`millis() ` | -|* :ref:`{} (curly braces) ` |* :ref:`unsigned char | | -| | ` (1 byte) |* :ref:`micros() ` | -|* :ref:`// (single-line comment) | | | -| ` |* :ref:`byte ` (1 byte) |* :ref:`delay() ` | +| | |**Time** | +|* :ref:`{} (curly braces) |* :ref:`unsigned char | | +| ` | ` (1 byte) |* :ref:`millis() ` | | | | | -|* :ref:`/\* \*/ (multi-line comment) |* :ref:`int ` (4 bytes) |* :ref:`delayMicroseconds() | -| ` | | ` | -| |* :ref:`unsigned int ` | | -|* :ref:`#define ` | (4 bytes) | | -| | |**Math** | -|* :ref:`#include ` |* :ref:`long ` (8 bytes) | | -| | |* :ref:`min() ` | +|* :ref:`// (single-line comment) |* :ref:`byte ` (1 byte) |* :ref:`micros() ` | +| ` | | | +| |* :ref:`int ` (4 bytes) |* :ref:`delay() ` | +|* :ref:`/\* \*/ (multi-line comment) | | | +| ` |* :ref:`unsigned int ` |* :ref:`delayMicroseconds() | +| | (4 bytes) | ` | +|* :ref:`#define ` | | | +| |* :ref:`long ` (8 bytes) | | +|* :ref:`#include ` | |**Math** | | |* :ref:`unsigned long ` | | -|**Arithmetic Operators** | (8 bytes) |* :ref:`max() ` | +| | (8 bytes) |* :ref:`min() ` | +|**Arithmetic Operators** | | | +| |* :ref:`float ` (4 bytes) |* :ref:`max() ` | +|* :ref:`= ` | | | +| (assignment operator) |* :ref:`double ` (8 bytes) |* :ref:`abs() ` | | | | | -|* :ref:`= ` |* :ref:`float ` (4 bytes) |* :ref:`abs() ` | -| (assignment operator) | | | -| |* :ref:`double ` (8 bytes) |* :ref:`constrain() ` | -|* :ref:`+ ` (addition) | | | -| |* :ref:`string ` |* :ref:`map() ` | -|* :ref:`- ` | | | -| (subtraction) |* :ref:`array ` |* :ref:`pow() ` | +|* :ref:`+ ` (addition) |* :ref:`Strings ` |* :ref:`constrain() ` | | | | | -|* :ref:`* ` |* See also: :ref:`built-in types reference |* :ref:`sqrt() ` | -| (multiplication) | `. | | +|* :ref:`- ` |* :ref:`Arrays ` |* :ref:`map() ` | +| (subtraction) | | | +| |* :ref:`enum ` |* :ref:`pow() ` | +|* :ref:`* ` | | | +| (multiplication) |* :ref:`Numeric types ` |* :ref:`sqrt() ` | | | | | -|* :ref:`/ ` (division) | |**Trigonometry** | -| |**Conversion** | | -|* :ref:`% ` (modulo) | |* :ref:`sin() ` | -| |* :ref:`char() ` | | -| | |* :ref:`cos() ` | -|**Comparison Operators** |* :ref:`byte() ` | | -| | |* :ref:`tan() ` | -|* :ref:`== ` (equal to) |* :ref:`int() ` | | +|* :ref:`/ ` (division) |**Conversion** | | +| | |**Trigonometry** | +|* :ref:`% ` (modulo) |* :ref:`char() ` | | +| | |* :ref:`sin() ` | +| |* :ref:`byte() ` | | +|**Comparison Operators** | |* :ref:`cos() ` | +| |* :ref:`int() ` | | +|* :ref:`== ` (equal to) | |* :ref:`tan() ` | +| |* :ref:`long() ` | | +|* :ref:`\!= ` | | | +| (not equal to) |* :ref:`float() ` |**Random Numbers** | | | | | -|* :ref:`\!= ` |* :ref:`long() ` |**Random Numbers** | -| (not equal to) | | | -| |* :ref:`float() ` |* :ref:`randomSeed() ` | -|* :ref:`< ` (less than) | | | -| |* :ref:`double() ` |* :ref:`random() ` | -|* :ref:`> ` | | | -| (greater than) | | | -| |**Variable Scope & Qualifiers** |**Bits and Bytes** | -|* :ref:`<= ` | | | -| (less than or equal to) |* :ref:`variables `, |* :ref:`lowByte() ` | -| | :ref:`scope ` | | -|* :ref:`>= ` | |* :ref:`highByte() ` is | -| (greater than or equal to) |* :ref:`static ` | provided, though its use is discouraged. | +|* :ref:`< ` (less than) |* :ref:`double() ` |* :ref:`randomSeed() ` | | | | | -| |* :ref:`volatile ` |* :ref:`bitRead() ` | -|**Boolean Operators** | | | -| |* :ref:`const ` |* :ref:`bitWrite() ` | -|* :ref:`&& ` (and) | | | -| | |* :ref:`bitSet() ` | -|* :ref:`|| ` (or) |**Utilities** | | -| | |* :ref:`bitClear() ` | -|* :ref:`\! ` (not) |* :ref:`sizeof() ` | | -| | (``sizeof`` operator) |* :ref:`bit() ` | +|* :ref:`> ` | |* :ref:`random() ` | +| (greater than) |**Variable Scope & Qualifiers** | | | | | | -|**Pointer Operators** | | | -| | |**External Interrupts** | -|* :ref:`* dereference operator | | | -| ` | |* :ref:`Reference Page ` | +|* :ref:`<= ` |* :ref:`variables `, |**Bits and Bytes** | +| (less than or equal to) | :ref:`scope ` | | +| | |* :ref:`lowByte() ` | +|* :ref:`>= ` |* :ref:`static ` | | +| (greater than or equal to) | |* :ref:`highByte() ` is | +| |* :ref:`volatile ` | provided, though its use is discouraged. | | | | | -|* :ref:`& reference operator | |* :ref:`attachInterrupt() | -| ` | | ` | +|**Boolean Operators** |* :ref:`const ` |* :ref:`bitRead() ` | | | | | -| | |* :ref:`detachInterrupt() | -|**Bitwise Operators** | | ` | +|* :ref:`&& ` (and) | |* :ref:`bitWrite() ` | +| |**Utilities** | | +|* :ref:`|| ` (or) | |* :ref:`bitSet() ` | +| |* :ref:`sizeof() ` | | +|* :ref:`\! ` (not) | |* :ref:`bitClear() ` | | | | | +| | |* :ref:`bit() ` | +|**Pointer Operators** | | | +| | | | +|* :ref:`* dereference operator | |**External Interrupts** | +| ` | | | +| | |* :ref:`Reference Page ` | +|* :ref:`& reference operator | | | +| ` | |* :ref:`attachInterrupt() | +| | | ` | +| | | | +|**Bitwise Operators** | |* :ref:`detachInterrupt() | +| | | ` | |* :ref:`& ` | | | -| (bitwise and) | |**Interrupts** | +| (bitwise and) | | | +| | |**Interrupts** | +|* :ref:`| ` | | | +| (bitwise or) | |* interrupts(): TODO | | | | | -|* :ref:`| ` | |* interrupts(): TODO | -| (bitwise or) | | | -| | |* noInterrupts(): TODO | -|* :ref:`^ ` | | | +|* :ref:`^ ` | |* noInterrupts(): TODO | | (bitwise xor) | | | -| | |**Communication** | -|* :ref:`~ ` | | | -| (bitwise not) | |* :ref:`SerialUSB ` | | | | | -|* :ref:`\<\< ` | |* :ref:`Serial ` | -| (shift left) | | | -| | |**Looking for something else?** | -|* :ref:`>> ` | | | -| (shift right) | | See the :ref:`libraries` page for interfacing with| +|* :ref:`~ ` | |**Communication** | +| (bitwise not) | | | +| | |* :ref:`SerialUSB ` | +|* :ref:`\<\< ` | | | +| (shift left) | |* :ref:`Serial ` | +| | | | +|* :ref:`>> ` | |**Looking for something else?** | +| (shift right) | | | +| | | See the :ref:`libraries` page for interfacing with| | | | particular types of hardware. Maple links | -| | | against `newlib `_ | -|**Compound Operators** | | and allows the use of any of its functions; see | -| | | its documentation for more details. | -|* :ref:`++ ` | | | +|**Compound Operators** | | against `newlib `_ | +| | | and allows the use of any of its functions; see | +|* :ref:`++ ` | | its documentation for more details. | | (increment) | | | | | | | |* :ref:`- - ` | | | | (decrement) | | | | | | | -|* :ref:`+= ` | | | +|* :ref:`+= ` | | | | (compound add) | | | | | | | |* :ref:`-= | | | -| ` (compound | | | +| ` (compound | | | | subtract) | | | | | | | |* :ref:`*= | | | -| ` (compound | | | +| ` (compound | | | | multiply) | | | | | | | |* :ref:`/= | | | -| ` (compound | | | +| ` (compound | | | | divide) | | | | | | | |* :ref:`&= | | | -| ` (compound | | | +| ` (compound | | | | bitwise and) | | | | | | | |* :ref:`|= | | | -| ` (compound | | | +| ` (compound | | | | bitwise or) | | | | | | | +|**Keywords** | | | +| | | | +|* :ref:`C++ Keywords ` | | | +| | | | | | | | +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 6a97b0e..6ecdf07 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -18,7 +18,7 @@ in the description of the library. .. contents:: Contents :local: -.. _liquid_crystal: +.. _libraries-liquid-crystal: LiquidCrystal ------------- @@ -32,7 +32,7 @@ At this time, no incompatibilities between the Maple and Arduino versions are known. Any observed differences should be considered bugs, and reported on the forums. -.. _wire: +.. _libraries-wire: Wire ---- diff --git a/docs/source/spi.rst b/docs/source/spi.rst index 4cfd7e7..ca9415c 100644 --- a/docs/source/spi.rst +++ b/docs/source/spi.rst @@ -35,7 +35,7 @@ Function Reference ``Spi.begin(freq, endianness, mode)`` - ``begin`` is usually called in `setup()`_ to configure the + ``begin`` is usually called in :ref:`lang-setup` to configure the baudrate of the given SPI port and to set up the header pins appropriately. ``freq`` is one of the set listed :ref:`above `; ``endianness`` is either ``LSBFIRST`` or diff --git a/docs/source/timers.rst b/docs/source/timers.rst index fe6ea4a..948805b 100644 --- a/docs/source/timers.rst +++ b/docs/source/timers.rst @@ -2,9 +2,8 @@ .. _timers: -======== - Timers -======== +Timers +====== There are four general purpose timers in the Maple microcontroller that can be configured to generate periodic or delayed events with @@ -52,7 +51,7 @@ configuration being the same. **Jitter:** other interrupts (USB, Serial, SysTick, or other timers) can and will get called before or during the timer - interrupt routines, causing pseudo-random delays and other + interrupt routines, causing pseudorandom delays and other frustrations. Disabling the USB port (by calling ``SerialUSB.end()``, or just @@ -90,7 +89,7 @@ General Timer Modes :ref:`PWM docs ` for more information on this mode. .. note:: - + ``Timer1.setChannel1Mode(TIMER_PWM)`` may not work as expected; if you want PWM functionality on a channel, make sure you don't set it to something else. @@ -240,7 +239,7 @@ LED blink void setup() { - // Set up the LED to blink + // Set up the LED to blink pinMode(LED_PIN, OUTPUT); // Setup Timer @@ -251,13 +250,13 @@ LED blink } void loop() { - // Nothing! It's all in the interrupts + // Nothing! It's all in the interrupts } void handler_led(void) { toggle ^= 1; digitalWrite(LED_PIN, toggle); - } + } Racing Counters ^^^^^^^^^^^^^^^ @@ -287,7 +286,7 @@ Racing Counters Timer3.setOverflow(30000); Timer4.setOverflow(30000); Timer3.setCompare1(1000); // somewhere in the middle - Timer4.setCompare1(1000); + Timer4.setCompare1(1000); Timer3.attachCompare1Interrupt(handler1); Timer4.attachCompare1Interrupt(handler2); Timer3.resume(); @@ -296,9 +295,9 @@ Racing Counters void loop() { // Display the running counts - SerialUSB.print("Count 1: "); + SerialUSB.print("Count 1: "); SerialUSB.print(count1); - SerialUSB.print("\t\tCount 2: "); + SerialUSB.print("\t\tCount 2: "); SerialUSB.println(count2); // Run... while BUT is held, pause Count2 @@ -314,7 +313,7 @@ Racing Counters void handler1(void) { count1++; - } + } void handler2(void) { count2++; - } + } diff --git a/docs/source/troubleshooting.rst b/docs/source/troubleshooting.rst index 9d452d1..7b80a3f 100644 --- a/docs/source/troubleshooting.rst +++ b/docs/source/troubleshooting.rst @@ -30,10 +30,8 @@ use :ref:`perpetual bootloader mode My board is bricked! I can't upload via the bootloader no matter what! ---------------------------------------------------------------------- -Use the hardcoded serial STM32 serial bootloader to re-flash the -bootloader. - -.. TODO insert docs on reflashing the bootloader +Use the hardcoded serial STM32 serial bootloader to :ref:`re-flash the +bootloader `. If it really is bricked, and you think it's our fault, `contact us `_\ ! @@ -100,18 +98,18 @@ a board selected. The work-around is to restart the IDE. Mysterious! ``NullPointerException`` ------------------------ -A classic! Make sure you have selected a board from the pulldown menu. +A classic! Make sure you have selected a board from the pulldown menu. .. TODO: remove when Python version is released ``undefined reference to setup()/loop()`` ----------------------------------------- -Your sketch/program either does not include one of the `setup -`_ or `loop `_ functions, or it was not found by the -compiler. Your program must include both ``void setup()`` and ``void -loop()`` functions; they don't have to do anything, but they **must** -be there. +Your sketch/program either does not include one of the :ref:`setup() +` or `loop() ` functions, or it was not found +by the compiler. Your program must include both ``void setup()`` and +``void loop()`` functions; they don't have to do anything, but they +**must** be there. You can start with an example program (to see one in the IDE, click on File > Examples > Stubs > BareMinimum) to get the basic structure. @@ -152,7 +150,7 @@ is several times more FLASH memory available for user programs. ``No DFU capable USB device found`` ----------------------------------- -This probably means you don't have a Maple plugged in or powered on! +This probably means you don't have a Maple plugged in or powered on! I have multiple Maples installed; how do I know which one will get flashed? --------------------------------------------------------------------------- diff --git a/docs/source/unix-toolchain.rst b/docs/source/unix-toolchain.rst index 2bb584a..e6039a2 100644 --- a/docs/source/unix-toolchain.rst +++ b/docs/source/unix-toolchain.rst @@ -97,12 +97,12 @@ This step is fairly straightforward: do a git clone of the `libmaple repository `_ to some directory, then download and extract the ARM compiler toolchain. -The :file:`arm/bin/` directory will need to be added to -:envvar:`PATH`; you can check that this worked by entering -``arm-none-`` and hitting tab to auto-complete (bash should show a -bunch of results). Regardless of where you put the toolchain, make -sure to preserve its internal directory layout, as the binaries make -relative path calls and references. +The :file:`arm/bin/` directory will need to be added to ``PATH``; you +can check that this worked by entering ``arm-none-`` and hitting tab +to auto-complete (bash should show a bunch of results). Regardless of +where you put the toolchain, make sure to preserve its internal +directory layout, as the binaries make relative path calls and +references. .. _toolchain-udev: @@ -176,7 +176,7 @@ You will need the following tools to get started: :file:`/Applications/OpenMoko Flasher.app/Contents/Mac OS/dfu-util` To get access to it from the command line, just make a symbolic link - to the binary from some place on your :envvar:`PATH`:: + to the binary from some place on your ``PATH``:: $ ln -s /Applications/OpenMoko\ Flasher.app/Contents/Mac\ OS/dfu-util \ /somewhere/on/your/PATH/dfu-util @@ -241,7 +241,7 @@ live with :: $ export PATH=$PATH:~/libmaple/arm/bin After that's done, you'll probably want to update your shell startup -script so :file:`~/libmaple/arm/bin` stays in your :envvar:`PATH`. +script so :file:`~/libmaple/arm/bin` stays in your ``PATH``. **So far, so good?** @@ -350,8 +350,8 @@ Starting your own projects -------------------------- So everything worked, and you want to start your own project? Great! -It's easy. Just set the environment variable :envvar:`LIB_MAPLE_HOME` -in your shell startup script to point to the libmaple repository you +It's easy. Just set the environment variable ``LIB_MAPLE_HOME`` in +your shell startup script to point to the libmaple repository you cloned (this tutorial assumes you put it in :file:`~/libmaple`). For example, if you use bash as your shell, just put this line in your :file:`~/.bashrc` or :file:`~/.bash_profile`:: @@ -417,10 +417,9 @@ but it might be helpful for people who are allergic to `vim `_. The simple configuration described here just calls down to the :file:`Makefile`, so follow the above directions to get the command line tools configured (you'll -definitely need the arm-none-eabi-* tools on your :envvar:`PATH`), -then `install Code::Blocks -`_. You can do this on Linux -with:: +definitely need the arm-none-eabi-* tools on your ``PATH``), then +`install Code::Blocks `_. You +can do this on Linux with:: $ sudo aptitude install codeblocks @@ -434,8 +433,8 @@ to get a feel for how it all works. To create your own "libmaple" project, start with an "Empty Project" with the "Folder to create project in" set to your -:envvar:`LIB_MAPLE_HOME`. Make sure that the "Resulting filename" is -in the top level directory as well. +``LIB_MAPLE_HOME``. Make sure that the "Resulting filename" is in the +top level directory as well. .. image:: /_static/img/codeblocks_newproject.png :align: center diff --git a/docs/source/usb.rst b/docs/source/usb.rst index baabde5..5494b06 100644 --- a/docs/source/usb.rst +++ b/docs/source/usb.rst @@ -6,21 +6,6 @@ USB ===== -.. note:: Changes and Caveats - - The SerialUSB functionality was modified for the 0.0.6 IDE - release. It now includes a 50 millisecond timeout for writes and - does not try to detect if the USB host is "really" connected or - just enumerated and initialized. This means that if you have a - number of SerialUSB writes or prints in your code and you are not - monitoring on a computer your program will run much, much slower - than if it is being monitored or totally disconnected (battery). - - You can avoid this behavior by :ref:`deciphering the port status - ` using the DTR and RTS line status; the behavior - of these control lines is platform dependent and we no longer - interpret them by default. - The Maple STM32 microprocessor includes a dedicated USB peripheral which can be configured to act as a general USB slave device with transfer rates up to 12Mbps (it unfortunately can't be configured as a @@ -30,152 +15,21 @@ and second, to emulate a regular serial port for use as a terminal (text read/write). The emulated terminal is relatively slow and inefficient; it is best -for transferring data at regular serial speeds (kilobaud). Users -requiring faster data transfer should consider implementing a -different communications protocol; the Maple could be reprogrammed to -appear as a mass storage device (thumb drive), human interface device -(mouse or keyboard), microphone, or any other USB device. +for transferring data at regular serial speeds (kilobaud). Library +support for accessing the emulated terminal is available at the +:ref:`SerialUSB ` reference. -The SerialUSB channel is also used as part of the auto-reset feature -of the IDE to program the board (on Maple Rev3): a :ref:`magic +The SerialUSB channel is used as part of the auto-reset feature of the +IDE to program the board on Maple Rev 3 and Rev 5: a :ref:`magic sequence of control line toggles and transmitted data ` causes the Maple to reset itself and enter bootloader mode. As an unfortunate consequence, the auto-reset will not work if the IDE can not access the serial port, either due to a conflict with another program (serial monitor) or because the interface has been disabled from the Maple side (through -``SerialUSB.end()``). - -Function Reference ------------------- - -``SerialUSB.print(...)``/\ ``SerialUSB.println(...)`` - - Writes data into the port buffer to be transmitted as soon as - possible. Accepts strings (``char*``). If a raw integer is passed - the corresponding ASCII character will be transmitted; to print - out a number in human readable form add a second parameter with - the base system. For example, to print out the decimal number - "1234", use ``SerialUSB.print(1234, DEC)``; to print out the - binary number "1001", use ``SerialUSB.print(9, BIN)``. - -.. _usb-write: - -``SerialUSB.write(bytes)`` - - ``write`` is a lower-level function that writes bytes directly - into the buffer. :ref:`print() ` often calls this - function dozens of times to write out a single formatted number; - user code can optimize raw data speed by calling this function - with 64-byte chunks instead. - -``SerialUSB.available()``/\ ``SerialUSB.read()`` - - ``SerialUSB.read()`` will return the next available character - (``byte``) that has been received over the port. - ``SerialUSB.available()`` returns how many such bytes are actually - available. If there is no data, ``read`` will block/fail, so the - usual program structure is to poll with ``available`` and only - ``read`` if there are data to read. - -``SerialUSB.read(buffer, length)`` - - An alternative version of ``SerialUSB.read``; will write the next - ``length`` available characters into the array ``buffer``. - -``SerialUSB.pending()`` - - Returns the number of bytes waiting in the transmit - buffer. Usercode can use this to prevent any blocking/waiting when - using the direct :ref:`write ` functions, or to check - if data was actually requested/received by the host. - -``SerialUSB.getRTS()`` - - Returns the state (1 or 0) of the virtual RTS ("ready to send") - line. This can be used to guess if the USB host is actively - waiting for data (e.g., if a serial monitor program is running) or - just "configured" (i.e., the virtual serial port is configured, - but no program is reading data). - -``SerialUSB.getDTR()`` - - Returns the state (1 or 0) of the virtual DTR ("data terminal - ready") line. This can be used to guess if the USB host is - actively waiting for data (e.g., if a serial monitor program is - running) or just "configured" (i.e., the virtual serial port is - configured, but no program is reading data). - -.. TODO deprecate crap out of above two functions; write a sane API - -``SerialUSB.isConnected()`` - - Returns 1 if the USB host is connected and the virtual serial - interface is initialized (though not necessarily active). - Otherwise, returns 0. - -``SerialUSB.end()``/\ ``SerialUSB.begin()`` - - The USB peripheral is enabled by default so that the auto-reset - feature will work, but it can be disabled/restarted at any time - with the ``SerialUSB.end()`` and ``SerialUSB.begin()`` - functions. - - ``SerialUSB.end()`` is a relatively hard shutdown, similar to - unplugging the board; this may crash or confuse any programs - running host-side. Note that calling this function will require - the Maple to be put into :ref:`perpetual bootloader mode - ` before another program can - be uploaded onto it, unless ``SerialUSB.begin()`` is called before - the upload is attempted. - - It's probably wise to wait a few seconds between calls to - ``SerialUSB.end()`` and ``SerialUSB.begin()`` (or to - ``SerialUSB.begin()`` and ``SerialUSB.print()``) to let the - computer reconfigure. - -Code Examples -------------- - -.. _usb-safe-print: - -Safe Print -^^^^^^^^^^ - -This function should run smoothly and not block; the LED should blink -at roughly the same speed whether being monitored, running from -battery, or connected but not monitored. You may need to experiment -with the DTR/RTS logic for your platform and device configuration. :: - - #define LED_PIN 13 - - void setup() { - /* Set up the LED to blink */ - pinMode(LED_PIN, OUTPUT); - } - - void loop() { - // LED will stay off if we are disconnected; - // will blink quickly if USB is unplugged (battery etc) - if(SerialUSB.isConnected()) { - digitalWrite(LED_PIN, 1); - } - delay(100); - - // If this logic fails to detect if bytes are going to - // be read by the USB host, then the println() will fully - // many times, causing a very slow LED blink. - // If the characters are printed and read, the blink will - // only slow a small amount when "really" connected, and fast - // when the virtual port is only configured. - if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { - for(int i=0; i<10; i++) { - SerialUSB.println(123456,BIN); - } - } - digitalWrite(LED_PIN, 0); - delay(100); - } +:ref:`SerialUSB.end() `). A solution to the +second problem is the use of :ref:`perpetual bootloader mode +`. Recommended Reading ------------------- diff --git a/libmaple/usb/usb_callbacks.c b/libmaple/usb/usb_callbacks.c index 4cdaf73..250acea 100644 --- a/libmaple/usb/usb_callbacks.c +++ b/libmaple/usb/usb_callbacks.c @@ -8,19 +8,19 @@ #include "usb_hardware.h" ONE_DESCRIPTOR Device_Descriptor = { - (uint8*)&usbVcomDescriptor_Device, - sizeof(USB_Descriptor_Device) + (uint8*)&usbVcomDescriptor_Device, + sizeof(USB_Descriptor_Device) }; ONE_DESCRIPTOR Config_Descriptor = { - (uint8*)&usbVcomDescriptor_Config, - 0x43//sizeof(USB_Descriptor_Config) + (uint8*)&usbVcomDescriptor_Config, + 0x43//sizeof(USB_Descriptor_Config) }; ONE_DESCRIPTOR String_Descriptor[3] = { - {(uint8*)&usbVcomDescriptor_LangID, USB_DESCRIPTOR_STRING_LEN(1)}, - {(uint8*)&usbVcomDescriptor_iManufacturer,USB_DESCRIPTOR_STRING_LEN(8)}, - {(uint8*)&usbVcomDescriptor_iProduct, USB_DESCRIPTOR_STRING_LEN(8)} + {(uint8*)&usbVcomDescriptor_LangID, USB_DESCRIPTOR_STRING_LEN(1)}, + {(uint8*)&usbVcomDescriptor_iManufacturer,USB_DESCRIPTOR_STRING_LEN(8)}, + {(uint8*)&usbVcomDescriptor_iProduct, USB_DESCRIPTOR_STRING_LEN(8)} }; uint8 last_request = 0; @@ -42,12 +42,12 @@ RESET_STATE reset_state = DTR_UNSET; uint8 line_dtr_rts = 0; void vcomDataTxCb(void) { - /* do whatever after data has been sent to host */ + /* do whatever after data has been sent to host */ - /* allows usbSendBytes to stop blocking */ + /* allows usbSendBytes to stop blocking */ - countTx = 0; + countTx = 0; } /* we could get arbitrarily complicated here for speed purposes @@ -56,296 +56,296 @@ void vcomDataTxCb(void) { in the fifo. this number will be reincremented after calls to usbReceiveBytes */ void vcomDataRxCb(void) { - /* do whatever after data has been received from host */ - - /* setEPRxCount on the previous cycle should garuntee - we havnt received more bytes than we can fit */ - uint8 newBytes = GetEPRxCount(VCOM_RX_ENDP); - /* assert (newBytes <= maxNewBytes); */ - - /* todo, not checking very carefully for edge cases. USUALLY, - if we emit the reset pulse and send 4 bytes, then newBytes - should be 4. But its POSSIBLE that this would be violated - in some cases */ - - /* magic number, {0x31, 0x45, 0x41, 0x46} is "1EAF" */ - char chkBuf[4]; - char cmpBuf[4] = {0x31, 0x45, 0x41, 0x46}; - if (reset_state == DTR_NEGEDGE) { - reset_state = DTR_LOW; - - if (newBytes >= 4) { - unsigned int target = (unsigned int)usbWaitReset | 0x1; - - PMAToUserBufferCopy(chkBuf,VCOM_RX_ADDR,4); - - int i; - USB_Bool cmpMatch = TRUE; - for (i=0; i<4; i++) { - if (chkBuf[i] != cmpBuf[i]) { - cmpMatch = FALSE; - } - } - - if (cmpMatch) { - asm volatile("mov r0, %[stack_top] \n\t" // Reset the stack - "mov sp, r0 \n\t" - "mov r0, #1 \n\t" - "mov r1, %[target_addr] \n\t" - "mov r2, %[cpsr] \n\t" - "push {r2} \n\t" // Fake xPSR - "push {r1} \n\t" // Target address for PC - "push {r0} \n\t" // Fake LR - "push {r0} \n\t" // Fake R12 - "push {r0} \n\t" // Fake R3 - "push {r0} \n\t" // Fake R2 - "push {r0} \n\t" // Fake R1 - "push {r0} \n\t" // Fake R0 - "mov lr, %[exc_return] \n\t" - "bx lr" - : - : [stack_top] "r" (STACK_TOP), - [target_addr] "r" (target), - [exc_return] "r" (EXC_RETURN), - [cpsr] "r" (DEFAULT_CPSR) - : "r0", "r1", "r2"); - /* should never get here */ - } + /* do whatever after data has been received from host */ + + /* setEPRxCount on the previous cycle should garuntee + we havnt received more bytes than we can fit */ + uint8 newBytes = GetEPRxCount(VCOM_RX_ENDP); + /* assert (newBytes <= maxNewBytes); */ + + /* todo, not checking very carefully for edge cases. USUALLY, + if we emit the reset pulse and send 4 bytes, then newBytes + should be 4. But its POSSIBLE that this would be violated + in some cases */ + + /* magic number, {0x31, 0x45, 0x41, 0x46} is "1EAF" */ + char chkBuf[4]; + char cmpBuf[4] = {0x31, 0x45, 0x41, 0x46}; + if (reset_state == DTR_NEGEDGE) { + reset_state = DTR_LOW; + + if (newBytes >= 4) { + unsigned int target = (unsigned int)usbWaitReset | 0x1; + + PMAToUserBufferCopy(chkBuf,VCOM_RX_ADDR,4); + + int i; + USB_Bool cmpMatch = TRUE; + for (i=0; i<4; i++) { + if (chkBuf[i] != cmpBuf[i]) { + cmpMatch = FALSE; + } + } + + if (cmpMatch) { + asm volatile("mov r0, %[stack_top] \n\t" // Reset the stack + "mov sp, r0 \n\t" + "mov r0, #1 \n\t" + "mov r1, %[target_addr] \n\t" + "mov r2, %[cpsr] \n\t" + "push {r2} \n\t" // Fake xPSR + "push {r1} \n\t" // Target address for PC + "push {r0} \n\t" // Fake LR + "push {r0} \n\t" // Fake R12 + "push {r0} \n\t" // Fake R3 + "push {r0} \n\t" // Fake R2 + "push {r0} \n\t" // Fake R1 + "push {r0} \n\t" // Fake R0 + "mov lr, %[exc_return] \n\t" + "bx lr" + : + : [stack_top] "r" (STACK_TOP), + [target_addr] "r" (target), + [exc_return] "r" (EXC_RETURN), + [cpsr] "r" (DEFAULT_CPSR) + : "r0", "r1", "r2"); + /* should never get here */ + } + } } - } - if (recvBufIn + newBytes < VCOM_RX_EPSIZE) { - PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,newBytes); - recvBufIn += newBytes; - } else { - /* we have to copy the data in two chunks because we roll over - the edge of the circular buffer */ - uint8 tailBytes = VCOM_RX_EPSIZE - recvBufIn; - uint8 remaining = newBytes - tailBytes; + if (recvBufIn + newBytes < VCOM_RX_EPSIZE) { + PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,newBytes); + recvBufIn += newBytes; + } else { + /* we have to copy the data in two chunks because we roll over + the edge of the circular buffer */ + uint8 tailBytes = VCOM_RX_EPSIZE - recvBufIn; + uint8 remaining = newBytes - tailBytes; - PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,tailBytes); - PMAToUserBufferCopy(&vcomBufferRx[0], VCOM_RX_ADDR,remaining); + PMAToUserBufferCopy(&vcomBufferRx[recvBufIn],VCOM_RX_ADDR,tailBytes); + PMAToUserBufferCopy(&vcomBufferRx[0], VCOM_RX_ADDR,remaining); - recvBufIn = (recvBufIn + newBytes ) % VCOM_RX_EPSIZE; - } + recvBufIn = (recvBufIn + newBytes ) % VCOM_RX_EPSIZE; + } - maxNewBytes -= newBytes; - SetEPRxCount(VCOM_RX_ENDP,maxNewBytes); - SetEPRxValid(VCOM_RX_ENDP); + maxNewBytes -= newBytes; + SetEPRxCount(VCOM_RX_ENDP,maxNewBytes); + SetEPRxValid(VCOM_RX_ENDP); } void vcomManagementCb(void) { -/* unused. This enpoint would callback if we had sent a linestate - changed notification */ + /* unused. This enpoint would callback if we had sent a linestate + changed notification */ } u8* vcomGetSetLineCoding(uint16 length) { - if (length == 0) { - pInformation->Ctrl_Info.Usb_wLength = sizeof(USB_Line_Coding); - } - return (uint8*)&line_coding; + if (length == 0) { + pInformation->Ctrl_Info.Usb_wLength = sizeof(USB_Line_Coding); + } + return (uint8*)&line_coding; } vcomSetLineState(void) { } void usbInit(void) { - pInformation->Current_Configuration = 0; - usbPowerOn(); + pInformation->Current_Configuration = 0; + usbPowerOn(); - _SetISTR(0); - wInterrupt_Mask = ISR_MSK; - _SetCNTR(wInterrupt_Mask); + _SetISTR(0); + wInterrupt_Mask = ISR_MSK; + _SetCNTR(wInterrupt_Mask); - usbEnbISR(); - bDeviceState = UNCONNECTED; + usbEnbISR(); + bDeviceState = UNCONNECTED; } void usbReset(void) { - pInformation->Current_Configuration = 0; + pInformation->Current_Configuration = 0; - /* current feature is current bmAttributes */ - pInformation->Current_Feature = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED); + /* current feature is current bmAttributes */ + pInformation->Current_Feature = (USB_CONFIG_ATTR_BUSPOWERED | USB_CONFIG_ATTR_SELF_POWERED); - _SetBTABLE(USB_BTABLE_ADDRESS); + _SetBTABLE(USB_BTABLE_ADDRESS); - /* setup control endpoint 0 */ - _SetEPType(ENDP0, EP_CONTROL); - _SetEPTxStatus(ENDP0, EP_TX_STALL); - _SetEPRxAddr(ENDP0,VCOM_CTRL_RX_ADDR); - _SetEPTxAddr(ENDP0,VCOM_CTRL_TX_ADDR); - Clear_Status_Out(ENDP0); + /* setup control endpoint 0 */ + _SetEPType(ENDP0, EP_CONTROL); + _SetEPTxStatus(ENDP0, EP_TX_STALL); + _SetEPRxAddr(ENDP0,VCOM_CTRL_RX_ADDR); + _SetEPTxAddr(ENDP0,VCOM_CTRL_TX_ADDR); + Clear_Status_Out(ENDP0); - SetEPRxCount(ENDP0, pProperty->MaxPacketSize); - SetEPRxValid(ENDP0); - - /* setup management endpoint 1 */ - SetEPType (VCOM_NOTIFICATION_ENDP, EP_INTERRUPT); - SetEPTxAddr (VCOM_NOTIFICATION_ENDP, VCOM_NOTIFICATION_ADDR); - SetEPTxStatus (VCOM_NOTIFICATION_ENDP, EP_TX_NAK); - SetEPRxStatus (VCOM_NOTIFICATION_ENDP, EP_RX_DIS); - - /* setup data endpoint OUT (rx) */ -/* SetEPType (VCOM_RX_ENDP, EP_BULK); */ -/* SetEPRxAddr (VCOM_RX_ENDP, VCOM_RX_ADDR); */ -/* SetEPRxCount (VCOM_RX_ENDP, VCOM_RX_EPSIZE); */ -/* // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); */ -/* SetEPRxStatus (VCOM_RX_ENDP, EP_RX_VALID); */ - - SetEPType (3, EP_BULK); - SetEPRxAddr (3, 0x110); - SetEPRxCount (3,64); - // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); - SetEPRxStatus (3, EP_RX_VALID); - - /* setup data endpoint IN (tx) */ - SetEPType (VCOM_TX_ENDP, EP_BULK); - SetEPTxAddr (VCOM_TX_ENDP, VCOM_TX_ADDR); - SetEPTxStatus (VCOM_TX_ENDP, EP_TX_NAK); - SetEPRxStatus (VCOM_TX_ENDP, EP_RX_DIS); - - bDeviceState = ATTACHED; - SetDeviceAddress(0); - - /* reset the rx fifo */ - recvBufIn = 0; - recvBufOut = 0; - maxNewBytes = VCOM_RX_EPSIZE; - countTx = 0; + SetEPRxCount(ENDP0, pProperty->MaxPacketSize); + SetEPRxValid(ENDP0); + + /* setup management endpoint 1 */ + SetEPType (VCOM_NOTIFICATION_ENDP, EP_INTERRUPT); + SetEPTxAddr (VCOM_NOTIFICATION_ENDP, VCOM_NOTIFICATION_ADDR); + SetEPTxStatus (VCOM_NOTIFICATION_ENDP, EP_TX_NAK); + SetEPRxStatus (VCOM_NOTIFICATION_ENDP, EP_RX_DIS); + + /* setup data endpoint OUT (rx) */ + /* SetEPType (VCOM_RX_ENDP, EP_BULK); */ + /* SetEPRxAddr (VCOM_RX_ENDP, VCOM_RX_ADDR); */ + /* SetEPRxCount (VCOM_RX_ENDP, VCOM_RX_EPSIZE); */ + /* // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); */ + /* SetEPRxStatus (VCOM_RX_ENDP, EP_RX_VALID); */ + + SetEPType (3, EP_BULK); + SetEPRxAddr (3, 0x110); + SetEPRxCount (3,64); + // SetEPTxStatus (VCOM_RX_ENDP, EP_TX_DIS); + SetEPRxStatus (3, EP_RX_VALID); + + /* setup data endpoint IN (tx) */ + SetEPType (VCOM_TX_ENDP, EP_BULK); + SetEPTxAddr (VCOM_TX_ENDP, VCOM_TX_ADDR); + SetEPTxStatus (VCOM_TX_ENDP, EP_TX_NAK); + SetEPRxStatus (VCOM_TX_ENDP, EP_RX_DIS); + + bDeviceState = ATTACHED; + SetDeviceAddress(0); + + /* reset the rx fifo */ + recvBufIn = 0; + recvBufOut = 0; + maxNewBytes = VCOM_RX_EPSIZE; + countTx = 0; } void usbStatusIn(void) { - /* adjust the usart line coding - if we wish to couple the CDC line coding - with the real usart port */ + /* adjust the usart line coding + if we wish to couple the CDC line coding + with the real usart port */ } void usbStatusOut(void) { } RESULT usbDataSetup(uint8 request) { - uint8 *(*CopyRoutine)(uint16); - CopyRoutine = NULL; - - if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { - switch (request) { - case (GET_LINE_CODING): - CopyRoutine = vcomGetSetLineCoding; - last_request = GET_LINE_CODING; - break; - case (SET_LINE_CODING): - CopyRoutine = vcomGetSetLineCoding; - last_request = SET_LINE_CODING; - break; - default: break; + uint8 *(*CopyRoutine)(uint16); + CopyRoutine = NULL; + + if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { + switch (request) { + case (GET_LINE_CODING): + CopyRoutine = vcomGetSetLineCoding; + last_request = GET_LINE_CODING; + break; + case (SET_LINE_CODING): + CopyRoutine = vcomGetSetLineCoding; + last_request = SET_LINE_CODING; + break; + default: break; + } } - } - if (CopyRoutine == NULL) { - return USB_UNSUPPORT; - } + if (CopyRoutine == NULL) { + return USB_UNSUPPORT; + } - pInformation->Ctrl_Info.CopyData = CopyRoutine; - pInformation->Ctrl_Info.Usb_wOffset = 0; - (*CopyRoutine)(0); - return USB_SUCCESS; + pInformation->Ctrl_Info.CopyData = CopyRoutine; + pInformation->Ctrl_Info.Usb_wOffset = 0; + (*CopyRoutine)(0); + return USB_SUCCESS; } RESULT usbNoDataSetup(u8 request) { - uint8 new_signal; - - /* we support set com feature but dont handle it */ - if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { - - switch (request) { - case (SET_COMM_FEATURE): - return USB_SUCCESS; - case (SET_CONTROL_LINE_STATE): - /* to reset the board, pull both dtr and rts low - then pulse dtr by itself */ - new_signal = pInformation->USBwValues.bw.bb0 & (CONTROL_LINE_DTR | CONTROL_LINE_RTS); - line_dtr_rts = new_signal & 0x03; - - switch (reset_state) { - /* no default, covered enum */ - case DTR_UNSET: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_HIGH: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_NEGEDGE; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_NEGEDGE: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - - case DTR_LOW: - if ((new_signal & CONTROL_LINE_DTR) == 0 ) { - reset_state = DTR_LOW; - } else { - reset_state = DTR_HIGH; - } - break; - } - - return USB_SUCCESS; + uint8 new_signal; + + /* we support set com feature but dont handle it */ + if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) { + + switch (request) { + case (SET_COMM_FEATURE): + return USB_SUCCESS; + case (SET_CONTROL_LINE_STATE): + /* to reset the board, pull both dtr and rts low + then pulse dtr by itself */ + new_signal = pInformation->USBwValues.bw.bb0 & (CONTROL_LINE_DTR | CONTROL_LINE_RTS); + line_dtr_rts = new_signal & 0x03; + + switch (reset_state) { + /* no default, covered enum */ + case DTR_UNSET: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_HIGH: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_NEGEDGE; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_NEGEDGE: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + + case DTR_LOW: + if ((new_signal & CONTROL_LINE_DTR) == 0 ) { + reset_state = DTR_LOW; + } else { + reset_state = DTR_HIGH; + } + break; + } + + return USB_SUCCESS; + } } - } - return USB_UNSUPPORT; + return USB_UNSUPPORT; } RESULT usbGetInterfaceSetting(uint8 interface, uint8 alt_setting) { - if (alt_setting > 0) { - return USB_UNSUPPORT; - } else if (interface > 1) { - return USB_UNSUPPORT; - } + if (alt_setting > 0) { + return USB_UNSUPPORT; + } else if (interface > 1) { + return USB_UNSUPPORT; + } - return USB_SUCCESS; + return USB_SUCCESS; } u8* usbGetDeviceDescriptor(u16 length) { - return Standard_GetDescriptorData(length, &Device_Descriptor); + return Standard_GetDescriptorData(length, &Device_Descriptor); } u8* usbGetConfigDescriptor(u16 length) { - return Standard_GetDescriptorData(length, &Config_Descriptor); + return Standard_GetDescriptorData(length, &Config_Descriptor); } u8* usbGetStringDescriptor(u16 length) { - uint8 wValue0 = pInformation->USBwValue0; + uint8 wValue0 = pInformation->USBwValue0; - if (wValue0 > 2) { - return NULL; - } - return Standard_GetDescriptorData(length, &String_Descriptor[wValue0]); + if (wValue0 > 2) { + return NULL; + } + return Standard_GetDescriptorData(length, &String_Descriptor[wValue0]); } /* internal callbacks to respond to standard requests */ void usbSetConfiguration(void) { - if (pInformation->Current_Configuration != 0) { - bDeviceState = CONFIGURED; - } + if (pInformation->Current_Configuration != 0) { + bDeviceState = CONFIGURED; + } } void usbSetDeviceAddress(void) { - bDeviceState = ADDRESSED; + bDeviceState = ADDRESSED; } diff --git a/wirish/comm/HardwareSerial.h b/wirish/comm/HardwareSerial.h index 17be49f..fdfc06d 100644 --- a/wirish/comm/HardwareSerial.h +++ b/wirish/comm/HardwareSerial.h @@ -33,6 +33,13 @@ #include "Print.h" +/* NB: this class documented "by hand" (i.e., not using Doxygen) in: + + libmaple/docs/source/lang/serial.rst + + If you alter the public HardwareSerial interface, you must update + the documentation accordingly. */ + class HardwareSerial : public Print { private: uint8 usart_num; @@ -50,7 +57,7 @@ class HardwareSerial : public Print { uint8 rx_pin, uint8 timer_num, uint8 compare_num); - void begin(uint32); + void begin(uint32 baud); void end(void); uint32 available(void); uint8 read(void); diff --git a/wirish/io.h b/wirish/io.h index f01efcb..24f2611 100644 --- a/wirish/io.h +++ b/wirish/io.h @@ -79,8 +79,8 @@ typedef enum WiringPinMode { when it is closer to 0v (ground) it is low. If no external circuit is pulling the pin voltage to high or low, it will tend to randomly oscillate and be very - sensitive to noise (eg a breath of air across the pin - will cause the state to flip). */ + sensitive to noise (e.g., a breath of air across the pin + might cause the state to flip). */ INPUT_ANALOG, /**< This is a special mode for when the pin will be used for analog (not digital) reads. Enables ADC @@ -101,7 +101,7 @@ typedef enum WiringPinMode { the state will be low unless an external device is specifically pulling the pin up to 3.3v, in which case the "gentle" pull down will not - effect the state of the input. */ + affect the state of the input. */ INPUT_FLOATING, /**< Synonym for INPUT. */ -- cgit v1.2.3 From 3b7f16dba295da3a0071564ac284c25dc56e6b18 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Mon, 29 Nov 2010 18:08:04 -0500 Subject: New documentation content is done. Next step is to theme. --- docs/source/_static/img/button-new.png | Bin 0 -> 234 bytes docs/source/_static/img/button-open.png | Bin 0 -> 259 bytes docs/source/_static/img/button-save.png | Bin 0 -> 253 bytes docs/source/_static/img/button-serial-monitor.png | Bin 0 -> 249 bytes docs/source/_static/img/button-stop.png | Bin 0 -> 294 bytes docs/source/_static/img/button-upload.png | Bin 0 -> 291 bytes docs/source/_static/img/button-verify.png | Bin 0 -> 326 bytes docs/source/_static/img/ide-blinky.png | Bin 0 -> 29213 bytes docs/source/_static/img/serial-monitor.png | Bin 0 -> 55975 bytes docs/source/arm-gcc.rst | 72 ++++++--- docs/source/bootloader.rst | 105 +++++++++++- docs/source/compatibility.rst | 187 ++++++++++++++++++---- docs/source/epilog.rst | 53 ------ docs/source/errata.rst | 144 ++++++++++++++++- docs/source/hardware.rst | 24 --- docs/source/ide.rst | 123 +++++++++++++- docs/source/index.rst | 21 ++- docs/source/jtag.rst | 5 +- docs/source/lang/analogwrite.rst | 2 + docs/source/lang/serial.rst | 31 ++-- docs/source/lang/serialusb.rst | 2 + docs/source/lang/unimplemented/stringclass.rst | 3 - docs/source/language.rst | 16 +- docs/source/libmaple-api.rst | 11 -- docs/source/libmaple.rst | 22 +-- docs/source/libraries.rst | 3 + docs/source/maple-quickstart.rst | 4 +- docs/source/pwm.rst | 23 ++- docs/source/troubleshooting.rst | 4 +- docs/source/usart.rst | 80 +-------- 30 files changed, 663 insertions(+), 272 deletions(-) create mode 100644 docs/source/_static/img/button-new.png create mode 100644 docs/source/_static/img/button-open.png create mode 100644 docs/source/_static/img/button-save.png create mode 100644 docs/source/_static/img/button-serial-monitor.png create mode 100644 docs/source/_static/img/button-stop.png create mode 100644 docs/source/_static/img/button-upload.png create mode 100644 docs/source/_static/img/button-verify.png create mode 100644 docs/source/_static/img/ide-blinky.png create mode 100644 docs/source/_static/img/serial-monitor.png delete mode 100644 docs/source/hardware.rst delete mode 100644 docs/source/libmaple-api.rst (limited to 'docs/source/lang') diff --git a/docs/source/_static/img/button-new.png b/docs/source/_static/img/button-new.png new file mode 100644 index 0000000..3fd98be Binary files /dev/null and b/docs/source/_static/img/button-new.png differ diff --git a/docs/source/_static/img/button-open.png b/docs/source/_static/img/button-open.png new file mode 100644 index 0000000..466fc10 Binary files /dev/null and b/docs/source/_static/img/button-open.png differ diff --git a/docs/source/_static/img/button-save.png b/docs/source/_static/img/button-save.png new file mode 100644 index 0000000..7eba286 Binary files /dev/null and b/docs/source/_static/img/button-save.png differ diff --git a/docs/source/_static/img/button-serial-monitor.png b/docs/source/_static/img/button-serial-monitor.png new file mode 100644 index 0000000..aec9741 Binary files /dev/null and b/docs/source/_static/img/button-serial-monitor.png differ diff --git a/docs/source/_static/img/button-stop.png b/docs/source/_static/img/button-stop.png new file mode 100644 index 0000000..4812ae9 Binary files /dev/null and b/docs/source/_static/img/button-stop.png differ diff --git a/docs/source/_static/img/button-upload.png b/docs/source/_static/img/button-upload.png new file mode 100644 index 0000000..0f41eeb Binary files /dev/null and b/docs/source/_static/img/button-upload.png differ diff --git a/docs/source/_static/img/button-verify.png b/docs/source/_static/img/button-verify.png new file mode 100644 index 0000000..95abeb8 Binary files /dev/null and b/docs/source/_static/img/button-verify.png differ diff --git a/docs/source/_static/img/ide-blinky.png b/docs/source/_static/img/ide-blinky.png new file mode 100644 index 0000000..3cccdb4 Binary files /dev/null and b/docs/source/_static/img/ide-blinky.png differ diff --git a/docs/source/_static/img/serial-monitor.png b/docs/source/_static/img/serial-monitor.png new file mode 100644 index 0000000..6162dab Binary files /dev/null and b/docs/source/_static/img/serial-monitor.png differ diff --git a/docs/source/arm-gcc.rst b/docs/source/arm-gcc.rst index 8435a1f..ef745f5 100644 --- a/docs/source/arm-gcc.rst +++ b/docs/source/arm-gcc.rst @@ -1,34 +1,70 @@ .. _arm-gcc: -============ - GCC on ARM -============ +GCC for Maple +============= -This document provides an introduction to using -:command:`arm-none-eabi-gcc`\ , the `CodeSourcery -`_ version of the GNU `GCC -`_ compilers used to compile programs for the -Maple. +This document provides notes on the current usage of +``arm-none-eabi-gcc``, the `CodeSourcery `_ +version of the GNU `GCC `_ compilers used to +compile programs for the Maple. It is not intended as a reference +manual for GCC; such manuals are available `elsewhere +`_. -Stub. +Obtaining ``arm-none-eabi-gcc`` +------------------------------- +Recent versions of ``arm-none-eabi-gcc`` and associated tools are +included with the :ref:`Maple IDE `. -.. _arm-gcc-avr-gcc-diff: +Users who wish to use ``arm-none-eabi-gcc`` in concert with a standard +Unix toolchain are referred to our :ref:`unix-toolchain` reference, +which describes how to set up such an environment. +LeafLabs mirrors some of the more recent versions of the compiler +under http://static.leaflabs.com/pub/codesourcery/\ , including +versions for OS X, win32, and 32-bit Linux. -Differences with AVR-GCC ------------------------- +Compiler Flags Used by libmaple +------------------------------- -people coming from arduino and other Atmel AVR powered microcontroller -platforms are likely to be used to AVR-GCC. our compiler is -different. explain why (stub). +This section documents the flags passed to ``arm-none-eabi-gcc`` by +the :ref:`Maple IDE ` and the default Makefile provided with +:ref:`libmaple `. The information in this section is +subject to change without notice. +.. highlight:: sh + +The following flags are among those passed to the C compiler:: + + -Os -g -mcpu=cortex-m3 -mthumb -march=armv7-m -nostdlib + -ffunction-sections -fdata-sections -Wl,--gc-sections + +The following flags are among those passed to the C++ compiler:: + + -fno-rtti -fno-exceptions -Wall + +The following flags are among those passed to the assembler:: + + -mcpu=cortex-m3 -march=armv7-m -mthumb + +.. highlight:: cpp + +.. _arm-gcc-avr-gcc: + +Switching from AVR-GCC +---------------------- + +This section, which is expected to grow over time, describes +techniques for porting code which uses AVR-GCC features (AVR-GCC is +the compiler used by many Atmel AVR-based microcontroller boards, +including Arduino) for use on the Maple. .. _arm-gcc-attribute-flash: -Tips and Tricks ---------------- +- Replacing ``PROGMEM``: You can direct the linker script provided + with libmaple to store a variable in flash by using + ``__attribute__((section (".USER_FLASH")))``, like so:: -* you can use ``__attribute__`` to stick things in flash (stub) + uint32 arr[] __attribute__((section (".USER_FLASH"))) = {...}; diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index 1cfd17f..d42c050 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -95,8 +95,8 @@ platforms to make everything work this way. .. _bootloader-rev3: -Maple Rev3/Rev5 ---------------- +Maple Rev3/Rev5 - DFU +--------------------- Maple Rev 3 takes a completely different tack, more along the lines of Arduino. In Rev 3, the device resets into bootloader mode, which @@ -143,6 +143,11 @@ bringing up the USB serial. Maple Rev6 - The Serial Bootloader (Tentative) ---------------------------------------------- +.. note:: This section documents an in-progress version of the Maple + bootloader. **No Maples yet sold use this bootloader protocol**. + It has not been yet been publicly released, and its interface is + not stable. + The bootloader in Rev3/Rev5 works well on Linux, acceptably on Mac, but was unsatisfactory on Windows. Unlike the other operating systems, Windows needed to be manually pointed to both the driver to use for @@ -580,4 +585,98 @@ SOFT_RESET response: Flashing A Custom Bootloader ---------------------------- -Stub (flashing a custom bootloader) +The STM32 microprocessor on the Maple comes with a built-in hardware +bootloader that can be used to flash a new (software) bootloader onto +the chip. This section describes how to go about this, using a Maple +Rev 3 or higher (if you have a Maple Rev 1; you don't have a BUT +button, and won't be able to follow these directions. A workaround is +detailed in `this forum posting +`_). + +.. warning:: This section is directed at users wishing to write a + custom bootloader for the Maple, or update their bootloader to a + more recent version. It's generally not necessary to do so, and it + is possible to make a mistake and e.g. render your Maple unable to + communicate with the IDE. Know what you're doing, and proceed with + caution. + +.. highlight:: sh + +Setup +^^^^^ + +In order to follow these instructions, you will need: + +- A binary of the bootloader you want to upload +- Hardware for communicating between the Maple and your computer over + serial. +- `Python `_ version 2.5 or higher, with the + `PySerial `_ library installed. + +**Step 1: Obtain a bootloader binary**. The first thing you'll need to +do is to compile your bootloader binary. Note that an ASCII +representation of the binary, such as the Intel .hex format, will not +suffice. For example, you can run (on a :ref:`suitably configured +system `) the following to obtain a binary of the +bootloader currently used on the Maple:: + + $ git checkout git://github.com/leaflabs/maple-bootloader.git + $ cd maple-bootloader + $ make + $ ls -lh build/maple-boot.bin # this is the compiled bootloader binary + +**Step 2: Connect Maple Serial1 to your computer**. +There are a variety of ways of doing this. We use Sparkfun's `FTDI +breakout boards `_, but you +could use another Maple, an Arduino, etc. -- anything that allows your +computer to communicate with the Maple you want to reprogram over a +serial interface. + +If you do use an FTDI breakout board, first make sure your Maple is +disconnected from an external power source, be it battery, USB, or +barrel jack. Then, connect the FTDI board's TX pin to ``Serial1``\ 's +RX pin (pin 8), FTDI RX to ``Serial1`` TX (pin 7), FTDI ground to +Maple's GND, and its 3.3V pin to Maple's Vin (use the Maple's +silkscreen for help locating these pins). At this point, you're ready +to plug the FTDI board into your computer (via USB). + +The ``Serial1`` pins are documented :ref:`here `. + +**Step 3: Put your Maple into serial bootloader mode**. Do this by +pressing the RESET button, then *while RESET is held down*, pressing +and holding the BUT button. Next, *making sure to keep BUT held +down*, release the RESET button and wait for a few seconds before +releasing BUT. + +**Step 4: Obtain stm32loader.py**. The +script ``stm32loader.py`` is provided with libmaple. If you have set +up the :ref:`Unix toolchain `, it is available in +libmaple/support/stm32loader.py. Otherwise, you can download it +directly from `github +`_ +(click the link, then save the file somewhere on your system). + +Flashing the new Bootloader +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We'll use ``new-boot.bin``, ``ser-port``, and ``stm32loader.py`` to +respectively refer to the absolute paths to the bootloader binary +(from Step 1), the serial port device file or COMM port (from Steps 2 +and 3), and the stm32loader.py script. + +.. highlight:: sh + +You can run :: + + $ python stm32loader.py -h + +to obtain usage information. The incantation for uploading a +bootloader binary ``new-bootloader.bin`` is :: + + $ python stm32loader.py -p ser-port -evw new-boot.bin + +If all goes well, you'll see a bunch of output, then "Verification +OK". If something goes wrong, the `forum`_ is probably your best bet +for obtaining help, with IRC (irc.freenode.net, #leafblowers) being +another option. If all else fails, you can always `contact us +directly`_! diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index 7eb0a8f..a070b42 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -17,10 +17,13 @@ that the Maple uses a 32-bit ARM Cortex-M3 architecture chip while the Arduinos have 8-bit Atmel AVR chips. The different instruction set means that machine code (executable binary programs) is incompatible between the two, and a different compiler (actually just a different -version of `gcc `_) is required. The compiler for -the regular Arduino IDE is the popular :command:`avr-gcc` package; the -compiler for the Maple version of the IDE is CodeSourcery's edition of -gcc for the ARM EABI target (:command:`arm-non-eabi-gcc`). +version of `gcc `_) is required. + +The compiler for the regular Arduino IDE is the popular +:command:`avr-gcc` package; the compiler for the Maple version of the +IDE is CodeSourcery's edition of gcc for the ARM EABI target +(:command:`arm-non-eabi-gcc`). A (preliminary) reference on +:ref:`using arm-none-eabi-gcc ` is available. The bitwidth of the processor means that the Maple can process 32-bit operations (like adding two 32-bit integers) in a single instruction, @@ -45,8 +48,8 @@ numbered separately (A0-A5) from the digital pins (D0\ -D13). The incompatible hardware differences are: -* |i2c| port: on most Arduinos, the |i2c| port is Analog Input - 4 (SDA) and Analog Input 5 (SCL); on the Maple, |i2c| port 1 is D5 +* **I2C port**: on most Arduinos, the |i2c| port is Analog Input 4 + (SDA) and Analog Input 5 (SCL); on the Maple, |i2c| port 1 is D5 (SCL) and D9 (SDA), and |i2c| port 2 is D29 (SCL) and D30 (SDA). It should be possible to skywire, sacrificing signal quality (due to @@ -54,21 +57,22 @@ The incompatible hardware differences are: reasonably well in software. This peripheral could potentially be rerouted internally, but we haven't looked into it. -* :ref:`PWM ` on D10: all the other standard Arduino PWM headers have PWM - functionality on the Maple (D2,D3,D6,D9,D11), but not D10. We did - our best! It may be possible to reroute this peripheral internally - using low level configuration, but we haven't looked in to it. +* :ref:`PWM ` **on D10**: all the other standard Arduino PWM + headers have PWM functionality on the Maple (D2,D3,D6,D9,D11), but + not D10. We did our best! It may be possible to reroute this + peripheral internally using low level configuration, but we haven't + looked in to it. -* No External Voltage Reference: The Arduino has an Aref pin which +* **No External Voltage Reference**: The Arduino has an Aref pin which allows the use of an external ADC voltage reference; the Maple has an extra GPIO pin (14) with PWM capability in this spot, and does not allow an external voltage reference to be configured. -* EEPROM: the Maple does not have any internal EEPROM. This +* **EEPROM**: the Maple does not have any internal EEPROM. This functionality can be emulated with regular persistent flash memory, or with an external EEPROM chip. -* ISP Programming: the Maple does not use an ISP/ICSP bus for +* **ISP Programming**: the Maple does not use an ISP/ICSP bus for debugging; it uses :ref:`JTAG `. @@ -76,14 +80,18 @@ Software Language/Library Changes --------------------------------- With :ref:`a few exceptions `, the entire -Arduino language is supported. However, there are some subtle +Wiring/Arduino language is supported. However, there are some subtle differences, most of which are improvements: -* 32-bit integers: many standard functions either expect or return +* **32-bit integers**: many standard functions either expect or return full 32-bit (4 byte) integer values instead of the regular 16-bit (2 byte) Arduino values. -* :ref:`pinMode() ` types: any :ref:`GPIO ` +* **64-bit doubles**: The :ref:`double ` type is a full + double-precision floating point type on the Maple; it is a + single-precision floating point value on the Arduino. + +* :ref:`pinMode() ` **types**: any :ref:`GPIO ` (including analog pins) can be configured into one of the following modes with a single call to ```pinMode()``: ``OUTPUT``, ``OUTPUT_OPEN_DRAIN``, ``INPUT_FLOATING``, ``INPUT_PULLUP``, @@ -91,41 +99,162 @@ differences, most of which are improvements: be configured as ``INPUT_ANALOG`` and ``PWM`` respectively. See the :ref:`GPIO documentation ` for more information. -* ``Serial1`` syntax: like the `Arduino Mega +* :ref:`Serial port ` **syntax**: like the `Arduino Mega `_, the Maple has multiple :ref:`USART ports `. By default, ``Serial`` is not mapped to any of them, use ``Serial1`` through ``Serial3`` instead. -* 16-bit :ref:`PWM `: Arduino boards support 8-bit PWM, which +* **16-bit** :ref:`PWM `: Arduino boards support 8-bit PWM, which means that calls to :ref:`analogWrite() ` take values between 0 (always off) and 255 (always on). The Maple supports 16-bit PWM, so the corresponding values should be between 0 (always off) and 65535 (always on). -* 12-bit :ref:`ADC `: Arduino boards support 10-bit ADC, which +* **12-bit** :ref:`ADC `: Arduino boards support 10-bit ADC, which means that calls to :ref:`analogRead() ` will return values between 0 and 1023. The Maple supports 12-bit ADC, so the same call will instead return values between 0 and 4095. -Stub (unfinished) +Shield and Device Compatibility +------------------------------- + +.. TODO update for 0.0.9 + +.. list-table:: + :header-rows: 1 + + * - Shield/Device + - Compatible? + - Notes + + * - Ethernet shield + - Yes! + - Tested; no library yet + + * - WiFi Shield + - Yes! + - Tested; no library yet (expected for 0.0.9) + + * - MIDI shield + - Yes! + - Tested; no library yet + + * - XBee shield + - Unknown + - + + * - Bluetooth shield + - Unknown + - + + * - Cellular shield + - Unknown + - + +Library Porting Status +---------------------- + +The state of currently ported Arduino libraries is the +:ref:`libraries`. + +.. TODO update for 0.0.9; update as libraries are ported. + +.. list-table:: + :header-rows: 1 + + * - Library + - Ported? + - Notes + + * - Wire + - Preliminary + - In progress; see :ref:`library reference `. + + * - LiquidCrystal + - **Yes** + - :ref:`Included since IDE 0.0.7 ` + + * - Ethernet + - Not yet + - Planned -.. class:: ported-feature + * - EEPROM + - No + - The Maple doesn't have EEPROM; use flash instead. Perhaps this + library could be emulated? -I am supported! + * - Firmata + - Not yet + - Planned -This should be ordinary + * - Matrix + - Not yet + - Planned -.. class:: non-ported-feature + * - SoftwareSerial + - Not yet + - Planned -I can't do it :( + * - Sprite + - Not yet + - Planned -Also ordinary + * - Stepper + - Not yet + - Planned -.. class:: partly-ported-feature +Sketch and Library Porting HOWTO +-------------------------------- -I sorta work +In addition to the suggestions in this section, you may find many of +the individual :ref:`language reference ` pages useful. As +appropriate, these have "Arduino Compatibility" sections; one good +example is the :ref:`analogWrite() ` +function. -And I am also ordinary +- Check the hardware and header differences above, and see if your + project or shield needs to be modified (eg, add 3.3V level + converters or reroute PWM to header D10). +- Check for ported library functionality. We intend to port all of the + core and popular libraries (like Wire, Ethernet, and the LCD screen + driver), but this task is not yet finished. (Patches are welcome!) +- Check for peripheral conflicts; changing the configuration of timers + and bus speeds for a feature on one header may impact all the + features on that hardware "port". For example, changing the timer + prescaler to do long PWM pulses could impact |i2c| communications on + nearby headers. + +- Rewrite any low-level code. This could potentially be very + difficult, but hopefully you've used the Arduino libraries to + abstract away the registers and other hardware-specific + details. Your sketch probably doesn't have any low-level code; a + library which wraps a particular peripheral very well may. Some + help is available in the :ref:`arm-gcc` reference. + +- Redeclare variable sizes if necessary: generics like ``int`` will + probably work unless you depend on side-effects like rollover. + +- Check every ``pinMode()``: the Maple has more modes for GPIO + pins. For example, make sure to set analog pins to ``INPUT_ANALOG`` + before reading and PWM pins to ``PWM`` before writing. The full set + of pin modes is documented in the :ref:`lang-pinmode` reference. + +- Modify PWM writes: ``pinMode()`` must be set to ``PWM``, the + frequency of the PWM pulse configured, and the duty cycle written + with up to 16-bit resolution. + +- Modify ADC reads: :ref:`lang-analogread` takes the full pin number + (not 0-5) and returns a full 12-bit reading. The ADC pin must have + its ``pinMode()`` set to ``INPUT_ANALOG``. + +- Possibly convert all Serial-over-USB communications to use + :ref:`lang-serialusb` instead of a USART :ref:`serial port + `. The Maple has a dedicated USB port which is not + connected to the USART TX/RX pins in any way. + +- Check timing: Maple clock cycles are just 13.9 nanoseconds, though + the peripheral bus speeds (which limit GPIO output) are clocked + slower. diff --git a/docs/source/epilog.rst b/docs/source/epilog.rst index 4234dd9..e64103c 100644 --- a/docs/source/epilog.rst +++ b/docs/source/epilog.rst @@ -6,56 +6,3 @@ .. _forum: http://forums.leaflabs.com .. _contact: http://leaflabs.com/contact/ .. _contact us directly: http://leaflabs.com/contact/ - -.. Arduino built-in functions - -.. _setup(): http://arduino.cc/en/Reference/Setup -.. _loop(): http://arduino.cc/en/Reference/Loop - -.. _pinMode(): http://arduino.cc/en/Reference/PinMode -.. _digitalWrite(): http://arduino.cc/en/Reference/DigitalWrite -.. _digitalRead(): http://arduino.cc/en/Reference/DigitalRead - -.. _analogReference(): http://arduino.cc/en/Reference/AnalogReference -.. _analogRead(): http://arduino.cc/en/Reference/AnalogRead -.. _analogWrite(): http://arduino.cc/en/Reference/AnalogWrite - -.. _tone(): http://arduino.cc/en/Reference/Tone -.. _noTone(): http://arduino.cc/en/Reference/NoTone -.. _shiftOut(): http://arduino.cc/en/Reference/ShiftOut -.. _pulseIn(): http://arduino.cc/en/Reference/PulseIn - -.. _millis(): http://arduino.cc/en/Reference/Millis -.. _micros(): http://arduino.cc/en/Reference/Micros -.. _delay(): http://arduino.cc/en/Reference/Delay -.. _delayMicroseconds(): http://arduino.cc/en/Reference/DelayMicroseconds - -.. _min(): http://arduino.cc/en/Reference/Min -.. _max(): http://arduino.cc/en/Reference/Max -.. _abs(): http://arduino.cc/en/Reference/Abs -.. _constrain(): http://arduino.cc/en/Reference/Constrain - -.. _map(): http://arduino.cc/en/Reference/Map -.. _pow(): http://arduino.cc/en/Reference/Pow -.. _sqrt(): http://arduino.cc/en/Reference/Sqrt - -.. _sin(): http://arduino.cc/en/Reference/Sin -.. _cos(): http://arduino.cc/en/Reference/Cos -.. _tan(): http://arduino.cc/en/Reference/Tan - -.. _randomSeed(): http://arduino.cc/en/Reference/RandomSeed -.. _random(): http://arduino.cc/en/Reference/Random - -.. _lowByte(): http://arduino.cc/en/Reference/LowByte -.. _highByte(): http://arduino.cc/en/Reference/HighByte -.. _bitRead(): http://arduino.cc/en/Reference/BitRead -.. _bitWrite(): http://arduino.cc/en/Reference/BitWrite -.. _bitSet(): http://arduino.cc/en/Reference/BitSet -.. _bitClear(): http://arduino.cc/en/Reference/BitClear -.. _bit(): http://arduino.cc/en/Reference/Bit - -.. _attachInterrupt(): http://arduino.cc/en/Reference/AttachInterrupt -.. _detachInterrupt(): http://arduino.cc/en/Reference/DetachInterrupt - -.. _interrupts(): http://arduino.cc/en/Reference/Interrupts -.. _noInterrupts(): http://arduino.cc/en/Reference/NoInterrupts diff --git a/docs/source/errata.rst b/docs/source/errata.rst index 4b03513..a3bb66a 100644 --- a/docs/source/errata.rst +++ b/docs/source/errata.rst @@ -7,10 +7,148 @@ This page is a collection of known issues and warnings for each revision of the Maple board. The failure modes aren't design errors, but are easy ways to break or damage your board permanently. For a -list of differences between the Maple and Arduinos, see the page on -:ref:`compatibility `. +list of differences between the Maple and Arduinos, see the +:ref:`compatibility reference `. .. contents:: Contents :local: -Stub. +Maple Rev 5 +----------- + +These boards went on sale in November 2010. They have white buttons, +and "r5" in small print near the "LeafLabs Maple" text next to the +"infinity-leaf" logo, among other changes: + +.. figure:: /_static/img/maple_rev5.png + :align: center + :alt: Maple Rev 5 + +Known issues: + +* **GPIO 39-43 not configured**: this is really more of a software + "TODO" item. Some of the JTAG header pins are numbered 39-43. These + STM32 pins are indeed fully functional :ref:`GPIO ` when the a + :ref:`JTAG ` device is not connected, but we have not enabled + them in software and thus they can not be accessed with the regular + :ref:`lang-pinmode` or :ref:`lang-digitalwrite` functions. + +Potential failure modes: + +* **TTL voltage on non-tolerant pins**: not all header pins are 5V + compatible; connecting certain serial devices in the wrong way could + over voltage the pins. The :ref:`Pin-Mapping Mega Table + ` details which pins are 5V-tolerant. + +Maple Rev 3 +----------- + +This batch of boards went on sale beginning in May 2010. They have a +darker red silkscreen and the "infinity-leaf" logo: + +.. figure:: /_static/img/maple_rev3.png + :align: center + :alt: Maple Rev 3 + +Known issues: + +* **Bad/Sticky Buttons**: a number of Rev 3 boards sold in May-June 2010 + have questionable RESET and BUT buttons. + + What seems to have happened is that the flux remover we used to + clean the boards before shipping eroded the plastic internals, which + resulted in intermittent functionality. All buttons on all shipped + boards did function in testing, but some may have been unreliable in + regular use. + + If you have this problem, we will be happy to ship you new buttons + if you think you can re-solder them yourself, or you can ship us + your board and we will swap out that part. + + For reference, the button part number is KMR211GLFS and the flux + remover we used is "Precision Electronics Cleaner" from RadioShack, + which is "Safe on most plastics" and contains Dipropylene glycol + monomethyl ether, hydrotreated heavy naphtha, dipropylene glycol + methyl ether acetate (really?), and carbon dioxide. + +* **Resistors on pins 0 and 1**: these header pins, which are RX/TX on + USART2 (:ref:`Serial2 `), have resistors in-line + between the STM32 and the headers. These resistors increase the + impedance of the lines for ADC reads and affect the open drain GPIO + functionality of the pins. + + These resistors were accidentally copied over from older Arduino USB + designs, where they appear to protect the USB-Serial converter from + TTL voltage on the headers. + +* **GPIO 39-43 not configured**: this is really more of a software + "TODO" item. Some of the JTAG header pins are numbered 39-43. These + STM32 pins are indeed fully functional :ref:`GPIO ` when the a + :ref:`JTAG ` device is not connected, but we have not enabled + them in software and thus they can not be accessed with the regular + :ref:`lang-pinmode` or :ref:`lang-digitalwrite` functions. + +* **Silkscreen Errors**: the silkscreen on the bottom indicated PWM + functionality on pin 25 and listen the external header GND pin as + number 38 (actually 38 is connected to the BUT button). We manually + sharpied over both of these mistakes. + +* **PWM Marketing Mistake**: We originally sold the Maple advertising + 22 channels of 16-bit hardware PWM; actually the Maple only has 15. + +Potential failure modes: + +* **TTL voltage on non-tolerant pins**: not all header pins are 5V + compatible; connecting certain serial devices in the wrong way could + over voltage the pins. The :ref:`Pin-Mapping Mega Table + ` details which pins are 5V-tolerant. + +Maple Rev 1 +----------- + +This batch of 100 boards shipped in later 2009. They have a red +silkscreen and the logo is a single pixelated leaf: + +.. figure:: /_static/img/maple_rev1.png + :align: center + :alt: Maple Rev 1 + +Known issues: + +* **ADC noise**: generally very high, in particular when the USB port + is being used for communications (including keep-alive pings when + connected to a computer). + + This issue was resolved in Rev 3 with a 4-layer design and a + geometrically isolated ADC V\ :sub:`ref` plane. + +* **Resistors on pins 0 and 1**: these header pins, which are RX/TX on + USART2 (:ref:`Serial2 `), have resistors in-line + between the STM32 and the headers. These resistors increase the + impedance of the lines for ADC reads and affect the open drain GPIO + functionality of the pins. + + These resistors were accidentally copied over from older Arduino USB + designs, where they appear to protect the USB-Serial converter from + TTL voltage on the headers. + +* **Silkscreen Differences**: the pin numbering scheme on Rev 1 is + different from Rev 3, and thus Rev 3 software is difficult to use + with Rev 1 boards. Notably, the analog input bank is labeled A0-A4 + on Rev 1 but 15-20 on Rev 3, and the extra header bank does not have + a pinout table on the bottom. + +* **No BUT Button**: the BUT button, useful for serial bootloading, + was only added in Rev 3. As a workaround, you can directly short the + appropriate MCU pin to Vcc; see `this forum posting + `_. + +* **PWM Marketing Mistake**: We originally sold the Maple advertising + 22 channels of 16-bit hardware PWM; actually the Maple only has 15. + +Potential failure modes: + +* **TTL voltage on non-tolerant pins**: not all header pins are 5v + compatible; connecting certain serial devices in the wrong way could + over voltage the pins. The :ref:`Pin-Mapping Mega Table + ` details which pins are 5V-tolerant. diff --git a/docs/source/hardware.rst b/docs/source/hardware.rst deleted file mode 100644 index 1fa3554..0000000 --- a/docs/source/hardware.rst +++ /dev/null @@ -1,24 +0,0 @@ -.. _hardware: - -================================= - Hardware-Specific Documentation -================================= - -This page indexes the Maple's capabilities for interacting with -external hardware peripherals. For information about a particular -device or protocol, see its individual reference page. - -Individual reference pages: - -.. toctree:: - :maxdepth: 2 - - i2c - pwm - gpio - usb - jtag - adc - spi - usart - timers diff --git a/docs/source/ide.rst b/docs/source/ide.rst index 00dcf03..f38f6cd 100644 --- a/docs/source/ide.rst +++ b/docs/source/ide.rst @@ -1,23 +1,130 @@ .. _ide: -Maple IDE Documentation -======================= +Maple IDE +========= -Stub. +.. figure:: /_static/img/ide-blinky.png + :align: center + :alt: Maple IDE -.. TODO stub sections for all the other buttons, etc. +This page documents the basic functionality of the Maple IDE. +Specifically, it describes the operation of the buttons on the main +toolbar. It is expected to become more comprehensive over time. -.. _ide-serial-monitor: - -Serial Monitor --------------- +The :ref:`Maple Quickstart ` is another source of +information on the IDE; it is especially useful for setting up a +computer for the first time. .. _ide-verify: Verify ------ +.. image:: /_static/img/button-verify.png + :align: left + +Click Verify to compile the current sketch. + +.. _ide-stop: + +Stop +---- + +.. image:: /_static/img/button-stop.png + +Click Stop to cancel a compilation. + +.. _ide-new: + +New +--- + +.. image:: /_static/img/button-new.png + +Click New to begin a fresh sketch. + +.. _ide-open: + +Open +---- + +.. image:: /_static/img/button-open.png + +Click Open to open a new sketch. By default, this will look in you +*sketchbook*, which is a directory on your system which contains all +of your sketches. The default directory of your sketchbook varies by +operating system; you can change it in the IDE preferences. + +.. _ide-save: + +Save +---- + +.. image:: /_static/img/button-save.png + +Click Save to save the currently opened sketch. + .. _ide-upload: Upload ------ + +.. image:: /_static/img/button-upload.png + +Click Upload to send the compiled sketch to your Maple to run. Before +you click Upload, you must have a memory location and serial port +selected. The memory location, either Flash or RAM, determines +whether the compiled sketch binary will be stored on the Maple. You +can choose this using the Tools > Board menu. The serial port +corresponds to the Serial-over-USB connection the Maple has +established with your computer. This looks like "COM1", "COM2", +etc. on Windows, "/dev/tty.usbmodemXXX" on Mac (where "XXX" is some +sequence of letters and numbers), or "/dev/ttyACMXXX" on Linux (again, +where "XXX" is some sequence of letters and numbers). You can choose +a serial port using the Tools > Serial Port menu. + +If you click Upload without having made these choices; The IDE +*should* prompt you to do so. However, if you're trying to upload and +are unsuccessful, make sure you've made choices for both board and +serial port. + +For more help, the upload process is documented in more detail (with +screenshots) in the :ref:`quickstart `. + +If all else fails, try putting your Maple in :ref:`perpetual +bootloader mode ` before +uploading. + +In any case, you can always find us on the `forum`_ or `contact us +directly`_. + +.. _ide-serial-monitor: + +Serial Monitor +-------------- + +.. image:: /_static/img/button-serial-monitor.png + +Click Serial Monitor to open up a communications channel between your +PC and the Maple's :ref:`Serial-over-USB ` +(``SerialUSB``) virtual serial port. + +If the serial monitor is open, any information sent to the computer +(e.g. using :ref:`SerialUSB.println() ` will +be displayed in the large text area. You can send data to the Maple +(to be read with e.g. :ref:`SerialUSB.read() `) +by typing into the small text box and either hitting the Enter key or +pressing the Send button. + +Here is an example serial monitor session with the InteractiveTest +sketch (which you can load in the IDE by choosing menu item File > +Examples > Maple > InteractiveTest): + +.. image:: /_static/img/serial-monitor.png + +This is the result of typing "?" in the text box and clicking Send. + +.. note:: You cannot upload a sketch while the serial monitor is open. + If you click :ref:`Upload ` while the serial monitor is + open, the IDE will close it for you before proceeding with the + upload. diff --git a/docs/source/index.rst b/docs/source/index.rst index 32fa28f..42d1bd0 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -17,7 +17,7 @@ If you're having problems, you might want to visit the `_ to ask questions to the LeafLabs team and other Maple users. Good luck, and have fun! -Table of contents: +General documentation: .. toctree:: :maxdepth: 1 @@ -30,15 +30,24 @@ Table of contents: Library Reference Command-Line Tools and APIs Troubleshooting - Hardware-Specific Documentation External Interrupts Bootloader Known Problems Language Reference Index -Indices and tables -================== +.. _index-hardware: -* :ref:`genindex` -* :ref:`search` +Hardware features: +.. toctree:: + :maxdepth: 1 + + i2c + pwm + gpio + usb + jtag + adc + spi + usart + timers diff --git a/docs/source/jtag.rst b/docs/source/jtag.rst index 9b8ee14..7cfba5f 100644 --- a/docs/source/jtag.rst +++ b/docs/source/jtag.rst @@ -32,7 +32,7 @@ Wiring Diagram JTAG wiring diagram to connect a standard 20-pin ARM JTAG device to the 8-pin JTAG port on the Maple. -.. TODO jtag wiring diagram (above) looks terrible; replace it +.. FIXME jtag wiring diagram (above) looks terrible; replace it The Maple has holes for a 8-pin JTAG header but that header is not soldered on by default. If you know ahead of time that you'll be @@ -56,8 +56,7 @@ Compatible Devices We have had good experience with the `Olimex ARM-USB-OCD `_ device, which costs -about 55 euro plus shipping (as of October 2010). - +about 55 euro plus shipping (as of November 2010). Recommended Reading ------------------- diff --git a/docs/source/lang/analogwrite.rst b/docs/source/lang/analogwrite.rst index 3d05f44..2c50a42 100644 --- a/docs/source/lang/analogwrite.rst +++ b/docs/source/lang/analogwrite.rst @@ -25,6 +25,8 @@ analogWrite() .. contents:: Contents :local: +.. _lang-analogwrite-compatibility: + Arduino Compatibility --------------------- diff --git a/docs/source/lang/serial.rst b/docs/source/lang/serial.rst index f96547d..ca89b31 100644 --- a/docs/source/lang/serial.rst +++ b/docs/source/lang/serial.rst @@ -20,25 +20,24 @@ pins summarized in the following table: :header-rows: 1 * - Serial port - - Pins (TX, RX) + - TX, RX, CK + - CTS, RTS (if present) * - ``Serial1`` - - 7, 8 + - 7, 8, 6 + - * - ``Serial2`` - - 1, 0 + - 1, 0, 10 + - 2, 3 * - ``Serial3`` - - 29, 30 + - 29, 30, 31 + - 32, 33 Thus, if you use a particular serial port, you cannot also use its communication pins for other purposes at the same time. -Unlike the Arduino, none of these serial ports is connected to the USB -port on the Maple board. Thus, to use these pins to communicate with -your personal computer, you will need an additional USB-to-serial -adaptor. - If you want to communicate with the Maple using the provided USB port, use :ref:`SerialUSB ` instead. @@ -60,8 +59,8 @@ means that you can use any of these functions on any of ``Serial1``, .. cpp:class:: HardwareSerial - Serial port class. Predefined instances are Serial1, Serial2, and - Serial3. + Serial port class. Predefined instances are ``Serial1``, + ``Serial2``, and ``Serial3``. .. cpp:function:: HardwareSerial::begin(unsigned int baud) @@ -73,7 +72,7 @@ means that you can use any of these functions on any of ``Serial1``, .. cpp:function:: HardwareSerial::end() Disables the USART associated with this object, allowing any - associated TX and RX pins to be used for other purposes. + associated communication pins to be used for other purposes. .. cpp:function:: unsigned int HardwareSerial::available() @@ -203,6 +202,14 @@ means that you can use any of these functions on any of ``Serial1``, ``println()`` functions is likely to be more useful when printing multiple characters, when formatting numbers for printing, etc. +Arduino Compatibility Note +-------------------------- + +Unlike the Arduino, none of the Maple's serial ports is connected to +the USB port on the Maple board (for that, use :ref:`SerialUSB +`). Thus, to use these pins to communicate with your +personal computer, you will need an additional USB-to-serial adaptor. + .. TODO LATER port these examples over .. Examples diff --git a/docs/source/lang/serialusb.rst b/docs/source/lang/serialusb.rst index 9beee82..af3a7e0 100644 --- a/docs/source/lang/serialusb.rst +++ b/docs/source/lang/serialusb.rst @@ -71,6 +71,8 @@ world!")``. 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 diff --git a/docs/source/lang/unimplemented/stringclass.rst b/docs/source/lang/unimplemented/stringclass.rst index cdd385d..b893e83 100644 --- a/docs/source/lang/unimplemented/stringclass.rst +++ b/docs/source/lang/unimplemented/stringclass.rst @@ -3,7 +3,4 @@ String Class ============ -Stub. - - .. include:: /lang/cc-attribution.txt diff --git a/docs/source/language.rst b/docs/source/language.rst index 350b0c3..463041e 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -222,8 +222,6 @@ more exhaustive index is available at the :ref:`language-index`. Missing Arduino Features ------------------------ -Stub TODO: fill in other missing features - **analogReference()** It is not possible to implement this function on the Maple @@ -252,6 +250,20 @@ Stub TODO: fill in other missing features typedef uint16 word; +Unimplemented Arduino Features +------------------------------ + +The following Wiring/Arduino features are currently unimplemented on +the Maple. However, they will be present in future versions: + +- `interrupts() `_ +- `noInterrupts() `_ +- `noTone() `_ +- `pulseIn() `_ +- `shiftOut() `_ +- `String `_ +- `tone() `_ + .. _our reference page: http://leaflabs.com/docs/external-interrupts/ .. _newlib: http://sourceware.org/newlib/ diff --git a/docs/source/libmaple-api.rst b/docs/source/libmaple-api.rst deleted file mode 100644 index d5b90b6..0000000 --- a/docs/source/libmaple-api.rst +++ /dev/null @@ -1,11 +0,0 @@ -.. _libmaple_api: - -======================== - libmaple API reference -======================== - -This page documents the lower-level features of libmaple, which may be -of use to programmers who don't wish to use the Arduino-style -environment provided by the `Maple IDE `_. - -Stub. diff --git a/docs/source/libmaple.rst b/docs/source/libmaple.rst index b161afb..b76c7c8 100644 --- a/docs/source/libmaple.rst +++ b/docs/source/libmaple.rst @@ -2,19 +2,19 @@ .. _libmaple: -==================== - libmaple Reference -==================== +``libmaple`` Reference +====================== .. image:: /_static/img/libmaple-screenshot-small.png :align: center :alt: libmaple screenshot -`LeafLabs libmaple `_ is the low level library we have developed for for the ARM -Cortex-M3 chips manufactured by STMicroelectronics used in the Maple -boards (the `STM32F103x`_ series). We found the generic peripheral -libraries too painful to build on top of, and reimplemented the -functionality we needed in a simpler (and less general) form. +`LeafLabs libmaple `_ is the low level library we +have developed for for the ARM Cortex-M3 chips manufactured by +STMicroelectronics used in the Maple boards (the `STM32F103x`_ +series). We found the generic peripheral libraries too painful to +build on top of, and reimplemented the functionality we needed in a +simpler (and less general) form. .. _libmaple-libmaple: http://github.com/leaflabs/libmaple .. _STM32F103x: http://www.st.com/stonline/stappl/productcatalog/app?path=/pages/stcom/PcStComPartNumberSearch.searchPartNumber&search=stm32f103 @@ -22,7 +22,7 @@ functionality we needed in a simpler (and less general) form. This library is transparently included in the `Maple IDE `_, but we develop it separately using good old Unix command line tools and release it for advanced -users who might chafe at the “sketch” programming model of the +users who might chafe at the "sketch" programming model of the IDE. Included are some examples, a Makefile, and the compatibility wrappers and code to imitate the Arduino programming library. @@ -36,5 +36,7 @@ wrappers and code to imitate the Arduino programming library. :maxdepth: 2 Unix Toolchain Quickstart - libmaple API reference Guide to using GCC's ARM target + +.. TODO LATER create, style, and host a pure Doxygen libmaple +.. reference docs. This implies determining a stable API. diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 6ecdf07..4c87539 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -7,6 +7,9 @@ Maple Library Reference ========================= +.. Note: if you port an Arduino library and document it here, be sure +.. to update compatibility.rst to reflect that fact. + This page briefly summarizes the Arduino libraries that have been ported to Maple. You can use a library from within a sketch by going to Sketch > Import Library... from within the IDE, then choosing the diff --git a/docs/source/maple-quickstart.rst b/docs/source/maple-quickstart.rst index 6d99a4a..ca902f3 100644 --- a/docs/source/maple-quickstart.rst +++ b/docs/source/maple-quickstart.rst @@ -66,6 +66,8 @@ bottom window, and then a confirmation message will appear: :align: center :alt: Code verified successfully. +.. _maple-quickstart-upload: + Upload that program! -------------------- @@ -127,7 +129,7 @@ OS X: :alt: Board type and serial port for the OS X Then press the "Upload" button to upload your program to the -Maple. +Maple. .. image:: /_static/img/upload-button.png :align: center diff --git a/docs/source/pwm.rst b/docs/source/pwm.rst index 42dc1a5..fd72842 100644 --- a/docs/source/pwm.rst +++ b/docs/source/pwm.rst @@ -1,10 +1,9 @@ .. _pwm: -============================== - Pulse-Width Modulation (PWM) -============================== +PWM +=== -Pulse Width Modulation is a basic technique to create repeated square +Pulse Width Modulation (PWM) is a basic technique to create repeated square waves (digital high/low voltage transitions) of user defined length and duty cycle. It can be used as a way to encode an "analog" signal on a single digital (high/low) line using the time between transitions @@ -42,7 +41,7 @@ to track down exactly which timer *channel* corresponds to each pin. Timer1 | D6,D7,D8 Timer2 | D0,D1,D2,D3 Timer3 | D11,D12,D27,D28 - Timer4 | D5,D9,D14,D24 + Timer4 | D5,D9,D14,D24 Background ---------- @@ -96,11 +95,11 @@ Function Reference ``pinMode(pin_num, PWM)`` - This command is usually called from `setup()`_ to tell the - microcontroller that pin_num should be configured to PWM - output. ``PWM`` implies regular driven OUTPUT; ``PWM_OPEN_DRAIN`` is - also available (see the list of :ref:`GPIO modes ` for - more information). + This command is usually called from :ref:`setup() ` to + tell the microcontroller that pin_num should be configured to PWM + output. ``PWM`` implies regular driven OUTPUT; ``PWM_OPEN_DRAIN`` + is also available (see the list of :ref:`GPIO modes ` + for more information). .. _pwm-pwmwrite: @@ -144,8 +143,8 @@ Function Reference For instance, an 8MHz frequency can be achieved by setting ``prescale`` to 9, since 72MHz / 9 = 8MHz. - This function is normally called once from, `setup()`_, but the - timer can be reconfigured with a new prescaler at any time. + This function is normally called once from, :ref:`lang-setup`, but + the timer can be reconfigured with a new prescaler at any time. * Configure the prescaler and overflow values to generate a timer * reload with a period as close to the given number of diff --git a/docs/source/troubleshooting.rst b/docs/source/troubleshooting.rst index 7b80a3f..0c10d01 100644 --- a/docs/source/troubleshooting.rst +++ b/docs/source/troubleshooting.rst @@ -41,8 +41,8 @@ My 5v peripheral doesn't work! (I2C, SPI, USART, etc) Yup, the Maple is a 3.3v board. You may need to use a level converter. See the :ref:`compatibility `, :ref:`GPIO -`, or other :ref:`hardware specific documentation ` -for more information. +`, or other :ref:`hardware specific documentation +` for more information. The reset and D38/serial buttons don't seem to work reliably! ------------------------------------------------------------- diff --git a/docs/source/usart.rst b/docs/source/usart.rst index 19b054f..c0334a9 100644 --- a/docs/source/usart.rst +++ b/docs/source/usart.rst @@ -10,82 +10,18 @@ Hardware/Circuit Design ----------------------- -The Maple has 3 separate USART devices: ``Serial1``, ``Serial2``, and -``Serial3``. In the most simple use case, the RX and TX pins are used -to send data at a predetermined baudrate with the line voltage level -relative to ground. - -+-----------+--------+-----+ -|Port |Function|Pin | -+===========+========+=====+ -|``Serial1``|TX |D7 | -| | | | -| |RX |D8 | -| | | | -| |CK |D6 | -+-----------+--------+-----+ -|``Serial2``|TX |D1 | -| | | | -| |RX |D0 | -| | | | -| |CK |D10 | -| | | | -| |CTS |D2 | -| | | | -| |RTS |D3 | -+-----------+--------+-----+ -|``Serial3``|TX |D29 | -| | | | -| |RX |D30 | -| | | | -| |CK |D31 | -| | | | -| |CTS |D32 | -| | | | -| |RTS |D33 | -+-----------+--------+-----+ - -.. TODO make above less ugly +The Maple has 3 separate USART devices. In the most simple use case, +the RX and TX pins are used to send data at a predetermined baudrate +with the line voltage level relative to ground. Their usage is +documented in the :ref:`Serial Ports ` language reference +page. Compatible Devices and Specifications ------------------------------------- -We have successfully used the Maple USART ports with an FT232R-based USB-serial converter at up to 115200 baud; higher speeds should certainly be possible. - -Function Reference ------------------- - -In the following, you may replace ``SerialN`` with ``Serial1``, -``Serial2``, or ``Serial3``. - -``SerialN.begin(baudrate)`` - - ``SerialN.begin`` is usually called in `setup()`_ to configure the - baudrate of the given serial port and to set up the header pins - appropriately. It can be called at any time to reconfigure a port - or to change the baudrate. 9600 baud is the generic speed most - widely supported by other devices and terminals. - -``SerialN.print(...)``/\ ``SerialN.println(...)`` - - Writes data into the port buffer to be transmitted as soon as - possible. Accepts strings (``char*``). If a raw integer is - passed, the corresponding ASCII character will be transmitted; to - print out a number in human readable form add a second parameter - with the base system. - - For example, to print out the decimal number '1234' use - ``SerialN.print(1234, DEC)``; to print out the binary number - '1001', use ``SerialN.print(9, BIN)``. - -``SerialN.available()``/\ ``SerialN.read()`` - - ``SerialN.read()`` will return the next unread character that has - been received over the port. ``SerialN.available()`` returns how - many such bytes are available (or zero if none are). If none are - available, ``SerialN.read()`` will block/fail, so the usual - program structure is to poll with ``SerialN.available`` and only - read if a nonzero value is returned. +We have successfully used the Maple USART ports with an FT232R-based +USB-serial converter at up to 115200 baud; higher speeds should +certainly be possible. Recommended Reading ------------------- -- cgit v1.2.3 From a0549b4a15a7093f990fffa4bc1d2d52ec1c16e2 Mon Sep 17 00:00:00 2001 From: Hanna Mendes Levitin Date: Wed, 1 Dec 2010 03:37:07 -0600 Subject: docs, now with style --- docs/source/_static/apilist.html | 5 + docs/source/_static/img/round_logo_32x32.ico | Bin 0 -> 4286 bytes docs/source/_static/img/round_logo_60x60.png | Bin 0 -> 5552 bytes docs/source/conf.py | 45 +++- docs/source/confDefaultGreen.txt | 250 ++++++++++++++++++++++ docs/source/cpp.rst | 13 ++ docs/source/home.rst | 33 +++ docs/source/home.rtf | 43 ++++ docs/source/ide.rst | 16 +- docs/source/index.rst | 61 +++--- docs/source/lang/api/abs.rst | 49 +++++ docs/source/lang/api/analogread.rst | 154 ++++++++++++++ docs/source/lang/api/analogwrite.rst | 169 +++++++++++++++ docs/source/lang/api/attachinterrupt.rst | 102 +++++++++ docs/source/lang/api/bit.rst | 44 ++++ docs/source/lang/api/bitclear.rst | 44 ++++ docs/source/lang/api/bitread.rst | 46 ++++ docs/source/lang/api/bitset.rst | 46 ++++ docs/source/lang/api/bitwrite.rst | 46 ++++ docs/source/lang/api/cc-attribution.txt | 9 + docs/source/lang/api/constants.rst | 304 +++++++++++++++++++++++++++ docs/source/lang/api/constrain.rst | 69 ++++++ docs/source/lang/api/cos.rst | 32 +++ docs/source/lang/api/delay.rst | 72 +++++++ docs/source/lang/api/delaymicroseconds.rst | 65 ++++++ docs/source/lang/api/detachinterrupt.rst | 37 ++++ docs/source/lang/api/digitalread.rst | 58 +++++ docs/source/lang/api/digitalwrite.rst | 68 ++++++ docs/source/lang/api/highbyte.rst | 59 ++++++ docs/source/lang/api/loop.rst | 45 ++++ docs/source/lang/api/lowbyte.rst | 25 +++ docs/source/lang/api/map.rst | 68 ++++++ docs/source/lang/api/max.rst | 65 ++++++ docs/source/lang/api/micros.rst | 46 ++++ docs/source/lang/api/millis.rst | 52 +++++ docs/source/lang/api/min.rst | 66 ++++++ docs/source/lang/api/pinmode.rst | 77 +++++++ docs/source/lang/api/pow.rst | 23 ++ docs/source/lang/api/pwmwrite.rst | 49 +++++ docs/source/lang/api/random.rst | 73 +++++++ docs/source/lang/api/randomseed.rst | 60 ++++++ docs/source/lang/api/serial.rst | 226 ++++++++++++++++++++ docs/source/lang/api/serialusb.rst | 242 +++++++++++++++++++++ docs/source/lang/api/setup.rst | 29 +++ docs/source/lang/api/sin.rst | 32 +++ docs/source/lang/api/sq.rst | 46 ++++ docs/source/lang/api/tan.rst | 31 +++ docs/source/lang/api/volatile.rst | 65 ++++++ docs/source/lang/cpp/arithmetic.rst | 127 +++++++++++ docs/source/lang/cpp/array.rst | 123 +++++++++++ docs/source/lang/cpp/assignment.rst | 70 ++++++ docs/source/lang/cpp/bitshift.rst | 144 +++++++++++++ docs/source/lang/cpp/bitwisemath.rst | 186 ++++++++++++++++ docs/source/lang/cpp/boolean.rst | 91 ++++++++ docs/source/lang/cpp/booleanvariables.rst | 54 +++++ docs/source/lang/cpp/break.rst | 35 +++ docs/source/lang/cpp/byte.rst | 34 +++ docs/source/lang/cpp/bytecast.rst | 50 +++++ docs/source/lang/cpp/cc-attribution.txt | 9 + docs/source/lang/cpp/char.rst | 50 +++++ docs/source/lang/cpp/charcast.rst | 36 ++++ docs/source/lang/cpp/comments.rst | 67 ++++++ docs/source/lang/cpp/comparison.rst | 87 ++++++++ docs/source/lang/cpp/compoundarithmetic.rst | 44 ++++ docs/source/lang/cpp/compoundbitwise.rst | 231 ++++++++++++++++++++ docs/source/lang/cpp/const.rst | 52 +++++ docs/source/lang/cpp/continue.rst | 32 +++ docs/source/lang/cpp/curly-braces.rst | 109 ++++++++++ docs/source/lang/cpp/define.rst | 56 +++++ docs/source/lang/cpp/double.rst | 48 +++++ docs/source/lang/cpp/doublecast.rst | 27 +++ docs/source/lang/cpp/dowhile.rst | 27 +++ docs/source/lang/cpp/enum.rst | 53 +++++ docs/source/lang/cpp/float.rst | 50 +++++ docs/source/lang/cpp/floatcast.rst | 28 +++ docs/source/lang/cpp/for.rst | 142 +++++++++++++ docs/source/lang/cpp/goto.rst | 130 ++++++++++++ docs/source/lang/cpp/if.rst | 121 +++++++++++ docs/source/lang/cpp/include.rst | 72 +++++++ docs/source/lang/cpp/increment.rst | 37 ++++ docs/source/lang/cpp/int.rst | 64 ++++++ docs/source/lang/cpp/intcast.rst | 29 +++ docs/source/lang/cpp/keywords.rst | 205 ++++++++++++++++++ docs/source/lang/cpp/long.rst | 52 +++++ docs/source/lang/cpp/longcast.rst | 27 +++ docs/source/lang/cpp/modulo.rst | 70 ++++++ docs/source/lang/cpp/numeric-types.rst | 79 +++++++ docs/source/lang/cpp/pointer.rst | 31 +++ docs/source/lang/cpp/return.rst | 61 ++++++ docs/source/lang/cpp/scope.rst | 120 +++++++++++ docs/source/lang/cpp/semicolon.rst | 25 +++ docs/source/lang/cpp/sizeof.rst | 64 ++++++ docs/source/lang/cpp/sqrt.rst | 25 +++ docs/source/lang/cpp/static.rst | 57 +++++ docs/source/lang/cpp/string.rst | 128 +++++++++++ docs/source/lang/cpp/switchcase.rst | 118 +++++++++++ docs/source/lang/cpp/unsignedchar.rst | 33 +++ docs/source/lang/cpp/unsignedint.rst | 55 +++++ docs/source/lang/cpp/unsignedlong.rst | 41 ++++ docs/source/lang/cpp/variables.rst | 170 +++++++++++++++ docs/source/lang/cpp/void.rst | 31 +++ docs/source/lang/cpp/while.rst | 38 ++++ docs/source/language-index.rst | 34 ++- docs/source/language.rst | 10 +- docs/source/libraries.rst | 4 +- docs/source/specs.rst | 28 +++ 106 files changed, 7224 insertions(+), 56 deletions(-) create mode 100644 docs/source/_static/apilist.html create mode 100644 docs/source/_static/img/round_logo_32x32.ico create mode 100644 docs/source/_static/img/round_logo_60x60.png create mode 100644 docs/source/confDefaultGreen.txt create mode 100644 docs/source/cpp.rst create mode 100644 docs/source/home.rst create mode 100644 docs/source/home.rtf create mode 100644 docs/source/lang/api/abs.rst create mode 100644 docs/source/lang/api/analogread.rst create mode 100644 docs/source/lang/api/analogwrite.rst create mode 100644 docs/source/lang/api/attachinterrupt.rst create mode 100644 docs/source/lang/api/bit.rst create mode 100644 docs/source/lang/api/bitclear.rst create mode 100644 docs/source/lang/api/bitread.rst create mode 100644 docs/source/lang/api/bitset.rst create mode 100644 docs/source/lang/api/bitwrite.rst create mode 100644 docs/source/lang/api/cc-attribution.txt create mode 100644 docs/source/lang/api/constants.rst create mode 100644 docs/source/lang/api/constrain.rst create mode 100644 docs/source/lang/api/cos.rst create mode 100644 docs/source/lang/api/delay.rst create mode 100644 docs/source/lang/api/delaymicroseconds.rst create mode 100644 docs/source/lang/api/detachinterrupt.rst create mode 100644 docs/source/lang/api/digitalread.rst create mode 100644 docs/source/lang/api/digitalwrite.rst create mode 100644 docs/source/lang/api/highbyte.rst create mode 100644 docs/source/lang/api/loop.rst create mode 100644 docs/source/lang/api/lowbyte.rst create mode 100644 docs/source/lang/api/map.rst create mode 100644 docs/source/lang/api/max.rst create mode 100644 docs/source/lang/api/micros.rst create mode 100644 docs/source/lang/api/millis.rst create mode 100644 docs/source/lang/api/min.rst create mode 100644 docs/source/lang/api/pinmode.rst create mode 100644 docs/source/lang/api/pow.rst create mode 100644 docs/source/lang/api/pwmwrite.rst create mode 100644 docs/source/lang/api/random.rst create mode 100644 docs/source/lang/api/randomseed.rst create mode 100644 docs/source/lang/api/serial.rst create mode 100644 docs/source/lang/api/serialusb.rst create mode 100644 docs/source/lang/api/setup.rst create mode 100644 docs/source/lang/api/sin.rst create mode 100644 docs/source/lang/api/sq.rst create mode 100644 docs/source/lang/api/tan.rst create mode 100644 docs/source/lang/api/volatile.rst create mode 100644 docs/source/lang/cpp/arithmetic.rst create mode 100644 docs/source/lang/cpp/array.rst create mode 100644 docs/source/lang/cpp/assignment.rst create mode 100644 docs/source/lang/cpp/bitshift.rst create mode 100644 docs/source/lang/cpp/bitwisemath.rst create mode 100644 docs/source/lang/cpp/boolean.rst create mode 100644 docs/source/lang/cpp/booleanvariables.rst create mode 100644 docs/source/lang/cpp/break.rst create mode 100644 docs/source/lang/cpp/byte.rst create mode 100644 docs/source/lang/cpp/bytecast.rst create mode 100644 docs/source/lang/cpp/cc-attribution.txt create mode 100644 docs/source/lang/cpp/char.rst create mode 100644 docs/source/lang/cpp/charcast.rst create mode 100644 docs/source/lang/cpp/comments.rst create mode 100644 docs/source/lang/cpp/comparison.rst create mode 100644 docs/source/lang/cpp/compoundarithmetic.rst create mode 100644 docs/source/lang/cpp/compoundbitwise.rst create mode 100644 docs/source/lang/cpp/const.rst create mode 100644 docs/source/lang/cpp/continue.rst create mode 100644 docs/source/lang/cpp/curly-braces.rst create mode 100644 docs/source/lang/cpp/define.rst create mode 100644 docs/source/lang/cpp/double.rst create mode 100644 docs/source/lang/cpp/doublecast.rst create mode 100644 docs/source/lang/cpp/dowhile.rst create mode 100644 docs/source/lang/cpp/enum.rst create mode 100644 docs/source/lang/cpp/float.rst create mode 100644 docs/source/lang/cpp/floatcast.rst create mode 100644 docs/source/lang/cpp/for.rst create mode 100644 docs/source/lang/cpp/goto.rst create mode 100644 docs/source/lang/cpp/if.rst create mode 100644 docs/source/lang/cpp/include.rst create mode 100644 docs/source/lang/cpp/increment.rst create mode 100644 docs/source/lang/cpp/int.rst create mode 100644 docs/source/lang/cpp/intcast.rst create mode 100644 docs/source/lang/cpp/keywords.rst create mode 100644 docs/source/lang/cpp/long.rst create mode 100644 docs/source/lang/cpp/longcast.rst create mode 100644 docs/source/lang/cpp/modulo.rst create mode 100644 docs/source/lang/cpp/numeric-types.rst create mode 100644 docs/source/lang/cpp/pointer.rst create mode 100644 docs/source/lang/cpp/return.rst create mode 100644 docs/source/lang/cpp/scope.rst create mode 100644 docs/source/lang/cpp/semicolon.rst create mode 100644 docs/source/lang/cpp/sizeof.rst create mode 100644 docs/source/lang/cpp/sqrt.rst create mode 100644 docs/source/lang/cpp/static.rst create mode 100644 docs/source/lang/cpp/string.rst create mode 100644 docs/source/lang/cpp/switchcase.rst create mode 100644 docs/source/lang/cpp/unsignedchar.rst create mode 100644 docs/source/lang/cpp/unsignedint.rst create mode 100644 docs/source/lang/cpp/unsignedlong.rst create mode 100644 docs/source/lang/cpp/variables.rst create mode 100644 docs/source/lang/cpp/void.rst create mode 100644 docs/source/lang/cpp/while.rst create mode 100644 docs/source/specs.rst (limited to 'docs/source/lang') diff --git a/docs/source/_static/apilist.html b/docs/source/_static/apilist.html new file mode 100644 index 0000000..e9eb8e3 --- /dev/null +++ b/docs/source/_static/apilist.html @@ -0,0 +1,5 @@ +{# Filename: .static/apilist.html #} +{% set parents = parents.pop() %} +{% if parents %} +{{ parents.title }} +{% endif %} \ No newline at end of file diff --git a/docs/source/_static/img/round_logo_32x32.ico b/docs/source/_static/img/round_logo_32x32.ico new file mode 100644 index 0000000..29fb2bf Binary files /dev/null and b/docs/source/_static/img/round_logo_32x32.ico differ diff --git a/docs/source/_static/img/round_logo_60x60.png b/docs/source/_static/img/round_logo_60x60.png new file mode 100644 index 0000000..dacd36a Binary files /dev/null and b/docs/source/_static/img/round_logo_60x60.png differ diff --git a/docs/source/conf.py b/docs/source/conf.py index 74090f6..755f4ce 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -37,7 +37,7 @@ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'breathe'] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ['_templates', '_static'] # The suffix of source filenames. source_suffix = '.rst' @@ -69,7 +69,7 @@ release = '0.0.9' # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -116,26 +116,46 @@ html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +html_theme_options = { + ## Sidebar placement options + #'stickysidebar' : 'true', + 'rightsidebar' : 'true', + #'collapsiblesidebar' : 'true', + + ## Color + 'sidebarbgcolor' : '#C8C8C8', + 'sidebarlinkcolor' : 'green', + 'sidebartextcolor' : 'black', + #'sidebarbtncolor' : 'black', + 'footerbgcolor' : 'green', + 'relbarbgcolor' : 'green', + 'headlinkcolor' : '#000000', + 'linkcolor' : 'green', + 'visitedlinkcolor' : 'green', + + ## Font + 'headfont' : 'Georgia', + 'bodyfont' : 'Lucidia' +} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +#html_theme_path = ['_static'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +html_title = 'LeafLabs' + project + ' v' + release + ' Documentation' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +html_logo = '_static/img/round_logo_60x60.png' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +html_favicon = '_static/img/round_logo_32x32.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -144,14 +164,19 @@ html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# re-add commented line when custom template for api finished +html_sidebars = { + '**': ['globaltoc.html', 'searchbox.html'], + #'lang/api**':['searchbox.html', 'apilist.html'], +} + # Additional templates that should be rendered to pages, maps page names to # template names. @@ -161,7 +186,7 @@ html_static_path = ['_static'] #html_domain_indices = True # If false, no index is generated. -#html_use_index = True +html_use_index = False # If true, the index is split into individual pages for each letter. #html_split_index = False diff --git a/docs/source/confDefaultGreen.txt b/docs/source/confDefaultGreen.txt new file mode 100644 index 0000000..789a5a0 --- /dev/null +++ b/docs/source/confDefaultGreen.txt @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# +# libmaple documentation build configuration file, created by +# sphinx-quickstart on Thu Oct 7 06:42:30 2010. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# We rely on Michael Jones's breathe as a Doxygen-to-Sphinx bridge. +# See libmaple/docs/README for information on obtaining it and letting +# Sphinx know where it is. +sys.path.append(os.environ['BREATHE_HOME']) + +# -- General configuration ---------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', + 'sphinx.ext.intersphinx', 'sphinx.ext.todo', + 'sphinx.ext.coverage', 'breathe'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Maple' +copyright = u'2010, LeafLabs, LLC' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.0' +# The full version, including alpha/beta/rc tags. +release = '0.0.9' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['epilog.rst', 'prolog.rst'] + +# Included at the end of every source file that is read. +with open('epilog.rst', 'r') as ep: + rst_epilog = ep.read() + +# Included at the beginning of every source file that is read. +with open('prolog.rst', 'r') as pr: + rst_prolog = pr.read() + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# Warn about all references where the target cannot be found. +nitpicky = True + +# -- Options for HTML output -------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'nature' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +html_title = project + ' v' + release + ' Documentation' + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +html_logo = '_static/img/round_logo_60x60.png' + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +html_favicon = '_static/img/round_logo_32x32.ico' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +html_sidebars = { + '**': ['globaltoc.html', 'searchbox.html'], +} + + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +html_use_index = False + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'mapledoc' + + +# -- Options for LaTeX output ------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target file, title, author, documentclass [howto/manual]) +latex_documents = [ + ('index', 'maple.tex', u'Maple Documentation', + u'LeafLabs, LLC', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output ------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'maple', u'Maple Documentation', + [u'LeafLabs, LLC'], 1) +] + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'http://docs.python.org/': None} + + +# -- Options for breathe integration ------------------------------------------ + +breathe_projects = {'libmaple' : os.path.join(os.environ['LIB_MAPLE_HOME'], + 'docs', 'doxygen', 'xml')} + +breathe_default_project = 'libmaple' diff --git a/docs/source/cpp.rst b/docs/source/cpp.rst new file mode 100644 index 0000000..a20578e --- /dev/null +++ b/docs/source/cpp.rst @@ -0,0 +1,13 @@ +.. _cpp: + +============== +C++ for Maple +============== + +.. _index-language-index-cpp-index: + +.. toctree:: + :maxdepth: 1 + :glob: + + lang/cpp/* \ No newline at end of file diff --git a/docs/source/home.rst b/docs/source/home.rst new file mode 100644 index 0000000..9193e90 --- /dev/null +++ b/docs/source/home.rst @@ -0,0 +1,33 @@ +.. _home: + +======================== +Maple Documentation Home +======================== + + +Welcome! + +Maple is a user-friendly prototyping platform developed by LeafLabs in Cambridge, MA. Using Maple, creators with any level of experience can implement beautiful ideas that require the power of a 32-bit processor. For more details about Maple's hardware, please see its :ref:`technical specifications `. To start using your Maple, keep reading. + +.. contents:: Contents + :local: + +.. _home-Getting-Started: + +Getting Started +^^^^^^^^^^^^^^^ + +:ref:`Quickstart ` + +:ref:`Basic Language Reference ` + +:ref:`Full Documentation ` + +.. _home-Problem-Solving: + +Problem Solving +^^^^^^^^^^^^^^^ + +Check out our :ref:`troubleshooting ` and :ref:`known problems` pages. + +If you don't find what you're looking for, hit the `forums `_ to ask the LeafLabs team and other Maple users questions. Good luck, and have fun! diff --git a/docs/source/home.rtf b/docs/source/home.rtf new file mode 100644 index 0000000..dda3ecd --- /dev/null +++ b/docs/source/home.rtf @@ -0,0 +1,43 @@ +.. _home: + +=================== +Maple Documentation +=================== + +.. image:: /_static/img/maple_rev3.jpg + :align: left + +Welcome! + +Maple is a user-friendly prototyping platform developed by LeafLabs in Cambridge, MA. Using Maple, creators with any level of experience can implement beautiful ideas that require the power of a 32-bit processor. + +Based on a ARM Cortex M3 (STFM32F103RB) chip, Maple runs at up to 72 MHz and has 39 digital input/out pins, 16 analog inputs, native full speed USB, 3 USARTs, integrated SPI/I2C support, and is Arduino compatible. + +Getting Started +^^^^^^^^^^^^^^^ +.. sidebar:: Tech Specs + + Microcontroller: STM32 F103RB + Clock Speed: 72 MHz + Operating Voltage: 3.3V + Input Voltage (recommended): 3.0V-12V + Digital I/O Pins: 39 + Analog Input Pins: 16 + Flash Memory: 128 KB + SRAM: 20KB + 64 Channel nested vector interrupt handler (including external interrupt on GPIO’s) + Integrated SPI/I2C and 7 Channels of Direct Memory Access (DMA) + Supplies up to 800mA @ 3.3v + Support for low power and sleep modes (<500uA) + Dimensions: 2.05″x2.1″ + +:ref:`Quickstart ` + +:ref:`Basic Language Reference ` Program your Maple. + +:ref:`Full Documentation ` + +Problem Solving +^^^^^^^^^^^^^^^^^ + +Check out our :ref:`troubleshooting guide ` and :ref:`known problems` page. If you don't find what you're looking for, hit the `forums `_ to ask questions to the LeafLabs team and other Maple users. Good luck, and have fun! \ No newline at end of file diff --git a/docs/source/ide.rst b/docs/source/ide.rst index f38f6cd..b3ef653 100644 --- a/docs/source/ide.rst +++ b/docs/source/ide.rst @@ -3,18 +3,18 @@ Maple IDE ========= -.. figure:: /_static/img/ide-blinky.png - :align: center - :alt: Maple IDE - This page documents the basic functionality of the Maple IDE. Specifically, it describes the operation of the buttons on the main toolbar. It is expected to become more comprehensive over time. -The :ref:`Maple Quickstart ` is another source of +The :ref:`Maple Quickstart ` is another good source of information on the IDE; it is especially useful for setting up a computer for the first time. +.. figure:: /_static/img/ide-blinky.png + :align: center + :alt: Maple IDE + .. _ide-verify: Verify @@ -31,6 +31,7 @@ Stop ---- .. image:: /_static/img/button-stop.png + :align: left Click Stop to cancel a compilation. @@ -40,6 +41,7 @@ New --- .. image:: /_static/img/button-new.png + :align: left Click New to begin a fresh sketch. @@ -49,6 +51,7 @@ Open ---- .. image:: /_static/img/button-open.png + :align: left Click Open to open a new sketch. By default, this will look in you *sketchbook*, which is a directory on your system which contains all @@ -61,6 +64,7 @@ Save ---- .. image:: /_static/img/button-save.png + :align: left Click Save to save the currently opened sketch. @@ -70,6 +74,7 @@ Upload ------ .. image:: /_static/img/button-upload.png + :align: left Click Upload to send the compiled sketch to your Maple to run. Before you click Upload, you must have a memory location and serial port @@ -104,6 +109,7 @@ Serial Monitor -------------- .. image:: /_static/img/button-serial-monitor.png + :align: left Click Serial Monitor to open up a communications channel between your PC and the Maple's :ref:`Serial-over-USB ` diff --git a/docs/source/index.rst b/docs/source/index.rst index 42d1bd0..9fee4d2 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,47 +1,44 @@ .. _index: -Maple Documentation Index -========================= +Maple Documentation Contents +============================= -Welcome! This is the Maple documentation index. It contains -tutorials, quickstarts, and technical documentation. +.. _index-usage: -If you just got a new Maple, you probably want to begin with the -:ref:`quickstart `. You can then move on to reading -about the programming language you use with the Maple at the -:ref:`language reference `. +**Usage Guides:** -If you're having problems, you might want to visit the -:ref:`troubleshooting ` and :ref:`known problems -` pages. Finally, you can always hit the `forums -`_ to ask questions to the LeafLabs team -and other Maple users. Good luck, and have fun! +.. toctree:: + :maxdepth: 2 + + Quickstart + IDE Installation + IDE Anatomy -General documentation: +.. _index-maple-programming: + +**Maple Programming:** .. toctree:: - :maxdepth: 1 + :maxdepth: 2 - Quickstart Guide - IDE Installation Guide - IDE Documentation - Language Reference - Arduino Compatibility Reference - Library Reference - Command-Line Tools and APIs - Troubleshooting + Maple Language + Maple Libraries + Arduino Compatibility External Interrupts + Command-Line Tools & APIs Bootloader + + + Troubleshooting Known Problems - Language Reference Index .. _index-hardware: -Hardware features: +**Hardware Features:** .. toctree:: :maxdepth: 1 - + i2c pwm gpio @@ -51,3 +48,15 @@ Hardware features: spi usart timers + +.. _index-reference: + +**Reference:** + +.. toctree:: + :maxdepth: 1 + + Technical Specifications + Complete Language Index + + diff --git a/docs/source/lang/api/abs.rst b/docs/source/lang/api/abs.rst new file mode 100644 index 0000000..0cc6c23 --- /dev/null +++ b/docs/source/lang/api/abs.rst @@ -0,0 +1,49 @@ +.. 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:: 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..c614aca --- /dev/null +++ b/docs/source/lang/api/analogread.rst @@ -0,0 +1,154 @@ +.. 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 board +contains a 16-channel, 12-bit analog to digital converter. This means +that it will map input voltages between 0 and 3.3 volts into integer +values between 0 and 4095. This yields a resolution between readings +of 3.3V / 4096 units, or 0.8 millivolts. 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`\ ). + +It takes about 0.8 microseconds (.0000008 seconds) to read an analog +input, so the maximum sample rate using this function is approximately +1.3 million samples per second\ [#fsamp]_. + + +Parameter Discussion +-------------------- + +The pin parameter is the number of the analog input pin to read from. +Header pins on the Maple with ADC functionality (marked as "AIN" on +the silkscreen) are: + + 0, 1, 2, 3, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 27, 28 + +Note that pins 3, 27, and 28 are not marked AIN on the silkscreen +for Maple revisions through Rev 5, however, they **do work** as +analog input pins. + +Note +---- + +If the analog input pin is not connected to anything, the value +returned by analogRead() will fluctuate based on a number of factors +(e.g. the values of the other analog inputs, how close your hand is to +the board, etc.) in a seemingly random way. + + +Example +------- + + :: + + + int analogPin = 3; // potentiometer wiper (middle terminal) connected + // to analog pin 3. outside leads to ground and +3.3V + int val = 0; // variable to store the value read + + void setup() { + pinMode(analogPin, INPUT_ANALOG); // set up pin for analog input + SerialUSB.begin(); // set up usb virtual COM port + } + + void loop() { + val = analogRead(analogPin); // read the input pin + SerialUSB.println(val); // 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 ` the value of a Maple readout by 2, like so:: + + // right shift means that the result will be between 0 and 1023; + // be aware that you're losing a lot of precision if you do this + int adc_reading = analogRead(pin) >> 2; + +On the Arduino, the input range and resolution can be changed using +their implementation of `analogReference() +`_\ . Because of the +way its hardware (as of Rev 5) was designed, it's not possible to +implement analogReference on the Maple, so this function doesn't +exist. If your inputs lie in a different voltage range than 0V--3.3V, +you'll need to bring them into that range before using analogRead. +Some basic tools to accomplish this are `resistor dividers +`_ and `Zener diodes +`_\ +. However, opamps and other powered components can also be used if +greater precision is required. + +Finally, On the Arduino, it takes significantly longer to read analog +input: about 100 microseconds (0.0001 s), so the maximum reading rate +is 10,000 times a second. + + +See also +-------- + +- :ref:`ADC note ` +- `(Arduino) Tutorial: Analog Input Pins `_ + + +.. rubric:: Footnotes + +.. [#fsamp] This is based on the current configuration of a 55.5 cycle + sample time, at 72 MHz. However, the minimum sample time *possible* + is 1.5 cycles, leading to a theoretical maximum of approximately 48 + million samples per second (of course, doing anything with the + readings also consumes cycles, so this maximum can't be reached in + practice). + + See the `STM32 Reference Manual `_, §§11.12.4--5 + (pp. 225--226), for more information on the low-level bit twiddling + currently necessary to change the sample time. For examples of how + the ADCs are configured in libmaple, see `adc.h + `_ + and `adc.c + `_\ + . Be aware that changing the sample time has important + consequences related to the impedance of the device connected to + the input pin. If you want to make changes, as a minimum, you + should first read ST's application notes on `ADC modes + `_ and `ADC oversampling + `_. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/analogwrite.rst b/docs/source/lang/api/analogwrite.rst new file mode 100644 index 0000000..01820ef --- /dev/null +++ b/docs/source/lang/api/analogwrite.rst @@ -0,0 +1,169 @@ +.. highlight:: cpp + +.. _lang-analogwrite: + +.. _lang-api-analogwrite: + + +analogWrite() +============= + +.. note:: + + On the Maple, calling analogWrite() is the same as calling + :ref:`lang-pwmwrite`\ ; see that function's documentation for more + information. + + This is because PWM is not true analog output (i.e., is not the + output of a `DAC + `_\ ), so + the function is badly named. For instance, **analogWrite() has + absolutely nothing to do with** :ref:`lang-analogread`\ , which is + potentially confusing. + + The alias of analogWrite() to pwmWrite() is provided (sigh) for the + sake of compatibility with Arduino, but we recommend using + :ref:`lang-pwmwrite` when writing new software, for clarity. + +.. contents:: Contents + :local: + +.. _lang-analogwrite-compatibility: + +Arduino Compatibility +--------------------- + +There are a few important differences between Arduino's `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 ` the argument to +analogWrite into the right range:: + + // Arduino code: + analogWrite(pin, duty); + + // Becomes Maple code: + analogWrite(pin, map(duty, 0, 255, 0, 65535)); + +This will convert values in the range 0-255 to values in the range +0--65,635, which is the correct default range for all of the timers +which control PWM output. See the :ref:`timers reference ` +for more information. + +Another fix is to consult the :ref:`pin mapping mega table +` to find the timer which controls PWM on the +pin you're using, then set that Timer's overflow to 255. Subsequent +calls to analogWrite() should work as on the Arduino (with the same +loss of precision). Note, however, that that affects the overflow for +the **entire timer**, so other code relying on that timer (such as any +:ref:`interrupts ` 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, and 14, or twelve pins in total. That is at least as +*many* PWM pins as any Arduino board, but there are differences in +*which* pins support it. + +* On **most Arduino boards** (those with the ATmega168 or ATmega328; + this includes the **Arduino Uno**), this function works on pins 3, + 5, 6, 9, 10, and 11, or six pins total. Note that these boards + support PWM on pin 10, while Maple does not. + +* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins + total. Note that this board supports PWM on pins 4, 10, and 13, + while the Maple does not. Maple supports PWM on pins 0, 1, and 14, + which the Mega does not, making the total number of pins supporting + PWM equal on these boards. + +* **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, 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 `\ ). + +If your application absolutely requires Arduino's PWM frequency (it +probably doesn't), then the steps are: + +1. Figure out which timer controls PWM output on your pin (\ :ref:`this table ` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. + +2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. + +Be aware that this will change the period for the **entire timer**\ , +and will affect anything else in your program that depends on that +timer. One example is :ref:`interrupts `\ . +You've been :ref:`warned `\ . + +See also +-------- + +- :ref:`Maple PWM tutorial ` + +.. 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:: cc-attribution.txt diff --git a/docs/source/lang/api/attachinterrupt.rst b/docs/source/lang/api/attachinterrupt.rst new file mode 100644 index 0000000..0b8907f --- /dev/null +++ b/docs/source/lang/api/attachinterrupt.rst @@ -0,0 +1,102 @@ +.. highlight:: cpp + +.. _lang-attachinterrupt: + +attachInterrupt() +================= + +Used to specify a function to call when an external interrupt (like an +GPIO changing from LOW to HIGH, a button getting pressed, etc.) +occurs. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: attachInterrupt + +.. doxygenenum:: ExtIntTriggerMode + +.. doxygentypedef:: voidFuncPtr + +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 a few constraints you should be aware of if you're using +more than one interrupt at a time; the :ref:`external-interrupts` page +has the details. + + +Using Interrupts +---------------- + +Interrupts are useful for making things happen automatically in +microcontroller programs, and can help solve timing problems. A +good task for using an interrupt might be reading a rotary encoder, +or monitoring user input. + + +If you wanted to insure that a program always caught the pulses +from a rotary encoder, never missing a pulse, it would make it very +tricky to write a program to do anything else, because the program +would need to constantly poll the sensor lines for the encoder, in +order to catch pulses when they occurred. Other sensors have a +similar interface dynamic too, such as trying to read a sound +sensor that is trying to catch a click, or an infrared slot sensor +(photo-interrupter) trying to catch a coin drop. In all of these +situations, using an interrupt can free the microcontroller to get +some other work done while not missing the doorbell. + + +Example +------- + +:: + + int maple_led_pin = 13; + volatile int state = LOW; // must declare volatile, since it's + // modified within the blink handler + + void setup() { + pinMode(maple_led_pin, OUTPUT); + attachInterrupt(0, blink, CHANGE); + } + + void loop() { + digitalWrite(maple_led_pin, state); + } + + void blink() { + state = !state; + } + + +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:`detachInterrupt ` +- :ref:`external-interrupts` + + + +.. include:: 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..dd5c050 --- /dev/null +++ b/docs/source/lang/api/bit.rst @@ -0,0 +1,44 @@ +.. _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:: 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..941f912 --- /dev/null +++ b/docs/source/lang/api/bitclear.rst @@ -0,0 +1,44 @@ +.. _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 +------- + +None. + + +Arduino Compatibility +--------------------- + +This implementation is compatible with that of Arduino. + + +See also +-------- + +- :ref:`bit `\ () +- :ref:`bitRead `\ () +- :ref:`bitWrite `\ () +- :ref:`bitSet `\ () + + +.. include:: 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..46b4478 --- /dev/null +++ b/docs/source/lang/api/bitread.rst @@ -0,0 +1,46 @@ +.. _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:: 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..ccd76de --- /dev/null +++ b/docs/source/lang/api/bitset.rst @@ -0,0 +1,46 @@ +.. _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:: 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..b3feff2 --- /dev/null +++ b/docs/source/lang/api/bitwrite.rst @@ -0,0 +1,46 @@ +.. 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 version of ``bitWrite()`` is compatible with Arduino. + +See also +-------- + +- :ref:`bit() ` +- :ref:`bitRead() ` +- :ref:`bitSet() ` +- :ref:`bitClear() ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/cc-attribution.txt b/docs/source/lang/api/cc-attribution.txt new file mode 100644 index 0000000..e100140 --- /dev/null +++ b/docs/source/lang/api/cc-attribution.txt @@ -0,0 +1,9 @@ +.. Included in all this directory's files in order to satisfy the +.. Arduino CC Attribution-ShareAlike 3.0 License + +.. admonition:: License and Attribution + + This documentation page was adapted from the `Arduino Reference + Documentation `_\ , which + is released under a `Creative Commons Attribution-ShareAlike 3.0 + License `_. diff --git a/docs/source/lang/api/constants.rst b/docs/source/lang/api/constants.rst new file mode 100644 index 0000000..bc5c894 --- /dev/null +++ b/docs/source/lang/api/constants.rst @@ -0,0 +1,304 @@ +.. _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 `. 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). + + +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() +`), and read with :ref:`digitalRead() +`, the microcontroller will report ``HIGH`` if a +voltage of 3 volts or more is present at the pin. + +.. TODO? Following seems false; check it out sometime, leave out for now: + +.. A pin may also be configured as an ``INPUT`` with ``pinMode()``, and +.. subsequently made ``HIGH`` with :ref:`digitalWrite() +.. `, this will set the internal pullup resistors, +.. which will *steer* the input pin to a HIGH reading unless it is pulled +.. LOW by external circuitry. + +When a pin is configured to ``OUTPUT`` with pinMode, and set to +``HIGH`` with :ref:`digitalWrite() `, the pin is at +3.3 volts. In this state it can *source* current, e.g. light an LED +that is connected through a series resistor to ground, or to another +pin configured as an output and set to ``LOW``. + +.. _lang-constants-low: + +LOW +^^^ + +The meaning of ``LOW`` also has a different meaning depending on +whether a pin is set to ``INPUT`` or ``OUTPUT``. When a pin is +configured as an ``INPUT`` with :ref:`pinMode() `, and +read with :ref:`digitalRead() `, the microcontroller +will report ``LOW`` if a voltage of 2 volts or less is present at the +pin. + +When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to +``LOW`` with :ref:`digitalWrite() `, the +microcontroller will attempt to keep that pin's voltage at 0V. In this +state it can *sink* current, e.g. light an LED that is connected +through a series resistor to +3.3V, or to another pin configured as an +output, and set to ``HIGH``. + +Pin Modes +--------- + +Digital pins can be used in a variety of modes. The basic modes, +``INPUT`` and ``OUTPUT``, have been introduced above. Changing a pin +from ``INPUT`` TO ``OUTPUT`` with :ref:`pinMode() ` +drastically changes the electrical behavior of the pin. + +This section describes the basic digital pin modes (``INPUT`` and +``OUTPUT``) only. For a detailed description of all possible pin +modes, see the :ref:`pinMode() ` reference page. + +.. _lang-constants-input: + +INPUT +^^^^^ + +Maple (STM32) pins configured as ``INPUT`` are said to be in a +high-impedance state. One way of explaining this is that pins +configured as ``INPUT`` make extremely small demands on the circuit +that they are sampling. This makes them useful for reading a sensor, +but not powering an LED. + +.. _lang-constants-output: + +OUTPUT +^^^^^^ + +Pins configured as ``OUTPUT`` with :ref:`pinMode() ` are +said to be in a low-impedance state. This means that they can provide +a substantial amount of current to other circuits. STM32 pins can +source (provide positive current) or sink (provide negative current) +up to 50 mA (milliamps) of current to other devices/circuits. This +makes them useful for powering LEDs, but useless for reading sensors. + +Pins configured as outputs can also be damaged or destroyed if short +circuited to either ground or 3.3V power rails. The amount of current +provided by an STM32 pin is also not enough to power most relays or +motors, and some interface circuitry will be required. + +.. _lang-constants-integers: + +Integer Constants +----------------- + +Integer constants (or more properly speaking, integer *literals*) are +numbers used directly in a sketch, like ``123``. By default, an +integer literal is treated as a (signed) :ref:`int `, but +you can change this with the U and L modifiers (see :ref:`below +`). You can specify negative numbers by +putting a minus sign in front, like ``-123``. + +Normally, integer literals are treated as base 10 (decimal) integers, +but special notation (formatters) may be used to enter numbers in +other bases. These are summarized in the following table: + +.. list-table:: + :header-rows: 1 + + * - Base + - Example + - Formatter + - Comment + + * - 10 (decimal) + - ``123`` + - None + - + + * - 2 (binary) + - ``0b1111011`` + - Leading "0b" + - GCC extension; not standard C++ + + * - 8 (octal) + - ``0173`` + - Leading "0" + - Characters 0-7 valid + + * - 16 (hexadecimal) + - ``0x7B`` + - Leading "0x" + - Characters 0-9, A-F (or a-f) valid + +Binary constants (like ``B1111011``) for values between 0 and 255 are +supported for compatibility with Arduino only. Their use in new +programs is discouraged. + +.. _lang-constants-integers-dec: + +**Decimal** is base 10. This is the common 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`` (this is a :ref:`GCC +` extension; it's not standard C++). + +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 + interpret it in octal. + +.. _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 +may be typed in upper or lower case (a-f). + +For example, the hexadecimal literal ``0x101`` is two hundred fifty +seven: 1×16\ :sup:`2` + 0×16\ :sup:`1` + 1×16\ :sup:`0` = 257. + +The hexadecimal literal ``0xCF2`` is three thousand, three hundred +fourteen: 12×16\ :sup:`2` + 15×16\ :sup:`1` + 2×16\ :sup:`0` = 3314. + +(Remember that in hex, ``A`` means 10, and counting up, ``B``\ =11, so +``C``\ =12 and ``F``\ =15). + +.. _lang-constants-integers-u-l: + +U and L Suffixes +^^^^^^^^^^^^^^^^ + +By default, an integer constant is treated as an :ref:`int +`, with the attendant :ref:`limitations in values +`. To specify an integer constant with another data +type, follow it with: + +- a ``u`` or ``U`` to interpret the constant as an unsigned value. + For example, ``33U`` is an :ref:`unsigned int `. + +- an ``l`` or ``L`` to interpret the constant as a long value. For + example, ``100000L`` is a :ref:`long `. + +- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an + :ref:`unsigned long `. + +.. _lang-constants-fp: + +Floating-Point Constants +------------------------ + +Similar to integer literals, floating point constants (properly: +floating-point *literals*) are used to make code more readable. +Floating point literals are swapped at compile time for the value to +which the expression evaluates. + +A floating point literal is any number which includes a decimal point. +For instance, ``3.0`` is a floating-point literal for the number 3. +By default, a floating-point literal is a :ref:`double `. +In order for the literal to be interpreted as a :ref:`float +`, you can write ``f`` directly after it. For example, +``3.0f`` is a floating-point literal with type ``float``. + +Floating point constants can also be expressed in a variety of +scientific notation. ``E`` and ``e`` are both accepted as valid +exponent indicators. Some examples are given in the following table: + + +.. list-table:: + :header-rows: 1 + + * - Floating-point literal + - 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`` + +See Also +-------- + +- :ref:`pinMode() ` +- :ref:`Boolean Variables ` +- :ref:`#define ` +- :ref:`int ` +- :ref:`unsigned int ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`float ` +- :ref:`double ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/constrain.rst b/docs/source/lang/api/constrain.rst new file mode 100644 index 0000000..d19b61c --- /dev/null +++ b/docs/source/lang/api/constrain.rst @@ -0,0 +1,69 @@ +.. 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() ` +- :ref:`max() ` + + +.. include:: 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..3fbb0af --- /dev/null +++ b/docs/source/lang/api/cos.rst @@ -0,0 +1,32 @@ +.. _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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See also +-------- + + +- :ref:`sin() ` +- :ref:`tan() ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: 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..90ca268 --- /dev/null +++ b/docs/source/lang/api/delay.rst @@ -0,0 +1,72 @@ +.. 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() ` function +and the "Blink Without Delay" sketch cited :ref:`below +`\ . 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() `\ ) values +and pin states are maintained, and :ref:`interrupts +` will work as they should. + + +Example +------- + +:: + + int ledPin = 13; // LED connected to pin 13 + + void setup() { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + +.. _lang-delay-seealso: + +See also +-------- + + +- :ref:`millis() ` +- :ref:`micros() ` +- :ref:`delayMicroseconds() ` +- (Arduino) `Blink Without Delay + `_ example (works + unmodified on Maple) + + +.. include:: 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..24a8286 --- /dev/null +++ b/docs/source/lang/api/delaymicroseconds.rst @@ -0,0 +1,65 @@ +.. 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 ` +- :ref:`micros ` +- :ref:`delay ` + + + + +.. include:: 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..adb2439 --- /dev/null +++ b/docs/source/lang/api/detachinterrupt.rst @@ -0,0 +1,37 @@ +.. _lang-detachinterrupt: + +detachInterrupt() +================= + +Used to disable an interrupt specified with +:ref:`lang-attachinterrupt`\ . + + +Library Documentation +--------------------- + +.. doxygenfunction:: detachInterrupt + +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() ` + + + + +.. include:: 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..3502587 --- /dev/null +++ b/docs/source/lang/api/digitalread.rst @@ -0,0 +1,58 @@ +.. highlight:: cpp + +.. _lang-digitalread: + +digitalRead() +============= + +Reads the value from a specified digital pin, either :ref:`HIGH +` or :ref:`LOW `. + + +Library Documentation +--------------------- + +.. doxygenfunction:: digitalRead + + +Example +------- + +The following example turns the LED on when the button is pressed:: + + int ledPin = 13; // LED connected to Maple pin 13 + int buttonPin = 38; // BUT connected to Maple pin 38 + + void setup() { + pinMode(ledPin, OUTPUT); + pinMode(buttonPin, INPUT); + } + + void loop() { + int val = digitalRead(buttonPin); // reads the input pin + digitalWrite(ledPin, val); + } + +Note +---- + +If the pin isn't connected to anything, ``digitalRead()`` can return +either HIGH or LOW (and this can change in a way that seems random). + +Arduino Compatibility +--------------------- + +The Maple version of ``digitalRead()`` is compatible with Arduino. + + +See Also +-------- + +- :ref:`pinMode ` +- :ref:`digitalWrite ` + + + + + +.. include:: 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..6124d5f --- /dev/null +++ b/docs/source/lang/api/digitalwrite.rst @@ -0,0 +1,68 @@ +.. highlight:: cpp + +.. _lang-digitalwrite: + +digitalWrite() +============== + +Write a :ref:`HIGH ` or a :ref:`LOW +` value to a pin configured as :ref:`OUTPUT +`. + +Library Documentation +--------------------- + +.. doxygenfunction:: digitalWrite + +Discussion +---------- + +If the pin has been configured as an ``OUTPUT`` with :ref:`pinMode() +` its voltage will be set to the corresponding value: +3.3V for ``HIGH``, and 0V (ground) for ``LOW``. + +.. TODO make the following paragraphs true, but refer the reader to +.. INPUT_PULLUP and INPUT_PULLDOWN: + +If the pin is configured as an ``INPUT``, writing a ``HIGH`` value +with ``digitalWrite()`` will enable an internal pullup resistor. +Writing ``LOW`` will disable the pullup. The pullup resistor is enough +to light an LED dimly, so if LEDs appear to work, but very dimly, this +is a likely cause. The remedy is to set the pin to an output with the +:ref:`pinMode() ` function. + +.. note:: Pin 13 is harder to use as an input than the other pins + because it has an LED and resistor soldered to it in series. If you + enable its internal pull-up resistor, it will likely hang at around + 1.1V instead of the expected 3.3V because the onboard LED and + series resistor pull the voltage level down. If you must use pin 13 + as a digital input, use an external pull-down resistor. + +Example +------- + +The following example sets pin 13 to ``HIGH``, makes a one-second-long +delay, sets the pin back to ``LOW``, and delays again, causing a +blinking pattern:: + + + int ledPin = 13; // LED connected to digital pin 13 + + void setup() { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + +See Also +-------- + +- :ref:`pinMode ` +- :ref:`digitalRead ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/highbyte.rst b/docs/source/lang/api/highbyte.rst new file mode 100644 index 0000000..50a1fa6 --- /dev/null +++ b/docs/source/lang/api/highbyte.rst @@ -0,0 +1,59 @@ +.. 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() ` + + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/loop.rst b/docs/source/lang/api/loop.rst new file mode 100644 index 0000000..d8f6183 --- /dev/null +++ b/docs/source/lang/api/loop.rst @@ -0,0 +1,45 @@ +.. highlight:: cpp + +.. _lang-loop: + +loop() +====== + +After creating a :ref:`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() ` + + +.. include:: 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..58e622f --- /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:: 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..79122b3 --- /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() ` 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 `), 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() ` + +.. include:: 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..d38eebe --- /dev/null +++ b/docs/source/lang/api/max.rst @@ -0,0 +1,65 @@ +.. 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() + ` 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 version of ``max()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`min() ` +- :ref:`constrain() ` + + +.. include:: 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..f12976b --- /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() ` +- :ref:`delay() ` +- :ref:`delayMicroseconds() ` + +.. include:: 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..54e4507 --- /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 + Serial.println(time); + + // wait a second so as not to send massive amounts of data + delay(1000); + } + +Tip +--- + +Since the return value for ``millis()`` is an :ref:`unsigned long +`, overflow errors may occur if you try to do math +with other data types, such as :ref:`ints `. + +See Also +-------- + +- :ref:`micros ` +- :ref:`delay ` +- :ref:`delayMicroseconds ` + +.. include:: 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..1245f6f --- /dev/null +++ b/docs/source/lang/api/min.rst @@ -0,0 +1,66 @@ +.. 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() ` +- :ref:`constrain() ` + + +.. include:: 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..b9095da --- /dev/null +++ b/docs/source/lang/api/pinmode.rst @@ -0,0 +1,77 @@ +.. highlight:: cpp + +.. _lang-pinmode: + +pinMode() +========= + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pinMode + +.. 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 +------- + +:: + + int ledPin = 13; // LED connected to digital pin 13 + + void setup() { + pinMode(ledPin, OUTPUT); // sets the digital pin as output + } + + void loop() { + digitalWrite(ledPin, HIGH); // sets the LED on + delay(1000); // waits for a second + digitalWrite(ledPin, LOW); // sets the LED off + delay(1000); // waits for a second + } + +Arduino Compatibility +--------------------- + +.. TODO check out Arduino vs. Maple static discilpline cutoffs to +.. ensure accuracy of following: + +The libmaple implementation of ``pinMode()`` supports the ``INPUT`` +and ``OUTPUT`` modes with semantics identical to that of the Arduino +function (however, be advised that the Maple, as a 3.3V device, will +only drive 3.3V to an ``OUTPUT`` pin that has been set ``HIGH``). + +``INPUT_ANALOG`` and ``PWM`` modes were added because the Maple does +not distinguish between analog and digital pins the same way the +Arduino does. Unlike the Arduino, you **must call** ``pinMode()`` to +set up a pin for these purposes before a call to, e.g., +:ref:`lang-analogRead`. In practice, this should only add a few lines +to your :ref:`lang-setup` function. + +.. TODO verify following before putting it in: + +.. ``OUTPUT_OPEN_DRAIN``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``, and +.. ``PWM_OPEN_DRAIN`` modes represent functionality not currently +.. available on Arduino boards. + +See also +-------- + +- :ref:`lang-constants` +- :ref:`lang-digitalwrite` +- :ref:`lang-digitalread` +- Maple :ref:`GPIO ` reference page + + + +.. include:: 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..4280400 --- /dev/null +++ b/docs/source/lang/api/pow.rst @@ -0,0 +1,23 @@ +.. _lang-pow: + +pow() +===== + +Calculates the value of a number raised to a power. + +Library Documentation +--------------------- + +.. doxygenfunction:: pow + +.. TODO LATER some examples + +See Also +-------- + +- :ref:`sqrt() ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: 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..7a1d51f --- /dev/null +++ b/docs/source/lang/api/pwmwrite.rst @@ -0,0 +1,49 @@ +.. highlight:: cpp + +.. _lang-pwmwrite: + +pwmWrite() +========== + +Writes a :ref:`PWM wave ` to a pin. You can use this to make an +LED get brighter or dimmer, control a servomotor, etc. After a call to +pwmWrite(), the pin will output a steady square wave with the given +duty cycle. You can change the duty cycle later by calling pwmWrite() +again with the same pin and a different duty. + +.. contents:: Contents + :local: + +Library Documentation +--------------------- + +.. doxygenfunction:: pwmWrite + +Example +------- + +Sets the output to the LED proportional to the value read from the +potentiometer:: + + int ledPin = 13; // LED connected to pin 13 (Maple) + int analogPin = 3; // potentiometer connected to analog pin 3 + int val = 0; // variable to store the read value + + void setup() { + pinMode(ledPin, OUTPUT); // sets the LED pin as output + + pinMode(analogPin, PWM); // sets the potentiometer pin as PWM + // output + } + + void loop() { + val = analogRead(analogPin); // read the input pin + + analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, + // analogWrite values from 0 to 65535 + } + +See Also +-------- + +- :ref:`Maple PWM tutorial ` diff --git a/docs/source/lang/api/random.rst b/docs/source/lang/api/random.rst new file mode 100644 index 0000000..f2a9762 --- /dev/null +++ b/docs/source/lang/api/random.rst @@ -0,0 +1,73 @@ +.. highlight:: cpp + +.. _lang-random: + +random() +======== + +The ``random()`` function generates pseudo-random numbers. + +.. TODO keep tracking Sphinx/Breathe's ability to reference overloaded +.. functions so we can use doxygenfunction instead of manually +.. documenting this. + +Library Documentation +--------------------- + +.. 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() ` to differ, on subsequent executions of a +sketch, use :ref:`randomSeed() ` to initialize the +random number generator with a fairly random input, such as +:ref:`analogRead() ` on an unconnected pin. + +Conversely, it can occasionally be useful to use 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 +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +` each time it is run:: + + long randNumber; + + void setup() { + pinMode(0, INPUT_ANALOG); + randomSeed(analogRead(0)); + } + + void loop() { + randNumber = random(300); + SerialUSB.println(randNumber); + + delay(50); + } + +See Also +-------- + +- :ref:`randomSeed() ` + +.. include:: 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..d0a15b7 --- /dev/null +++ b/docs/source/lang/api/randomseed.rst @@ -0,0 +1,60 @@ +.. highlight:: cpp + +.. _lang-randomseed: + +randomSeed() +============ + +``randomSeed()`` initializes the `pseudorandom number generator +`_, +causing it to start at an arbitrary point in its random sequence. +This sequence, while very long, and random, is always the same. + + +Library Documentation +--------------------- + +.. doxygenfunction:: randomSeed + +Discussion +---------- + +If it is important for a sequence of values generated by +:ref:`random() ` to differ, on subsequent executions of a +sketch, use ``randomSeed()`` to initialize the random number generator +with a fairly random input, such as :ref:`analogRead() +` on an unconnected pin. + +Conversely, it can occasionally be useful to use 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 +` reading of pin 0. If this pin is unconnected, the Sketch +should print different values to the :ref:`serial monitor +` each time it is run:: + + long randNumber; + + void setup() { + pinMode(0, INPUT_ANALOG); + randomSeed(analogRead(0)); + } + + void loop() { + randNumber = random(300); + SerialUSB.println(randNumber); + + delay(50); + } + +See Also +-------- + +- :ref:`random() ` + +.. include:: 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..ca89b31 --- /dev/null +++ b/docs/source/lang/api/serial.rst @@ -0,0 +1,226 @@ +.. _lang-serial: + +Serial Ports (``Serial1``, ``Serial2``, ``Serial3``) +==================================================== + +Used for communication between the Maple board and a computer or other +devices. + +.. contents:: Contents + :local: + +Introduction +------------ + +The Maple has three serial ports (also known as a UARTs or USARTs): +``Serial1``, ``Serial2``, and ``Serial3``. They communicate using the +pins summarized in the following table: + +.. list-table:: + :header-rows: 1 + + * - Serial port + - TX, RX, CK + - CTS, RTS (if present) + + * - ``Serial1`` + - 7, 8, 6 + - + + * - ``Serial2`` + - 1, 0, 10 + - 2, 3 + + * - ``Serial3`` + - 29, 30, 31 + - 32, 33 + +Thus, if you use a particular serial port, you cannot also use its +communication pins for other purposes at the same time. + +If you want to communicate with the Maple using the provided USB port, +use :ref:`SerialUSB ` instead. + +To use them to communicate with an external TTL serial device, connect +the TX pin to your device's RX pin, the RX to your device's TX pin, +and the ground of your Maple to your device's ground. + +.. warning:: Don't connect these pins directly to an RS232 serial + port; they operate at +/- 12V and can damage your board. + + +Library Documentation +--------------------- + +All of the ``Serial[1,2,3]`` objects are instances of the +``HardwareSerial`` class, which is documented in this section. (This +means that you can use any of these functions on any of ``Serial1``, +``Serial2``, and ``Serial3``). + +.. cpp:class:: HardwareSerial + + Serial port class. Predefined instances are ``Serial1``, + ``Serial2``, and ``Serial3``. + +.. cpp:function:: HardwareSerial::begin(unsigned int baud) + + Set up a ``HardwareSerial`` object for communications. This method + must be called before attempting to use the ``HardwareSerial`` + object (typically, you call this in your :ref:`setup() + ` function). + +.. cpp:function:: HardwareSerial::end() + + Disables the USART associated with this object, allowing any + associated 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 + `), the call will block until one + becomes available. + +.. cpp:function:: HardwareSerial::flush() + + Removes the contents of the Serial's associated USART RX FIFO. + That is, clears any buffered characters, so that the next character + read is guaranteed to be new. + +.. cpp:function:: HardwareSerial::print(unsigned char b) + + Print the given byte over the USART. + +.. cpp:function:: HardwareSerial::print(char c) + + Print the given character over the USART. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: HardwareSerial::print(const char *str) + + Print the given null-terminated string over the USART. + +.. cpp:function:: HardwareSerial::print(int n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned int n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n) + + Print the argument's digits over the USART, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(unsigned long n) + + Print the argument's digits over the USART, in decimal format. + +.. cpp:function:: HardwareSerial::print(long n, int base) + + Print the digits of ``n`` over the USART, in base ``base`` (which + may be between 2 and 16). The ``base`` value 2 corresponds to + binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. Negative + values will be prefixed with a ``'-'`` character. + +.. cpp:function:: HardwareSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. + +.. _lang-serial-println: + +.. cpp:function:: HardwareSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: HardwareSerial::println() + + Prints ``"\r\n"`` over the USART. + +.. cpp:function:: HardwareSerial::write(unsigned char ch) + + Sends one character over the USART. This function is currently + blocking, although nonblocking writes are a planned future + extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: HardwareSerial::write(const char* str) + + Send the given null-terminated character string over the USART. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: HardwareSerial::write(void *buf, unsigned int size) + + 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. + +Arduino Compatibility Note +-------------------------- + +Unlike the Arduino, none of the Maple's serial ports is connected to +the USB port on the Maple board (for that, use :ref:`SerialUSB +`). Thus, to use these pins to communicate with your +personal computer, you will need an additional USB-to-serial adaptor. + +.. TODO LATER port these examples over + +.. Examples +.. -------- + +.. - `ASCII Table `_ +.. - `Dimmer `_ +.. - `Graph `_ +.. - `Physical Pixel `_ +.. - `Virtual Color Mixer `_ +.. - `Serial Call Response `_ +.. - `Serial Call Response ASCII `_ + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/serialusb.rst b/docs/source/lang/api/serialusb.rst new file mode 100644 index 0000000..af3a7e0 --- /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 `, the Maple's +STM32 microprocessor includes a dedicated USB peripheral. This +peripheral is used to emulate a regular serial port for use as a +terminal (text read/write). The emulated terminal is relatively slow +and inefficient; it is best for transferring data at regular serial +speeds (kilobaud). + +Library access to the emulated serial port is provided through the +``SerialUSB`` object. You can mostly use ``SerialUSB`` as a drop-in +replacement for ``Serial1``, ``Serial2``, and ``Serial3``. + +.. warning:: The ``SerialUSB`` functionality includes a 50 millisecond + timeout for writes, and does not try to detect if the USB host is + "really" connected, or just enumerated and initialized. + + This means that if you have a number of calls to one of the + ``SerialUSB`` ``write()`` or ``print()`` functions in your code, + and you are not monitoring the emulated on a computer, your program + will run much, much slower than if it is being monitored or totally + disconnected (run off of a battery). + + You can avoid this behavior by :ref:`deciphering the port status + using the DTR and RTS line status `; the + behavior of these control lines is platform dependent and we no + longer interpret them by default. + +Library Documentation +--------------------- + +The ``SerialUSB`` object is an instance of the ``USBSerial`` class, +which is documented in this section. This means that you can use any +of these functions by writing +``SerialUSB.functionName(arguments...)``. For example, to print the +message "hello, world!", you can write ``USBSerial.println("hello, +world!")``. + +.. cpp:class:: USBSerial + + Emulated serial-over-USB class. ``SerialUSB`` is the predefined + instance. + +.. cpp:function:: USBSerial::begin() + + Set up the USB peripheral for emulated serial communication. The + peripheral is configured this way by default; calling this function + should only be necessary if you have disabled the peripheral using + ``SerialUSB.end()``. + +.. _lang-serialusb-end: + +.. cpp:function:: USBSerial::end() + + Disables the USB peripheral. + +.. cpp:function:: unsigned int USBSerial::available() + + Returns the number of bytes available for reading. + +.. _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 + `), the call will block until one + becomes available. + +.. cpp:function:: USBSerial::flush() + + Removes the contents of the Serial's associated input buffer. That + is, clears any buffered characters, so that the next character read + is guaranteed to be new. + +.. cpp:function:: USBSerial::print(unsigned char b) + + Print the given byte over the USB connection. + +.. cpp:function:: USBSerial::print(char c) + + Print the given character over the USB connection. 7-bit clean characters + are typically interpreted as ASCII text. + +.. cpp:function:: USBSerial::print(const char *str) + + Print the given null-terminated string over the USB connection. + +.. cpp:function:: USBSerial::print(int n) + + Print the argument's digits over the USB connection, in decimal format. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned int n) + + Print the argument's digits over the USB connection, in decimal format. + +.. cpp:function:: USBSerial::print(long n) + + Print the argument's digits over the USB connection, in decimal + format. Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(unsigned long n) + + Print the argument's digits over the USB connection, in decimal + format. + +.. cpp:function:: USBSerial::print(long n, int base) + + Print the digits of ``n`` over the USB connection, in base ``base`` + (which may be between 2 and 16). The ``base`` value 2 corresponds + to binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. + Negative values will be prefixed with a ``'-'`` character. + +.. cpp:function:: USBSerial::print(double n) + + Print ``n``, accurate to 2 digits after the decimal point. + +.. _lang-serialusb-println: + +.. cpp:function:: USBSerial::println(char c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(const char *c) + + Like ``print(c)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned char b) + + Like ``print(b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned int n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(unsigned long n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(long n, int base) + + Like ``print(n, b)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println(double n) + + Like ``print(n)``, followed by ``"\r\n"``. + +.. cpp:function:: USBSerial::println() + + Prints ``"\r\n"`` over the USB connection. + +.. cpp:function:: USBSerial::write(unsigned char ch) + + Sends one character over the USB connection. This function is + currently blocking, although nonblocking writes are a planned + future extension. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(const char* str) + + Send the given null-terminated character string over the USB + connection. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +.. cpp:function:: USBSerial::write(void *buf, unsigned int size) + + Writes the first ``size`` bytes of ``buf`` over the USB connection. + Each byte is transmitted as an individual character. + + This is a low-level function. One of the ``print()`` or + ``println()`` functions is likely to be more useful when printing + multiple characters, when formatting numbers for printing, etc. + +Examples +-------- + +.. _lang-serialusb-safe-print: + +**Safe print**: This function should run smoothly and not block; the +LED should blink at roughly the same speed whether being monitored, +running from battery, or connected but not monitored. You may need to +experiment with the DTR/RTS logic for your platform and device +configuration. :: + + #define LED_PIN 13 + + void setup() { + /* Set up the LED to blink */ + pinMode(LED_PIN, OUTPUT); + } + + void loop() { + // LED will stay off if we are disconnected; + // will blink quickly if USB is unplugged (battery etc) + if(SerialUSB.isConnected()) { + digitalWrite(LED_PIN, 1); + } + delay(100); + + // If this logic fails to detect if bytes are going to + // be read by the USB host, then the println() will fully + // many times, causing a very slow LED blink. + // If the characters are printed and read, the blink will + // only slow a small amount when "really" connected, and fast + // when the virtual port is only configured. + if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { + for(int i=0; i<10; i++) { + SerialUSB.println(123456,BIN); + } + } + digitalWrite(LED_PIN, 0); + delay(100); + } + diff --git a/docs/source/lang/api/setup.rst b/docs/source/lang/api/setup.rst new file mode 100644 index 0000000..837ddd6 --- /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 `, :ref:`pin modes +`, start using :ref:`libraries `, etc. The +``setup()`` function will only run once, after each power-up or reset +of the Maple board. + +Example +------- + +:: + + int buttonPin = 38; + + void setup() { + pinMode(buttonPin, INPUT); + } + + void loop() { + // ... + } + +.. include:: 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..398b8f3 --- /dev/null +++ b/docs/source/lang/api/sin.rst @@ -0,0 +1,32 @@ +.. _lang-sin: + +sin() +===== + +Calculates the `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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See Also +-------- + +- :ref:`cos ` +- :ref:`tan ` +- :ref:`float ` +- :ref:`double ` + + +.. include:: 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..bd32648 --- /dev/null +++ b/docs/source/lang/api/sq.rst @@ -0,0 +1,46 @@ +.. 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:: 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..4bbe0db --- /dev/null +++ b/docs/source/lang/api/tan.rst @@ -0,0 +1,31 @@ +.. _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 +`_\ , while Arduino's is that of +`avr-libc `_\ . + +See Also +-------- + + +- :ref:`sin ` +- :ref:`cos ` +- :ref:`float ` +- :ref:`double ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/api/volatile.rst b/docs/source/lang/api/volatile.rst new file mode 100644 index 0000000..276bb6a --- /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 `). + +Specifically, it directs the compiler to read the variable's value +fresh every time it is used, rather than "backing up" the value and +reading from its backup copy. (Compilers often "back up" a variable's +value in RAM into a storage location called a *register*; this is done +for efficiency). + +A variable should be declared ``volatile`` whenever its value can be +changed by something beyond the control of the code section in which +it appears, such as an :ref:`external interrupt +`. On the Maple, the only place that this is +likely to occur is in sections of code associated with interrupts. + +Example +------- + +:: + + // 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 ` +- :ref:`lang-attachinterrupt` +- :ref:`lang-detachinterrupt` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/arithmetic.rst b/docs/source/lang/cpp/arithmetic.rst new file mode 100644 index 0000000..91fe22e --- /dev/null +++ b/docs/source/lang/cpp/arithmetic.rst @@ -0,0 +1,127 @@ +.. highlight:: cpp + +.. _lang-arithmetic: + +Arithmetic Operators (``+``, ``-``, ``*``, ``/``) +================================================= + +The operators ``+``, ``-``, ``*``, and ``/`` respectively evaluate to +the sum, difference, product, or quotient (respectively) of the two +operands. The operation is conducted using the data type of the +operands, so, for example, ``9 / 4`` gives ``2`` since 9 and 4 are +:ref:`int variables `. + +This also means that the operation can overflow if the result is +larger than that which can be stored in the data type (e.g. adding 1 +to an :ref:`lang-int` with the value 2,147,483,647 gives +-2,147,483,648). + +.. _lang-arithmetic-typeconversion: + +If the operands are of different types, the "larger" type is used for +the calculation. If one of the numbers (operands) are of the type +**float** or of type **double**, floating point math will be used for +the calculation. + +.. note:: The specifics of these rules are beyond the scope of this + documentation; for more information, see `The C++ Programming + Language `_\ , by Bjarne + Stroustroup, Appendix C, especially §§C.4-C.6, or `this WikiBooks + entry on C++ type conversion + `_. + +.. note:: For more information on how computers represent integers, + see the Wikipedia page on `two's complement + `_. + +.. contents:: Contents + :local: + +Examples +-------- + + :: + + y = y + 3; + x = x - 7; + i = j * 6; + r = r / 5; + + +Syntax +------ + + :: + + result = value1 + value2; + result = value1 - value2; + result = value1 * value2; + result = value1 / value2; + + +Parameters +---------- + +**value1**: any numeric variable or constant + +**value2**: any numeric variable or constant + +Programming Tips +---------------- + +- Know that :ref:`integer constants ` + default to :ref:`int `, so some constant calculations + may overflow (e.g., 200000 * 5000000 will yield a negative result). + +- Choose variable sizes that are large enough to hold the largest + results from your calculations. + +- Know at what point your variable will "roll over" and also what + happens in the other direction e.g. (0 - 1) for unsigned arithmetic, + or (0 - -2,147,483,648) for signed arithmetic. + +- For math that requires fractions, float variables may be used, but + be aware of their drawbacks: large size and slow computation speeds + (the STM32 has no floating point hardware, so all floating point + calculations have to be done in software). + +- Use cast operator, e.g. ``(int)myFloat`` to convert one variable type + to another on the fly. + +Arduino Compatibility +--------------------- + +Since the STM32 processor on the Maple is a 32-bit machine, the int +type overflows at a much higher value on Maple than on Arduino. In +particular, on Maple, ints do not overflow (become negative) until +they reach 2,147,483,648; on the Arduino, they overflow at 32,767. +Because of this, programs running on Maple are much less likely to run +into overflow issues. The following table summarizes the sizes and +ranges of integer datatypes on the Maple (the ranges of long long +types are approximate): + +.. _lang-arithmetic-int-sizes: + +.. csv-table:: + :header: Datatype, Unsigned range, Signed range, Size (bytes) + :widths: 8, 12, 17, 8 + + ``char``, 0 --- 255, -128 --- 127, 1 + ``short``, "0 --- 65,535", "-32,768 --- 32,767", 2 + ``int``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 + ``long long``, "0 --- 1.8*10\ :sup:`19`\ " (approx.), "-9.2*10\ :sup:`18` --- 9.2*10\ :sup:`18` (approx.)", 8 + + +See Also +-------- + +- The individual sizes (in bits) of various available types are + defined in `libmaple_types.h + `_\ + . + +- :ref:`sizeof `\ () + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/array.rst b/docs/source/lang/cpp/array.rst new file mode 100644 index 0000000..30a818f --- /dev/null +++ b/docs/source/lang/cpp/array.rst @@ -0,0 +1,123 @@ +.. highlight:: cpp + +.. _lang-array: + +Arrays +====== + +An array is a collection of variables that are accessed with an index +number. Arrays in the C++ programming language, in which the Maple is +programmed, can be complicated, but using simple arrays is relatively +straightforward. + +.. contents:: Contents + :local: + +Creating (Declaring) an Array +----------------------------- + +All of the methods below are valid ways to create (declare) an +array. :: + + int myInts[6]; + int myPins[] = {2, 4, 8, 3, 6}; + int mySensVals[6] = {2, 4, -8, 3, 2}; + char message[6] = "hello"; + +You can declare an array without initializing it, as with myInts. In +the line referring to myPins, we declare an array without explicitly +choosing a size. The compiler counts the elements and creates an +array of the appropriate size. + +Finally, you can both initialize and size your array, as in +mySensVals. Note that when declaring an array with elements of type +char, one more element than your initialization is required, to hold +the required `null character `_. + + +Accessing an Array +------------------ + + +.. compound:: + + Arrays are **zero indexed**; that is, referring to the array + initialization above, the first element of the array is at index 0, + hence :: + + mySensVals[0] == 2; + mySensVals[1] == 4 + + and so forth. + +It also means that in an array with ten elements, index nine is the +last element. Hence:: + + int myArray[10]={9,3,2,4,3,2,7,8,9,11}; + // myArray[9] contains 11 + // myArray[10] is invalid and contains random information (other memory address) + +For this reason, you should be careful in accessing arrays. Accessing +past the end of an array (using an index number greater than your +declared array size - 1) is reading from memory that is in use for +other purposes. Reading from these locations is probably not going to +do much except yield invalid data. Writing to random memory locations +is definitely a bad idea, and can often lead to unhappy results such +as crashes or program malfunction. This can also be a difficult bug to +track down. + +Unlike Basic or Java, the C compiler does no checking to see if array +access is within legal bounds of the array size that you have +declared. + + +To assign a value to an array +----------------------------- + :: + + mySensVals[0] = 10; + + +To retrieve a value from an array +--------------------------------- + + :: + + x = mySensVals[4]; + + +Arrays and ``for`` Loops +------------------------ + +Arrays are often manipulated inside :ref:`for loops `, where +the loop counter is used as the index for each array element. For +example, to print the elements of an array over the serial port, you +could do something like this:: + + int i; + for (i = 0; i < 5; i = i + 1) { + SerialUSB.println(myPins[i]); + } + + +Example +------- + +For a complete program that demonstrates the use of arrays, see the +Arduino `Knight Rider example +`_\ (which will run +unmodified on the Maple). + +Arduino Compatibility +--------------------- + +Arrays on Maple are identical those on Arduino. + +See also +-------- + +- :ref:`Storing arrays in FLASH memory ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/assignment.rst b/docs/source/lang/cpp/assignment.rst new file mode 100644 index 0000000..b6ad4d5 --- /dev/null +++ b/docs/source/lang/cpp/assignment.rst @@ -0,0 +1,70 @@ +.. highlight:: cpp + +.. _lang-assignment: + +Assignment Operator (``=``) +=========================== + +Stores the value to the right of the equal sign in the variable to +the left of the equal sign. + +The single equal sign in the C++ programming language is called the +assignment operator. It has a different meaning than in algebra +class, where it indicated an equation or equality. The assignment +operator tells the microcontroller to evaluate whatever value or +expression is on the right side of the equal sign, and store it in +the variable to the left of the equal sign [#fgross]_. + + + +Example +------- + +:: + + int sensVal; // declare an integer variable named sensVal + senVal = analogRead(0); // store the (digitized) input voltage at analog pin 0 in SensVal + + + +Programming Tips +---------------- + +The variable on the left side of the assignment operator ( = sign ) +needs to be able to hold the value stored in it. If it is not large +enough to hold a value, the value stored in the variable will be +incorrect. + +Don't confuse the assignment operator [ = ] (single equal sign) +with the comparison operator [ == ] (double equal signs), which +evaluates whether two expressions are equal. + + +Arduino Compatibility +--------------------- + +Assignments on the Maple are identical to those on Arduino. + + + +See Also +-------- + + +- `if (comparison operators) `_ +- `char `_ +- `int `_ +- `long `_ + + +.. rubric:: Footnotes + +.. [#fgross] Experienced C++ programmers know this to be an + oversimplification of what happens when the variable on the left + hand side is an object. See Richard Gillam's wonderful and scary + `The Anatomy of the Assignment Operator + `_ + for more information. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/bitshift.rst b/docs/source/lang/cpp/bitshift.rst new file mode 100644 index 0000000..e1c8de0 --- /dev/null +++ b/docs/source/lang/cpp/bitshift.rst @@ -0,0 +1,144 @@ +.. highlight:: cpp + +.. _lang-bitshift: + +Bit Shift Operators (``<<``, ``>>``) +==================================== + +(Adapted from `The Bit Math Tutorial +`_ in `The Arduino +Playground `_\ ) + +There are two bit shift operators in C++: the left shift operator +``<<`` and the right shift operator ``>>``. These operators cause the +bits in the left operand to be shifted left or right by the number of +positions specified by the right operand. + +More information on bitwise math can be obtained in the Wikipedia +article on `bitwise operations +`_\ , especially the +section on shifts in `C, C++, and Java +`_\ . + + +Syntax +------ + +``some_int << number_of_bits`` + +``some_int >> number_of_bits`` + + +Parameters +---------- + +* **some_int** An integer value or variable. + +* **number_of_bits** integer whose value is at most ``8 * + sizeof(variable)`` (so ``number_of_bits`` can be at most 32 for + ``int`` values, at most ``8`` for ``char`` values, etc.; the various + integer sizes are summarized :ref:`in this table + `\ ). + + + +Example: +-------- + +Here are some examples of bit shifting, with the binary representation of the number in comments:: + + int a = 5; // binary: 101 + int b = a << 3; // binary: 101000, or 40 in decimal + int c = b >> 3; // binary: 101, or back to 5 like we started with + + +When you left shift a value x by y bits (x << y), the leftmost y bits +in x are lost, literally shifted out of existence. We'll do this +example with ``char`` values (which are integers in the range 0-255, +and take up 8 bits of memory):: + + char a = 5; // binary (all 8 bits): 00000101 + char b = a << 7; // binary: 10000000 - the first 1 in 101 was discarded + + +If you are certain that none of the ones in a value are being shifted +into oblivion, a simple way to think of the left-shift operator is +that it multiplies the left operand by 2 raised to the right operand +power (in math notation, ``x << y`` equals x * 2\ :sup:`y`\ , as long +as none of the bits of x get shifted out). For example, to generate +powers of 2, the following expressions can be employed:: + + 1 << 0 == 1 + 1 << 1 == 2 + 1 << 2 == 4 + 1 << 3 == 8 + ... + 1 << 8 == 256 + 1 << 9 == 512 + 1 << 10 == 1024 + ... + +.. _lang-bitshift-signbit-gotcha: + +When you shift x right by y bits (``x >> y``), and the highest bit in +x is a 1, the behavior depends on the exact data type of x. If x is of +type ``int``, the highest bit is special, and determines whether x is +negative or not; the details are too complicated to explain here, but +they are thoroughly explained in the Wikipedia article on `two's +complement arithmetic +`_\ , which the +system most computers use to store integers. In that case, the sign +bit is copied into lower bits, for esoteric historical reasons:: + + int x = -16; // binary (all 32 bits): 11111111111111111111111111110000 + int y = x >> 3; // binary: 11111111111111111111111111111110 + + + +This behavior, called "sign extension", is often not what you +want. You probably wish zeros to be shifted in from the left. It +turns out that the right shift rules are different for ``unsigned +int`` values, so you can use a type cast to suppress ones being copied +from the left:: + + int x = -16; // binary: 11111111111111111111111111110000 + int y = (unsigned int)x >> 3; // binary: 00011111111111111111111111111110 + + + +If you are careful to avoid sign extension, you can use the +right-shift operator, ``>>``, as a way to divide by powers of 2. For +example:: + + int x = 1000; + int y = x >> 3; // integer division of 1000 by 8, causing y = 125. + + +Arduino Compatibility +--------------------- + +Since it's part of the C++ language, bit shifting on the Maple is +compatible with the Arduino; however, you should keep in mind that the +Maple has bigger integer types (as in, more bits) than the Arduino. + +Since the STM32 is a 32-bit processor, the ``int`` type takes up 32 +bits instead of 16, like on Arduino's 16-bit microcontroller. This +means that you can shift left, like ``x << y``, with bigger values of +``y`` on the Maple before ones in ``x`` start to get shifted out. + +To calculate the number of bits of an integer type on the Maple, +multiply its size in bytes (see :ref:`this table +` for these) by 8, since there are 8 +bits in 1 byte. For example, a ``short`` takes up 2 bytes of memory, +or 2 * 8 = 16 bits. + +See Also +-------- + +- :ref:`lang-bit` +- :ref:`lang-bitread` +- :ref:`lang-bitwrite` +- :ref:`lang-bitclear` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/bitwisemath.rst b/docs/source/lang/cpp/bitwisemath.rst new file mode 100644 index 0000000..28fe6bf --- /dev/null +++ b/docs/source/lang/cpp/bitwisemath.rst @@ -0,0 +1,186 @@ +.. highlight:: cpp + +.. _lang-bitwisemath: + +Bitwise Operators (``&``, ``|``, ``^``, ``~``) +============================================== + +The bitwise operators perform their calculations at the bit level of +variables. They help solve a wide range of common programming +problems. + +Much of the material here is adapted for Maple from an (Arduino) +`tutorial on bitwise math +`_\ . Another great +resource is the Wikipedia article on `bitwise operations +`_\ . + +Below are descriptions and syntax for all of the operators. + +.. contents:: Contents + :local: + +.. _lang-bitwisemath-and: + +Bitwise AND (``&``) +------------------- + +The bitwise AND operator in C++ is a single ampersand, ``&``, used +between two other integer expressions. Bitwise AND operates on each +bit position of the surrounding expressions independently, according +to this rule: if both input bits are 1, the resulting output is 1, +otherwise the output is 0. Another way of expressing this is:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + + +On the Maple, the type ``int`` is a 32-bit value, so using ``&`` +between two ``int`` expressions causes 32 simultaneous AND operations +to occur. In a code fragment like:: + + int a = 92; // in binary: 00000000000000000000000001011100 + int b = 101; // in binary: 00000000000000000000000001100101 + int c = a & b; // result: 00000000000000000000000001000100, + // (or 68 in decimal). + + +Each of the 32 bits in ``a`` and ``b`` are processed using bitwise +AND, and all 32 resulting bits are stored in ``c``, resulting in the +value 1000100 in binary, which is 68 in decimal. + + +.. _lang-bitwisemath-or: + +Bitwise OR (``|``) +------------------ + +The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like +the ``&`` operator, ``|`` operates independently on each bit in its +two surrounding integer expressions, but what it does is +different. The bitwise OR of two bits is 1 if either or both of the +input bits is 1, otherwise it is 0. For example:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Here is an example of bitwise OR used in a snippet of C++ code (using +``char``, which takes up 8 bits of memory, instead of ``int``, which +uses 32):: + + char a = 92; // in binary: 01011100 + char b = 101; // in binary: 01100101 + char c = a | b; // result: 01111101, or 125 in decimal. + +.. _lang-bitwisemath-xor: + +Bitwise XOR (``^``) +------------------- + +There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE +OR, also known as bitwise XOR. (In English, this is usually pronounced +"zor" or "ex-or"). The bitwise XOR operator is written using the caret +symbol, ``^``. This operator is very similar to the bitwise OR +operator ``|``, except it evaluates to 0 for a given bit position when +both of the input bits for that position are 1:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + + +Another way to look at bitwise XOR is that each bit in the result +is a 1 if the input bits are different, or 0 if they are the same. + +Here is a simple example:: + + int x = 12; // binary (ignoring extra bits): 1100 + int y = 10; // binary: 1010 + int z = x ^ y; // binary: 0110, or decimal 6 + + + +The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 +to 0) some of the bits in an integer expression. In a bitwise OR +operation if there is a 1 in the mask bit, that bit is inverted; if +there is a 0, the bit is not inverted and stays the same. Below is a +program to blink digital pin 13 (the LED pin on Maple):: + + // Blink Maple LED pin + + int led_pin = 13; + int toggle = 0; + + // demo for Exclusive OR + void setup(){ + pinMode(led_pin, OUTPUT); + } + + void loop(){ + toggle = toggle ^ 1; + digitalWrite(led_pin, toggle); + delay(100); + } + +.. _lang-bitwisemath-not: + +Bitwise NOT (``~``) +------------------- + +The bitwise NOT operator in C++ is the tilde character ``~``. Unlike +``&`` and ``|``, the bitwise NOT operator is applied to a single +operand to its right. Bitwise NOT changes each bit to its opposite: 0 +becomes 1, and 1 becomes 0. For example:: + + 0 1 operand1 + ---- + 1 0 ~operand1 = result + +Another example:: + + char a = 103; // binary: 01100111 + char b = ~a; // binary: 10011000 = -104 + +You might be surprised to see a negative number like -104 as the +result of this operation. This is because the highest bit in an int +variable is the so-called "sign bit". If the highest bit is 1, the +number is interpreted as negative. This encoding of positive and +negative numbers is referred to as *two's complement*. For more +information, see the Wikipedia article on `two's +complement. `_ + +As an aside, it is interesting to note that (under two's complement +arithmetic) for any integer ``x``, ``~x`` is the same as ``-x-1``. + +At times, the sign bit in a signed integer expression can cause +some unwanted surprises. + + +Uses +---- + +One of the most common uses of bitwise operations is to select or +manipulate a particular bit (or bits) from an integer value, often +called `bit masking +`_\ . See the +linked Wikipedia article for more information and examples. + +If you really want to see bit-twiddling techniques in their full +glory, you could do much worse than to get yourself a copy of +`Hacker's Delight `_\ . + + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Compound bitwise operations ` (``&=``, + ``|=``, ``^=``). + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/boolean.rst b/docs/source/lang/cpp/boolean.rst new file mode 100644 index 0000000..8d6aa5c --- /dev/null +++ b/docs/source/lang/cpp/boolean.rst @@ -0,0 +1,91 @@ +.. highlight:: cpp + +.. _lang-boolean: + +Boolean Operators +================= + +These can be used inside the condition of an :ref:`if ` +statement. Evaluate to :ref:`true ` or +:ref:`false `. + +.. contents:: Contents + :local: + +.. _lang-boolean-and: + +&& (logical and) +---------------- + +True only if both operands are true. For example:: + + if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches + // ... + } + +is true only if both inputs are high. Another example:: + + if (a >= 10 && a <= 20){} // true if a is between 10 and 20 + +**Be careful** not to say ``10 <= a <= 20``! This won't work the way +you want. You have to separately test whether ``a`` is at least 10 +using ``a >= 10``, then test whether ``a`` is at most 20 using ``a <= +20``, then combine the results using ``&&``. + + +.. _lang-boolean-or: + +\|\| (logical or) +----------------- + +True if either operand is true. For example:: + + if (x > 0 || y > 0) { + // ... + } + +is true if either ``x`` or ``y`` is greater than 0. + +.. _lang-boolean-not: + +! (logical not) +--------------- + +True if the operand is false. For example:: + + if (!x) { + // ... + } + +is true if ``x`` is false (i.e. if ``x`` is zero). + +Some Advice +----------- + +.. warning:: + + Make sure you don't mistake the boolean AND operator ``&&`` + (double ampersand) for the :ref:`bitwise AND operator + ` ``&`` (single ampersand). They are + entirely different beasts. + + Similarly, do not confuse the boolean OR operator ``||`` (double + pipe) with the :ref:`bitwise OR operator ` + ``|`` (single pipe). + + The :ref:`bitwise NOT operator ` ``~`` + (tilde) looks much different than the boolean not operator ``!`` + (exclamation point, or "bang", as some programmers say), but you + still have to be sure which one you want. + + +See Also +-------- + +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) +- :ref:`Compound bitwise operators ` (``&=``, + ``|=``, ``^=``). +- :ref:`if statement ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/booleanvariables.rst b/docs/source/lang/cpp/booleanvariables.rst new file mode 100644 index 0000000..6051b8c --- /dev/null +++ b/docs/source/lang/cpp/booleanvariables.rst @@ -0,0 +1,54 @@ +.. highlight:: cpp + +.. _lang-booleanvariables: + +Booleans +======== + +A **boolean** holds one of two values, :ref:`true +` or :ref:`false `. On a +Maple, each boolean variable has type ``bool``. + +.. warning:: + + On an Arduino, the type ``boolean`` is also provided. While the + Maple also has this type for compatibility, **its use is strongly + discouraged**. The ``bool`` type is a standard part of C++, while + ``boolean`` is a non-standard extension that serves no purpose. + +Example +------- + +:: + + int ledPin = 13; // LED on pin 13 + int switchPin = 12; // momentary switch on 12, other side connected to ground + + // running is a boolean variable: + bool running = false; + + void setup() { + pinMode(ledPin, OUTPUT); + pinMode(switchPin, INPUT); + digitalWrite(switchPin, HIGH); // turn on pullup resistor + } + + void loop() { + if (digitalRead(switchPin) == LOW) { + // switch is pressed - pullup keeps pin high normally + delay(100); // delay to debounce switch + running = !running; // toggle running variable + digitalWrite(ledPin, running) // indicate via LED + } + } + +See also +-------- + + +- :ref:`Boolean constants ` +- :ref:`Boolean operators ` +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/break.rst b/docs/source/lang/cpp/break.rst new file mode 100644 index 0000000..ce8ac17 --- /dev/null +++ b/docs/source/lang/cpp/break.rst @@ -0,0 +1,35 @@ +.. highlight:: cpp + +.. _lang-break: + +``break`` +========= + +``break`` is used to exit from a :ref:`while `\ , +:ref:`for `\ , or :ref:`do/while ` loop, +bypassing the normal loop condition. It is also used to exit from a +:ref:`switch ` statement. + + +Example +------- + +:: + + for (x = 0; x < 255; x ++) + { + digitalWrite(PWMpin, x); + sens = analogRead(sensorPin); + if (sens > threshold){ // bail out on sensor detect + x = 0; + // this line of code means that we'll immediately exit + // from the "for" loop: + break; + } + delay(50); + } + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/byte.rst b/docs/source/lang/cpp/byte.rst new file mode 100644 index 0000000..45c9d5f --- /dev/null +++ b/docs/source/lang/cpp/byte.rst @@ -0,0 +1,34 @@ +.. highlight:: cpp + +.. _lang-byte: + +byte +==== + +The ``byte`` type stores a 1-byte (8-bit) unsigned integer number, +from 0 to 255. + +.. warning:: + + The ``byte`` type is provided for compatibility with Arduino. + However, it is a non-standard extension. The standard C++ type for + storing an 8-bit unsigned integer is ``unsigned char``; we + recommend using that instead. (Your code will still work on an + Arduino). + + +Example +------- + +:: + + byte b = 134; + +See Also +-------- + +- :ref:`byte() ` (casting a value to a byte) +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/bytecast.rst b/docs/source/lang/cpp/bytecast.rst new file mode 100644 index 0000000..b3f0de2 --- /dev/null +++ b/docs/source/lang/cpp/bytecast.rst @@ -0,0 +1,50 @@ +.. highlight:: cpp + +.. _lang-bytecast: + +byte() (cast) +============= + +Converts a value to the :ref:`byte ` data type. + +.. note:: + + Casting to the byte type is provided for compatibility with + Arduino. However, the recommended Maple type for storing an 8-bit + unsigned integer is ``uint8``. (C and C++ programmers: ``stdint.h`` + is also available). + + In order to cast a variable ``x`` to a ``uint8``, the + following syntax can be used:: + + uint8(x); + +Syntax +------ + +``byte(x)`` + + +Parameters +---------- + +**x**: a value of any integer type + + +Returns +------- + +The value, converted to a ``byte``. Note, however, that if the value +is larger than the maximum value you can store in a byte (255), then +the results might be strange and unexpected. + + +See Also +-------- + +- :ref:`lang-byte` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/cc-attribution.txt b/docs/source/lang/cpp/cc-attribution.txt new file mode 100644 index 0000000..e100140 --- /dev/null +++ b/docs/source/lang/cpp/cc-attribution.txt @@ -0,0 +1,9 @@ +.. Included in all this directory's files in order to satisfy the +.. Arduino CC Attribution-ShareAlike 3.0 License + +.. admonition:: License and Attribution + + This documentation page was adapted from the `Arduino Reference + Documentation `_\ , which + is released under a `Creative Commons Attribution-ShareAlike 3.0 + License `_. diff --git a/docs/source/lang/cpp/char.rst b/docs/source/lang/cpp/char.rst new file mode 100644 index 0000000..b8747f3 --- /dev/null +++ b/docs/source/lang/cpp/char.rst @@ -0,0 +1,50 @@ +.. highlight:: cpp + +.. _lang-char: + +``char`` +======== + +The ``char`` type stores a 1-byte character value (or integer with +value from -128 to 127). Character literals are written in single +quotes, like this: ``'A'`` (for multiple characters - strings - use +double quotes: ``"ABC"``). + + +Just like everything else on a computer, characters are stored as +numbers. You can see the specific encoding in the `ASCII chart +`_\ +. This means that it is possible to do arithmetic on characters, in +which the ASCII value of the character is used (e.g. ``'A' + 1`` has the +decimal value 66, since the ASCII value of the capital letter A in +decimal is 65). See the :ref:`Serial.println() +` documentation for more information about how +characters are converted into numbers. + +The ``char`` datatype is a signed type, meaning that it encodes +numbers from -128 to 127. For an unsigned type, which stores values +from 0 to 255, just use the type ``unsigned char`` (two words). + + +Example +------- + +:: + + // the following two lines are equivalent, using the ASCII + // character encoding: + char c = 'A'; + char c = 65; + + +See also +-------- + + +- :ref:`lang-int` +- :ref:`lang-array` (a string is just an array of ``char``\ s) +- :ref:`Serial.println() ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/charcast.rst b/docs/source/lang/cpp/charcast.rst new file mode 100644 index 0000000..a480dec --- /dev/null +++ b/docs/source/lang/cpp/charcast.rst @@ -0,0 +1,36 @@ +.. highlight:: cpp + +.. _lang-charcast: + +``char()`` (cast) +================= + +Converts a value to the :ref:`char ` data type. + +Syntax +------ + +``char(x)`` + + +Parameters +---------- + +**x**: a value of any type + + +Returns +------- + +The value, converted to a ``char``. Note, however, that if the value +is outside the range of a ``char`` (-128 to 127), then the results +might be strange and unexpected. + + +See Also +-------- + +- :ref:`char ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/comments.rst b/docs/source/lang/cpp/comments.rst new file mode 100644 index 0000000..c5f118a --- /dev/null +++ b/docs/source/lang/cpp/comments.rst @@ -0,0 +1,67 @@ +.. highlight:: cpp + +.. _lang-comments: + +Comments +======== + +Comments are lines in the program that are used to inform yourself or +others about the way the program works. They are ignored by the +compiler, and not exported to the processor, so they don't take up any +space in RAM or Flash. + +One use for comments is to help you understand (or remember) how your +program works, or to inform others how your program works. There are +two different ways of making comments. + +.. _lang-comments-singleline: + +**Single line comment**: Anything following two slashes, ``//``, until +the end of the line, is a comment:: + + x = 5; // the rest of this line is a comment + +.. _lang-comments-multiline: + +**Multi-line comment**: Anything in between a pair of ``/*`` and ``*/`` +is a comment:: + + /* <-- a slash-star begins a multi-line comment + + all of this in the multi-line comment - you can use it to comment + out whole blocks of code + + if (gwb == 0){ // single line comment is OK inside a multi-line comment + x = 3; + } + + // don't forget the "closing" star-slash - they have to be balanced: + */ + +Note that it's okay to use single-line comments within a multi-line +comment, but you can't use multi-line comments within a multi-line +comment. Here's an example:: + + /* ok, i started a multi-line comment + + x = 3; /* this next star-slash ENDS the multi-line comment: */ + + x = 4; // this line is outside of the multi-line comment + + // next line is also outside of the comment, and causes a compile error: + */ + +Programming Tip +--------------- + +When experimenting with code, "commenting out" parts of your program +is a convenient way to remove lines that may be buggy. This leaves +the lines in the code, but turns them into comments, so the compiler +just ignores them. This can be especially useful when trying to locate +a problem, or when a program refuses to compile and the compiler error +is cryptic or unhelpful. + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/comparison.rst b/docs/source/lang/cpp/comparison.rst new file mode 100644 index 0000000..b24355f --- /dev/null +++ b/docs/source/lang/cpp/comparison.rst @@ -0,0 +1,87 @@ +.. highlight:: cpp + +.. _lang-comparison: + +Comparison Operators (``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``) +=================================================================== + +The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and +``>=`` are used to compare two numbers. They are :ref:`true +` when the comparison is true, and :ref:`false +` otherwise. They are based on the symbols +=, ≠, <, >, ≤, and ≥ from mathematics. + +Here are some examples, with their meaning in comments:: + + // "eq" is true when x is equal to y + bool eq = (x == y); + + // "neq" is true when x is different than y + bool neq = (x != y); + + // "lt" is true when x is less than, but NOT equal to, y + bool lt = (x < y); + + // "gt" is true when x is greater than, but NOT equal to, y + bool gt = (x > y); + + // "lte" is true when x is less than or equal to y + bool lte = (x <= y); + + // "gte" is true when x is greater than or equal to y + bool gte = (x >= y); + +The parentheses are optional; they are present only for clarity. For +example, the following two lines are the same:: + + bool eq = x == y; + + bool eq = (x == y); + +Uses +---- + +Comparison operators, along with :ref:`boolean operators +`, are useful inside the conditionals of :ref:`if +` statements. Here's one example:: + + if (x < 50) { + // only execute these lines if x is less than 50 + SerialUSB.println("delaying:"); + SerialUSB.println(x); + delay(x); + } + +.. warning:: + Beware of accidentally using the single equal sign (``=``) when you + meant to test if two numbers are equal (``==``). This is a common + mistake inside of ``if`` statement conditionals, e.g.:: + + // DON'T MAKE THIS MISTAKE + if (x = 10) { + // body + } + + The single equal sign is the assignment operator, and sets x to 10 + (puts the value 10 into the variable x). Instead use the double equal + sign (e.g. ``if (x == 10)``), which is the comparison operator, and + tests *whether* x is equal to 10 or not. The latter statement is only + true if x equals 10, but the former statement will always be true. + + This is because C evaluates the statement ``if (x=10)`` as follows: 10 + is assigned to x (remember that the single equal sign is the + :ref:`assignment operator `), so x now + contains 10. Then the 'if' conditional evaluates 10, which evaluates + to :ref:`true `, since any non-zero number + evaluates to ``true``. + + Consequently, the conditional of an ``if`` statement like ``if (x = + 10) {...}`` will always evaluate to ``true``, and the variable x + will be set to 10, which is probably not what you meant. + + (This sometimes has uses, though, so just because an assignment + appears within a conditional doesn't mean it's automatically wrong. + Be careful to know what you mean.) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/compoundarithmetic.rst b/docs/source/lang/cpp/compoundarithmetic.rst new file mode 100644 index 0000000..420f1db --- /dev/null +++ b/docs/source/lang/cpp/compoundarithmetic.rst @@ -0,0 +1,44 @@ +.. highlight:: cpp + +.. _lang-compoundarithmetic: + +Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) +=============================================================== + +These oparators perform a mathematical operation on a variable with +another constant or variable. These operators are just a convenient +shorthand:: + + x += y; // equivalent to the expression x = x + y; + x -= y; // equivalent to the expression x = x - y; + x *= y; // equivalent to the expression x = x * y; + x /= y; // equivalent to the expression x = x / y; + +Here is an example:: + + int x = 2; + int y = 10; + + x += 4; // x now contains 6 + x -= 3; // x now contains 3 + x *= y; // x now contains 30 + x /= 2; // x now contains 15 + x += max(20, 6); // x now contains 35 + x -= sq(5); // x now contains 15 + +Parameters +---------- + +**x**: a numeric variable + +**y**: a numeric variable, number constant, or any other expression +that evaluates to a number (e.g. call to a function that returns a +number). + +See Also +-------- + +- :ref:`Arithmetic operators ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/compoundbitwise.rst b/docs/source/lang/cpp/compoundbitwise.rst new file mode 100644 index 0000000..a4bbb24 --- /dev/null +++ b/docs/source/lang/cpp/compoundbitwise.rst @@ -0,0 +1,231 @@ +.. highlight:: cpp + +.. _lang-compoundbitwise: + +Compound Bitwise Operators (``&=``, ``|=``, ``^=``) +=================================================== + +The compound bitwise operators perform their calculations at the +bit level of variables. They are often used to clear and set +specific bits of a variable. + +See the :ref:`bitwise math tutorial ` for more +information on bitwise operators. + +.. contents:: Contents + :local: + +.. _lang-compoundbitwise-and: + +Compound bitwise AND (``&=``) +----------------------------- + +The compound bitwise AND operator ``&=`` is often used with a variable +and a constant to force particular bits in a variable to be zero. This +is often referred to in programming guides as "clearing" or +"resetting" bits. In a program, writing the line ``x &= y;`` is +equivalent to writing ``x = x & y;``. That is, the value of ``x`` +after the line will be equal to its old value bitwise ANDed with the +value of ``y``:: + + x &= y; // equivalent to x = x & y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any :ref:`integer value +` (like ``3`` or ``0x20``) for ``y``. + +Before doing an example of ``&=``, let's first review the Bitwise AND +(``&``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 0 0 1 (operand1 & operand2) = result + +As shown above, bits that are "bitwise ANDed" with 0 become 0, while +bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` +is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & +B11111111`` equals ``b``. + +.. _lang-compoundbitwise-binconst: + +.. note:: The above uses :ref:`binary constants + `\ . The numbers are still the same + value in other representations, they just might not be as easy to + understand. + + Normally, in C and C++ code, :ref:`hexadecimal + ` or :ref:`octal + ` are used when we're interested in + an integer's bits, rather than its value as a number. + + While hexadecimal and octal literals might be harder to understand + at first, you should really take the time to learn them. They're + part of C, C++, and many other programming languages, while binary + constants are available only for compatibility with Arduino. + + Also, ``B00000000`` is shown for clarity, but zero in any number + format is zero. + +So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while +leaving the rest of the variable's bits unchanged, use the compound +bitwise AND operator ``&=`` with the constant ``B11111100`` +(hexadecimal ``0xFC``\ ):: + + 1 0 1 0 1 0 1 0 variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + 1 0 1 0 1 0 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +Here is the same representation with the variable's bits replaced +with the symbol ``x``\ :: + + x x x x x x x x variable + 1 1 1 1 1 1 0 0 mask + ---------------------- + x x x x x x 0 0 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged cleared + + +So, using a byte variable ``b``\ , if we say:: + + b = B10101010; // B10101010 == 0xAA + b &= B11111100; // B11111100 == 0xFC + +then we will have :: + + b == B10101000; // B10101000 == 0xA8 + +.. _lang-compoundbitwise-or: + +Compound bitwise OR (``|=``) +---------------------------- + +The compound bitwise OR operator ``|=`` is often used with a variable +and a constant to "set" (set to 1) particular bits in a variable. In +a program, writing the line ``x |= y;`` is equivalent to writing ``x = +x | y;``. That is, the value of ``x`` after the line will be equal to +its old value bitwise ORed with the value of ``y``:: + + x |= y; // equivalent to x = x | y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`compound bitwise AND +`\ , ``&=``). + +Before doing an example of ``|=``, let's first review the Bitwise OR +(``|``) operator:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 1 (operand1 | operand2) = result + +Bits that are "bitwise ORed" with 0 are unchanged, while bits that are +"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` +variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` +equals ``B11111111`` (here we've used binary constants; see the +:ref:`note ` above). + +So, to set bits 0 and 1 of a one-byte variable, while leaving the rest +of the variable unchanged, use the compound bitwise OR operator +(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +Here is the same representation with the variable's bits replaced with +the symbol ``x``:: + + x x x x x x x x variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + x x x x x x 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged set + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b |= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101011; // B10101011 == 0xAB + +.. _lang-compoundbitwise-xor: + +Compound bitwise XOR (``^=``) +----------------------------- + +The compound bitwise XOR operator ``^=`` is used with a variable and a +constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a +variable. In a program, writing the line ``x ^= y;`` is equivalent to +writing ``x = x ^ y;``. That is, the value of ``x`` after the line +will be equal to its old value bitwise XORed with the value of ``y``:: + + x ^= y; // equivalent to x = x ^ y; + +You can use any integer variable for ``x`` (i.e., any variable of type +``int``, ``long``, ``char``, ``byte``, etc.). You can use either an +integer variable or any integer value (like ``3`` or ``0x20``) for +``y``. (This works the same way as :ref:`&= +` and :ref:`\|= +`; in fact, these three operators all +work the same in this way). + +Before doing an example of ``^=``, let's first review the Bitwise +XOR operator, ``^``:: + + 0 0 1 1 operand1 + 0 1 0 1 operand2 + ---------- + 0 1 1 0 (operand1 ^ operand2) = result + +One way to look at bitwise XOR is that each bit in the result is a 1 +if the input bits are different, or 0 if they are the same. Another +way to think about it is that the result bit will be 1 when *exactly* +one (no more, no less) of the input bits is 1; otherwise, it will be +zero. This means that if you XOR a bit with 1, it will change (or +toggle) its value, while if you XOR a bit with 0, it stays the same. + +So, to toggle bits 0 and 1 of a one-byte variable, while leaving the +rest of the variable unchanged, use the compound bitwise XOR operator +``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see +:ref:`note ` above):: + + 1 0 1 0 1 0 1 0 variable + 0 0 0 0 0 0 1 1 mask + ---------------------- + 1 0 1 0 1 0 1 1 + ^^^^^^^^^^^^^^^^ ^^^^ + unchanged toggled + +So, using a byte variable ``b``, if we say:: + + b = B10101010; // B10101010 == 0xAA + b ^= B00000011; // B00000011 == 0x3 + +then we will have :: + + b == B10101001; // B10101001 == 0xA9 + +See Also +-------- + +- :ref:`Boolean operations ` (``&&``, ``||``) +- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/const.rst b/docs/source/lang/cpp/const.rst new file mode 100644 index 0000000..52de85f --- /dev/null +++ b/docs/source/lang/cpp/const.rst @@ -0,0 +1,52 @@ +.. highlight:: cpp + +.. _lang-const: + +``const`` +========= + +The ``const`` keyword stands for "constant". It is a variable +*qualifier* that modifies the behavior of the variable, making a +variable "*read-only*". This means that the variable can be used just +as any other variable of its type, but its value cannot be +changed. You will get a compiler error if you try to assign a value to +a ``const`` variable. + +Constants defined with the ``const`` keyword obey the same rules of +:ref:`variable scoping ` that govern other +variables. This, and the pitfalls of using :ref:`#define +`, often makes using the ``const`` keyword a superior +method for defining constants than ``#define``. + +Example +------- + +:: + + // this defines a variable called "pi", which cannot be changed: + const float pi = 3.14; + float x; + + // .... + + x = pi * 2; // it's fine to find the value of a const variable + + pi = 7; // illegal - you can't write to (modify) a constant + + +**#define** or **const** +------------------------ + +You can use either ``const`` or ``#define`` for creating numeric or +string constants. For :ref:`arrays `\ , you will need +to use ``const``. In general, ``const`` is preferred over ``#define`` +for defining constants. + +See Also +-------- + +- :ref:`#define ` +- :ref:`volatile ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/continue.rst b/docs/source/lang/cpp/continue.rst new file mode 100644 index 0000000..13d1815 --- /dev/null +++ b/docs/source/lang/cpp/continue.rst @@ -0,0 +1,32 @@ +.. highlight:: cpp + +.. _lang-continue: + +``continue`` +============ + +The ``continue`` keyword skips the rest of the current iteration of a +:ref:`while `\ , :ref:`for `\ , or +:ref:`do/while ` loop. It continues by checking the +conditional expression of the loop, and proceeding with any subsequent +iterations. + +Example +------- + +:: + + + for (x = 0; x < 255; x ++) { + if (x > 40 && x < 120) { // create jump in values + continue; // skips the next two lines and goes to the + // beginning of the loop, with the next value of x + } + + digitalWrite(PWMpin, x); + delay(50); + } + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/curly-braces.rst b/docs/source/lang/cpp/curly-braces.rst new file mode 100644 index 0000000..a4bd3dc --- /dev/null +++ b/docs/source/lang/cpp/curly-braces.rst @@ -0,0 +1,109 @@ +.. highlight:: cpp + +.. _lang-curly-braces: + +Curly Braces (``{``, ``}``) +=========================== + +.. contents:: Contents + :local: + +Introduction +------------ + +Curly braces (also referred to as just "braces" or as "curly +brackets") are a major part of the C and C++ programming +languages. They are used in several different constructs, outlined +below, and this can sometimes be confusing for beginners. + +An opening curly brace, ``{`` must always be followed by a closing +curly brace ``}``. This is a condition that is often referred to as +the braces being *balanced*. The Maple IDE (integrated development +environment) includes a convenient feature to check the balance of +curly braces. Just select a brace, or even click the insertion point +immediately following a brace, and its companion will be highlighted\ +[#fbug]_\ . + +Beginning programmers, and programmers coming to C++ from languages +without braces, often find using them confusing or daunting. + +Because the use of the curly brace is so varied, it is good +programming practice to type the closing brace immediately after +typing the opening brace when inserting a construct which requires +curly braces. Then insert some blank lines between your braces and +begin inserting statements. Your braces, and your attitude, will never +become unbalanced. + +Unbalanced braces can often lead to cryptic, impenetrable compiler +errors that can sometimes be hard to track down in a large program. +Because of their varied usages, braces are also incredibly important +to the syntax of a program and moving a brace one or two lines will +usually dramatically affect the meaning of a program. + +The main uses of curly braces +----------------------------- + +**Functions**:: + + // a function body needs braces around it + void myFunction(datatype argument) { + // ... function body goes in here ... + } + +**Loops** (see the :ref:`while `\ , :ref:`for +`\ , and :ref:`do/while ` loop reference +pages for more information):: + + // you should put braces around the body of a loop: + + while (boolean expression) { + // code inside the loop goes here + } + + for (initialisation; termination condition; incrementing expr) { + // code inside the loop goes here + } + + do { + // code inside the loop goes here + } while (boolean expression); + + +**Conditional statements** (see the :ref:`if statement ` +reference page for more information):: + + // you should put braces around the body of an "if", "else if", + // or "else": + + if (boolean expression) { + // code inside the "if" + } + else if (boolean expression) { + // code inside the "else if" + } + else { + // code inside the "else" + } + +**Switch statements** (see the :ref:`switch statement +` reference page for more information):: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + +.. rubric:: Footnotes + +.. TODO remove this once IDE 0.1.0 released + +.. [#fbug] At present this feature is slightly buggy as the IDE will + often find (incorrectly) a brace in text that has been commented + out. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/define.rst b/docs/source/lang/cpp/define.rst new file mode 100644 index 0000000..677390d --- /dev/null +++ b/docs/source/lang/cpp/define.rst @@ -0,0 +1,56 @@ +.. highlight:: cpp + +.. _lang-define: + +``#define`` +=========== + +``#define`` is a useful C and C++ feature that allows the programmer +to give a name to a constant value before the program is compiled. +The compiler will replace references to these constants with the +defined value at compile time. + +This can have some unwanted side effects. In general, the :ref:`const +` keyword is preferred for defining constants. + + +Syntax +------ + +The following line would define the name ``MY_CONSTANT`` to have value +``value``:: + + #define MY_CONSTANT value + +Note that the ``#`` is necessary. It is usually good style for the +name to be capitalized, although this is not required. + +There is no semicolon after the #define statement. If you include one, +the compiler will likely throw cryptic errors in unrelated places. +That is, **don't do this**:: + + // DON'T DO THIS! THE SEMICOLON SHOULDN'T BE THERE! + #define NAME value; + +Similarly, including an equal sign after the ``#define`` line will +also generate a cryptic compiler error further down the page. That +is, **don't do this, either**:: + + // DON'T DO THIS, EITHER! THE EQUALS SIGN SHOULDN'T BE THERE! + #define NAME = value + +Example +------- + +:: + + #define LED_PIN 13 + // The compiler will replace any mention of LED_PIN with + // the value 3 at compile time. + +See Also +-------- +- :ref:`const ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/double.rst b/docs/source/lang/cpp/double.rst new file mode 100644 index 0000000..1527778 --- /dev/null +++ b/docs/source/lang/cpp/double.rst @@ -0,0 +1,48 @@ +.. _lang-double: + +``double`` +========== + +Double precision floating point type. Occupies 8 bytes. On Maple, the +``double`` type has a range of approximately -1.79769×10^308 to +1.79769×10^308; the ``double`` type subject to the same :ref:`overflow +issues ` as any numeric data type. + +Floating point numbers are not exact, and may yield strange results +when compared. For example ``6.0 / 3.0`` may not equal ``2.0``. You +should instead check that the absolute value of the difference between +the numbers is less than some small number. + +Floating point math is also much slower than integer math in +performing calculations, so should be avoided if, for example, a loop +has to run at top speed for a critical timing function. Programmers +often go to some lengths to convert floating point calculations to +integer math to increase speed. + +For more information, see the `Wikipedia article on floating point +math `_\ . + +Floating-point numbers represent numbers with "decimal point", unlike +integral types, which always represent whole numbers. Floating-point +numbers are often used to approximate analog and continuous values +because they have greater resolution than integers. + +The double implementation on the Maple uses twice the number of bytes +as a :ref:`float `, with the corresponding gains in +precision. + +Tip +--- + +Users who borrow code from other sources that includes ``double`` +variables may wish to examine the code to see if the implied range and +precision are different from that actually achieved on the Maple. + +See Also +-------- + +- :ref:`float ` + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/doublecast.rst b/docs/source/lang/cpp/doublecast.rst new file mode 100644 index 0000000..511fe24 --- /dev/null +++ b/docs/source/lang/cpp/doublecast.rst @@ -0,0 +1,27 @@ +.. highlight:: cpp + +.. _lang-doublecast: + +``double()`` (cast) +=================== + +Converts a value to the :ref:`double ` floating point +data type. Here is an example:: + + int x = 2; + double d = double(x); // d now holds 2.0, a double value + +The value ``x`` can be of any type. However, if ``x`` is not a number +(like an ``int`` or ``long``), you will get strange results. + +See the :ref:`double ` reference for details about the +precision and limitations of ``double`` values on the Maple. + +See Also +-------- + +- :ref:`double ` +- :ref:`float ` +- :ref:`float() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/dowhile.rst b/docs/source/lang/cpp/dowhile.rst new file mode 100644 index 0000000..fe92226 --- /dev/null +++ b/docs/source/lang/cpp/dowhile.rst @@ -0,0 +1,27 @@ +.. highlight:: cpp + +.. _lang-dowhile: + +``do``/``while`` +================ + +A ``do`` loop works in the same manner as a :ref:`while +` loop, with the exception that the condition is tested +at the end of the loop, so the ``do`` loop will *always* run at least +once. + +This is the basic syntax:: + + do { + // statement block + } while (test condition); + +Example:: + + do { + delay(50); // wait for sensors to stabilize + x = readSensors(); // check the sensors + } while (x < 100); + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/enum.rst b/docs/source/lang/cpp/enum.rst new file mode 100644 index 0000000..ba82383 --- /dev/null +++ b/docs/source/lang/cpp/enum.rst @@ -0,0 +1,53 @@ +.. highlight:: cpp + +.. _lang-enum: + +``enum`` +======== + +The ``enum`` keyword is used to specify an enumeration type. An +enumeration type is a type whose values are taken from a specified, +fixed list of constant values. + +Example +------- + +Here's an example defining an enumeration type called ``weather``, +which has values ``HOT``, ``COMFY``, and ``COLD``:: + + enum weather {HOT, COMFY, COLD}; + +Once you've defined this type, you can create variables of type +``weather``, in the same way you would with an :ref:`int ` +or a :ref:`long `:: + + // create a weather variable named theWeather, with value COMFY: + weather theWeather = COMFY; + +Enumeration types are useful within :ref:`switch statements +`. If you know that an argument is of an enumeration +type, you can make ``case`` statements for all of that type's possible +values, so you know you won't miss anything:: + + void describeWeather(weather currentWeather) { + switch(currentWeather) { + case HOT: + SerialUSB.println("it's hot out"); + break; + case COMFY: + SerialUSB.println("it's nice today"); + break; + case COLD: + SerialUSB.println("it's freezing!"); + break; + } + } + +Such a ``switch`` statement would need no :ref:`default +`, since we know that ``currentWeather`` must +be either ``HOT``, ``COMFY``, or ``COLD``. + +See Also +-------- + +- :ref:`lang-switchcase` diff --git a/docs/source/lang/cpp/float.rst b/docs/source/lang/cpp/float.rst new file mode 100644 index 0000000..6937c8c --- /dev/null +++ b/docs/source/lang/cpp/float.rst @@ -0,0 +1,50 @@ +.. highlight:: cpp + +.. _lang-float: + +``float`` +========= + +Single-precision floating point number. Occupies 4 bytes. On Maple, +the ``float`` type has a range of approximately -3.40282×10^38 to +3.40282×10^38; the ``float`` type is subject to the same +:ref:`overflow issues ` as any numeric data +type. + +``float``\ s have only 6-7 decimal digits of precision. That means the +total number of digits, not the number to the right of the decimal +point. You can get more precision by using a :ref:`double +` (which has a precision of about 16 decimal digits). + +The following example declares a ``float`` value named ``myfloat``:: + + float myfloat; + +This example declares a ``float`` value named ``sensorCalibrate``, +with value 1.117:: + + float sensorCalibrate = 1.117; + +The general syntax for declaring a float named ``var`` with value +``val`` is:: + + float var = val; + +Here is a more extended example involving a :ref:`float cast +`:: + + int x; + int y; + float z; + + x = 1; + y = x / 2; // y now contains 0, ints can't hold fractions + z = float(x) / 2; // z now contains .5 + +See Also +-------- + +- :ref:`double ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/floatcast.rst b/docs/source/lang/cpp/floatcast.rst new file mode 100644 index 0000000..4766478 --- /dev/null +++ b/docs/source/lang/cpp/floatcast.rst @@ -0,0 +1,28 @@ +.. highlight:: cpp + +.. _lang-floatcast: + +``float()`` (cast) +================== + +Converts a value to the :ref:`float ` data type. Here is +an example (see the :ref:`constants reference ` for +an explanation of the "2.0f"):: + + int x = 2; + float f = float(x); // f now holds 2.0f, a float value + +The value ``x`` can be of any type. However, if ``x`` is not a number +(like an ``int``), you will get strange results. + +See the :ref:`float ` reference for details about the +precision and limitations of ``float`` values on the Maple. + +See Also +-------- + +- :ref:`float ` +- :ref:`double ` +- :ref:`double() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/for.rst b/docs/source/lang/cpp/for.rst new file mode 100644 index 0000000..71c5aca --- /dev/null +++ b/docs/source/lang/cpp/for.rst @@ -0,0 +1,142 @@ +.. highlight:: cpp + +.. _lang-for: + +``for`` +======= + +A ``for`` loop is used to repeat a block of statements enclosed in +curly braces. ``for`` loops are useful for performing repetitive +operations, and are often used in combination with :ref:`arrays +` to operate on collections of data or multiple +:ref:`pins `. A ``for`` loop is composed of two parts: first, a +*header*, which sets up the for loop, and then a *body*, which is made +up of lines of code enclosed in curly braces. + +.. contents:: Contents + :local: + +Syntax +------ + +There are three parts to the ``for`` loop header: an *initialization* +expression, *loop condition* expression, and a *post-loop* +expression. The general syntax looks like this:: + + for (initialization; condition; post-loop) { + // all of these lines inside the curly braces are part + // of the loop body. + statement 1; + statement 2; + ... + } + +(Note that there is no semicolon after the post-loop). The +initialization happens first and exactly once, before the loop begins. +Each time through the loop, the condition is tested. The condition is +a :ref:`boolean ` expression. If it is true, then the +list of statements inside the curly braces are executed. Next, the +post-loop is executed. The loop then begins again by evaluating the +condition again, entering the loop body if it is true. This proceeds +until the condition becomes false. + +Examples +-------- + +Here's an example:: + + // Dim an LED using a PWM pin + int pwmPin = 9; // LED in series with 470 ohm resistor on pin 9 + + void setup() { + pinMode(pwmPin, PWM); + } + + void loop() { + for (int i=0; i <= 65535; i++) { + pwmWrite(pwmPin, i); + delay(1); + } + } + +There is a ``for`` loop In the :ref:`loop() ` function of +the above example. This loop starts by declaring an ``int`` variable +named ``i``, whose value starts out at zero. The loop proceeds by +checking if ``i`` is less than or equal to 65535. Since ``i`` is +zero, this is true, and so the calls to :ref:`pwmWrite() +` and :ref:`delay() ` happen next. At this +point, the post-loop expression ``i++`` is evaluated, which +:ref:`increments ` ``i``, so that ``i`` becomes one. +That concludes the first time through the loop. Each "time through +the loop" is referred to as an *iteration*. + +The loop then jumps back to the beginning, checking the condition as +the beginning of its second iteration (initialization is skipped, +since this only happens once, before the first iteration). One is +less than 65535, so the loop statements are executed again. This +proceeds over and over until the iteration when ``i`` finally +reaches 65536. At that point, the condition is no longer true, so the +loop stops executing, and the ``loop()`` function returns. + +Here's another example, using a ``for`` loop to brighten and fade an +LED (see the :ref:`pwmWrite() ` reference for more +information):: + + int pwmPin = 9; // hook up the LED to pin 9 + void loop() { + int x = 1; + for (int i = 0; i >= 0; i += x) { + analogWrite(pwmPin, i); // controls the brightness of the LED + if (i == 65535) { + x = -1; // switch direction, so i starts decreasing + } + delay(1); + } + } + +Coding Tips +----------- + +The C ``for`` loop is more flexible than ``for`` loops found in some +other computer languages, including BASIC. Any or all of the three +header elements may be left blank, although the semicolons are +required. Also the statements for initialization, condition, and +post-loop can be any valid C statements, and use any C datatypes, +including :ref:`floating point numbers `. These types +of unusual ``for`` loops sometimes provide solutions to less-common +programming problems. + +For example, using a multiplication in the post-loop line will +generate a `geometric progression +`_:: + + for(int x = 1; x <= 100; x = x * 2) { + SerialUSB.println(x); + } + + +This loop prints out the numbers 1, 2, 4, 8, ..., 64. Check +your understanding of ``for`` loops by answering the following two +questions (answers are in footnote [#fanswers]_\ ): + +1. How many iterations occur before the loop finishes? + +2. Why does it stop at 64? + +See also +-------- + +- :ref:`while ` loops +- :ref:`do ` loops + +.. rubric:: Footnotes + +.. [#fanswers] + 1. Seven. + + 2. After the seventh iteration, the post-loop causes ``x`` to + equal 128. This is larger than 100, so the loop condition is + false, and the loop stops. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/goto.rst b/docs/source/lang/cpp/goto.rst new file mode 100644 index 0000000..ff2f248 --- /dev/null +++ b/docs/source/lang/cpp/goto.rst @@ -0,0 +1,130 @@ +.. highlight:: cpp + +.. _lang-goto: + +Labels and ``goto`` +=================== + +A *label* gives a name to a line of code within a function. You can +label a line by writing a name for it, then a colon (``:``), before +the line starts. The ``goto`` keyword allows program flow to transfer +to a labeled line from anywhere within the same function. + +.. warning:: The use of ``goto`` is discouraged in C and C++ + programming. It is *never necessary* to use ``goto`` to write a + program. + + Unless you know what you're doing, using ``goto`` tends to + encourage code which is harder to debug and understand than + programs without ``goto`` that do the same thing. That said, + however, it's sometimes useful; :ref:`see below ` + for a concrete example. + +Using Labels and goto +--------------------- + +Labels and ``goto`` are probably best explained through example. +Let's start with an example of how to label lines. The first line +(``int x = analogRead(some_pin);``) in the :ref:`loop ` +function below has label ``readpin``. The third line (``delay(x);``) +has label ``startdelay``. The second line (``SerialUSB.println(x);``) +does not have a label:: + + void loop() { + readpin: + int x = analogRead(some_pin); + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +Anything which can be a :ref:`variable ` name can +be a label. + +Let's say that we wanted to print ``x`` only if it was very large, say +at least 2000. We might want to do this just so anybody watching on a +:ref:`serial monitor ` would know they were in for +a longer wait than usual. We can accomplish this through the use of a +``goto`` statement that skips the printing if ``x`` is less than +2000:: + + void loop() { + readpin: + int x = analogRead(some_pin); + if (x < 2000) { + goto startdelay; + } + SerialUSB.println(x); // for debugging + startdelay: + delay(x); + // ... more code ... + } + +In this modified program, whenever ``x`` is less than 2000, the body +of the :ref:`if ` statement in the second line is +executed. The ``goto`` statement inside the ``if`` body skips +straight to the line labeled ``startdelay``, passing over the line +doing the printing. + +A ``goto`` does not have to "move forwards"; it can go "backwards", +too. For example, the following program prints "5" forever (why?):: + + void loop() { + printfive: + SerialUSB.println(5); + goto printfive; + SerialUSB.println(6); + } + +.. _goto-when-to-use: + +When to Use goto +---------------- + +As mentioned above, use of ``goto`` is `generally discouraged +`_. However, +when used with care, ``goto`` can simplify certain programs. One +important use case for ``goto`` is breaking out of deeply nested +:ref:`for ` loops or :ref:`if ` logic blocks. +Here's an example:: + + for(int r = 0; r < 255; r++) { + for(int g = 255; g > -1; g--) { + for(int b = 0; b < 255; b++) { + if (analogRead(0) > 250) { + goto bailout; + } + // more statements ... + } + // innermost loop ends here + } + } + bailout: + // more code here + +In the above example, whenever the :ref:`analog reading +` on pin 0 was greater than 250, the program would +jump to the line labeled ``bailout``, exiting all three loops at once. + +While there is already a :ref:`break ` keyword for +breaking out of a loop, it will only break out of the *innermost* +loop. So, if instead of saying "``goto bailout;``", there was a +"``break;``" instead, the program would only exit from the loop with +header "``for(int b = 0; b < 255; b++)``". The program would continue +at the line which reads "``// innermost loop ends here``", which is +clearly undesirable if you wanted to leave all three loops at once. + +More examples of when ``goto`` is a good choice are given in Donald +Knuth's paper, "Structured Programming with go to Statements"; see +below for a link. + +See Also +-------- + +- Dijkstra, Edsger W. `Go To Statement Considered Harmful `_ (PDF) + +- Knuth, Donald. `Structured Programming with go to Statements `_ (PDF) + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/if.rst b/docs/source/lang/cpp/if.rst new file mode 100644 index 0000000..bef89e2 --- /dev/null +++ b/docs/source/lang/cpp/if.rst @@ -0,0 +1,121 @@ +.. highlight:: cpp + +.. _lang-if: + +``if``/``else`` +=============== + +An ``if`` statement is used to execute code when certain conditions +are met. The general syntax for an ``if`` statement is:: + + if (condition) { + body + } + +An ``if`` statement first tests whether its *condition* is true (such +as an input being above a certain number). If the condition is true, +the ``if`` statement executes its *body*, which is made up of lines of +code inside :ref:`curly braces `. If the condition +is false, the body is not executed. Here's a more concrete example:: + + if (someVariable > 50) { + // do something here + } + +The program tests to see if ``someVariable`` is greater than 50. If it +is, the program executes every line in the curly braces (which in the +above example does nothing, since the body is just the :ref:`comment +` line "``// do something here``"). + +Put another way, if the statement in parentheses is true, the +statements inside the braces are run. If not, the program skips over +the code. + +An ``if`` statement's condition (which is inside the parentheses after +``if``) often uses one or more :ref:`boolean ` or +:ref:`comparison ` operators. + +Writing the if Body +------------------- + +The brackets may be omitted after an ``if`` statement's +conditional. If this is done, the next line (which ends in a +semicolon) becomes the only line in the body. The following three +``if`` statements all do the same thing:: + + if (x > 120) digitalWrite(ledPin, HIGH); + + if (x > 120) + digitalWrite(ledPin, HIGH); + + if (x > 120) { + digitalWrite(ledPin, HIGH); + } + +However, the following two examples are different:: + + // example 1: two lines of code in the if body + if (x > 120) { + digitalWrite(ledPin1, HIGH); + digitalWrite(ledPin2, HIGH); + } + + // example 2: one line of code in the if body, and + // another line of code after the if statement + if (x > 120) + digitalWrite(ledPin1, HIGH); // this is in the if body + digitalWrite(ledPin2, HIGH); // this is NOT in the if body + +In the first example, since the body is enclosed in curly braces, both +lines are included. In the second example, since the curly braces are +missing, only the first line is in the ``if`` body. + +``else`` +-------- + +``if``/\ ``else`` allows greater control over the flow of code than +the basic :ref:`if ` statement, by allowing multiple tests to +be grouped together. For example, an :ref:`analog input +` could be tested, with one action taken if the input +was less than 500, and another action taken if the input was 500 or +greater. The code would look like this:: + + if (pinFiveInput < 500) { + // action A + } else { + // action B + } + +``else`` can precede another ``if`` test, so that multiple, mutually +exclusive tests can be run at the same time. + +Each test will proceed to the next one until a true test is +encountered. When a true test is found, its associated block of code +is run, and the program then skips to the line following the entire +if/else construction. If no test proves to be true, the default +``else`` block is executed, if one is present, and sets the default +behavior. + +Note that an ``else if`` block may be used with or without a +terminating ``else`` block, and vice-versa. An unlimited number of +such ``else if`` branches is allowed. Here is a code example:: + + if (pinFiveInput < 500) { + // do Thing A + } else if (pinFiveInput >= 1000) { + // do Thing B + } else { + // do Thing C + } + +Another way to express branching, mutually exclusive tests, is with a +:ref:`switch/case ` statement. + + +See Also +-------- + +- :ref:`boolean operators ` +- :ref:`comparison operators ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/include.rst b/docs/source/lang/cpp/include.rst new file mode 100644 index 0000000..74fe7af --- /dev/null +++ b/docs/source/lang/cpp/include.rst @@ -0,0 +1,72 @@ +.. highlight:: cpp + +.. _lang-include: + +``#include`` +============ + +``#include`` is used to include outside libraries in your sketch. +This gives the programmer access to a large group of standard C +libraries (groups of pre-made functions and data types), and also +libraries written especially for Maple. + +Example +------- + +This example (from the `Arduino LiquidCrystal Tutorial +`_) includes a library +that is used to control :ref:`LCD displays +`:: + + // include the library code: + #include + + // initialize the library with the numbers of the interface pins + LiquidCrystal lcd(12, 11, 5, 4, 3, 2); + + void setup() { + // set up the LCD's number of columns and rows: + lcd.begin(16, 2); + // Print a message to the LCD. + lcd.print("hello, world!"); + } + + void loop() { + // set the cursor to column 0, line 1 + // (note: line 1 is the second row, since counting begins with 0): + lcd.setCursor(0, 1); + // print the number of seconds since reset: + lcd.print(millis()/1000); + } + +Note that a ``#include`` line, like :ref:`#define `, +has **no semicolon**. The compiler will print strange error messages +if you add one. + +C Standard Library +------------------ + +The standard C library that comes with Maple is called `newlib +`_. Its main sources of documentation +are its `main reference `_ +page and its `math functions +`_ reference page. Here's an +example that imports the math.h library in order to take the `cube +root `_ of a number:: + + #include + + void setup() { + // no setup necessary + } + + void loop() { + // "cbrt" stands for "cube root" + double cubeRootOf3 = cbrt(3.0); + // prints a number that is approximately the cube root of 3: + SerialUSB.println(cubeRootOf3); + } + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/increment.rst b/docs/source/lang/cpp/increment.rst new file mode 100644 index 0000000..6dffa80 --- /dev/null +++ b/docs/source/lang/cpp/increment.rst @@ -0,0 +1,37 @@ +.. highlight:: cpp + +.. _lang-increment: + +Increment and Decrement Operators (``++``, ``--``) +================================================== + +These operators increment (add one to) or decrement (subtract one +from) a variable. If they come before the variable, they return its +new value; otherwise, they return its old value. + +Some quick examples:: + + x++; // adds one to x, and returns the old value of x + ++x; // adds one to x, and returns the new value of x + + x--; // decrement x by one and returns the old value of x + --x; // decrement x by one and returns the new value of x + +A more extended example:: + + x = 2; + y = ++x; // x now contains 3, y contains 3 + y = x--; // x contains 2 again, y still contains 3 + +.. warning:: Be careful! You cannot put a space in between the two + ``+`` or ``-`` signs. This example is broken:: + + // this line won't compile (notice the extra space): + int y = x+ +; + +See Also +-------- + +- :ref:`lang-compoundarithmetic` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/int.rst b/docs/source/lang/cpp/int.rst new file mode 100644 index 0000000..ca75f75 --- /dev/null +++ b/docs/source/lang/cpp/int.rst @@ -0,0 +1,64 @@ +.. highlight:: cpp + +.. _lang-int: + +``int`` +======= + +The ``int`` data type represents integers. Integers are your primary +data type for number storage, and store a 4 byte value. This yields a +range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a +maximum value of (2^31) - 1; that's about negative 2 billion to +positive 2 billion). + +An ``int`` stores a negative number with a technique called `two's +complement math +`_\ . +The highest bit in an ``int``, sometimes refered to as the "sign" bit, +flags the number as a negative number. (See the linked article on +two's complement for more information). + +The Maple takes care of dealing with negative numbers for you, so that +arithmetic operations work mostly as you'd expect. There can be an +:ref:`unexpected complication ` in +dealing with the :ref:`bitshift right operator (>>) +`, however. + +Here is an example of declaring an ``int`` variable named ``ledPin``, +then giving it value 13:: + + int ledPin = 13; + +The general syntax for declaring an ``int`` variable named ``var``, +then giving it value ``val``, looks like:: + + int var = val; + +.. _lang-int-overflow: + +Integer Overflow +---------------- + +When ``int`` variables leave the range specified above, they +:ref:`roll over ` in the other direction. +Here are some examples:: + + int x; + x = -2,147,483,648; + x--; // x now contains 2,147,483,647; rolled over "left to right" + + x = 2,147,483,647; + x++; // x now contains -2,147,483,648; rolled over "right to left" + +See Also +-------- + +- :ref:`unsigned int ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/intcast.rst b/docs/source/lang/cpp/intcast.rst new file mode 100644 index 0000000..386fe14 --- /dev/null +++ b/docs/source/lang/cpp/intcast.rst @@ -0,0 +1,29 @@ +.. highlight:: cpp + +.. _lang-intcast: + +``int()`` (cast) +================ + +Converts a value to the :ref:`int ` data type. Here is +an example:: + + double d = 2.5; + int i = int(d); // i holds "2", an int value + +The value inside of the parentheses (``int(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. + +See the :ref:`int ` reference for details about the +precision and limitations of ``int`` variables on the Maple. + +See Also +-------- + +- :ref:`int ` + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/keywords.rst b/docs/source/lang/cpp/keywords.rst new file mode 100644 index 0000000..e4ebe99 --- /dev/null +++ b/docs/source/lang/cpp/keywords.rst @@ -0,0 +1,205 @@ +.. _lang-keywords: + +Keywords +======== + +This page lists all of the C++ keywords, and either links to a +reference page explaining their use, or provides a brief description. + +List of Keywords +---------------- + +The C++ keywords are: + +``and``, ``and_eq``, ``asm``, ``auto``, ``bitand``, ``bitor``, +``bool``, ``break``, ``case``, ``catch``, ``char``, ``class``, +``compl``, ``const``, ``const_cast``, ``continue``, ``default``, +``delete``, ``do``, ``double``, ``dynamic_cast``, ``else``, ``enum``, +``explicit``, ``export``, ``extern``, ``false``, ``float``, ``for``, +``friend``, ``goto``, ``if``, ``inline``, ``int``, ``long``, +``mutable``, ``namespace``, ``new``, ``not``, ``not_eq``, +``operator``, ``or``, ``or_eq``, ``private``, ``protected``, +``public``, ``register``, ``reinterpret_cast``, ``return``, ``short``, +``signed``, ``sizeof``, ``static``, ``static_cast``, ``struct``, +``switch``, ``template``, ``this``, ``throw``, ``true``, ``try``, +``typedef``, ``typeid``, ``typename``, ``union``, ``unsigned``, +``using``, ``virtual``, ``void``, ``volatile``, ``wchar_t``, +``while``, ``xor``, ``xor_eq`` + +Boolean Operator Synonyms +------------------------- + +- ``and`` is a synonym for :ref:`&& `. +- ``not`` is a synonym for :ref:`\! `. +- ``not_eq`` is a synonym for :ref:`\!= `. +- ``or`` is a synonym for :ref:`|| `. + +Bitwise Operator Synonyms +------------------------- + +- ``and_eq`` is a synonym for :ref:`&= `. +- ``bitand`` is a synonym for (bitwise) :ref:`& `. +- ``bitor`` is a synonym for :ref:`\| `. +- ``compl`` is a synonym for :ref:`~ `. +- ``or_eq`` is a synonym for :ref:`|= `. +- ``xor`` is a synonym for :ref:`^ `. +- ``xor_eq`` is a synonym for :ref:`^= `. + +Constants +--------- + +- ``true`` and ``false`` are the :ref:`boolean constants + `. + +Control Flow +------------ + +- ``break`` can exit out of a :ref:`switch statement + ` or a :ref:`for `, :ref:`do + `, or :ref:`while ` loop. + +- ``case`` defines alternatives in a :ref:`switch statement `. + +- ``continue`` will move control flow to the next iteration of the + enclosing :ref:`for `, :ref:`do `, or + :ref:`while ` loop. + +- ``default`` defines the default alternative in a :ref:`switch + statement `. + +- ``do`` introduces a :ref:`do ` loop. + +- ``else`` is used in :ref:`if statements `. + +- ``for`` introduces a :ref:`for ` loop. + +- ``goto`` :ref:`jumps ` to a label. + +- ``if`` introduces an :ref:`if statement `. + +- ``return`` :ref:`transfers flow to a function's caller `. + +- ``switch`` introduces a :ref:`switch statement `. + +- ``while`` introduces a :ref:`while ` loop. + +Types +----- + +The following keywords are used for built-in types. + +- :ref:`bool ` +- :ref:`lang-char` +- :ref:`lang-double` +- :ref:`lang-float` +- :ref:`lang-int` +- :ref:`lang-long` +- :ref:`short ` +- :ref:`void ` (not really a type, but used in the absence + of one) + +The following keywords are used to introduce new types. + +- :ref:`enum ` + +Qualifiers +---------- + +- :ref:`static ` can be used to declare persistent local + variables; it has other uses not documented here. + +- ``unsigned`` is used to specify an unsigned integral type. + Examples: :ref:`lang-unsignedint`, :ref:`lang-unsignedchar`, + :ref:`lang-unsignedlong`. + +- :ref:`volatile ` is useful when declaring variables + that may be modified by external interrupts. + +- :ref:`const ` is used to define constants. + +Other +----- + +These keywords are not described in the Maple documentation. For more +information, consult a C++ reference. + +- ``asm`` is used to insert literal assembly language. + +- ``auto`` is used to declare that a variable has automatic storage. + +- ``catch`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``class`` is used to define classes. + +- ``const_cast`` is used in typecasting. + +- ``delete`` is used to free ``new``\ -allocated storage. Note that + dynamic memory allocation is not available by default on the Maple, + so you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``dynamic_cast`` is used in typecasting. + +- ``explicit`` is used to declare constructors that can be called only + explicitly. + +- ``export`` declares a template definition accessible to other + compilation units. + +- ``extern`` can mark a declaration as a declaration and not a + definition, and also grant external linkage to a ``const`` or + ``typedef``. + +- ``friend`` is used to declare that certain functions have access to + a class's private variables. + +- ``inline`` is a compiler hint to inline a function. + +- ``mutable`` specifies that a member can be updated, even when a + member of a ``const`` object. + +- ``namespace`` declares a new namespace. + +- ``new`` dynamically allocates space for a value. Note that dynamic + memory allocation is not available by default on the Maple, so + you'll have to bring your own ``new`` and ``delete`` if you want + this. + +- ``operator`` is used to define type-specific operator overrides. + +- ``private`` declares a private class member. + +- ``protected`` declares a protected class member. + +- ``public`` declares a public class member. + +- ``register`` is a compiler hint to store a variable in a register. + +- ``reinterpret_cast`` is used in typecasting. + +- ``signed`` is the opposite of ``unsigned``. + +- ``static_cast`` is used in typecasting. + +- ``struct`` declares a new struct. + +- ``template`` introduces a template class, function, etc. + +- ``this`` is a pointer to the receiver object. + +- ``throw`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``try`` is used in exception handling. Note that the default + flags we pass to :ref:`GCC ` include ``-fno-exceptions``. + +- ``typedef`` defines a type synonym. + +- ``union`` defines an untagged union. + +- ``using`` is a directive related to namespaces. + +- ``virtual`` declares a method which may be overridden. + +- ``wchar_t`` is the wide character type. diff --git a/docs/source/lang/cpp/long.rst b/docs/source/lang/cpp/long.rst new file mode 100644 index 0000000..d8498c0 --- /dev/null +++ b/docs/source/lang/cpp/long.rst @@ -0,0 +1,52 @@ +.. highlight:: cpp + +.. _lang-long: + +``long`` +======== + +The ``long`` data type stores extended size integer values. You can +use a ``long`` when your values are too large to fit into an :ref:`int +`. A ``long`` occupies 8 bytes of memory. This yields a +range of approximately -9.2×10^18 to 9.2×10^18 (that's 9.2 billion +billion, or about 92 million times the number of stars in the Milky +Way galaxy). The exact range of a ``long`` on the Maple is from +-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, or -2^63 to +(2^63-1). A ``long`` it is subject to the same :ref:`overflow issues +` as any numeric data type. + +Here's an example of declaring a long (see :ref:`integer constants +` for an explanation of the "L" at the end of the +number):: + + // Speed of light in nanometers per second (approximate). + long c = 299792458000000000L; + +The general syntax for declaring an ``long`` variable named ``var``, +then giving it value ``val``, looks like:: + + long var = val; + +This is identical to the ``int`` syntax, with ``long`` replacing +``int``. + +Note that ``long`` values will still :ref:`overflow +`, just like ``int`` values, but their much +larger range makes this less likely to happen. + +The downside to using a ``long`` instead of an ``int`` (besides the +extra storage) is that :ref:`arithmetic ` operations +on ``long``\ s will take slightly longer than on ``int``\ s. + +See Also +-------- + +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`int ` +- :ref:`unsigned int ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/longcast.rst b/docs/source/lang/cpp/longcast.rst new file mode 100644 index 0000000..2b92345 --- /dev/null +++ b/docs/source/lang/cpp/longcast.rst @@ -0,0 +1,27 @@ +.. highlight:: cpp + +.. _lang-longcast: + +``long()`` (cast) +================= + +Converts a value to the :ref:`long ` data type. Here is +an example:: + + double d = 2.5; + long i = long(d); // i holds "2L", an long value + +The value inside of the parentheses (``long(...)``) can be of any type. +However, if it is not a numeric type (like ``double``, ``char``, +etc.), you will get strange results. + +See the :ref:`long ` reference for details about the +precision and limitations of ``long`` variables on the Maple. + +See Also +-------- + +- :ref:`long ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/modulo.rst b/docs/source/lang/cpp/modulo.rst new file mode 100644 index 0000000..289fba0 --- /dev/null +++ b/docs/source/lang/cpp/modulo.rst @@ -0,0 +1,70 @@ +.. highlight:: cpp + +.. _lang-modulo: + +Modulo Operator (``%``) +======================= + +Calculates the `remainder `_ +when one integer is divided by another. It is useful for keeping a +variable within a particular range (e.g. the size of an array). + +Syntax +------ + +:: + + dividend % divisor + +Parameters +---------- + +**dividend**: the number to be divided + +**divisor**: the number to divide by + +Returns +------- + +The remainder of **dividend**\ /\ **divisor**\ . + +Examples +-------- + +:: + + int x; + x = 7 % 5; // x now contains 2 + x = 9 % 5; // x now contains 4 + x = 5 % 5; // x now contains 0 + x = 4 % 5; // x now contains 4 + +:: + + /* update one value in an array each time through a loop */ + + int values[10]; + int i = 0; + + void setup() { + // no setup necessary + } + + void loop() { + values[i] = analogRead(0); + i = (i + 1) % 10; // modulo operator makes sure i stays between 0 and 9 + } + +Tip +--- + +The modulo operator does not work on floats. For that, you can use +the C standard library function `fmod() +`_. + +See Also +-------- + +- :ref:`Arithmetic ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/numeric-types.rst b/docs/source/lang/cpp/numeric-types.rst new file mode 100644 index 0000000..9d2be48 --- /dev/null +++ b/docs/source/lang/cpp/numeric-types.rst @@ -0,0 +1,79 @@ +.. _lang-numeric-types: + +Numeric types +============= + +This document serves as a reference for all of the built-in numeric +types which are available when programming in the IDE. Programmers +using the :ref:`command-line tools ` will have access +to these types as long as they have imported ``wirish.h``; several are +defined in in `libmaple_types.h +`_. + +.. _lang-numeric-types-integral: + +Integral types +-------------- + +.. cpp:type:: char + + 8-bit integer value. + +.. cpp:type:: short + + 16-bit integer value. + +.. cpp:type:: int + + 32-bit integer value. + +.. cpp:type:: long + + 64-bit integer value. + +.. cpp:type:: long long + + 64-bit integer value. + +.. cpp:type:: int8 + + Synonym for ``char``. + +.. cpp:type:: uint8 + + Synonym for ``unsigned char``. + +.. cpp:type:: int16 + + Synonym for ``short``. + +.. cpp:type:: uint16 + + Synonym for ``unsigned short``. + +.. cpp:type:: int32 + + Synonym for ``int``. + +.. cpp:type:: uint32 + + Synonym for ``unsigned int`` + +.. cpp:type:: int64 + + Synonym for ``long long`` + +.. cpp:type:: uint64 + + Synonym for ``unsigned long long``. + +Floating-Point Types +-------------------- + +.. cpp:type:: float + + 32-bit, IEEE 754 single-precision floating-point type. + +.. cpp:type:: double + + 64-bit, IEEE 754 double-precision floating-point type. diff --git a/docs/source/lang/cpp/pointer.rst b/docs/source/lang/cpp/pointer.rst new file mode 100644 index 0000000..0a42270 --- /dev/null +++ b/docs/source/lang/cpp/pointer.rst @@ -0,0 +1,31 @@ +.. _lang-pointer: + +Pointer Operators (``&``, ``*``) +================================ + +The pointer operators ``&`` (reference) and ``*`` (dereference) are +different from the bitwise math operator :ref:`& +` and the arithmetic operator :ref:`* +`. + +Pointers are one of the more complicated subjects for beginners in +learning C, and it is possible to write many useful Arduino sketches +without ever encountering pointers. However, for manipulating certain +data structures, the use of pointers can simplify the code, improve +its efficiency, and generally provide many benefits that would be +difficult to achieve without the use of pointers. + +Introducing pointers is somewhat outside the scope of this +documentation. However, a good `pointer tutorial +`_ is available. +Also see the `Wikipedia article on pointers +`_, especially +the section on `pointers in C +`_. + +See Also +-------- + +- http://xkcd.com/138/ + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/return.rst b/docs/source/lang/cpp/return.rst new file mode 100644 index 0000000..7b5039e --- /dev/null +++ b/docs/source/lang/cpp/return.rst @@ -0,0 +1,61 @@ +.. highlight:: cpp + +.. _lang-return: + +``return`` +========== + +Terminates a function and return a value from a function to the +calling function, if the function has non-``void`` return type. + +Syntax: +------- + +:: + + // from within a "void" function: + return; + + // from within a non-"void" function: + return value; + +In the second case, ``value`` should have a type which is the same as +the return type of the function, or be convertible to it (like an +``int`` to a ``long``, etc.; see :ref:`this note +` for some references). + +Examples: +--------- + +A function to compare a sensor input to a threshold:: + + // converts analog readings between 0 and 400 to 0, and 400 up to 1. + int checkSensor() { + if (analogRead(0) > 400) { + return 1; + else { + return 0; + } + } + +An early ``return`` is also useful when testing a section of code +without having to "comment out" large sections of possibly buggy code, +like so:: + + void loop() { + + // brilliant code idea to test here + + return; + + // the rest of a dysfunctional sketch here + // this code will never be executed + } + +See Also +-------- + +- :ref:`comments ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/scope.rst b/docs/source/lang/cpp/scope.rst new file mode 100644 index 0000000..7b65bab --- /dev/null +++ b/docs/source/lang/cpp/scope.rst @@ -0,0 +1,120 @@ +.. highlight:: cpp + +.. _lang-scope: + +Scope +===== + +Variables in the C++ programming language, which Maple uses (all of +your sketches are C++ programs in disguise), have a property called +*scope*. Simply put, a variable's scope is made up of all of the +lines where the variable can be used. + +Scope in C++ is a fairly complex topic, so we won't try to describe it +in full here. Instead, we present a simplified view, describing two +different kinds of scopes, *global* and *local*. For more detailed +information, consult a C++ reference. + +Global and Local Variables +-------------------------- + +A global variable is one that can be "seen" by every function in a +program. In the :ref:`Maple IDE `, any variable declared outside +of a function (like :ref:`setup() ` and :ref:`loop() +`) is a global variable. + +A local variable can only be "seen" inside of a particular function. +You can declare a variable to be local to a function by declaring it +inside of the :ref:`curly braces ` which enclose +that function. + +When programs start to get larger and more complex, local variables +are a useful way to ensure that a function has exclusive access to its +own variables. This prevents programming errors when one function +mistakenly modifies variables used by another function. + +It is also sometimes useful to declare and initialize a variable +inside a :ref:`for ` loop. This creates a variable that +can only be accessed from inside the loop body. + +Example +------- + +Here is an example sketch (which you can copy into the Maple IDE and +run on your Maple) that illustrates the use of global and local +variables, as well as declaring variables inside of a ``for`` loop. +Be sure to open a :ref:`serial monitor ` after you +:ref:`verify ` and :ref:`upload ` the sketch:: + + int globalVar; // any function will see this variable + + void setup() { + // since "globalVar" is declared outside of any function, + // every function can "see" and use it: + globalVar = 50; + + // the variables "i" and "d" declared inside the "loop" function + // can't be seen here. see what happens when you uncomment the + // following lines, and try to Verify (compile) the sketch: + // + // i = 16; + // SerialUSB.print("i = "); + // SerialUSB.println(i); + // d = 26.5; + // SerialUSB.print("d = "); + // SerialUSB.println(d); + } + + void loop() { + // since "i" and "d" are declared inside of the "loop" function, + // they can only be seen and used from inside of it: + int i; + double d; + + for (int j = 0; j < 5; j++) { + // variable i can be used anywhere inside the "loop" function; + // variable j can only be accessed inside the for-loop brackets: + i = j * j; + SerialUSB.print("i = "); + SerialUSB.println(i); + } + + // globalVar can be accessed from anywhere. note how even + // though we set globalVar = 50 in the "setup" function, we can + // see that value here: + SerialUSB.print("globalVar = "); + SerialUSB.println(globalVar); + + // d can be accessed from anywhere inside the "loop" function: + d = 26.5; + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (before separateFunction())"); + + separateFunction(); + + // notice how even though separateFunction() has a variable + // named "d", it didn't touch our (local) variable which has + // the same name: + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (after separateFunction())"); + } + + void separateFunction() { + // variable "d" here has the same name as variable "d" inside of + // the "loop" function, but since they're both _local_ + // variables, they don't affect each other: + double d = 30.5; + SerialUSB.print("d = "); + SerialUSB.print(d); + SerialUSB.println(" (inside of separateFunction())"); + } + +See Also +-------- + +- `C++ programming Wikibook `_. +- Wikipedia article on `scope `_ + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/semicolon.rst b/docs/source/lang/cpp/semicolon.rst new file mode 100644 index 0000000..8164616 --- /dev/null +++ b/docs/source/lang/cpp/semicolon.rst @@ -0,0 +1,25 @@ +.. highlight:: cpp + +.. _lang-semicolon: + +Semicolon (``;``) +================= + +Used to end a line of code. Example:: + + int a = 13; + +Tip +--- + +Forgetting to end a line in a semicolon will result in a compiler +error. The error text may be obvious, and refer to a missing +semicolon, or it may not. If an impenetrable or seemingly illogical +compiler error comes up, one of the first things to check is a +missing semicolon, in the immediate vicinity, preceding the line at +which the compiler complained. + + + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/sizeof.rst b/docs/source/lang/cpp/sizeof.rst new file mode 100644 index 0000000..eae509c --- /dev/null +++ b/docs/source/lang/cpp/sizeof.rst @@ -0,0 +1,64 @@ +.. highlight:: cpp + +.. _lang-sizeof: + +``sizeof()`` +============ + +The ``sizeof`` operator on the Maple returns the number of bytes +needed to store a value of a given type\ [#fcharsize]_. This can be +an ordinary numeric type, like ``int``. It can be something more +complicated, like a ``struct`` or ``union``. If the argument to +``sizeof`` is an array, it returns the total number of bytes occupied +by the array. + +The general syntax looks like this:: + + sizeof(type) + sizeof(var) + +Example +------- + +The ``sizeof`` operator is useful for dealing with arrays (such as +strings) where it is convenient to be able to change the size of the +array without breaking other parts of the program. + +This program prints out a text string one character at a time. Try +changing the text phrase:: + + char myStr[] = "this is a test"; + int i; + + void setup() { + Serial.begin(9600); + } + + void loop() { + for (i = 0; i < sizeof(myStr) - 1; i++) { + Serial.print(i, DEC); + Serial.print(" = "); + Serial.println(myStr[i], BYTE); + } + } + + +Note that ``sizeof`` returns the total number of bytes. So for larger +variable types such as ``int``, the :ref:`for loop ` +would look something like this:: + + for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { + // do something with myInts[i] + } + +.. rubric:: Footnotes + +.. [#fcharsize] Technically (and pedantically) speaking, ``sizeof`` + returns a multiple of the number of bits a ``char`` occupies in + memory. However, on the Maple (this goes for most C++ + implementations), a ``char`` occupies 8 bits = 1 byte. All the C++ + standard guarantees, however, is that a ``char`` occupies at + *least* 8 bits. + +.. include:: cc-attribution.txt + diff --git a/docs/source/lang/cpp/sqrt.rst b/docs/source/lang/cpp/sqrt.rst new file mode 100644 index 0000000..956a754 --- /dev/null +++ b/docs/source/lang/cpp/sqrt.rst @@ -0,0 +1,25 @@ +.. _lang-sqrt: + +sqrt() +====== + +Calculates the square root of a number. + +Library Documentation +--------------------- + +.. doxygenfunction:: sqrt + +Arduino Compatibility +--------------------- + +The Maple versino of ``sqrt()`` is compatible with Arduino. + +See Also +-------- + +- :ref:`pow ` +- :ref:`sq ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/static.rst b/docs/source/lang/cpp/static.rst new file mode 100644 index 0000000..5d1802e --- /dev/null +++ b/docs/source/lang/cpp/static.rst @@ -0,0 +1,57 @@ +.. highlight:: cpp + +.. _lang-static: + +``static`` +========== + +The ``static`` keyword can be used to create variables that are +visible to only one function. However, unlike local variables that get +created and destroyed every time a function is called, ``static`` +variables persist beyond the function call, preserving their data +between function calls. + +Variables declared as ``static`` will only be created and initialized +the first time a function is called. + +.. note:: This is only one use of the ``static`` keyword in C++. It + has some other important uses that are not documented here; consult + a reliable C++ reference for details. + +Example +------- + +One use case for ``static`` variables is implementing counters that +last longer than the functions which need them, but shouldn't be +shared to other functions. Here's an example:: + + void setup() { + SerialUSB.begin(); + } + + void loop() { + int reading; + if (timeToReadSensors()) { + reading = readSensors(); + } + // do something with reading + } + + int readSensors() { + static int numSensorReadings = 0; + numSensorReadings++; + if (numSensorReadings % 100 == 0) { + SerialUSB.print("just got to another 100 sensor readings"); + } + return analogRead(...); + } + +In this example, the static variable ``numSensorReadings`` is +initialized to zero the first time ``readSensors()`` is called, and +then incremented, so it starts out at one. Subsequent calls to +``readSensors()`` won't reset ``numSensorReadings`` to zero, because +it was declared ``static``. Thus, ``numSensorReadings`` is a count of +the number of times that ``readSensors()`` has been called. + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/string.rst b/docs/source/lang/cpp/string.rst new file mode 100644 index 0000000..0a270da --- /dev/null +++ b/docs/source/lang/cpp/string.rst @@ -0,0 +1,128 @@ +.. highlight:: cpp + +.. _lang-string: + +Strings +======= + +Text strings can be represented in two ways. You can + +1. Use the :ref:`String ` data type, which is +part of the core as of version 0.0.9, or + +2. You can make a string out of an array of type :ref:`char +` and null-terminate it. + +This page describes the second method. + +Examples +-------- + +All of the following are valid declarations for strings:: + + char str1[15]; + char str2[6] = {'m', 'a', 'p', 'l', 'e'}; + char str3[6] = {'m', 'a', 'p', 'l', 'e', '\0'}; + char str4[ ] = "maple"; + char str5[6] = "maple"; + char str6[15] = "maple"; + +As you can see, there are several methods available for declaring and +initializing strings: + +- Declare an array of ``char`` without initializing it, as with ``str1``. + +- Declare an array of ``char`` (with one extra ``char``) and the + compiler will add the required null character, as with ``str2``. + +- Explicitly add the null character (``'\0'``), as with ``str3``. + +- Initialize with a string constant in quotation marks (``"..."``); + the compiler will size the array to fit the string constant and a + terminating null character (``str4``). + +- Initialize the array with an explicit size and string constant, + (``str5``). + +- Initialize the array, leaving extra space for a larger string + (``str6``). + +Null Termination +---------------- + +Generally, strings are terminated with a null character (`ASCII +`_ code 0). This allows functions +(like ``SerialUSB.print()``) to tell where the end of a string is. +Otherwise, they would continue reading subsequent bytes of memory that +aren't actually part of the string. + +This means that your string needs to have space for one more character +than the text you want it to contain. That is why ``str2`` and +``str5`` need to be six characters, even though "maple" is only five +-- the last position is automatically filled with a NULL +character. ``str4`` will be automatically sized to six characters, one +for the extra null. In the case of ``str3``, we've explicitly included +the null character (written ``'\0'``) ourselves. + +Note that it's possible to have a string without a final null +character (e.g. if you had specified the length of ``str2`` as five +instead of six). This will break most functions that use strings, so +you shouldn't do it intentionally. If you notice something behaving +strangely (operating on characters not in the string), however, this +could be the problem. + +Single quotes or double quotes? +------------------------------- + +Strings are always defined inside double quotes (``"Abc"``) and +characters are always defined inside single quotes (``'A'``). + +Wrapping long strings +--------------------- + +You can wrap long strings like this:: + + char myString[] = "This is the first line" + " this is the second line" + " etcetera"; + +Arrays of Strings +----------------- + +It is often convenient, when working with large amounts of text, +such as a project with an LCD display, to setup an array of +strings. Because strings themselves are arrays, this is in actually +an example of a two-dimensional array. + +In the code below, the asterisk after the datatype char ``char *`` +indicates that this is an array of "pointers". All array names are +actually pointers, so this is required to make an array of arrays. +Pointers are one of the more esoteric parts of C for beginners to +understand, but it isn't necessary to understand pointers in detail to +use them effectively here:: + + char* myStrings[] = {"This is string 1", "This is string 2", + "This is string 3", "This is string 4", + "This is string 5", "This is string 6"}; + + void setup() { + SerialUSB.begin(); + } + + void loop() { + for (int i = 0; i < 6; i++) { + SerialUSB.println(myStrings[i]); + delay(500); + } + } + + +See Also +-------- + +- :ref:`array ` +- :ref:`__attribute__ ` +- :ref:`Variables ` + + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/switchcase.rst b/docs/source/lang/cpp/switchcase.rst new file mode 100644 index 0000000..b484bc5 --- /dev/null +++ b/docs/source/lang/cpp/switchcase.rst @@ -0,0 +1,118 @@ +.. highlight:: cpp + +.. _lang-switchcase: + +``switch``\ /\ ``case`` +======================= + +Like :ref:`if ` statements, A ``switch`` statement controls +program flow by allowing you to specify different code that should be +executed under various cases. + +The general syntax looks like this:: + + switch (var) { + case val1: + // statements + break; + case val2: + // statements + break; + ... + default: + // statements + } + +Where ``var`` is a variable whose value to investigate, and the +``val1``, ``val2`` after each ``case`` are constant values that +``var`` might be. + +Description +----------- + +A ``switch`` statement compares the value of a variable to the values +specified in ``case`` statements. When a ``case`` statement is found +whose value matches that of the variable, the code in that case +statement is run. + +Here's a more concrete example:: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + } + afterTheSwitch(); + +In the above example, if ``var == 1``, then the code beginning on the +line after ``case 1`` gets executed. That is, if ``var`` is one, +``doThing1()`` gets called first, and then the ``break`` statement is +executed. + +The ``break`` keyword exits the ``switch`` statement, and is typically +used at the end of each ``case``. Since there is a ``break`` at the +end of ``case 1``, the ``switch`` statement exits, and the next line +to be run is the one which calls ``afterTheSwitch()``. + +Without a ``break``, the ``switch`` statement will continue executing +the following ``case`` expressions ("falling-through") until a +``break`` (or the end of the switch statement) is reached. Let's +pretend the ``switch`` looked like this instead:: + + switch (var) { + case 1: + doThing1(); + // no break statement anymore + case 2: + doThing2(); + break; + } + afterTheSwitch(); + +Now, if ``var`` is one, ``doThing1()`` gets executed like before. +However, without a ``break``, the code would continue to be executed +line-by-line, so ``doThing2()`` would be called next. At this point, +a ``break`` has been reached, so the program continues by calling +``afterTheSwitch()``. This is usually not what you want, which is why +each ``case`` usually has a ``break`` at the end. + +.. _lang-switchcase-default: + +Writing "``default:``" instead of a ``case`` statement allows you to +specify what to do if none of the ``case`` statements matches. Having +a ``default`` is optional (you can leave it out), but if you have one, +it must appear after all of the ``case`` statements. Let's add a +``default`` to the ``switch`` we've been discussing:: + + switch (var) { + case 1: + doThing1(); + break; + case 2: + doThing2(); + break; + default: + doSomethingElse(); + } + afterTheSwitch(); + +If ``var`` is one, then ``doThing1()`` gets called. If ``var`` is +two, ``doThing2()`` gets called. If ``var`` is anything else, +``doSomethingElse()`` gets called. As stated above, a ``default`` is +optional. If you're missing one and none of the ``case`` statements +match, the ``switch`` does nothing at all, as if it weren't there. + +``switch`` statements are often used with an :ref:`enum ` +value as the variable to compare. In this case, you can write down +all of the values the ``enum`` takes as ``case`` statements, and be +sure you've covered all the possibilities. + +See also: +--------- + +- :ref:`if/else ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/unsignedchar.rst b/docs/source/lang/cpp/unsignedchar.rst new file mode 100644 index 0000000..5b946ed --- /dev/null +++ b/docs/source/lang/cpp/unsignedchar.rst @@ -0,0 +1,33 @@ +.. highlight:: cpp + +.. _lang-unsignedchar: + +``unsigned char`` +================= + +An unsigned version of the :ref:`char ` data type. An +``unsigned char`` occupies 1 byte of memory; it stores an integer from +0 to 255. + +Like an :ref:`unsigned int `, an ``unsigned char`` +won't store negative numbers; it is also subject to the same +:ref:`overflow issues ` as any integral data type. + +Example +------- + +:: + + unsigned char c = 240; + +See Also +-------- + + +- :ref:`byte ` +- :ref:`int ` +- :ref:`array ` +- :ref:`SerialUSB.println() ` +- :ref:`Serial.println() ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/unsignedint.rst b/docs/source/lang/cpp/unsignedint.rst new file mode 100644 index 0000000..f6311da --- /dev/null +++ b/docs/source/lang/cpp/unsignedint.rst @@ -0,0 +1,55 @@ +.. highlight:: cpp + +.. _lang-unsignedint: + +``unsigned int`` +================ + +An ``unsigned int`` (unsigned integer) is the same as an :ref:`int +` in that it stores a 4 byte integer value. However, +Instead of storing both negative and positive numbers, an ``unsigned +int`` can only store nonnegative values, yielding a range of 0 to +4,294,967,295 (the positive value is 2^32 - 1). + +The difference between an ``unsigned int`` and a (signed) ``int`` lies +in the way the highest bit, sometimes referred to as the "sign" bit, +is interpreted. In the case of the Maple ``int`` type (which is +signed), if the high bit is a "1", the number is interpreted as a +negative number, using a technique known as `two's complement math +`_. The +bits in an an ``unsigned int`` are interpreted according to the usual +rules for converting `binary to decimal +`_. + +An ``unsigned int`` is subject to the same :ref:`overflow issues +` as a regular ``int``; the only difference is +that an ``unsigned int`` will "underflow" at 0, and "overflow" at +4,294,967,295. Here is some example code which illustrates this:: + + unsigned int x; + x = 0; + x--; // x now contains 4,294,967,295; rolled over "left to right" + x++; // x now contains 0; rolled over "right to left" + +Here is an example of declaring an ``unsigned int`` variable named +``ledPin``, then giving it value 13:: + + unsigned int ledPin = 13; + +The general syntax for declaring an ``unsigned int`` variable named +``var``, then giving it value ``val``, looks like:: + + unsigned int var = val; + +See Also +-------- + +- :ref:`int ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`long ` +- :ref:`unsigned long ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/unsignedlong.rst b/docs/source/lang/cpp/unsignedlong.rst new file mode 100644 index 0000000..14a4fc3 --- /dev/null +++ b/docs/source/lang/cpp/unsignedlong.rst @@ -0,0 +1,41 @@ +.. highlight:: cpp + +.. _lang-unsignedlong: + +``unsigned long`` +================= + +An unsigned version of the :ref:`long ` data type. An +``unsigned long`` occupies 8 bytes of memory; it stores an integer +from 0 to 2^64-1, which is approximately 1.8×10^19 (18 quintillion, or +18 billion billion). + +Like an :ref:`unsigned int `, an ``unsigned long`` +won't store negative numbers; it is also subject to the same +:ref:`overflow issues ` as any integral data type. + +Here is an example of declaring an ``unsigned long`` variable named +``c``, then giving it value 299,792,458,000,000,000 (see :ref:`integer +constants ` for an explanation of the "L" +at the end of the number):: + + // Speed of light in nanometers per second (approximate). + unsigned long c = 299792458000000000L; + +The general syntax for declaring an ``unsigned long`` variable named +``var``, then giving it value ``val``, looks like:: + + unsigned long var = val; + +See Also +-------- + +- :ref:`long ` +- :ref:`int ` +- :ref:`unsigned ` +- :ref:`char ` +- :ref:`unsigned char ` +- :ref:`Integer Constants ` +- :ref:`Variables ` + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/variables.rst b/docs/source/lang/cpp/variables.rst new file mode 100644 index 0000000..9094cd5 --- /dev/null +++ b/docs/source/lang/cpp/variables.rst @@ -0,0 +1,170 @@ +.. highlight:: cpp + +.. _lang-variables: + +Variables +========= + +A variable is a way of naming and storing a value for later use by +the program, such as data from a sensor or an intermediate value +used in a calculation. + +.. contents:: Contents + :local: + +.. _lang-variables-declaring: + +Declaring Variables +------------------- + +Before they are used, all variables have to be *declared*. Declaring a +variable means defining its type, giving it a name, and (optionally) +giving it an initial value (this is often referred to as +*initializing* the variable). Variables do not have to be initialized +(given a value) when they are declared, but it is good style to give +them an initial value whenever possible. + +Here is an example of declaring a variable named ``inputVariable1`` +with type :ref:`int ` (the ``int`` type is used to store +integers, like -2, -1, 0, 1, etc.):: + + int inputVariable1; + +In the above declaration, we did not give the variable an initial +value. Here is another example, where we declare an ``int`` variable +named ``inputVariable2``, with an initial value of ``0``:: + + int inputVariable2 = 0; + +The Maple environment comes ready to use with many useful types of +variables. See the :ref:`built-in types ` page +for more information. + +Here are a few examples of declaring variables of different types:: + + int lightSensVal; + char currentLetter; + unsigned long speedOfLight = 186000UL; + char errorMessage = {"choose another option"}; // see string + +Naming Variables +---------------- + +The rules for naming a variable are simple. Names for variables can +contain letters, numbers, and underscores (the underscore is the +:kbd:`_` character), and cannot begin with a number. So +``temperature_reading``, ``tempReading``, ``tempReading1``, and +``tempReading2`` are all valid variable names, but ``4_temp_readings`` +is not, because it begins with a number. + +You cannot choose a name for a variable that is one of the C++ +:ref:`keywords `. + +Variable names are case-sensitive, so "tempreading" and "tempReading" +are different variables. However, it is very bad style to write code +that chooses variables which are the same up to case. + +You should give your variables descriptive names, so as to make your +code more readable. Variable names like ``tiltSensor`` or +``pushButton`` help you (and anyone else reading your code) understand +what the variable represents. Variable names like ``var`` or +``value``, on the other hand, do little to make your code readable. + +.. _lang-variables-scope: + +Variable Scope +-------------- + +An important choice that programmers face is where (in the program +text) to declare variables. The specific place that variables are +declared influences how various functions in a program will "see" the +variable. This is called variable *scope*. See the :ref:`scope +reference ` for more information. + +.. _lang-variables-initializing: + +Initializing Variables +---------------------- + +Variables may be *initialized* (assigned a starting value) when they +are declared or not. It is always good programming practice however to +double check that a variable has valid data in it before it is used. +Using a variable before you give it a value is a common source of +bugs. + +.. _lang-variables-rollover: + +Variable Rollover +----------------- + +Every (numeric) type has a valid *range*. The range of a type is the +smallest and largest value that a variable of that type can store. +For example, the :ref:`int ` type has a range of +-2,147,483,648 to 2,147,483,647 [#frange]_. + +When variables are made to exceed their range's maximum value, they +"roll over" back to their minimum value. Note that this happens in +both directions. It's like in the game *Pac-Man* -- when Pac-Man goes +past the right edge of the screen, he reappears on the left, and when +he goes past the left side of the screen, he reappears on the right:: + + int x; + x = -2,147,483,648; + x = x - 1; // x now contains -2,147,483,647; rolled over "left to right" + + x = 2,147,483,647; + x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" + +Each numeric type's reference page includes its range. See the +:ref:`built-in types ` reference for links to each +type's reference page. + +Using Variables +--------------- + +Once variables have been declared, they are given values using the +:ref:`assignment operator `, which is a single equals +sign, ``=``. The assignment operator tells the program to store the +value on the right side of the equals sign into the variable on the +left side:: + + inputVariable1 = 7; // sets variable named inputVariable1 to 7 + inputVariable2 = analogRead(2); // sets variable named inputVariable2 to + // the (digitized) input voltage read from + // analog pin #2 + +Once a variable has been set (assigned a value), you can test its +value to see if it meets certain conditions, or you can use its value +directly. For instance, the following code tests whether the +inputVariable2 is less than 100, then sets a delay based on +inputVariable2 (which, at that point, is at least 100):: + + if (inputVariable2 < 100) { + inputVariable2 = 100; + } + + delay(inputVariable2); + +See Also +-------- + +- :ref:`lang-scope` +- :ref:`lang-numeric-types` + +.. rubric:: Footnotes + +.. [#frange] This range might seem a little weird at first. The + reasons for this range of values have to do with the fact that an + ``int`` occupies 32 bits of memory, and the facts :: + + 2^31 = -2,147,483,648 + 2^31 - 1 = 2,147,483,647 + + + Why 2^31 instead of 2^32? Well, that has to do with `how ints are + (usually) stored + `_ on computers. + + +.. include:: cc-attribution.txt + diff --git a/docs/source/lang/cpp/void.rst b/docs/source/lang/cpp/void.rst new file mode 100644 index 0000000..88bd448 --- /dev/null +++ b/docs/source/lang/cpp/void.rst @@ -0,0 +1,31 @@ +.. highlight:: cpp + +.. _lang-void: + +``void`` +======== + +The ``void`` keyword is used only in function declarations. It +indicates that the function is expected to return no information to +the function from which it was called, or that it expects no arguments +from its caller. + +Example +------- + +:: + + // actions are performed in the functions "setup" and "loop" + // but no information is reported to the larger program + + void setup() { + // ... + } + + void loop() { + // ... + } + +.. TODO doc page on function declaration? + +.. include:: cc-attribution.txt diff --git a/docs/source/lang/cpp/while.rst b/docs/source/lang/cpp/while.rst new file mode 100644 index 0000000..9047d05 --- /dev/null +++ b/docs/source/lang/cpp/while.rst @@ -0,0 +1,38 @@ +.. highlight:: cpp + +.. _lang-while: + +``while`` +========= + +Syntax +------ + +:: + + while (expression) { + // block of code + } + +Description +----------- + +``while`` loops will repeat the statements inside their associated +block of code until the expression inside the parentheses becomes +:ref:`false `. Something must change the tested +expressions' value, or the ``while`` loop will never exit. This could +be in your code, such as an incremented variable, or an external +condition, such as testing a sensor. + +Example +------- + +:: + + var = 0; + while(var < 200) { + // do something repetitive 200 times + var++; + } + +.. include:: cc-attribution.txt diff --git a/docs/source/language-index.rst b/docs/source/language-index.rst index ddc7849..1c5e35f 100644 --- a/docs/source/language-index.rst +++ b/docs/source/language-index.rst @@ -1,16 +1,28 @@ .. _language-index: -Language Reference Index -======================== - -This is the index of the :ref:`language reference ` -documentation. - -.. toctree:: - :maxdepth: 1 - :glob: - - lang/* +============================= +Complete Maple Language Index +============================= + +This is the index of Maple's :ref:`language reference ` documentation. The 'Maple API' column includes language specific to Maple as a microcontroller development platform, while the language in 'C++ for Maple' is more generally applied. + +# Fix above explanation/have marti write it + +.. _index-language-index-cpp: +.. _index-language-index-api: + ++--------------------------------------------+----------------------------------------------+ +| Maple API | :ref:`C++ for Maple ` | +| | | ++============================================+==============================================+ +| | | +| .. toctree:: | .. toctree:: | +| :maxdepth: 1 | :maxdepth: 1 | +| :glob: | :glob: | +| | | +| lang/api/* | lang/cpp/* | +| | | ++--------------------------------------------+----------------------------------------------+ .. Unfinished, unimplemented in libmaple: diff --git a/docs/source/language.rst b/docs/source/language.rst index 463041e..8e5d454 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -268,10 +268,16 @@ the Maple. However, they will be present in future versions: .. _newlib: http://sourceware.org/newlib/ +.. _cpp-for-maple: + +C++ for Maple +-------------- +If you haven't programmed in C++, or if you just need to jog your memory, you may want to check out our :ref:`C++ for Maple Index`. It covers programming ideas and C++ that will definitely come in handy. + .. _arduino_c_for_c_hackers: -Note for C/C++ Programmers --------------------------- +Note for C/C++ Hackers +---------------------- This is a note for programmers comfortable with C or C++ (although, you C programmers should remember that `C++ is not a superset of C diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 4c87539..567aec8 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -57,8 +57,8 @@ the hardware i2c peripheral on the stm32 as well as the DMA for performance. Support for slave, smBUS, and multimaster modes are also slated for inclusion in the enhanced Wire port. -Function Reference -^^^^^^^^^^^^^^^^^^ +Wire Function Reference +^^^^^^^^^^^^^^^^^^^^^^^ ``Wire.begin()`` Joins the i2c bus as master, using pin 20 as SDA and pin 21 as SCL diff --git a/docs/source/specs.rst b/docs/source/specs.rst new file mode 100644 index 0000000..43c91a1 --- /dev/null +++ b/docs/source/specs.rst @@ -0,0 +1,28 @@ +.. _specs: + +.. _specs-Technical-Specifications: + +================================ +Maple's Technical Specifications +================================ + + * STM32 F103RB: a **32-bit** ARM Cortex M3 microprocessor + * Clock Speed: **72 MHz** + * Operating Voltage: 3.3V + * Input Voltage (recommended): 3.0V-12V + * 39 Digital I/O Pins (:ref:`GPIO `) + * **16 Analog** Input Pins (:ref:`ADC `) + * **15 PWM pins** at 16-bit resolution (:ref:`PWM `) + * Dedicated **USB** port for programming and communications (:ref:`USB`) + * External **JTAG** interface (:ref:`USB `) + * **128 Flash** and **20KB SRAM** + * 64 Channel nested vector interrupt handler (including external interrupt on GPIO’s) + * Integrated **SPI** (:ref:`SPI`) + * Integrated **I2C** (:ref:`I2C`) + * 7 Channels of Direct Memory Access (DMA) + * 3 **USART** divices (:ref:`USART `) + * Four 4-channel Timers (:ref:`Timers `) + * Supplies up to 800mA @ 3.3v + * Support for low power and sleep modes (<500uA) + * Dimensions are 2.05″x2.1″ + -- cgit v1.2.3 From 5ceac644e90c929e77f05d357d1d35d45e673fac Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Fri, 3 Dec 2010 20:18:00 -0500 Subject: cleaning up previous commits. note that addition of new files under docs/source/lang/api and docs/source/lang/cpp which were just copies of files in docs/source/lang/ imply that change history is lost to git. --- docs/source/confDefaultGreen.txt | 250 -------------------------- docs/source/home.rtf | 43 ----- docs/source/lang/abs.rst | 48 ----- docs/source/lang/analogread.rst | 152 ---------------- docs/source/lang/analogwrite.rst | 166 ----------------- docs/source/lang/arithmetic.rst | 127 ------------- docs/source/lang/array.rst | 123 ------------- docs/source/lang/assignment.rst | 70 -------- docs/source/lang/attachinterrupt.rst | 102 ----------- docs/source/lang/bit.rst | 44 ----- docs/source/lang/bitclear.rst | 44 ----- docs/source/lang/bitread.rst | 46 ----- docs/source/lang/bitset.rst | 46 ----- docs/source/lang/bitshift.rst | 144 --------------- docs/source/lang/bitwisemath.rst | 186 ------------------- docs/source/lang/bitwrite.rst | 46 ----- docs/source/lang/boolean.rst | 91 ---------- docs/source/lang/booleanvariables.rst | 54 ------ docs/source/lang/break.rst | 35 ---- docs/source/lang/byte.rst | 34 ---- docs/source/lang/bytecast.rst | 50 ------ docs/source/lang/char.rst | 50 ------ docs/source/lang/charcast.rst | 36 ---- docs/source/lang/comments.rst | 67 ------- docs/source/lang/comparison.rst | 87 --------- docs/source/lang/compoundarithmetic.rst | 44 ----- docs/source/lang/compoundbitwise.rst | 231 ------------------------ docs/source/lang/const.rst | 52 ------ docs/source/lang/constants.rst | 304 -------------------------------- docs/source/lang/constrain.rst | 69 -------- docs/source/lang/continue.rst | 32 ---- docs/source/lang/cos.rst | 32 ---- docs/source/lang/curly-braces.rst | 109 ------------ docs/source/lang/define.rst | 56 ------ docs/source/lang/delay.rst | 72 -------- docs/source/lang/delaymicroseconds.rst | 65 ------- docs/source/lang/detachinterrupt.rst | 37 ---- docs/source/lang/digitalread.rst | 58 ------ docs/source/lang/digitalwrite.rst | 68 ------- docs/source/lang/double.rst | 48 ----- docs/source/lang/doublecast.rst | 27 --- docs/source/lang/dowhile.rst | 27 --- docs/source/lang/enum.rst | 53 ------ docs/source/lang/float.rst | 50 ------ docs/source/lang/floatcast.rst | 28 --- docs/source/lang/for.rst | 142 --------------- docs/source/lang/goto.rst | 130 -------------- docs/source/lang/highbyte.rst | 59 ------- docs/source/lang/if.rst | 121 ------------- docs/source/lang/include.rst | 72 -------- docs/source/lang/increment.rst | 37 ---- docs/source/lang/int.rst | 64 ------- docs/source/lang/intcast.rst | 29 --- docs/source/lang/keywords.rst | 205 --------------------- docs/source/lang/long.rst | 52 ------ docs/source/lang/longcast.rst | 27 --- docs/source/lang/loop.rst | 45 ----- docs/source/lang/lowbyte.rst | 25 --- docs/source/lang/map.rst | 68 ------- docs/source/lang/max.rst | 65 ------- docs/source/lang/micros.rst | 46 ----- docs/source/lang/millis.rst | 52 ------ docs/source/lang/min.rst | 66 ------- docs/source/lang/modulo.rst | 70 -------- docs/source/lang/numeric-types.rst | 79 --------- docs/source/lang/pinmode.rst | 77 -------- docs/source/lang/pointer.rst | 31 ---- docs/source/lang/pow.rst | 23 --- docs/source/lang/pwmwrite.rst | 49 ----- docs/source/lang/random.rst | 73 -------- docs/source/lang/randomseed.rst | 60 ------- docs/source/lang/return.rst | 61 ------- docs/source/lang/scope.rst | 120 ------------- docs/source/lang/semicolon.rst | 25 --- docs/source/lang/serial.rst | 226 ------------------------ docs/source/lang/serialusb.rst | 242 ------------------------- docs/source/lang/setup.rst | 29 --- docs/source/lang/sin.rst | 32 ---- docs/source/lang/sizeof.rst | 64 ------- docs/source/lang/sq.rst | 46 ----- docs/source/lang/sqrt.rst | 25 --- docs/source/lang/static.rst | 57 ------ docs/source/lang/string.rst | 128 -------------- docs/source/lang/switchcase.rst | 118 ------------- docs/source/lang/tan.rst | 31 ---- docs/source/lang/unsignedchar.rst | 33 ---- docs/source/lang/unsignedint.rst | 55 ------ docs/source/lang/unsignedlong.rst | 41 ----- docs/source/lang/variables.rst | 170 ------------------ docs/source/lang/void.rst | 31 ---- docs/source/lang/volatile.rst | 65 ------- docs/source/lang/while.rst | 38 ---- 92 files changed, 7007 deletions(-) delete mode 100644 docs/source/confDefaultGreen.txt delete mode 100644 docs/source/home.rtf delete mode 100644 docs/source/lang/abs.rst delete mode 100644 docs/source/lang/analogread.rst delete mode 100644 docs/source/lang/analogwrite.rst delete mode 100644 docs/source/lang/arithmetic.rst delete mode 100644 docs/source/lang/array.rst delete mode 100644 docs/source/lang/assignment.rst delete mode 100644 docs/source/lang/attachinterrupt.rst delete mode 100644 docs/source/lang/bit.rst delete mode 100644 docs/source/lang/bitclear.rst delete mode 100644 docs/source/lang/bitread.rst delete mode 100644 docs/source/lang/bitset.rst delete mode 100644 docs/source/lang/bitshift.rst delete mode 100644 docs/source/lang/bitwisemath.rst delete mode 100644 docs/source/lang/bitwrite.rst delete mode 100644 docs/source/lang/boolean.rst delete mode 100644 docs/source/lang/booleanvariables.rst delete mode 100644 docs/source/lang/break.rst delete mode 100644 docs/source/lang/byte.rst delete mode 100644 docs/source/lang/bytecast.rst delete mode 100644 docs/source/lang/char.rst delete mode 100644 docs/source/lang/charcast.rst delete mode 100644 docs/source/lang/comments.rst delete mode 100644 docs/source/lang/comparison.rst delete mode 100644 docs/source/lang/compoundarithmetic.rst delete mode 100644 docs/source/lang/compoundbitwise.rst delete mode 100644 docs/source/lang/const.rst delete mode 100644 docs/source/lang/constants.rst delete mode 100644 docs/source/lang/constrain.rst delete mode 100644 docs/source/lang/continue.rst delete mode 100644 docs/source/lang/cos.rst delete mode 100644 docs/source/lang/curly-braces.rst delete mode 100644 docs/source/lang/define.rst delete mode 100644 docs/source/lang/delay.rst delete mode 100644 docs/source/lang/delaymicroseconds.rst delete mode 100644 docs/source/lang/detachinterrupt.rst delete mode 100644 docs/source/lang/digitalread.rst delete mode 100644 docs/source/lang/digitalwrite.rst delete mode 100644 docs/source/lang/double.rst delete mode 100644 docs/source/lang/doublecast.rst delete mode 100644 docs/source/lang/dowhile.rst delete mode 100644 docs/source/lang/enum.rst delete mode 100644 docs/source/lang/float.rst delete mode 100644 docs/source/lang/floatcast.rst delete mode 100644 docs/source/lang/for.rst delete mode 100644 docs/source/lang/goto.rst delete mode 100644 docs/source/lang/highbyte.rst delete mode 100644 docs/source/lang/if.rst delete mode 100644 docs/source/lang/include.rst delete mode 100644 docs/source/lang/increment.rst delete mode 100644 docs/source/lang/int.rst delete mode 100644 docs/source/lang/intcast.rst delete mode 100644 docs/source/lang/keywords.rst delete mode 100644 docs/source/lang/long.rst delete mode 100644 docs/source/lang/longcast.rst delete mode 100644 docs/source/lang/loop.rst delete mode 100644 docs/source/lang/lowbyte.rst delete mode 100644 docs/source/lang/map.rst delete mode 100644 docs/source/lang/max.rst delete mode 100644 docs/source/lang/micros.rst delete mode 100644 docs/source/lang/millis.rst delete mode 100644 docs/source/lang/min.rst delete mode 100644 docs/source/lang/modulo.rst delete mode 100644 docs/source/lang/numeric-types.rst delete mode 100644 docs/source/lang/pinmode.rst delete mode 100644 docs/source/lang/pointer.rst delete mode 100644 docs/source/lang/pow.rst delete mode 100644 docs/source/lang/pwmwrite.rst delete mode 100644 docs/source/lang/random.rst delete mode 100644 docs/source/lang/randomseed.rst delete mode 100644 docs/source/lang/return.rst delete mode 100644 docs/source/lang/scope.rst delete mode 100644 docs/source/lang/semicolon.rst delete mode 100644 docs/source/lang/serial.rst delete mode 100644 docs/source/lang/serialusb.rst delete mode 100644 docs/source/lang/setup.rst delete mode 100644 docs/source/lang/sin.rst delete mode 100644 docs/source/lang/sizeof.rst delete mode 100644 docs/source/lang/sq.rst delete mode 100644 docs/source/lang/sqrt.rst delete mode 100644 docs/source/lang/static.rst delete mode 100644 docs/source/lang/string.rst delete mode 100644 docs/source/lang/switchcase.rst delete mode 100644 docs/source/lang/tan.rst delete mode 100644 docs/source/lang/unsignedchar.rst delete mode 100644 docs/source/lang/unsignedint.rst delete mode 100644 docs/source/lang/unsignedlong.rst delete mode 100644 docs/source/lang/variables.rst delete mode 100644 docs/source/lang/void.rst delete mode 100644 docs/source/lang/volatile.rst delete mode 100644 docs/source/lang/while.rst (limited to 'docs/source/lang') diff --git a/docs/source/confDefaultGreen.txt b/docs/source/confDefaultGreen.txt deleted file mode 100644 index 789a5a0..0000000 --- a/docs/source/confDefaultGreen.txt +++ /dev/null @@ -1,250 +0,0 @@ -# -*- coding: utf-8 -*- -# -# libmaple documentation build configuration file, created by -# sphinx-quickstart on Thu Oct 7 06:42:30 2010. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -# We rely on Michael Jones's breathe as a Doxygen-to-Sphinx bridge. -# See libmaple/docs/README for information on obtaining it and letting -# Sphinx know where it is. -sys.path.append(os.environ['BREATHE_HOME']) - -# -- General configuration ---------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', - 'sphinx.ext.intersphinx', 'sphinx.ext.todo', - 'sphinx.ext.coverage', 'breathe'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Maple' -copyright = u'2010, LeafLabs, LLC' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '0.0' -# The full version, including alpha/beta/rc tags. -release = '0.0.9' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['epilog.rst', 'prolog.rst'] - -# Included at the end of every source file that is read. -with open('epilog.rst', 'r') as ep: - rst_epilog = ep.read() - -# Included at the beginning of every source file that is read. -with open('prolog.rst', 'r') as pr: - rst_prolog = pr.read() - -# The reST default role (used for this markup: `text`) to use for all -# documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# Warn about all references where the target cannot be found. -nitpicky = True - -# -- Options for HTML output -------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'nature' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -html_title = project + ' v' + release + ' Documentation' - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -html_logo = '_static/img/round_logo_60x60.png' - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -html_favicon = '_static/img/round_logo_32x32.ico' - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -html_sidebars = { - '**': ['globaltoc.html', 'searchbox.html'], -} - - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -html_use_index = False - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'mapledoc' - - -# -- Options for LaTeX output ------------------------------------------------- - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target file, title, author, documentclass [howto/manual]) -latex_documents = [ - ('index', 'maple.tex', u'Maple Documentation', - u'LeafLabs, LLC', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output ------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'maple', u'Maple Documentation', - [u'LeafLabs, LLC'], 1) -] - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} - - -# -- Options for breathe integration ------------------------------------------ - -breathe_projects = {'libmaple' : os.path.join(os.environ['LIB_MAPLE_HOME'], - 'docs', 'doxygen', 'xml')} - -breathe_default_project = 'libmaple' diff --git a/docs/source/home.rtf b/docs/source/home.rtf deleted file mode 100644 index dda3ecd..0000000 --- a/docs/source/home.rtf +++ /dev/null @@ -1,43 +0,0 @@ -.. _home: - -=================== -Maple Documentation -=================== - -.. image:: /_static/img/maple_rev3.jpg - :align: left - -Welcome! - -Maple is a user-friendly prototyping platform developed by LeafLabs in Cambridge, MA. Using Maple, creators with any level of experience can implement beautiful ideas that require the power of a 32-bit processor. - -Based on a ARM Cortex M3 (STFM32F103RB) chip, Maple runs at up to 72 MHz and has 39 digital input/out pins, 16 analog inputs, native full speed USB, 3 USARTs, integrated SPI/I2C support, and is Arduino compatible. - -Getting Started -^^^^^^^^^^^^^^^ -.. sidebar:: Tech Specs - - Microcontroller: STM32 F103RB - Clock Speed: 72 MHz - Operating Voltage: 3.3V - Input Voltage (recommended): 3.0V-12V - Digital I/O Pins: 39 - Analog Input Pins: 16 - Flash Memory: 128 KB - SRAM: 20KB - 64 Channel nested vector interrupt handler (including external interrupt on GPIO’s) - Integrated SPI/I2C and 7 Channels of Direct Memory Access (DMA) - Supplies up to 800mA @ 3.3v - Support for low power and sleep modes (<500uA) - Dimensions: 2.05″x2.1″ - -:ref:`Quickstart ` - -:ref:`Basic Language Reference ` Program your Maple. - -:ref:`Full Documentation ` - -Problem Solving -^^^^^^^^^^^^^^^^^ - -Check out our :ref:`troubleshooting guide ` and :ref:`known problems` page. If you don't find what you're looking for, hit the `forums `_ to ask questions to the LeafLabs team and other Maple users. Good luck, and have fun! \ No newline at end of file diff --git a/docs/source/lang/abs.rst b/docs/source/lang/abs.rst deleted file mode 100644 index 0f71d9b..0000000 --- a/docs/source/lang/abs.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. 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:: cc-attribution.txt diff --git a/docs/source/lang/analogread.rst b/docs/source/lang/analogread.rst deleted file mode 100644 index 0c93650..0000000 --- a/docs/source/lang/analogread.rst +++ /dev/null @@ -1,152 +0,0 @@ -.. highlight:: cpp - -.. _lang-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 board -contains a 16-channel, 12-bit analog to digital converter. This means -that it will map input voltages between 0 and 3.3 volts into integer -values between 0 and 4095. This yields a resolution between readings -of 3.3V / 4096 units, or 0.8 millivolts. 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`\ ). - -It takes about 0.8 microseconds (.0000008 seconds) to read an analog -input, so the maximum sample rate using this function is approximately -1.3 million samples per second\ [#fsamp]_. - - -Parameter Discussion --------------------- - -The pin parameter is the number of the analog input pin to read from. -Header pins on the Maple with ADC functionality (marked as "AIN" on -the silkscreen) are: - - 0, 1, 2, 3, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 27, 28 - -Note that pins 3, 27, and 28 are not marked AIN on the silkscreen -for Maple revisions through Rev 5, however, they **do work** as -analog input pins. - -Note ----- - -If the analog input pin is not connected to anything, the value -returned by analogRead() will fluctuate based on a number of factors -(e.g. the values of the other analog inputs, how close your hand is to -the board, etc.) in a seemingly random way. - - -Example -------- - - :: - - - int analogPin = 3; // potentiometer wiper (middle terminal) connected - // to analog pin 3. outside leads to ground and +3.3V - int val = 0; // variable to store the value read - - void setup() { - pinMode(analogPin, INPUT_ANALOG); // set up pin for analog input - SerialUSB.begin(); // set up usb virtual COM port - } - - void loop() { - val = analogRead(analogPin); // read the input pin - SerialUSB.println(val); // 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 ` the value of a Maple readout by 2, like so:: - - // right shift means that the result will be between 0 and 1023; - // be aware that you're losing a lot of precision if you do this - int adc_reading = analogRead(pin) >> 2; - -On the Arduino, the input range and resolution can be changed using -their implementation of `analogReference() -`_\ . Because of the -way its hardware (as of Rev 5) was designed, it's not possible to -implement analogReference on the Maple, so this function doesn't -exist. If your inputs lie in a different voltage range than 0V--3.3V, -you'll need to bring them into that range before using analogRead. -Some basic tools to accomplish this are `resistor dividers -`_ and `Zener diodes -`_\ -. However, opamps and other powered components can also be used if -greater precision is required. - -Finally, On the Arduino, it takes significantly longer to read analog -input: about 100 microseconds (0.0001 s), so the maximum reading rate -is 10,000 times a second. - - -See also --------- - -- :ref:`ADC note ` -- `(Arduino) Tutorial: Analog Input Pins `_ - - -.. rubric:: Footnotes - -.. [#fsamp] This is based on the current configuration of a 55.5 cycle - sample time, at 72 MHz. However, the minimum sample time *possible* - is 1.5 cycles, leading to a theoretical maximum of approximately 48 - million samples per second (of course, doing anything with the - readings also consumes cycles, so this maximum can't be reached in - practice). - - See the `STM32 Reference Manual `_, §§11.12.4--5 - (pp. 225--226), for more information on the low-level bit twiddling - currently necessary to change the sample time. For examples of how - the ADCs are configured in libmaple, see `adc.h - `_ - and `adc.c - `_\ - . Be aware that changing the sample time has important - consequences related to the impedance of the device connected to - the input pin. If you want to make changes, as a minimum, you - should first read ST's application notes on `ADC modes - `_ and `ADC oversampling - `_. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/analogwrite.rst b/docs/source/lang/analogwrite.rst deleted file mode 100644 index 2c50a42..0000000 --- a/docs/source/lang/analogwrite.rst +++ /dev/null @@ -1,166 +0,0 @@ -.. highlight:: cpp - -.. _lang-analogwrite: - -analogWrite() -============= - -.. note:: - - On the Maple, calling analogWrite() is the same as calling - :ref:`lang-pwmwrite`\ ; see that function's documentation for more - information. - - This is because PWM is not true analog output (i.e., is not the - output of a `DAC - `_\ ), so - the function is badly named. For instance, **analogWrite() has - absolutely nothing to do with** :ref:`lang-analogread`\ , which is - potentially confusing. - - The alias of analogWrite() to pwmWrite() is provided (sigh) for the - sake of compatibility with Arduino, but we recommend using - :ref:`lang-pwmwrite` when writing new software, for clarity. - -.. contents:: Contents - :local: - -.. _lang-analogwrite-compatibility: - -Arduino Compatibility ---------------------- - -There are a few important differences between Arduino's `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 ` the argument to -analogWrite into the right range:: - - // Arduino code: - analogWrite(pin, duty); - - // Becomes Maple code: - analogWrite(pin, map(duty, 0, 255, 0, 65535)); - -This will convert values in the range 0-255 to values in the range -0--65,635, which is the correct default range for all of the timers -which control PWM output. See the :ref:`timers reference ` -for more information. - -Another fix is to consult the :ref:`pin mapping mega table -` to find the timer which controls PWM on the -pin you're using, then set that Timer's overflow to 255. Subsequent -calls to analogWrite() should work as on the Arduino (with the same -loss of precision). Note, however, that that affects the overflow for -the **entire timer**, so other code relying on that timer (such as any -:ref:`interrupts ` 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, and 14, or twelve pins in total. That is at least as -*many* PWM pins as any Arduino board, but there are differences in -*which* pins support it. - -* On **most Arduino boards** (those with the ATmega168 or ATmega328; - this includes the **Arduino Uno**), this function works on pins 3, - 5, 6, 9, 10, and 11, or six pins total. Note that these boards - support PWM on pin 10, while Maple does not. - -* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins - total. Note that this board supports PWM on pins 4, 10, and 13, - while the Maple does not. Maple supports PWM on pins 0, 1, and 14, - which the Mega does not, making the total number of pins supporting - PWM equal on these boards. - -* **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, 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 `\ ). - -If your application absolutely requires Arduino's PWM frequency (it -probably doesn't), then the steps are: - -1. Figure out which timer controls PWM output on your pin (\ :ref:`this table ` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. - -2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. - -Be aware that this will change the period for the **entire timer**\ , -and will affect anything else in your program that depends on that -timer. One example is :ref:`interrupts `\ . -You've been :ref:`warned `\ . - -See also --------- - -- :ref:`Maple PWM tutorial ` - -.. 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:: cc-attribution.txt diff --git a/docs/source/lang/arithmetic.rst b/docs/source/lang/arithmetic.rst deleted file mode 100644 index 91fe22e..0000000 --- a/docs/source/lang/arithmetic.rst +++ /dev/null @@ -1,127 +0,0 @@ -.. highlight:: cpp - -.. _lang-arithmetic: - -Arithmetic Operators (``+``, ``-``, ``*``, ``/``) -================================================= - -The operators ``+``, ``-``, ``*``, and ``/`` respectively evaluate to -the sum, difference, product, or quotient (respectively) of the two -operands. The operation is conducted using the data type of the -operands, so, for example, ``9 / 4`` gives ``2`` since 9 and 4 are -:ref:`int variables `. - -This also means that the operation can overflow if the result is -larger than that which can be stored in the data type (e.g. adding 1 -to an :ref:`lang-int` with the value 2,147,483,647 gives --2,147,483,648). - -.. _lang-arithmetic-typeconversion: - -If the operands are of different types, the "larger" type is used for -the calculation. If one of the numbers (operands) are of the type -**float** or of type **double**, floating point math will be used for -the calculation. - -.. note:: The specifics of these rules are beyond the scope of this - documentation; for more information, see `The C++ Programming - Language `_\ , by Bjarne - Stroustroup, Appendix C, especially §§C.4-C.6, or `this WikiBooks - entry on C++ type conversion - `_. - -.. note:: For more information on how computers represent integers, - see the Wikipedia page on `two's complement - `_. - -.. contents:: Contents - :local: - -Examples --------- - - :: - - y = y + 3; - x = x - 7; - i = j * 6; - r = r / 5; - - -Syntax ------- - - :: - - result = value1 + value2; - result = value1 - value2; - result = value1 * value2; - result = value1 / value2; - - -Parameters ----------- - -**value1**: any numeric variable or constant - -**value2**: any numeric variable or constant - -Programming Tips ----------------- - -- Know that :ref:`integer constants ` - default to :ref:`int `, so some constant calculations - may overflow (e.g., 200000 * 5000000 will yield a negative result). - -- Choose variable sizes that are large enough to hold the largest - results from your calculations. - -- Know at what point your variable will "roll over" and also what - happens in the other direction e.g. (0 - 1) for unsigned arithmetic, - or (0 - -2,147,483,648) for signed arithmetic. - -- For math that requires fractions, float variables may be used, but - be aware of their drawbacks: large size and slow computation speeds - (the STM32 has no floating point hardware, so all floating point - calculations have to be done in software). - -- Use cast operator, e.g. ``(int)myFloat`` to convert one variable type - to another on the fly. - -Arduino Compatibility ---------------------- - -Since the STM32 processor on the Maple is a 32-bit machine, the int -type overflows at a much higher value on Maple than on Arduino. In -particular, on Maple, ints do not overflow (become negative) until -they reach 2,147,483,648; on the Arduino, they overflow at 32,767. -Because of this, programs running on Maple are much less likely to run -into overflow issues. The following table summarizes the sizes and -ranges of integer datatypes on the Maple (the ranges of long long -types are approximate): - -.. _lang-arithmetic-int-sizes: - -.. csv-table:: - :header: Datatype, Unsigned range, Signed range, Size (bytes) - :widths: 8, 12, 17, 8 - - ``char``, 0 --- 255, -128 --- 127, 1 - ``short``, "0 --- 65,535", "-32,768 --- 32,767", 2 - ``int``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 - ``long``, "0 --- 4,294,967,295", "-2,147,483,648 --- 2,147,483,647", 4 - ``long long``, "0 --- 1.8*10\ :sup:`19`\ " (approx.), "-9.2*10\ :sup:`18` --- 9.2*10\ :sup:`18` (approx.)", 8 - - -See Also --------- - -- The individual sizes (in bits) of various available types are - defined in `libmaple_types.h - `_\ - . - -- :ref:`sizeof `\ () - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/array.rst b/docs/source/lang/array.rst deleted file mode 100644 index 30a818f..0000000 --- a/docs/source/lang/array.rst +++ /dev/null @@ -1,123 +0,0 @@ -.. highlight:: cpp - -.. _lang-array: - -Arrays -====== - -An array is a collection of variables that are accessed with an index -number. Arrays in the C++ programming language, in which the Maple is -programmed, can be complicated, but using simple arrays is relatively -straightforward. - -.. contents:: Contents - :local: - -Creating (Declaring) an Array ------------------------------ - -All of the methods below are valid ways to create (declare) an -array. :: - - int myInts[6]; - int myPins[] = {2, 4, 8, 3, 6}; - int mySensVals[6] = {2, 4, -8, 3, 2}; - char message[6] = "hello"; - -You can declare an array without initializing it, as with myInts. In -the line referring to myPins, we declare an array without explicitly -choosing a size. The compiler counts the elements and creates an -array of the appropriate size. - -Finally, you can both initialize and size your array, as in -mySensVals. Note that when declaring an array with elements of type -char, one more element than your initialization is required, to hold -the required `null character `_. - - -Accessing an Array ------------------- - - -.. compound:: - - Arrays are **zero indexed**; that is, referring to the array - initialization above, the first element of the array is at index 0, - hence :: - - mySensVals[0] == 2; - mySensVals[1] == 4 - - and so forth. - -It also means that in an array with ten elements, index nine is the -last element. Hence:: - - int myArray[10]={9,3,2,4,3,2,7,8,9,11}; - // myArray[9] contains 11 - // myArray[10] is invalid and contains random information (other memory address) - -For this reason, you should be careful in accessing arrays. Accessing -past the end of an array (using an index number greater than your -declared array size - 1) is reading from memory that is in use for -other purposes. Reading from these locations is probably not going to -do much except yield invalid data. Writing to random memory locations -is definitely a bad idea, and can often lead to unhappy results such -as crashes or program malfunction. This can also be a difficult bug to -track down. - -Unlike Basic or Java, the C compiler does no checking to see if array -access is within legal bounds of the array size that you have -declared. - - -To assign a value to an array ------------------------------ - :: - - mySensVals[0] = 10; - - -To retrieve a value from an array ---------------------------------- - - :: - - x = mySensVals[4]; - - -Arrays and ``for`` Loops ------------------------- - -Arrays are often manipulated inside :ref:`for loops `, where -the loop counter is used as the index for each array element. For -example, to print the elements of an array over the serial port, you -could do something like this:: - - int i; - for (i = 0; i < 5; i = i + 1) { - SerialUSB.println(myPins[i]); - } - - -Example -------- - -For a complete program that demonstrates the use of arrays, see the -Arduino `Knight Rider example -`_\ (which will run -unmodified on the Maple). - -Arduino Compatibility ---------------------- - -Arrays on Maple are identical those on Arduino. - -See also --------- - -- :ref:`Storing arrays in FLASH memory ` - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/assignment.rst b/docs/source/lang/assignment.rst deleted file mode 100644 index b6ad4d5..0000000 --- a/docs/source/lang/assignment.rst +++ /dev/null @@ -1,70 +0,0 @@ -.. highlight:: cpp - -.. _lang-assignment: - -Assignment Operator (``=``) -=========================== - -Stores the value to the right of the equal sign in the variable to -the left of the equal sign. - -The single equal sign in the C++ programming language is called the -assignment operator. It has a different meaning than in algebra -class, where it indicated an equation or equality. The assignment -operator tells the microcontroller to evaluate whatever value or -expression is on the right side of the equal sign, and store it in -the variable to the left of the equal sign [#fgross]_. - - - -Example -------- - -:: - - int sensVal; // declare an integer variable named sensVal - senVal = analogRead(0); // store the (digitized) input voltage at analog pin 0 in SensVal - - - -Programming Tips ----------------- - -The variable on the left side of the assignment operator ( = sign ) -needs to be able to hold the value stored in it. If it is not large -enough to hold a value, the value stored in the variable will be -incorrect. - -Don't confuse the assignment operator [ = ] (single equal sign) -with the comparison operator [ == ] (double equal signs), which -evaluates whether two expressions are equal. - - -Arduino Compatibility ---------------------- - -Assignments on the Maple are identical to those on Arduino. - - - -See Also --------- - - -- `if (comparison operators) `_ -- `char `_ -- `int `_ -- `long `_ - - -.. rubric:: Footnotes - -.. [#fgross] Experienced C++ programmers know this to be an - oversimplification of what happens when the variable on the left - hand side is an object. See Richard Gillam's wonderful and scary - `The Anatomy of the Assignment Operator - `_ - for more information. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/attachinterrupt.rst b/docs/source/lang/attachinterrupt.rst deleted file mode 100644 index 0b8907f..0000000 --- a/docs/source/lang/attachinterrupt.rst +++ /dev/null @@ -1,102 +0,0 @@ -.. highlight:: cpp - -.. _lang-attachinterrupt: - -attachInterrupt() -================= - -Used to specify a function to call when an external interrupt (like an -GPIO changing from LOW to HIGH, a button getting pressed, etc.) -occurs. - -.. contents:: Contents - :local: - -Library Documentation ---------------------- - -.. doxygenfunction:: attachInterrupt - -.. doxygenenum:: ExtIntTriggerMode - -.. doxygentypedef:: voidFuncPtr - -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 a few constraints you should be aware of if you're using -more than one interrupt at a time; the :ref:`external-interrupts` page -has the details. - - -Using Interrupts ----------------- - -Interrupts are useful for making things happen automatically in -microcontroller programs, and can help solve timing problems. A -good task for using an interrupt might be reading a rotary encoder, -or monitoring user input. - - -If you wanted to insure that a program always caught the pulses -from a rotary encoder, never missing a pulse, it would make it very -tricky to write a program to do anything else, because the program -would need to constantly poll the sensor lines for the encoder, in -order to catch pulses when they occurred. Other sensors have a -similar interface dynamic too, such as trying to read a sound -sensor that is trying to catch a click, or an infrared slot sensor -(photo-interrupter) trying to catch a coin drop. In all of these -situations, using an interrupt can free the microcontroller to get -some other work done while not missing the doorbell. - - -Example -------- - -:: - - int maple_led_pin = 13; - volatile int state = LOW; // must declare volatile, since it's - // modified within the blink handler - - void setup() { - pinMode(maple_led_pin, OUTPUT); - attachInterrupt(0, blink, CHANGE); - } - - void loop() { - digitalWrite(maple_led_pin, state); - } - - void blink() { - state = !state; - } - - -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:`detachInterrupt ` -- :ref:`external-interrupts` - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bit.rst b/docs/source/lang/bit.rst deleted file mode 100644 index dd5c050..0000000 --- a/docs/source/lang/bit.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. _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:: cc-attribution.txt diff --git a/docs/source/lang/bitclear.rst b/docs/source/lang/bitclear.rst deleted file mode 100644 index 941f912..0000000 --- a/docs/source/lang/bitclear.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. _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 -------- - -None. - - -Arduino Compatibility ---------------------- - -This implementation is compatible with that of Arduino. - - -See also --------- - -- :ref:`bit `\ () -- :ref:`bitRead `\ () -- :ref:`bitWrite `\ () -- :ref:`bitSet `\ () - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitread.rst b/docs/source/lang/bitread.rst deleted file mode 100644 index 46b4478..0000000 --- a/docs/source/lang/bitread.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. _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:: cc-attribution.txt diff --git a/docs/source/lang/bitset.rst b/docs/source/lang/bitset.rst deleted file mode 100644 index ccd76de..0000000 --- a/docs/source/lang/bitset.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. _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:: cc-attribution.txt diff --git a/docs/source/lang/bitshift.rst b/docs/source/lang/bitshift.rst deleted file mode 100644 index e1c8de0..0000000 --- a/docs/source/lang/bitshift.rst +++ /dev/null @@ -1,144 +0,0 @@ -.. highlight:: cpp - -.. _lang-bitshift: - -Bit Shift Operators (``<<``, ``>>``) -==================================== - -(Adapted from `The Bit Math Tutorial -`_ in `The Arduino -Playground `_\ ) - -There are two bit shift operators in C++: the left shift operator -``<<`` and the right shift operator ``>>``. These operators cause the -bits in the left operand to be shifted left or right by the number of -positions specified by the right operand. - -More information on bitwise math can be obtained in the Wikipedia -article on `bitwise operations -`_\ , especially the -section on shifts in `C, C++, and Java -`_\ . - - -Syntax ------- - -``some_int << number_of_bits`` - -``some_int >> number_of_bits`` - - -Parameters ----------- - -* **some_int** An integer value or variable. - -* **number_of_bits** integer whose value is at most ``8 * - sizeof(variable)`` (so ``number_of_bits`` can be at most 32 for - ``int`` values, at most ``8`` for ``char`` values, etc.; the various - integer sizes are summarized :ref:`in this table - `\ ). - - - -Example: --------- - -Here are some examples of bit shifting, with the binary representation of the number in comments:: - - int a = 5; // binary: 101 - int b = a << 3; // binary: 101000, or 40 in decimal - int c = b >> 3; // binary: 101, or back to 5 like we started with - - -When you left shift a value x by y bits (x << y), the leftmost y bits -in x are lost, literally shifted out of existence. We'll do this -example with ``char`` values (which are integers in the range 0-255, -and take up 8 bits of memory):: - - char a = 5; // binary (all 8 bits): 00000101 - char b = a << 7; // binary: 10000000 - the first 1 in 101 was discarded - - -If you are certain that none of the ones in a value are being shifted -into oblivion, a simple way to think of the left-shift operator is -that it multiplies the left operand by 2 raised to the right operand -power (in math notation, ``x << y`` equals x * 2\ :sup:`y`\ , as long -as none of the bits of x get shifted out). For example, to generate -powers of 2, the following expressions can be employed:: - - 1 << 0 == 1 - 1 << 1 == 2 - 1 << 2 == 4 - 1 << 3 == 8 - ... - 1 << 8 == 256 - 1 << 9 == 512 - 1 << 10 == 1024 - ... - -.. _lang-bitshift-signbit-gotcha: - -When you shift x right by y bits (``x >> y``), and the highest bit in -x is a 1, the behavior depends on the exact data type of x. If x is of -type ``int``, the highest bit is special, and determines whether x is -negative or not; the details are too complicated to explain here, but -they are thoroughly explained in the Wikipedia article on `two's -complement arithmetic -`_\ , which the -system most computers use to store integers. In that case, the sign -bit is copied into lower bits, for esoteric historical reasons:: - - int x = -16; // binary (all 32 bits): 11111111111111111111111111110000 - int y = x >> 3; // binary: 11111111111111111111111111111110 - - - -This behavior, called "sign extension", is often not what you -want. You probably wish zeros to be shifted in from the left. It -turns out that the right shift rules are different for ``unsigned -int`` values, so you can use a type cast to suppress ones being copied -from the left:: - - int x = -16; // binary: 11111111111111111111111111110000 - int y = (unsigned int)x >> 3; // binary: 00011111111111111111111111111110 - - - -If you are careful to avoid sign extension, you can use the -right-shift operator, ``>>``, as a way to divide by powers of 2. For -example:: - - int x = 1000; - int y = x >> 3; // integer division of 1000 by 8, causing y = 125. - - -Arduino Compatibility ---------------------- - -Since it's part of the C++ language, bit shifting on the Maple is -compatible with the Arduino; however, you should keep in mind that the -Maple has bigger integer types (as in, more bits) than the Arduino. - -Since the STM32 is a 32-bit processor, the ``int`` type takes up 32 -bits instead of 16, like on Arduino's 16-bit microcontroller. This -means that you can shift left, like ``x << y``, with bigger values of -``y`` on the Maple before ones in ``x`` start to get shifted out. - -To calculate the number of bits of an integer type on the Maple, -multiply its size in bytes (see :ref:`this table -` for these) by 8, since there are 8 -bits in 1 byte. For example, a ``short`` takes up 2 bytes of memory, -or 2 * 8 = 16 bits. - -See Also --------- - -- :ref:`lang-bit` -- :ref:`lang-bitread` -- :ref:`lang-bitwrite` -- :ref:`lang-bitclear` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwisemath.rst b/docs/source/lang/bitwisemath.rst deleted file mode 100644 index 28fe6bf..0000000 --- a/docs/source/lang/bitwisemath.rst +++ /dev/null @@ -1,186 +0,0 @@ -.. highlight:: cpp - -.. _lang-bitwisemath: - -Bitwise Operators (``&``, ``|``, ``^``, ``~``) -============================================== - -The bitwise operators perform their calculations at the bit level of -variables. They help solve a wide range of common programming -problems. - -Much of the material here is adapted for Maple from an (Arduino) -`tutorial on bitwise math -`_\ . Another great -resource is the Wikipedia article on `bitwise operations -`_\ . - -Below are descriptions and syntax for all of the operators. - -.. contents:: Contents - :local: - -.. _lang-bitwisemath-and: - -Bitwise AND (``&``) -------------------- - -The bitwise AND operator in C++ is a single ampersand, ``&``, used -between two other integer expressions. Bitwise AND operates on each -bit position of the surrounding expressions independently, according -to this rule: if both input bits are 1, the resulting output is 1, -otherwise the output is 0. Another way of expressing this is:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 0 0 1 (operand1 & operand2) = result - - -On the Maple, the type ``int`` is a 32-bit value, so using ``&`` -between two ``int`` expressions causes 32 simultaneous AND operations -to occur. In a code fragment like:: - - int a = 92; // in binary: 00000000000000000000000001011100 - int b = 101; // in binary: 00000000000000000000000001100101 - int c = a & b; // result: 00000000000000000000000001000100, - // (or 68 in decimal). - - -Each of the 32 bits in ``a`` and ``b`` are processed using bitwise -AND, and all 32 resulting bits are stored in ``c``, resulting in the -value 1000100 in binary, which is 68 in decimal. - - -.. _lang-bitwisemath-or: - -Bitwise OR (``|``) ------------------- - -The bitwise OR operator in C++ is the vertical bar symbol, ``|``. Like -the ``&`` operator, ``|`` operates independently on each bit in its -two surrounding integer expressions, but what it does is -different. The bitwise OR of two bits is 1 if either or both of the -input bits is 1, otherwise it is 0. For example:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) = result - -Here is an example of bitwise OR used in a snippet of C++ code (using -``char``, which takes up 8 bits of memory, instead of ``int``, which -uses 32):: - - char a = 92; // in binary: 01011100 - char b = 101; // in binary: 01100101 - char c = a | b; // result: 01111101, or 125 in decimal. - -.. _lang-bitwisemath-xor: - -Bitwise XOR (``^``) -------------------- - -There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE -OR, also known as bitwise XOR. (In English, this is usually pronounced -"zor" or "ex-or"). The bitwise XOR operator is written using the caret -symbol, ``^``. This operator is very similar to the bitwise OR -operator ``|``, except it evaluates to 0 for a given bit position when -both of the input bits for that position are 1:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 0 (operand1 ^ operand2) = result - - -Another way to look at bitwise XOR is that each bit in the result -is a 1 if the input bits are different, or 0 if they are the same. - -Here is a simple example:: - - int x = 12; // binary (ignoring extra bits): 1100 - int y = 10; // binary: 1010 - int z = x ^ y; // binary: 0110, or decimal 6 - - - -The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 -to 0) some of the bits in an integer expression. In a bitwise OR -operation if there is a 1 in the mask bit, that bit is inverted; if -there is a 0, the bit is not inverted and stays the same. Below is a -program to blink digital pin 13 (the LED pin on Maple):: - - // Blink Maple LED pin - - int led_pin = 13; - int toggle = 0; - - // demo for Exclusive OR - void setup(){ - pinMode(led_pin, OUTPUT); - } - - void loop(){ - toggle = toggle ^ 1; - digitalWrite(led_pin, toggle); - delay(100); - } - -.. _lang-bitwisemath-not: - -Bitwise NOT (``~``) -------------------- - -The bitwise NOT operator in C++ is the tilde character ``~``. Unlike -``&`` and ``|``, the bitwise NOT operator is applied to a single -operand to its right. Bitwise NOT changes each bit to its opposite: 0 -becomes 1, and 1 becomes 0. For example:: - - 0 1 operand1 - ---- - 1 0 ~operand1 = result - -Another example:: - - char a = 103; // binary: 01100111 - char b = ~a; // binary: 10011000 = -104 - -You might be surprised to see a negative number like -104 as the -result of this operation. This is because the highest bit in an int -variable is the so-called "sign bit". If the highest bit is 1, the -number is interpreted as negative. This encoding of positive and -negative numbers is referred to as *two's complement*. For more -information, see the Wikipedia article on `two's -complement. `_ - -As an aside, it is interesting to note that (under two's complement -arithmetic) for any integer ``x``, ``~x`` is the same as ``-x-1``. - -At times, the sign bit in a signed integer expression can cause -some unwanted surprises. - - -Uses ----- - -One of the most common uses of bitwise operations is to select or -manipulate a particular bit (or bits) from an integer value, often -called `bit masking -`_\ . See the -linked Wikipedia article for more information and examples. - -If you really want to see bit-twiddling techniques in their full -glory, you could do much worse than to get yourself a copy of -`Hacker's Delight `_\ . - - -See Also --------- - -- :ref:`Boolean operations ` (``&&``, ``||``) -- :ref:`Compound bitwise operations ` (``&=``, - ``|=``, ``^=``). - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bitwrite.rst b/docs/source/lang/bitwrite.rst deleted file mode 100644 index b3feff2..0000000 --- a/docs/source/lang/bitwrite.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. 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 version of ``bitWrite()`` is compatible with Arduino. - -See also --------- - -- :ref:`bit() ` -- :ref:`bitRead() ` -- :ref:`bitSet() ` -- :ref:`bitClear() ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/boolean.rst b/docs/source/lang/boolean.rst deleted file mode 100644 index 8d6aa5c..0000000 --- a/docs/source/lang/boolean.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. highlight:: cpp - -.. _lang-boolean: - -Boolean Operators -================= - -These can be used inside the condition of an :ref:`if ` -statement. Evaluate to :ref:`true ` or -:ref:`false `. - -.. contents:: Contents - :local: - -.. _lang-boolean-and: - -&& (logical and) ----------------- - -True only if both operands are true. For example:: - - if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches - // ... - } - -is true only if both inputs are high. Another example:: - - if (a >= 10 && a <= 20){} // true if a is between 10 and 20 - -**Be careful** not to say ``10 <= a <= 20``! This won't work the way -you want. You have to separately test whether ``a`` is at least 10 -using ``a >= 10``, then test whether ``a`` is at most 20 using ``a <= -20``, then combine the results using ``&&``. - - -.. _lang-boolean-or: - -\|\| (logical or) ------------------ - -True if either operand is true. For example:: - - if (x > 0 || y > 0) { - // ... - } - -is true if either ``x`` or ``y`` is greater than 0. - -.. _lang-boolean-not: - -! (logical not) ---------------- - -True if the operand is false. For example:: - - if (!x) { - // ... - } - -is true if ``x`` is false (i.e. if ``x`` is zero). - -Some Advice ------------ - -.. warning:: - - Make sure you don't mistake the boolean AND operator ``&&`` - (double ampersand) for the :ref:`bitwise AND operator - ` ``&`` (single ampersand). They are - entirely different beasts. - - Similarly, do not confuse the boolean OR operator ``||`` (double - pipe) with the :ref:`bitwise OR operator ` - ``|`` (single pipe). - - The :ref:`bitwise NOT operator ` ``~`` - (tilde) looks much different than the boolean not operator ``!`` - (exclamation point, or "bang", as some programmers say), but you - still have to be sure which one you want. - - -See Also --------- - -- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) -- :ref:`Compound bitwise operators ` (``&=``, - ``|=``, ``^=``). -- :ref:`if statement ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/booleanvariables.rst b/docs/source/lang/booleanvariables.rst deleted file mode 100644 index 6051b8c..0000000 --- a/docs/source/lang/booleanvariables.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. highlight:: cpp - -.. _lang-booleanvariables: - -Booleans -======== - -A **boolean** holds one of two values, :ref:`true -` or :ref:`false `. On a -Maple, each boolean variable has type ``bool``. - -.. warning:: - - On an Arduino, the type ``boolean`` is also provided. While the - Maple also has this type for compatibility, **its use is strongly - discouraged**. The ``bool`` type is a standard part of C++, while - ``boolean`` is a non-standard extension that serves no purpose. - -Example -------- - -:: - - int ledPin = 13; // LED on pin 13 - int switchPin = 12; // momentary switch on 12, other side connected to ground - - // running is a boolean variable: - bool running = false; - - void setup() { - pinMode(ledPin, OUTPUT); - pinMode(switchPin, INPUT); - digitalWrite(switchPin, HIGH); // turn on pullup resistor - } - - void loop() { - if (digitalRead(switchPin) == LOW) { - // switch is pressed - pullup keeps pin high normally - delay(100); // delay to debounce switch - running = !running; // toggle running variable - digitalWrite(ledPin, running) // indicate via LED - } - } - -See also --------- - - -- :ref:`Boolean constants ` -- :ref:`Boolean operators ` -- :ref:`Variables ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/break.rst b/docs/source/lang/break.rst deleted file mode 100644 index ce8ac17..0000000 --- a/docs/source/lang/break.rst +++ /dev/null @@ -1,35 +0,0 @@ -.. highlight:: cpp - -.. _lang-break: - -``break`` -========= - -``break`` is used to exit from a :ref:`while `\ , -:ref:`for `\ , or :ref:`do/while ` loop, -bypassing the normal loop condition. It is also used to exit from a -:ref:`switch ` statement. - - -Example -------- - -:: - - for (x = 0; x < 255; x ++) - { - digitalWrite(PWMpin, x); - sens = analogRead(sensorPin); - if (sens > threshold){ // bail out on sensor detect - x = 0; - // this line of code means that we'll immediately exit - // from the "for" loop: - break; - } - delay(50); - } - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/byte.rst b/docs/source/lang/byte.rst deleted file mode 100644 index 45c9d5f..0000000 --- a/docs/source/lang/byte.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. highlight:: cpp - -.. _lang-byte: - -byte -==== - -The ``byte`` type stores a 1-byte (8-bit) unsigned integer number, -from 0 to 255. - -.. warning:: - - The ``byte`` type is provided for compatibility with Arduino. - However, it is a non-standard extension. The standard C++ type for - storing an 8-bit unsigned integer is ``unsigned char``; we - recommend using that instead. (Your code will still work on an - Arduino). - - -Example -------- - -:: - - byte b = 134; - -See Also --------- - -- :ref:`byte() ` (casting a value to a byte) -- :ref:`Variables ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/bytecast.rst b/docs/source/lang/bytecast.rst deleted file mode 100644 index b3f0de2..0000000 --- a/docs/source/lang/bytecast.rst +++ /dev/null @@ -1,50 +0,0 @@ -.. highlight:: cpp - -.. _lang-bytecast: - -byte() (cast) -============= - -Converts a value to the :ref:`byte ` data type. - -.. note:: - - Casting to the byte type is provided for compatibility with - Arduino. However, the recommended Maple type for storing an 8-bit - unsigned integer is ``uint8``. (C and C++ programmers: ``stdint.h`` - is also available). - - In order to cast a variable ``x`` to a ``uint8``, the - following syntax can be used:: - - uint8(x); - -Syntax ------- - -``byte(x)`` - - -Parameters ----------- - -**x**: a value of any integer type - - -Returns -------- - -The value, converted to a ``byte``. Note, however, that if the value -is larger than the maximum value you can store in a byte (255), then -the results might be strange and unexpected. - - -See Also --------- - -- :ref:`lang-byte` - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/char.rst b/docs/source/lang/char.rst deleted file mode 100644 index b8747f3..0000000 --- a/docs/source/lang/char.rst +++ /dev/null @@ -1,50 +0,0 @@ -.. highlight:: cpp - -.. _lang-char: - -``char`` -======== - -The ``char`` type stores a 1-byte character value (or integer with -value from -128 to 127). Character literals are written in single -quotes, like this: ``'A'`` (for multiple characters - strings - use -double quotes: ``"ABC"``). - - -Just like everything else on a computer, characters are stored as -numbers. You can see the specific encoding in the `ASCII chart -`_\ -. This means that it is possible to do arithmetic on characters, in -which the ASCII value of the character is used (e.g. ``'A' + 1`` has the -decimal value 66, since the ASCII value of the capital letter A in -decimal is 65). See the :ref:`Serial.println() -` documentation for more information about how -characters are converted into numbers. - -The ``char`` datatype is a signed type, meaning that it encodes -numbers from -128 to 127. For an unsigned type, which stores values -from 0 to 255, just use the type ``unsigned char`` (two words). - - -Example -------- - -:: - - // the following two lines are equivalent, using the ASCII - // character encoding: - char c = 'A'; - char c = 65; - - -See also --------- - - -- :ref:`lang-int` -- :ref:`lang-array` (a string is just an array of ``char``\ s) -- :ref:`Serial.println() ` - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/charcast.rst b/docs/source/lang/charcast.rst deleted file mode 100644 index a480dec..0000000 --- a/docs/source/lang/charcast.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. highlight:: cpp - -.. _lang-charcast: - -``char()`` (cast) -================= - -Converts a value to the :ref:`char ` data type. - -Syntax ------- - -``char(x)`` - - -Parameters ----------- - -**x**: a value of any type - - -Returns -------- - -The value, converted to a ``char``. Note, however, that if the value -is outside the range of a ``char`` (-128 to 127), then the results -might be strange and unexpected. - - -See Also --------- - -- :ref:`char ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/comments.rst b/docs/source/lang/comments.rst deleted file mode 100644 index c5f118a..0000000 --- a/docs/source/lang/comments.rst +++ /dev/null @@ -1,67 +0,0 @@ -.. highlight:: cpp - -.. _lang-comments: - -Comments -======== - -Comments are lines in the program that are used to inform yourself or -others about the way the program works. They are ignored by the -compiler, and not exported to the processor, so they don't take up any -space in RAM or Flash. - -One use for comments is to help you understand (or remember) how your -program works, or to inform others how your program works. There are -two different ways of making comments. - -.. _lang-comments-singleline: - -**Single line comment**: Anything following two slashes, ``//``, until -the end of the line, is a comment:: - - x = 5; // the rest of this line is a comment - -.. _lang-comments-multiline: - -**Multi-line comment**: Anything in between a pair of ``/*`` and ``*/`` -is a comment:: - - /* <-- a slash-star begins a multi-line comment - - all of this in the multi-line comment - you can use it to comment - out whole blocks of code - - if (gwb == 0){ // single line comment is OK inside a multi-line comment - x = 3; - } - - // don't forget the "closing" star-slash - they have to be balanced: - */ - -Note that it's okay to use single-line comments within a multi-line -comment, but you can't use multi-line comments within a multi-line -comment. Here's an example:: - - /* ok, i started a multi-line comment - - x = 3; /* this next star-slash ENDS the multi-line comment: */ - - x = 4; // this line is outside of the multi-line comment - - // next line is also outside of the comment, and causes a compile error: - */ - -Programming Tip ---------------- - -When experimenting with code, "commenting out" parts of your program -is a convenient way to remove lines that may be buggy. This leaves -the lines in the code, but turns them into comments, so the compiler -just ignores them. This can be especially useful when trying to locate -a problem, or when a program refuses to compile and the compiler error -is cryptic or unhelpful. - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/comparison.rst b/docs/source/lang/comparison.rst deleted file mode 100644 index b24355f..0000000 --- a/docs/source/lang/comparison.rst +++ /dev/null @@ -1,87 +0,0 @@ -.. highlight:: cpp - -.. _lang-comparison: - -Comparison Operators (``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``) -=================================================================== - -The comparison operators ``==``, ``!=``, ``<``, ``>``, ``<=``, and -``>=`` are used to compare two numbers. They are :ref:`true -` when the comparison is true, and :ref:`false -` otherwise. They are based on the symbols -=, ≠, <, >, ≤, and ≥ from mathematics. - -Here are some examples, with their meaning in comments:: - - // "eq" is true when x is equal to y - bool eq = (x == y); - - // "neq" is true when x is different than y - bool neq = (x != y); - - // "lt" is true when x is less than, but NOT equal to, y - bool lt = (x < y); - - // "gt" is true when x is greater than, but NOT equal to, y - bool gt = (x > y); - - // "lte" is true when x is less than or equal to y - bool lte = (x <= y); - - // "gte" is true when x is greater than or equal to y - bool gte = (x >= y); - -The parentheses are optional; they are present only for clarity. For -example, the following two lines are the same:: - - bool eq = x == y; - - bool eq = (x == y); - -Uses ----- - -Comparison operators, along with :ref:`boolean operators -`, are useful inside the conditionals of :ref:`if -` statements. Here's one example:: - - if (x < 50) { - // only execute these lines if x is less than 50 - SerialUSB.println("delaying:"); - SerialUSB.println(x); - delay(x); - } - -.. warning:: - Beware of accidentally using the single equal sign (``=``) when you - meant to test if two numbers are equal (``==``). This is a common - mistake inside of ``if`` statement conditionals, e.g.:: - - // DON'T MAKE THIS MISTAKE - if (x = 10) { - // body - } - - The single equal sign is the assignment operator, and sets x to 10 - (puts the value 10 into the variable x). Instead use the double equal - sign (e.g. ``if (x == 10)``), which is the comparison operator, and - tests *whether* x is equal to 10 or not. The latter statement is only - true if x equals 10, but the former statement will always be true. - - This is because C evaluates the statement ``if (x=10)`` as follows: 10 - is assigned to x (remember that the single equal sign is the - :ref:`assignment operator `), so x now - contains 10. Then the 'if' conditional evaluates 10, which evaluates - to :ref:`true `, since any non-zero number - evaluates to ``true``. - - Consequently, the conditional of an ``if`` statement like ``if (x = - 10) {...}`` will always evaluate to ``true``, and the variable x - will be set to 10, which is probably not what you meant. - - (This sometimes has uses, though, so just because an assignment - appears within a conditional doesn't mean it's automatically wrong. - Be careful to know what you mean.) - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/compoundarithmetic.rst b/docs/source/lang/compoundarithmetic.rst deleted file mode 100644 index 420f1db..0000000 --- a/docs/source/lang/compoundarithmetic.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. highlight:: cpp - -.. _lang-compoundarithmetic: - -Compound Arithmetic Operators (``+=`` , ``-=``, ``*=``, ``/=``) -=============================================================== - -These oparators perform a mathematical operation on a variable with -another constant or variable. These operators are just a convenient -shorthand:: - - x += y; // equivalent to the expression x = x + y; - x -= y; // equivalent to the expression x = x - y; - x *= y; // equivalent to the expression x = x * y; - x /= y; // equivalent to the expression x = x / y; - -Here is an example:: - - int x = 2; - int y = 10; - - x += 4; // x now contains 6 - x -= 3; // x now contains 3 - x *= y; // x now contains 30 - x /= 2; // x now contains 15 - x += max(20, 6); // x now contains 35 - x -= sq(5); // x now contains 15 - -Parameters ----------- - -**x**: a numeric variable - -**y**: a numeric variable, number constant, or any other expression -that evaluates to a number (e.g. call to a function that returns a -number). - -See Also --------- - -- :ref:`Arithmetic operators ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/compoundbitwise.rst b/docs/source/lang/compoundbitwise.rst deleted file mode 100644 index a4bbb24..0000000 --- a/docs/source/lang/compoundbitwise.rst +++ /dev/null @@ -1,231 +0,0 @@ -.. highlight:: cpp - -.. _lang-compoundbitwise: - -Compound Bitwise Operators (``&=``, ``|=``, ``^=``) -=================================================== - -The compound bitwise operators perform their calculations at the -bit level of variables. They are often used to clear and set -specific bits of a variable. - -See the :ref:`bitwise math tutorial ` for more -information on bitwise operators. - -.. contents:: Contents - :local: - -.. _lang-compoundbitwise-and: - -Compound bitwise AND (``&=``) ------------------------------ - -The compound bitwise AND operator ``&=`` is often used with a variable -and a constant to force particular bits in a variable to be zero. This -is often referred to in programming guides as "clearing" or -"resetting" bits. In a program, writing the line ``x &= y;`` is -equivalent to writing ``x = x & y;``. That is, the value of ``x`` -after the line will be equal to its old value bitwise ANDed with the -value of ``y``:: - - x &= y; // equivalent to x = x & y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any :ref:`integer value -` (like ``3`` or ``0x20``) for ``y``. - -Before doing an example of ``&=``, let's first review the Bitwise AND -(``&``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 0 0 1 (operand1 & operand2) = result - -As shown above, bits that are "bitwise ANDed" with 0 become 0, while -bits that are "bitwise ANDed" with 1 are left unchanged. So, if ``b`` -is a ``byte`` variable, then ``b & B00000000`` equals zero, and ``b & -B11111111`` equals ``b``. - -.. _lang-compoundbitwise-binconst: - -.. note:: The above uses :ref:`binary constants - `\ . The numbers are still the same - value in other representations, they just might not be as easy to - understand. - - Normally, in C and C++ code, :ref:`hexadecimal - ` or :ref:`octal - ` are used when we're interested in - an integer's bits, rather than its value as a number. - - While hexadecimal and octal literals might be harder to understand - at first, you should really take the time to learn them. They're - part of C, C++, and many other programming languages, while binary - constants are available only for compatibility with Arduino. - - Also, ``B00000000`` is shown for clarity, but zero in any number - format is zero. - -So, to clear (set to zero) bits 0 and 1 of a one-byte variable, while -leaving the rest of the variable's bits unchanged, use the compound -bitwise AND operator ``&=`` with the constant ``B11111100`` -(hexadecimal ``0xFC``\ ):: - - 1 0 1 0 1 0 1 0 variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - 1 0 1 0 1 0 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -Here is the same representation with the variable's bits replaced -with the symbol ``x``\ :: - - x x x x x x x x variable - 1 1 1 1 1 1 0 0 mask - ---------------------- - x x x x x x 0 0 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged cleared - - -So, using a byte variable ``b``\ , if we say:: - - b = B10101010; // B10101010 == 0xAA - b &= B11111100; // B11111100 == 0xFC - -then we will have :: - - b == B10101000; // B10101000 == 0xA8 - -.. _lang-compoundbitwise-or: - -Compound bitwise OR (``|=``) ----------------------------- - -The compound bitwise OR operator ``|=`` is often used with a variable -and a constant to "set" (set to 1) particular bits in a variable. In -a program, writing the line ``x |= y;`` is equivalent to writing ``x = -x | y;``. That is, the value of ``x`` after the line will be equal to -its old value bitwise ORed with the value of ``y``:: - - x |= y; // equivalent to x = x | y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any integer value (like ``3`` or ``0x20``) for -``y``. (This works the same way as :ref:`compound bitwise AND -`\ , ``&=``). - -Before doing an example of ``|=``, let's first review the Bitwise OR -(``|``) operator:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 1 (operand1 | operand2) = result - -Bits that are "bitwise ORed" with 0 are unchanged, while bits that are -"bitwise ORed" with 1 are set to 1. So if ``b`` is a ``byte`` -variable, then ``b | B00000000`` equals ``b``, and ``b & B11111111`` -equals ``B11111111`` (here we've used binary constants; see the -:ref:`note ` above). - -So, to set bits 0 and 1 of a one-byte variable, while leaving the rest -of the variable unchanged, use the compound bitwise OR operator -(``|=``) with the constant ``B00000011`` (hexadecimal ``0x3``):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -Here is the same representation with the variable's bits replaced with -the symbol ``x``:: - - x x x x x x x x variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - x x x x x x 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged set - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b |= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101011; // B10101011 == 0xAB - -.. _lang-compoundbitwise-xor: - -Compound bitwise XOR (``^=``) ------------------------------ - -The compound bitwise XOR operator ``^=`` is used with a variable and a -constant to "toggle" (change 0 to 1, and 1 to 0) particular bits in a -variable. In a program, writing the line ``x ^= y;`` is equivalent to -writing ``x = x ^ y;``. That is, the value of ``x`` after the line -will be equal to its old value bitwise XORed with the value of ``y``:: - - x ^= y; // equivalent to x = x ^ y; - -You can use any integer variable for ``x`` (i.e., any variable of type -``int``, ``long``, ``char``, ``byte``, etc.). You can use either an -integer variable or any integer value (like ``3`` or ``0x20``) for -``y``. (This works the same way as :ref:`&= -` and :ref:`\|= -`; in fact, these three operators all -work the same in this way). - -Before doing an example of ``^=``, let's first review the Bitwise -XOR operator, ``^``:: - - 0 0 1 1 operand1 - 0 1 0 1 operand2 - ---------- - 0 1 1 0 (operand1 ^ operand2) = result - -One way to look at bitwise XOR is that each bit in the result is a 1 -if the input bits are different, or 0 if they are the same. Another -way to think about it is that the result bit will be 1 when *exactly* -one (no more, no less) of the input bits is 1; otherwise, it will be -zero. This means that if you XOR a bit with 1, it will change (or -toggle) its value, while if you XOR a bit with 0, it stays the same. - -So, to toggle bits 0 and 1 of a one-byte variable, while leaving the -rest of the variable unchanged, use the compound bitwise XOR operator -``^=`` with the constant ``B00000011`` (hexadecimal ``0x3``\ ; see -:ref:`note ` above):: - - 1 0 1 0 1 0 1 0 variable - 0 0 0 0 0 0 1 1 mask - ---------------------- - 1 0 1 0 1 0 1 1 - ^^^^^^^^^^^^^^^^ ^^^^ - unchanged toggled - -So, using a byte variable ``b``, if we say:: - - b = B10101010; // B10101010 == 0xAA - b ^= B00000011; // B00000011 == 0x3 - -then we will have :: - - b == B10101001; // B10101001 == 0xA9 - -See Also --------- - -- :ref:`Boolean operations ` (``&&``, ``||``) -- :ref:`Bitwise operators ` (``&``, ``|``, ``^``, ``~``) - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/const.rst b/docs/source/lang/const.rst deleted file mode 100644 index 52de85f..0000000 --- a/docs/source/lang/const.rst +++ /dev/null @@ -1,52 +0,0 @@ -.. highlight:: cpp - -.. _lang-const: - -``const`` -========= - -The ``const`` keyword stands for "constant". It is a variable -*qualifier* that modifies the behavior of the variable, making a -variable "*read-only*". This means that the variable can be used just -as any other variable of its type, but its value cannot be -changed. You will get a compiler error if you try to assign a value to -a ``const`` variable. - -Constants defined with the ``const`` keyword obey the same rules of -:ref:`variable scoping ` that govern other -variables. This, and the pitfalls of using :ref:`#define -`, often makes using the ``const`` keyword a superior -method for defining constants than ``#define``. - -Example -------- - -:: - - // this defines a variable called "pi", which cannot be changed: - const float pi = 3.14; - float x; - - // .... - - x = pi * 2; // it's fine to find the value of a const variable - - pi = 7; // illegal - you can't write to (modify) a constant - - -**#define** or **const** ------------------------- - -You can use either ``const`` or ``#define`` for creating numeric or -string constants. For :ref:`arrays `\ , you will need -to use ``const``. In general, ``const`` is preferred over ``#define`` -for defining constants. - -See Also --------- - -- :ref:`#define ` -- :ref:`volatile ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/constants.rst b/docs/source/lang/constants.rst deleted file mode 100644 index bc5c894..0000000 --- a/docs/source/lang/constants.rst +++ /dev/null @@ -1,304 +0,0 @@ -.. _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 `. 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). - - -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() -`), and read with :ref:`digitalRead() -`, the microcontroller will report ``HIGH`` if a -voltage of 3 volts or more is present at the pin. - -.. TODO? Following seems false; check it out sometime, leave out for now: - -.. A pin may also be configured as an ``INPUT`` with ``pinMode()``, and -.. subsequently made ``HIGH`` with :ref:`digitalWrite() -.. `, this will set the internal pullup resistors, -.. which will *steer* the input pin to a HIGH reading unless it is pulled -.. LOW by external circuitry. - -When a pin is configured to ``OUTPUT`` with pinMode, and set to -``HIGH`` with :ref:`digitalWrite() `, the pin is at -3.3 volts. In this state it can *source* current, e.g. light an LED -that is connected through a series resistor to ground, or to another -pin configured as an output and set to ``LOW``. - -.. _lang-constants-low: - -LOW -^^^ - -The meaning of ``LOW`` also has a different meaning depending on -whether a pin is set to ``INPUT`` or ``OUTPUT``. When a pin is -configured as an ``INPUT`` with :ref:`pinMode() `, and -read with :ref:`digitalRead() `, the microcontroller -will report ``LOW`` if a voltage of 2 volts or less is present at the -pin. - -When a pin is configured to ``OUTPUT`` with ``pinMode()``, and set to -``LOW`` with :ref:`digitalWrite() `, the -microcontroller will attempt to keep that pin's voltage at 0V. In this -state it can *sink* current, e.g. light an LED that is connected -through a series resistor to +3.3V, or to another pin configured as an -output, and set to ``HIGH``. - -Pin Modes ---------- - -Digital pins can be used in a variety of modes. The basic modes, -``INPUT`` and ``OUTPUT``, have been introduced above. Changing a pin -from ``INPUT`` TO ``OUTPUT`` with :ref:`pinMode() ` -drastically changes the electrical behavior of the pin. - -This section describes the basic digital pin modes (``INPUT`` and -``OUTPUT``) only. For a detailed description of all possible pin -modes, see the :ref:`pinMode() ` reference page. - -.. _lang-constants-input: - -INPUT -^^^^^ - -Maple (STM32) pins configured as ``INPUT`` are said to be in a -high-impedance state. One way of explaining this is that pins -configured as ``INPUT`` make extremely small demands on the circuit -that they are sampling. This makes them useful for reading a sensor, -but not powering an LED. - -.. _lang-constants-output: - -OUTPUT -^^^^^^ - -Pins configured as ``OUTPUT`` with :ref:`pinMode() ` are -said to be in a low-impedance state. This means that they can provide -a substantial amount of current to other circuits. STM32 pins can -source (provide positive current) or sink (provide negative current) -up to 50 mA (milliamps) of current to other devices/circuits. This -makes them useful for powering LEDs, but useless for reading sensors. - -Pins configured as outputs can also be damaged or destroyed if short -circuited to either ground or 3.3V power rails. The amount of current -provided by an STM32 pin is also not enough to power most relays or -motors, and some interface circuitry will be required. - -.. _lang-constants-integers: - -Integer Constants ------------------ - -Integer constants (or more properly speaking, integer *literals*) are -numbers used directly in a sketch, like ``123``. By default, an -integer literal is treated as a (signed) :ref:`int `, but -you can change this with the U and L modifiers (see :ref:`below -`). You can specify negative numbers by -putting a minus sign in front, like ``-123``. - -Normally, integer literals are treated as base 10 (decimal) integers, -but special notation (formatters) may be used to enter numbers in -other bases. These are summarized in the following table: - -.. list-table:: - :header-rows: 1 - - * - Base - - Example - - Formatter - - Comment - - * - 10 (decimal) - - ``123`` - - None - - - - * - 2 (binary) - - ``0b1111011`` - - Leading "0b" - - GCC extension; not standard C++ - - * - 8 (octal) - - ``0173`` - - Leading "0" - - Characters 0-7 valid - - * - 16 (hexadecimal) - - ``0x7B`` - - Leading "0x" - - Characters 0-9, A-F (or a-f) valid - -Binary constants (like ``B1111011``) for values between 0 and 255 are -supported for compatibility with Arduino only. Their use in new -programs is discouraged. - -.. _lang-constants-integers-dec: - -**Decimal** is base 10. This is the common 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`` (this is a :ref:`GCC -` extension; it's not standard C++). - -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 - interpret it in octal. - -.. _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 -may be typed in upper or lower case (a-f). - -For example, the hexadecimal literal ``0x101`` is two hundred fifty -seven: 1×16\ :sup:`2` + 0×16\ :sup:`1` + 1×16\ :sup:`0` = 257. - -The hexadecimal literal ``0xCF2`` is three thousand, three hundred -fourteen: 12×16\ :sup:`2` + 15×16\ :sup:`1` + 2×16\ :sup:`0` = 3314. - -(Remember that in hex, ``A`` means 10, and counting up, ``B``\ =11, so -``C``\ =12 and ``F``\ =15). - -.. _lang-constants-integers-u-l: - -U and L Suffixes -^^^^^^^^^^^^^^^^ - -By default, an integer constant is treated as an :ref:`int -`, with the attendant :ref:`limitations in values -`. To specify an integer constant with another data -type, follow it with: - -- a ``u`` or ``U`` to interpret the constant as an unsigned value. - For example, ``33U`` is an :ref:`unsigned int `. - -- an ``l`` or ``L`` to interpret the constant as a long value. For - example, ``100000L`` is a :ref:`long `. - -- a ``ul`` or ``UL`` to do both. For example, ``32767UL`` is an - :ref:`unsigned long `. - -.. _lang-constants-fp: - -Floating-Point Constants ------------------------- - -Similar to integer literals, floating point constants (properly: -floating-point *literals*) are used to make code more readable. -Floating point literals are swapped at compile time for the value to -which the expression evaluates. - -A floating point literal is any number which includes a decimal point. -For instance, ``3.0`` is a floating-point literal for the number 3. -By default, a floating-point literal is a :ref:`double `. -In order for the literal to be interpreted as a :ref:`float -`, you can write ``f`` directly after it. For example, -``3.0f`` is a floating-point literal with type ``float``. - -Floating point constants can also be expressed in a variety of -scientific notation. ``E`` and ``e`` are both accepted as valid -exponent indicators. Some examples are given in the following table: - - -.. list-table:: - :header-rows: 1 - - * - Floating-point literal - - 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`` - -See Also --------- - -- :ref:`pinMode() ` -- :ref:`Boolean Variables ` -- :ref:`#define ` -- :ref:`int ` -- :ref:`unsigned int ` -- :ref:`long ` -- :ref:`unsigned long ` -- :ref:`float ` -- :ref:`double ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/constrain.rst b/docs/source/lang/constrain.rst deleted file mode 100644 index d19b61c..0000000 --- a/docs/source/lang/constrain.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. 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() ` -- :ref:`max() ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/continue.rst b/docs/source/lang/continue.rst deleted file mode 100644 index 13d1815..0000000 --- a/docs/source/lang/continue.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. highlight:: cpp - -.. _lang-continue: - -``continue`` -============ - -The ``continue`` keyword skips the rest of the current iteration of a -:ref:`while `\ , :ref:`for `\ , or -:ref:`do/while ` loop. It continues by checking the -conditional expression of the loop, and proceeding with any subsequent -iterations. - -Example -------- - -:: - - - for (x = 0; x < 255; x ++) { - if (x > 40 && x < 120) { // create jump in values - continue; // skips the next two lines and goes to the - // beginning of the loop, with the next value of x - } - - digitalWrite(PWMpin, x); - delay(50); - } - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/cos.rst b/docs/source/lang/cos.rst deleted file mode 100644 index 3fbb0af..0000000 --- a/docs/source/lang/cos.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. _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 -`_\ , while Arduino's is that of -`avr-libc `_\ . - -See also --------- - - -- :ref:`sin() ` -- :ref:`tan() ` -- :ref:`float ` -- :ref:`double ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/curly-braces.rst b/docs/source/lang/curly-braces.rst deleted file mode 100644 index a4bd3dc..0000000 --- a/docs/source/lang/curly-braces.rst +++ /dev/null @@ -1,109 +0,0 @@ -.. highlight:: cpp - -.. _lang-curly-braces: - -Curly Braces (``{``, ``}``) -=========================== - -.. contents:: Contents - :local: - -Introduction ------------- - -Curly braces (also referred to as just "braces" or as "curly -brackets") are a major part of the C and C++ programming -languages. They are used in several different constructs, outlined -below, and this can sometimes be confusing for beginners. - -An opening curly brace, ``{`` must always be followed by a closing -curly brace ``}``. This is a condition that is often referred to as -the braces being *balanced*. The Maple IDE (integrated development -environment) includes a convenient feature to check the balance of -curly braces. Just select a brace, or even click the insertion point -immediately following a brace, and its companion will be highlighted\ -[#fbug]_\ . - -Beginning programmers, and programmers coming to C++ from languages -without braces, often find using them confusing or daunting. - -Because the use of the curly brace is so varied, it is good -programming practice to type the closing brace immediately after -typing the opening brace when inserting a construct which requires -curly braces. Then insert some blank lines between your braces and -begin inserting statements. Your braces, and your attitude, will never -become unbalanced. - -Unbalanced braces can often lead to cryptic, impenetrable compiler -errors that can sometimes be hard to track down in a large program. -Because of their varied usages, braces are also incredibly important -to the syntax of a program and moving a brace one or two lines will -usually dramatically affect the meaning of a program. - -The main uses of curly braces ------------------------------ - -**Functions**:: - - // a function body needs braces around it - void myFunction(datatype argument) { - // ... function body goes in here ... - } - -**Loops** (see the :ref:`while `\ , :ref:`for -`\ , and :ref:`do/while ` loop reference -pages for more information):: - - // you should put braces around the body of a loop: - - while (boolean expression) { - // code inside the loop goes here - } - - for (initialisation; termination condition; incrementing expr) { - // code inside the loop goes here - } - - do { - // code inside the loop goes here - } while (boolean expression); - - -**Conditional statements** (see the :ref:`if statement ` -reference page for more information):: - - // you should put braces around the body of an "if", "else if", - // or "else": - - if (boolean expression) { - // code inside the "if" - } - else if (boolean expression) { - // code inside the "else if" - } - else { - // code inside the "else" - } - -**Switch statements** (see the :ref:`switch statement -` reference page for more information):: - - switch (var) { - case 1: - doThing1(); - break; - case 2: - doThing2(); - break; - } - -.. rubric:: Footnotes - -.. TODO remove this once IDE 0.1.0 released - -.. [#fbug] At present this feature is slightly buggy as the IDE will - often find (incorrectly) a brace in text that has been commented - out. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/define.rst b/docs/source/lang/define.rst deleted file mode 100644 index 677390d..0000000 --- a/docs/source/lang/define.rst +++ /dev/null @@ -1,56 +0,0 @@ -.. highlight:: cpp - -.. _lang-define: - -``#define`` -=========== - -``#define`` is a useful C and C++ feature that allows the programmer -to give a name to a constant value before the program is compiled. -The compiler will replace references to these constants with the -defined value at compile time. - -This can have some unwanted side effects. In general, the :ref:`const -` keyword is preferred for defining constants. - - -Syntax ------- - -The following line would define the name ``MY_CONSTANT`` to have value -``value``:: - - #define MY_CONSTANT value - -Note that the ``#`` is necessary. It is usually good style for the -name to be capitalized, although this is not required. - -There is no semicolon after the #define statement. If you include one, -the compiler will likely throw cryptic errors in unrelated places. -That is, **don't do this**:: - - // DON'T DO THIS! THE SEMICOLON SHOULDN'T BE THERE! - #define NAME value; - -Similarly, including an equal sign after the ``#define`` line will -also generate a cryptic compiler error further down the page. That -is, **don't do this, either**:: - - // DON'T DO THIS, EITHER! THE EQUALS SIGN SHOULDN'T BE THERE! - #define NAME = value - -Example -------- - -:: - - #define LED_PIN 13 - // The compiler will replace any mention of LED_PIN with - // the value 3 at compile time. - -See Also --------- -- :ref:`const ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/delay.rst b/docs/source/lang/delay.rst deleted file mode 100644 index 90ca268..0000000 --- a/docs/source/lang/delay.rst +++ /dev/null @@ -1,72 +0,0 @@ -.. 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() ` function -and the "Blink Without Delay" sketch cited :ref:`below -`\ . 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() `\ ) values -and pin states are maintained, and :ref:`interrupts -` will work as they should. - - -Example -------- - -:: - - int ledPin = 13; // LED connected to pin 13 - - void setup() { - pinMode(ledPin, OUTPUT); // sets the digital pin as output - } - - void loop() { - digitalWrite(ledPin, HIGH); // sets the LED on - delay(1000); // waits for a second - digitalWrite(ledPin, LOW); // sets the LED off - delay(1000); // waits for a second - } - -.. _lang-delay-seealso: - -See also --------- - - -- :ref:`millis() ` -- :ref:`micros() ` -- :ref:`delayMicroseconds() ` -- (Arduino) `Blink Without Delay - `_ example (works - unmodified on Maple) - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/delaymicroseconds.rst b/docs/source/lang/delaymicroseconds.rst deleted file mode 100644 index 24a8286..0000000 --- a/docs/source/lang/delaymicroseconds.rst +++ /dev/null @@ -1,65 +0,0 @@ -.. 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 ` -- :ref:`micros ` -- :ref:`delay ` - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/detachinterrupt.rst b/docs/source/lang/detachinterrupt.rst deleted file mode 100644 index adb2439..0000000 --- a/docs/source/lang/detachinterrupt.rst +++ /dev/null @@ -1,37 +0,0 @@ -.. _lang-detachinterrupt: - -detachInterrupt() -================= - -Used to disable an interrupt specified with -:ref:`lang-attachinterrupt`\ . - - -Library Documentation ---------------------- - -.. doxygenfunction:: detachInterrupt - -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() ` - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/digitalread.rst b/docs/source/lang/digitalread.rst deleted file mode 100644 index 3502587..0000000 --- a/docs/source/lang/digitalread.rst +++ /dev/null @@ -1,58 +0,0 @@ -.. highlight:: cpp - -.. _lang-digitalread: - -digitalRead() -============= - -Reads the value from a specified digital pin, either :ref:`HIGH -` or :ref:`LOW `. - - -Library Documentation ---------------------- - -.. doxygenfunction:: digitalRead - - -Example -------- - -The following example turns the LED on when the button is pressed:: - - int ledPin = 13; // LED connected to Maple pin 13 - int buttonPin = 38; // BUT connected to Maple pin 38 - - void setup() { - pinMode(ledPin, OUTPUT); - pinMode(buttonPin, INPUT); - } - - void loop() { - int val = digitalRead(buttonPin); // reads the input pin - digitalWrite(ledPin, val); - } - -Note ----- - -If the pin isn't connected to anything, ``digitalRead()`` can return -either HIGH or LOW (and this can change in a way that seems random). - -Arduino Compatibility ---------------------- - -The Maple version of ``digitalRead()`` is compatible with Arduino. - - -See Also --------- - -- :ref:`pinMode ` -- :ref:`digitalWrite ` - - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/digitalwrite.rst b/docs/source/lang/digitalwrite.rst deleted file mode 100644 index 6124d5f..0000000 --- a/docs/source/lang/digitalwrite.rst +++ /dev/null @@ -1,68 +0,0 @@ -.. highlight:: cpp - -.. _lang-digitalwrite: - -digitalWrite() -============== - -Write a :ref:`HIGH ` or a :ref:`LOW -` value to a pin configured as :ref:`OUTPUT -`. - -Library Documentation ---------------------- - -.. doxygenfunction:: digitalWrite - -Discussion ----------- - -If the pin has been configured as an ``OUTPUT`` with :ref:`pinMode() -` its voltage will be set to the corresponding value: -3.3V for ``HIGH``, and 0V (ground) for ``LOW``. - -.. TODO make the following paragraphs true, but refer the reader to -.. INPUT_PULLUP and INPUT_PULLDOWN: - -If the pin is configured as an ``INPUT``, writing a ``HIGH`` value -with ``digitalWrite()`` will enable an internal pullup resistor. -Writing ``LOW`` will disable the pullup. The pullup resistor is enough -to light an LED dimly, so if LEDs appear to work, but very dimly, this -is a likely cause. The remedy is to set the pin to an output with the -:ref:`pinMode() ` function. - -.. note:: Pin 13 is harder to use as an input than the other pins - because it has an LED and resistor soldered to it in series. If you - enable its internal pull-up resistor, it will likely hang at around - 1.1V instead of the expected 3.3V because the onboard LED and - series resistor pull the voltage level down. If you must use pin 13 - as a digital input, use an external pull-down resistor. - -Example -------- - -The following example sets pin 13 to ``HIGH``, makes a one-second-long -delay, sets the pin back to ``LOW``, and delays again, causing a -blinking pattern:: - - - int ledPin = 13; // LED connected to digital pin 13 - - void setup() { - pinMode(ledPin, OUTPUT); // sets the digital pin as output - } - - void loop() { - digitalWrite(ledPin, HIGH); // sets the LED on - delay(1000); // waits for a second - digitalWrite(ledPin, LOW); // sets the LED off - delay(1000); // waits for a second - } - -See Also --------- - -- :ref:`pinMode ` -- :ref:`digitalRead ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/double.rst b/docs/source/lang/double.rst deleted file mode 100644 index 1527778..0000000 --- a/docs/source/lang/double.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. _lang-double: - -``double`` -========== - -Double precision floating point type. Occupies 8 bytes. On Maple, the -``double`` type has a range of approximately -1.79769×10^308 to -1.79769×10^308; the ``double`` type subject to the same :ref:`overflow -issues ` as any numeric data type. - -Floating point numbers are not exact, and may yield strange results -when compared. For example ``6.0 / 3.0`` may not equal ``2.0``. You -should instead check that the absolute value of the difference between -the numbers is less than some small number. - -Floating point math is also much slower than integer math in -performing calculations, so should be avoided if, for example, a loop -has to run at top speed for a critical timing function. Programmers -often go to some lengths to convert floating point calculations to -integer math to increase speed. - -For more information, see the `Wikipedia article on floating point -math `_\ . - -Floating-point numbers represent numbers with "decimal point", unlike -integral types, which always represent whole numbers. Floating-point -numbers are often used to approximate analog and continuous values -because they have greater resolution than integers. - -The double implementation on the Maple uses twice the number of bytes -as a :ref:`float `, with the corresponding gains in -precision. - -Tip ---- - -Users who borrow code from other sources that includes ``double`` -variables may wish to examine the code to see if the implied range and -precision are different from that actually achieved on the Maple. - -See Also --------- - -- :ref:`float ` - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/doublecast.rst b/docs/source/lang/doublecast.rst deleted file mode 100644 index 511fe24..0000000 --- a/docs/source/lang/doublecast.rst +++ /dev/null @@ -1,27 +0,0 @@ -.. highlight:: cpp - -.. _lang-doublecast: - -``double()`` (cast) -=================== - -Converts a value to the :ref:`double ` floating point -data type. Here is an example:: - - int x = 2; - double d = double(x); // d now holds 2.0, a double value - -The value ``x`` can be of any type. However, if ``x`` is not a number -(like an ``int`` or ``long``), you will get strange results. - -See the :ref:`double ` reference for details about the -precision and limitations of ``double`` values on the Maple. - -See Also --------- - -- :ref:`double ` -- :ref:`float ` -- :ref:`float() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/dowhile.rst b/docs/source/lang/dowhile.rst deleted file mode 100644 index fe92226..0000000 --- a/docs/source/lang/dowhile.rst +++ /dev/null @@ -1,27 +0,0 @@ -.. highlight:: cpp - -.. _lang-dowhile: - -``do``/``while`` -================ - -A ``do`` loop works in the same manner as a :ref:`while -` loop, with the exception that the condition is tested -at the end of the loop, so the ``do`` loop will *always* run at least -once. - -This is the basic syntax:: - - do { - // statement block - } while (test condition); - -Example:: - - do { - delay(50); // wait for sensors to stabilize - x = readSensors(); // check the sensors - } while (x < 100); - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/enum.rst b/docs/source/lang/enum.rst deleted file mode 100644 index ba82383..0000000 --- a/docs/source/lang/enum.rst +++ /dev/null @@ -1,53 +0,0 @@ -.. highlight:: cpp - -.. _lang-enum: - -``enum`` -======== - -The ``enum`` keyword is used to specify an enumeration type. An -enumeration type is a type whose values are taken from a specified, -fixed list of constant values. - -Example -------- - -Here's an example defining an enumeration type called ``weather``, -which has values ``HOT``, ``COMFY``, and ``COLD``:: - - enum weather {HOT, COMFY, COLD}; - -Once you've defined this type, you can create variables of type -``weather``, in the same way you would with an :ref:`int ` -or a :ref:`long `:: - - // create a weather variable named theWeather, with value COMFY: - weather theWeather = COMFY; - -Enumeration types are useful within :ref:`switch statements -`. If you know that an argument is of an enumeration -type, you can make ``case`` statements for all of that type's possible -values, so you know you won't miss anything:: - - void describeWeather(weather currentWeather) { - switch(currentWeather) { - case HOT: - SerialUSB.println("it's hot out"); - break; - case COMFY: - SerialUSB.println("it's nice today"); - break; - case COLD: - SerialUSB.println("it's freezing!"); - break; - } - } - -Such a ``switch`` statement would need no :ref:`default -`, since we know that ``currentWeather`` must -be either ``HOT``, ``COMFY``, or ``COLD``. - -See Also --------- - -- :ref:`lang-switchcase` diff --git a/docs/source/lang/float.rst b/docs/source/lang/float.rst deleted file mode 100644 index 6937c8c..0000000 --- a/docs/source/lang/float.rst +++ /dev/null @@ -1,50 +0,0 @@ -.. highlight:: cpp - -.. _lang-float: - -``float`` -========= - -Single-precision floating point number. Occupies 4 bytes. On Maple, -the ``float`` type has a range of approximately -3.40282×10^38 to -3.40282×10^38; the ``float`` type is subject to the same -:ref:`overflow issues ` as any numeric data -type. - -``float``\ s have only 6-7 decimal digits of precision. That means the -total number of digits, not the number to the right of the decimal -point. You can get more precision by using a :ref:`double -` (which has a precision of about 16 decimal digits). - -The following example declares a ``float`` value named ``myfloat``:: - - float myfloat; - -This example declares a ``float`` value named ``sensorCalibrate``, -with value 1.117:: - - float sensorCalibrate = 1.117; - -The general syntax for declaring a float named ``var`` with value -``val`` is:: - - float var = val; - -Here is a more extended example involving a :ref:`float cast -`:: - - int x; - int y; - float z; - - x = 1; - y = x / 2; // y now contains 0, ints can't hold fractions - z = float(x) / 2; // z now contains .5 - -See Also --------- - -- :ref:`double ` -- :ref:`Variables ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/floatcast.rst b/docs/source/lang/floatcast.rst deleted file mode 100644 index 4766478..0000000 --- a/docs/source/lang/floatcast.rst +++ /dev/null @@ -1,28 +0,0 @@ -.. highlight:: cpp - -.. _lang-floatcast: - -``float()`` (cast) -================== - -Converts a value to the :ref:`float ` data type. Here is -an example (see the :ref:`constants reference ` for -an explanation of the "2.0f"):: - - int x = 2; - float f = float(x); // f now holds 2.0f, a float value - -The value ``x`` can be of any type. However, if ``x`` is not a number -(like an ``int``), you will get strange results. - -See the :ref:`float ` reference for details about the -precision and limitations of ``float`` values on the Maple. - -See Also --------- - -- :ref:`float ` -- :ref:`double ` -- :ref:`double() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/for.rst b/docs/source/lang/for.rst deleted file mode 100644 index 71c5aca..0000000 --- a/docs/source/lang/for.rst +++ /dev/null @@ -1,142 +0,0 @@ -.. highlight:: cpp - -.. _lang-for: - -``for`` -======= - -A ``for`` loop is used to repeat a block of statements enclosed in -curly braces. ``for`` loops are useful for performing repetitive -operations, and are often used in combination with :ref:`arrays -` to operate on collections of data or multiple -:ref:`pins `. A ``for`` loop is composed of two parts: first, a -*header*, which sets up the for loop, and then a *body*, which is made -up of lines of code enclosed in curly braces. - -.. contents:: Contents - :local: - -Syntax ------- - -There are three parts to the ``for`` loop header: an *initialization* -expression, *loop condition* expression, and a *post-loop* -expression. The general syntax looks like this:: - - for (initialization; condition; post-loop) { - // all of these lines inside the curly braces are part - // of the loop body. - statement 1; - statement 2; - ... - } - -(Note that there is no semicolon after the post-loop). The -initialization happens first and exactly once, before the loop begins. -Each time through the loop, the condition is tested. The condition is -a :ref:`boolean ` expression. If it is true, then the -list of statements inside the curly braces are executed. Next, the -post-loop is executed. The loop then begins again by evaluating the -condition again, entering the loop body if it is true. This proceeds -until the condition becomes false. - -Examples --------- - -Here's an example:: - - // Dim an LED using a PWM pin - int pwmPin = 9; // LED in series with 470 ohm resistor on pin 9 - - void setup() { - pinMode(pwmPin, PWM); - } - - void loop() { - for (int i=0; i <= 65535; i++) { - pwmWrite(pwmPin, i); - delay(1); - } - } - -There is a ``for`` loop In the :ref:`loop() ` function of -the above example. This loop starts by declaring an ``int`` variable -named ``i``, whose value starts out at zero. The loop proceeds by -checking if ``i`` is less than or equal to 65535. Since ``i`` is -zero, this is true, and so the calls to :ref:`pwmWrite() -` and :ref:`delay() ` happen next. At this -point, the post-loop expression ``i++`` is evaluated, which -:ref:`increments ` ``i``, so that ``i`` becomes one. -That concludes the first time through the loop. Each "time through -the loop" is referred to as an *iteration*. - -The loop then jumps back to the beginning, checking the condition as -the beginning of its second iteration (initialization is skipped, -since this only happens once, before the first iteration). One is -less than 65535, so the loop statements are executed again. This -proceeds over and over until the iteration when ``i`` finally -reaches 65536. At that point, the condition is no longer true, so the -loop stops executing, and the ``loop()`` function returns. - -Here's another example, using a ``for`` loop to brighten and fade an -LED (see the :ref:`pwmWrite() ` reference for more -information):: - - int pwmPin = 9; // hook up the LED to pin 9 - void loop() { - int x = 1; - for (int i = 0; i >= 0; i += x) { - analogWrite(pwmPin, i); // controls the brightness of the LED - if (i == 65535) { - x = -1; // switch direction, so i starts decreasing - } - delay(1); - } - } - -Coding Tips ------------ - -The C ``for`` loop is more flexible than ``for`` loops found in some -other computer languages, including BASIC. Any or all of the three -header elements may be left blank, although the semicolons are -required. Also the statements for initialization, condition, and -post-loop can be any valid C statements, and use any C datatypes, -including :ref:`floating point numbers `. These types -of unusual ``for`` loops sometimes provide solutions to less-common -programming problems. - -For example, using a multiplication in the post-loop line will -generate a `geometric progression -`_:: - - for(int x = 1; x <= 100; x = x * 2) { - SerialUSB.println(x); - } - - -This loop prints out the numbers 1, 2, 4, 8, ..., 64. Check -your understanding of ``for`` loops by answering the following two -questions (answers are in footnote [#fanswers]_\ ): - -1. How many iterations occur before the loop finishes? - -2. Why does it stop at 64? - -See also --------- - -- :ref:`while ` loops -- :ref:`do ` loops - -.. rubric:: Footnotes - -.. [#fanswers] - 1. Seven. - - 2. After the seventh iteration, the post-loop causes ``x`` to - equal 128. This is larger than 100, so the loop condition is - false, and the loop stops. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/goto.rst b/docs/source/lang/goto.rst deleted file mode 100644 index ff2f248..0000000 --- a/docs/source/lang/goto.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. highlight:: cpp - -.. _lang-goto: - -Labels and ``goto`` -=================== - -A *label* gives a name to a line of code within a function. You can -label a line by writing a name for it, then a colon (``:``), before -the line starts. The ``goto`` keyword allows program flow to transfer -to a labeled line from anywhere within the same function. - -.. warning:: The use of ``goto`` is discouraged in C and C++ - programming. It is *never necessary* to use ``goto`` to write a - program. - - Unless you know what you're doing, using ``goto`` tends to - encourage code which is harder to debug and understand than - programs without ``goto`` that do the same thing. That said, - however, it's sometimes useful; :ref:`see below ` - for a concrete example. - -Using Labels and goto ---------------------- - -Labels and ``goto`` are probably best explained through example. -Let's start with an example of how to label lines. The first line -(``int x = analogRead(some_pin);``) in the :ref:`loop ` -function below has label ``readpin``. The third line (``delay(x);``) -has label ``startdelay``. The second line (``SerialUSB.println(x);``) -does not have a label:: - - void loop() { - readpin: - int x = analogRead(some_pin); - SerialUSB.println(x); // for debugging - startdelay: - delay(x); - // ... more code ... - } - -Anything which can be a :ref:`variable ` name can -be a label. - -Let's say that we wanted to print ``x`` only if it was very large, say -at least 2000. We might want to do this just so anybody watching on a -:ref:`serial monitor ` would know they were in for -a longer wait than usual. We can accomplish this through the use of a -``goto`` statement that skips the printing if ``x`` is less than -2000:: - - void loop() { - readpin: - int x = analogRead(some_pin); - if (x < 2000) { - goto startdelay; - } - SerialUSB.println(x); // for debugging - startdelay: - delay(x); - // ... more code ... - } - -In this modified program, whenever ``x`` is less than 2000, the body -of the :ref:`if ` statement in the second line is -executed. The ``goto`` statement inside the ``if`` body skips -straight to the line labeled ``startdelay``, passing over the line -doing the printing. - -A ``goto`` does not have to "move forwards"; it can go "backwards", -too. For example, the following program prints "5" forever (why?):: - - void loop() { - printfive: - SerialUSB.println(5); - goto printfive; - SerialUSB.println(6); - } - -.. _goto-when-to-use: - -When to Use goto ----------------- - -As mentioned above, use of ``goto`` is `generally discouraged -`_. However, -when used with care, ``goto`` can simplify certain programs. One -important use case for ``goto`` is breaking out of deeply nested -:ref:`for ` loops or :ref:`if ` logic blocks. -Here's an example:: - - for(int r = 0; r < 255; r++) { - for(int g = 255; g > -1; g--) { - for(int b = 0; b < 255; b++) { - if (analogRead(0) > 250) { - goto bailout; - } - // more statements ... - } - // innermost loop ends here - } - } - bailout: - // more code here - -In the above example, whenever the :ref:`analog reading -` on pin 0 was greater than 250, the program would -jump to the line labeled ``bailout``, exiting all three loops at once. - -While there is already a :ref:`break ` keyword for -breaking out of a loop, it will only break out of the *innermost* -loop. So, if instead of saying "``goto bailout;``", there was a -"``break;``" instead, the program would only exit from the loop with -header "``for(int b = 0; b < 255; b++)``". The program would continue -at the line which reads "``// innermost loop ends here``", which is -clearly undesirable if you wanted to leave all three loops at once. - -More examples of when ``goto`` is a good choice are given in Donald -Knuth's paper, "Structured Programming with go to Statements"; see -below for a link. - -See Also --------- - -- Dijkstra, Edsger W. `Go To Statement Considered Harmful `_ (PDF) - -- Knuth, Donald. `Structured Programming with go to Statements `_ (PDF) - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/highbyte.rst b/docs/source/lang/highbyte.rst deleted file mode 100644 index 50a1fa6..0000000 --- a/docs/source/lang/highbyte.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. 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() ` - - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/if.rst b/docs/source/lang/if.rst deleted file mode 100644 index bef89e2..0000000 --- a/docs/source/lang/if.rst +++ /dev/null @@ -1,121 +0,0 @@ -.. highlight:: cpp - -.. _lang-if: - -``if``/``else`` -=============== - -An ``if`` statement is used to execute code when certain conditions -are met. The general syntax for an ``if`` statement is:: - - if (condition) { - body - } - -An ``if`` statement first tests whether its *condition* is true (such -as an input being above a certain number). If the condition is true, -the ``if`` statement executes its *body*, which is made up of lines of -code inside :ref:`curly braces `. If the condition -is false, the body is not executed. Here's a more concrete example:: - - if (someVariable > 50) { - // do something here - } - -The program tests to see if ``someVariable`` is greater than 50. If it -is, the program executes every line in the curly braces (which in the -above example does nothing, since the body is just the :ref:`comment -` line "``// do something here``"). - -Put another way, if the statement in parentheses is true, the -statements inside the braces are run. If not, the program skips over -the code. - -An ``if`` statement's condition (which is inside the parentheses after -``if``) often uses one or more :ref:`boolean ` or -:ref:`comparison ` operators. - -Writing the if Body -------------------- - -The brackets may be omitted after an ``if`` statement's -conditional. If this is done, the next line (which ends in a -semicolon) becomes the only line in the body. The following three -``if`` statements all do the same thing:: - - if (x > 120) digitalWrite(ledPin, HIGH); - - if (x > 120) - digitalWrite(ledPin, HIGH); - - if (x > 120) { - digitalWrite(ledPin, HIGH); - } - -However, the following two examples are different:: - - // example 1: two lines of code in the if body - if (x > 120) { - digitalWrite(ledPin1, HIGH); - digitalWrite(ledPin2, HIGH); - } - - // example 2: one line of code in the if body, and - // another line of code after the if statement - if (x > 120) - digitalWrite(ledPin1, HIGH); // this is in the if body - digitalWrite(ledPin2, HIGH); // this is NOT in the if body - -In the first example, since the body is enclosed in curly braces, both -lines are included. In the second example, since the curly braces are -missing, only the first line is in the ``if`` body. - -``else`` --------- - -``if``/\ ``else`` allows greater control over the flow of code than -the basic :ref:`if ` statement, by allowing multiple tests to -be grouped together. For example, an :ref:`analog input -` could be tested, with one action taken if the input -was less than 500, and another action taken if the input was 500 or -greater. The code would look like this:: - - if (pinFiveInput < 500) { - // action A - } else { - // action B - } - -``else`` can precede another ``if`` test, so that multiple, mutually -exclusive tests can be run at the same time. - -Each test will proceed to the next one until a true test is -encountered. When a true test is found, its associated block of code -is run, and the program then skips to the line following the entire -if/else construction. If no test proves to be true, the default -``else`` block is executed, if one is present, and sets the default -behavior. - -Note that an ``else if`` block may be used with or without a -terminating ``else`` block, and vice-versa. An unlimited number of -such ``else if`` branches is allowed. Here is a code example:: - - if (pinFiveInput < 500) { - // do Thing A - } else if (pinFiveInput >= 1000) { - // do Thing B - } else { - // do Thing C - } - -Another way to express branching, mutually exclusive tests, is with a -:ref:`switch/case ` statement. - - -See Also --------- - -- :ref:`boolean operators ` -- :ref:`comparison operators ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/include.rst b/docs/source/lang/include.rst deleted file mode 100644 index 74fe7af..0000000 --- a/docs/source/lang/include.rst +++ /dev/null @@ -1,72 +0,0 @@ -.. highlight:: cpp - -.. _lang-include: - -``#include`` -============ - -``#include`` is used to include outside libraries in your sketch. -This gives the programmer access to a large group of standard C -libraries (groups of pre-made functions and data types), and also -libraries written especially for Maple. - -Example -------- - -This example (from the `Arduino LiquidCrystal Tutorial -`_) includes a library -that is used to control :ref:`LCD displays -`:: - - // include the library code: - #include - - // initialize the library with the numbers of the interface pins - LiquidCrystal lcd(12, 11, 5, 4, 3, 2); - - void setup() { - // set up the LCD's number of columns and rows: - lcd.begin(16, 2); - // Print a message to the LCD. - lcd.print("hello, world!"); - } - - void loop() { - // set the cursor to column 0, line 1 - // (note: line 1 is the second row, since counting begins with 0): - lcd.setCursor(0, 1); - // print the number of seconds since reset: - lcd.print(millis()/1000); - } - -Note that a ``#include`` line, like :ref:`#define `, -has **no semicolon**. The compiler will print strange error messages -if you add one. - -C Standard Library ------------------- - -The standard C library that comes with Maple is called `newlib -`_. Its main sources of documentation -are its `main reference `_ -page and its `math functions -`_ reference page. Here's an -example that imports the math.h library in order to take the `cube -root `_ of a number:: - - #include - - void setup() { - // no setup necessary - } - - void loop() { - // "cbrt" stands for "cube root" - double cubeRootOf3 = cbrt(3.0); - // prints a number that is approximately the cube root of 3: - SerialUSB.println(cubeRootOf3); - } - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/increment.rst b/docs/source/lang/increment.rst deleted file mode 100644 index 6dffa80..0000000 --- a/docs/source/lang/increment.rst +++ /dev/null @@ -1,37 +0,0 @@ -.. highlight:: cpp - -.. _lang-increment: - -Increment and Decrement Operators (``++``, ``--``) -================================================== - -These operators increment (add one to) or decrement (subtract one -from) a variable. If they come before the variable, they return its -new value; otherwise, they return its old value. - -Some quick examples:: - - x++; // adds one to x, and returns the old value of x - ++x; // adds one to x, and returns the new value of x - - x--; // decrement x by one and returns the old value of x - --x; // decrement x by one and returns the new value of x - -A more extended example:: - - x = 2; - y = ++x; // x now contains 3, y contains 3 - y = x--; // x contains 2 again, y still contains 3 - -.. warning:: Be careful! You cannot put a space in between the two - ``+`` or ``-`` signs. This example is broken:: - - // this line won't compile (notice the extra space): - int y = x+ +; - -See Also --------- - -- :ref:`lang-compoundarithmetic` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/int.rst b/docs/source/lang/int.rst deleted file mode 100644 index ca75f75..0000000 --- a/docs/source/lang/int.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. highlight:: cpp - -.. _lang-int: - -``int`` -======= - -The ``int`` data type represents integers. Integers are your primary -data type for number storage, and store a 4 byte value. This yields a -range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a -maximum value of (2^31) - 1; that's about negative 2 billion to -positive 2 billion). - -An ``int`` stores a negative number with a technique called `two's -complement math -`_\ . -The highest bit in an ``int``, sometimes refered to as the "sign" bit, -flags the number as a negative number. (See the linked article on -two's complement for more information). - -The Maple takes care of dealing with negative numbers for you, so that -arithmetic operations work mostly as you'd expect. There can be an -:ref:`unexpected complication ` in -dealing with the :ref:`bitshift right operator (>>) -`, however. - -Here is an example of declaring an ``int`` variable named ``ledPin``, -then giving it value 13:: - - int ledPin = 13; - -The general syntax for declaring an ``int`` variable named ``var``, -then giving it value ``val``, looks like:: - - int var = val; - -.. _lang-int-overflow: - -Integer Overflow ----------------- - -When ``int`` variables leave the range specified above, they -:ref:`roll over ` in the other direction. -Here are some examples:: - - int x; - x = -2,147,483,648; - x--; // x now contains 2,147,483,647; rolled over "left to right" - - x = 2,147,483,647; - x++; // x now contains -2,147,483,648; rolled over "right to left" - -See Also --------- - -- :ref:`unsigned int ` -- :ref:`char ` -- :ref:`unsigned char ` -- :ref:`long ` -- :ref:`unsigned long ` -- :ref:`Integer Constants ` -- :ref:`Variables ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/intcast.rst b/docs/source/lang/intcast.rst deleted file mode 100644 index 386fe14..0000000 --- a/docs/source/lang/intcast.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. highlight:: cpp - -.. _lang-intcast: - -``int()`` (cast) -================ - -Converts a value to the :ref:`int ` data type. Here is -an example:: - - double d = 2.5; - int i = int(d); // i holds "2", an int value - -The value inside of the parentheses (``int(...)``) can be of any type. -However, if it is not a numeric type (like ``double``, ``char``, -etc.), you will get strange results. - -See the :ref:`int ` reference for details about the -precision and limitations of ``int`` variables on the Maple. - -See Also --------- - -- :ref:`int ` - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/keywords.rst b/docs/source/lang/keywords.rst deleted file mode 100644 index e4ebe99..0000000 --- a/docs/source/lang/keywords.rst +++ /dev/null @@ -1,205 +0,0 @@ -.. _lang-keywords: - -Keywords -======== - -This page lists all of the C++ keywords, and either links to a -reference page explaining their use, or provides a brief description. - -List of Keywords ----------------- - -The C++ keywords are: - -``and``, ``and_eq``, ``asm``, ``auto``, ``bitand``, ``bitor``, -``bool``, ``break``, ``case``, ``catch``, ``char``, ``class``, -``compl``, ``const``, ``const_cast``, ``continue``, ``default``, -``delete``, ``do``, ``double``, ``dynamic_cast``, ``else``, ``enum``, -``explicit``, ``export``, ``extern``, ``false``, ``float``, ``for``, -``friend``, ``goto``, ``if``, ``inline``, ``int``, ``long``, -``mutable``, ``namespace``, ``new``, ``not``, ``not_eq``, -``operator``, ``or``, ``or_eq``, ``private``, ``protected``, -``public``, ``register``, ``reinterpret_cast``, ``return``, ``short``, -``signed``, ``sizeof``, ``static``, ``static_cast``, ``struct``, -``switch``, ``template``, ``this``, ``throw``, ``true``, ``try``, -``typedef``, ``typeid``, ``typename``, ``union``, ``unsigned``, -``using``, ``virtual``, ``void``, ``volatile``, ``wchar_t``, -``while``, ``xor``, ``xor_eq`` - -Boolean Operator Synonyms -------------------------- - -- ``and`` is a synonym for :ref:`&& `. -- ``not`` is a synonym for :ref:`\! `. -- ``not_eq`` is a synonym for :ref:`\!= `. -- ``or`` is a synonym for :ref:`|| `. - -Bitwise Operator Synonyms -------------------------- - -- ``and_eq`` is a synonym for :ref:`&= `. -- ``bitand`` is a synonym for (bitwise) :ref:`& `. -- ``bitor`` is a synonym for :ref:`\| `. -- ``compl`` is a synonym for :ref:`~ `. -- ``or_eq`` is a synonym for :ref:`|= `. -- ``xor`` is a synonym for :ref:`^ `. -- ``xor_eq`` is a synonym for :ref:`^= `. - -Constants ---------- - -- ``true`` and ``false`` are the :ref:`boolean constants - `. - -Control Flow ------------- - -- ``break`` can exit out of a :ref:`switch statement - ` or a :ref:`for `, :ref:`do - `, or :ref:`while ` loop. - -- ``case`` defines alternatives in a :ref:`switch statement `. - -- ``continue`` will move control flow to the next iteration of the - enclosing :ref:`for `, :ref:`do `, or - :ref:`while ` loop. - -- ``default`` defines the default alternative in a :ref:`switch - statement `. - -- ``do`` introduces a :ref:`do ` loop. - -- ``else`` is used in :ref:`if statements `. - -- ``for`` introduces a :ref:`for ` loop. - -- ``goto`` :ref:`jumps ` to a label. - -- ``if`` introduces an :ref:`if statement `. - -- ``return`` :ref:`transfers flow to a function's caller `. - -- ``switch`` introduces a :ref:`switch statement `. - -- ``while`` introduces a :ref:`while ` loop. - -Types ------ - -The following keywords are used for built-in types. - -- :ref:`bool ` -- :ref:`lang-char` -- :ref:`lang-double` -- :ref:`lang-float` -- :ref:`lang-int` -- :ref:`lang-long` -- :ref:`short ` -- :ref:`void ` (not really a type, but used in the absence - of one) - -The following keywords are used to introduce new types. - -- :ref:`enum ` - -Qualifiers ----------- - -- :ref:`static ` can be used to declare persistent local - variables; it has other uses not documented here. - -- ``unsigned`` is used to specify an unsigned integral type. - Examples: :ref:`lang-unsignedint`, :ref:`lang-unsignedchar`, - :ref:`lang-unsignedlong`. - -- :ref:`volatile ` is useful when declaring variables - that may be modified by external interrupts. - -- :ref:`const ` is used to define constants. - -Other ------ - -These keywords are not described in the Maple documentation. For more -information, consult a C++ reference. - -- ``asm`` is used to insert literal assembly language. - -- ``auto`` is used to declare that a variable has automatic storage. - -- ``catch`` is used in exception handling. Note that the default - flags we pass to :ref:`GCC ` include ``-fno-exceptions``. - -- ``class`` is used to define classes. - -- ``const_cast`` is used in typecasting. - -- ``delete`` is used to free ``new``\ -allocated storage. Note that - dynamic memory allocation is not available by default on the Maple, - so you'll have to bring your own ``new`` and ``delete`` if you want - this. - -- ``dynamic_cast`` is used in typecasting. - -- ``explicit`` is used to declare constructors that can be called only - explicitly. - -- ``export`` declares a template definition accessible to other - compilation units. - -- ``extern`` can mark a declaration as a declaration and not a - definition, and also grant external linkage to a ``const`` or - ``typedef``. - -- ``friend`` is used to declare that certain functions have access to - a class's private variables. - -- ``inline`` is a compiler hint to inline a function. - -- ``mutable`` specifies that a member can be updated, even when a - member of a ``const`` object. - -- ``namespace`` declares a new namespace. - -- ``new`` dynamically allocates space for a value. Note that dynamic - memory allocation is not available by default on the Maple, so - you'll have to bring your own ``new`` and ``delete`` if you want - this. - -- ``operator`` is used to define type-specific operator overrides. - -- ``private`` declares a private class member. - -- ``protected`` declares a protected class member. - -- ``public`` declares a public class member. - -- ``register`` is a compiler hint to store a variable in a register. - -- ``reinterpret_cast`` is used in typecasting. - -- ``signed`` is the opposite of ``unsigned``. - -- ``static_cast`` is used in typecasting. - -- ``struct`` declares a new struct. - -- ``template`` introduces a template class, function, etc. - -- ``this`` is a pointer to the receiver object. - -- ``throw`` is used in exception handling. Note that the default - flags we pass to :ref:`GCC ` include ``-fno-exceptions``. - -- ``try`` is used in exception handling. Note that the default - flags we pass to :ref:`GCC ` include ``-fno-exceptions``. - -- ``typedef`` defines a type synonym. - -- ``union`` defines an untagged union. - -- ``using`` is a directive related to namespaces. - -- ``virtual`` declares a method which may be overridden. - -- ``wchar_t`` is the wide character type. diff --git a/docs/source/lang/long.rst b/docs/source/lang/long.rst deleted file mode 100644 index d8498c0..0000000 --- a/docs/source/lang/long.rst +++ /dev/null @@ -1,52 +0,0 @@ -.. highlight:: cpp - -.. _lang-long: - -``long`` -======== - -The ``long`` data type stores extended size integer values. You can -use a ``long`` when your values are too large to fit into an :ref:`int -`. A ``long`` occupies 8 bytes of memory. This yields a -range of approximately -9.2×10^18 to 9.2×10^18 (that's 9.2 billion -billion, or about 92 million times the number of stars in the Milky -Way galaxy). The exact range of a ``long`` on the Maple is from --9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, or -2^63 to -(2^63-1). A ``long`` it is subject to the same :ref:`overflow issues -` as any numeric data type. - -Here's an example of declaring a long (see :ref:`integer constants -` for an explanation of the "L" at the end of the -number):: - - // Speed of light in nanometers per second (approximate). - long c = 299792458000000000L; - -The general syntax for declaring an ``long`` variable named ``var``, -then giving it value ``val``, looks like:: - - long var = val; - -This is identical to the ``int`` syntax, with ``long`` replacing -``int``. - -Note that ``long`` values will still :ref:`overflow -`, just like ``int`` values, but their much -larger range makes this less likely to happen. - -The downside to using a ``long`` instead of an ``int`` (besides the -extra storage) is that :ref:`arithmetic ` operations -on ``long``\ s will take slightly longer than on ``int``\ s. - -See Also --------- - -- :ref:`char ` -- :ref:`unsigned char ` -- :ref:`int ` -- :ref:`unsigned int ` -- :ref:`unsigned long ` -- :ref:`Integer Constants ` -- :ref:`Variables ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/longcast.rst b/docs/source/lang/longcast.rst deleted file mode 100644 index 2b92345..0000000 --- a/docs/source/lang/longcast.rst +++ /dev/null @@ -1,27 +0,0 @@ -.. highlight:: cpp - -.. _lang-longcast: - -``long()`` (cast) -================= - -Converts a value to the :ref:`long ` data type. Here is -an example:: - - double d = 2.5; - long i = long(d); // i holds "2L", an long value - -The value inside of the parentheses (``long(...)``) can be of any type. -However, if it is not a numeric type (like ``double``, ``char``, -etc.), you will get strange results. - -See the :ref:`long ` reference for details about the -precision and limitations of ``long`` variables on the Maple. - -See Also --------- - -- :ref:`long ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/loop.rst b/docs/source/lang/loop.rst deleted file mode 100644 index d8f6183..0000000 --- a/docs/source/lang/loop.rst +++ /dev/null @@ -1,45 +0,0 @@ -.. highlight:: cpp - -.. _lang-loop: - -loop() -====== - -After creating a :ref:`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() ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/lowbyte.rst b/docs/source/lang/lowbyte.rst deleted file mode 100644 index 58e622f..0000000 --- a/docs/source/lang/lowbyte.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. _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:: cc-attribution.txt diff --git a/docs/source/lang/map.rst b/docs/source/lang/map.rst deleted file mode 100644 index 79122b3..0000000 --- a/docs/source/lang/map.rst +++ /dev/null @@ -1,68 +0,0 @@ -.. 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() ` 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 `), 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() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/max.rst b/docs/source/lang/max.rst deleted file mode 100644 index d38eebe..0000000 --- a/docs/source/lang/max.rst +++ /dev/null @@ -1,65 +0,0 @@ -.. 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() - ` 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 version of ``max()`` is compatible with Arduino. - -See Also --------- - -- :ref:`min() ` -- :ref:`constrain() ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/micros.rst b/docs/source/lang/micros.rst deleted file mode 100644 index f12976b..0000000 --- a/docs/source/lang/micros.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. 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() ` -- :ref:`delay() ` -- :ref:`delayMicroseconds() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/millis.rst b/docs/source/lang/millis.rst deleted file mode 100644 index 54e4507..0000000 --- a/docs/source/lang/millis.rst +++ /dev/null @@ -1,52 +0,0 @@ -.. 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 - Serial.println(time); - - // wait a second so as not to send massive amounts of data - delay(1000); - } - -Tip ---- - -Since the return value for ``millis()`` is an :ref:`unsigned long -`, overflow errors may occur if you try to do math -with other data types, such as :ref:`ints `. - -See Also --------- - -- :ref:`micros ` -- :ref:`delay ` -- :ref:`delayMicroseconds ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/min.rst b/docs/source/lang/min.rst deleted file mode 100644 index 1245f6f..0000000 --- a/docs/source/lang/min.rst +++ /dev/null @@ -1,66 +0,0 @@ -.. 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() ` -- :ref:`constrain() ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/modulo.rst b/docs/source/lang/modulo.rst deleted file mode 100644 index 289fba0..0000000 --- a/docs/source/lang/modulo.rst +++ /dev/null @@ -1,70 +0,0 @@ -.. highlight:: cpp - -.. _lang-modulo: - -Modulo Operator (``%``) -======================= - -Calculates the `remainder `_ -when one integer is divided by another. It is useful for keeping a -variable within a particular range (e.g. the size of an array). - -Syntax ------- - -:: - - dividend % divisor - -Parameters ----------- - -**dividend**: the number to be divided - -**divisor**: the number to divide by - -Returns -------- - -The remainder of **dividend**\ /\ **divisor**\ . - -Examples --------- - -:: - - int x; - x = 7 % 5; // x now contains 2 - x = 9 % 5; // x now contains 4 - x = 5 % 5; // x now contains 0 - x = 4 % 5; // x now contains 4 - -:: - - /* update one value in an array each time through a loop */ - - int values[10]; - int i = 0; - - void setup() { - // no setup necessary - } - - void loop() { - values[i] = analogRead(0); - i = (i + 1) % 10; // modulo operator makes sure i stays between 0 and 9 - } - -Tip ---- - -The modulo operator does not work on floats. For that, you can use -the C standard library function `fmod() -`_. - -See Also --------- - -- :ref:`Arithmetic ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/numeric-types.rst b/docs/source/lang/numeric-types.rst deleted file mode 100644 index 9d2be48..0000000 --- a/docs/source/lang/numeric-types.rst +++ /dev/null @@ -1,79 +0,0 @@ -.. _lang-numeric-types: - -Numeric types -============= - -This document serves as a reference for all of the built-in numeric -types which are available when programming in the IDE. Programmers -using the :ref:`command-line tools ` will have access -to these types as long as they have imported ``wirish.h``; several are -defined in in `libmaple_types.h -`_. - -.. _lang-numeric-types-integral: - -Integral types --------------- - -.. cpp:type:: char - - 8-bit integer value. - -.. cpp:type:: short - - 16-bit integer value. - -.. cpp:type:: int - - 32-bit integer value. - -.. cpp:type:: long - - 64-bit integer value. - -.. cpp:type:: long long - - 64-bit integer value. - -.. cpp:type:: int8 - - Synonym for ``char``. - -.. cpp:type:: uint8 - - Synonym for ``unsigned char``. - -.. cpp:type:: int16 - - Synonym for ``short``. - -.. cpp:type:: uint16 - - Synonym for ``unsigned short``. - -.. cpp:type:: int32 - - Synonym for ``int``. - -.. cpp:type:: uint32 - - Synonym for ``unsigned int`` - -.. cpp:type:: int64 - - Synonym for ``long long`` - -.. cpp:type:: uint64 - - Synonym for ``unsigned long long``. - -Floating-Point Types --------------------- - -.. cpp:type:: float - - 32-bit, IEEE 754 single-precision floating-point type. - -.. cpp:type:: double - - 64-bit, IEEE 754 double-precision floating-point type. diff --git a/docs/source/lang/pinmode.rst b/docs/source/lang/pinmode.rst deleted file mode 100644 index b9095da..0000000 --- a/docs/source/lang/pinmode.rst +++ /dev/null @@ -1,77 +0,0 @@ -.. highlight:: cpp - -.. _lang-pinmode: - -pinMode() -========= - -.. contents:: Contents - :local: - -Library Documentation ---------------------- - -.. doxygenfunction:: pinMode - -.. 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 -------- - -:: - - int ledPin = 13; // LED connected to digital pin 13 - - void setup() { - pinMode(ledPin, OUTPUT); // sets the digital pin as output - } - - void loop() { - digitalWrite(ledPin, HIGH); // sets the LED on - delay(1000); // waits for a second - digitalWrite(ledPin, LOW); // sets the LED off - delay(1000); // waits for a second - } - -Arduino Compatibility ---------------------- - -.. TODO check out Arduino vs. Maple static discilpline cutoffs to -.. ensure accuracy of following: - -The libmaple implementation of ``pinMode()`` supports the ``INPUT`` -and ``OUTPUT`` modes with semantics identical to that of the Arduino -function (however, be advised that the Maple, as a 3.3V device, will -only drive 3.3V to an ``OUTPUT`` pin that has been set ``HIGH``). - -``INPUT_ANALOG`` and ``PWM`` modes were added because the Maple does -not distinguish between analog and digital pins the same way the -Arduino does. Unlike the Arduino, you **must call** ``pinMode()`` to -set up a pin for these purposes before a call to, e.g., -:ref:`lang-analogRead`. In practice, this should only add a few lines -to your :ref:`lang-setup` function. - -.. TODO verify following before putting it in: - -.. ``OUTPUT_OPEN_DRAIN``, ``INPUT_PULLUP``, ``INPUT_PULLDOWN``, and -.. ``PWM_OPEN_DRAIN`` modes represent functionality not currently -.. available on Arduino boards. - -See also --------- - -- :ref:`lang-constants` -- :ref:`lang-digitalwrite` -- :ref:`lang-digitalread` -- Maple :ref:`GPIO ` reference page - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/pointer.rst b/docs/source/lang/pointer.rst deleted file mode 100644 index 0a42270..0000000 --- a/docs/source/lang/pointer.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. _lang-pointer: - -Pointer Operators (``&``, ``*``) -================================ - -The pointer operators ``&`` (reference) and ``*`` (dereference) are -different from the bitwise math operator :ref:`& -` and the arithmetic operator :ref:`* -`. - -Pointers are one of the more complicated subjects for beginners in -learning C, and it is possible to write many useful Arduino sketches -without ever encountering pointers. However, for manipulating certain -data structures, the use of pointers can simplify the code, improve -its efficiency, and generally provide many benefits that would be -difficult to achieve without the use of pointers. - -Introducing pointers is somewhat outside the scope of this -documentation. However, a good `pointer tutorial -`_ is available. -Also see the `Wikipedia article on pointers -`_, especially -the section on `pointers in C -`_. - -See Also --------- - -- http://xkcd.com/138/ - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/pow.rst b/docs/source/lang/pow.rst deleted file mode 100644 index 4280400..0000000 --- a/docs/source/lang/pow.rst +++ /dev/null @@ -1,23 +0,0 @@ -.. _lang-pow: - -pow() -===== - -Calculates the value of a number raised to a power. - -Library Documentation ---------------------- - -.. doxygenfunction:: pow - -.. TODO LATER some examples - -See Also --------- - -- :ref:`sqrt() ` -- :ref:`float ` -- :ref:`double ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/pwmwrite.rst b/docs/source/lang/pwmwrite.rst deleted file mode 100644 index 7a1d51f..0000000 --- a/docs/source/lang/pwmwrite.rst +++ /dev/null @@ -1,49 +0,0 @@ -.. highlight:: cpp - -.. _lang-pwmwrite: - -pwmWrite() -========== - -Writes a :ref:`PWM wave ` to a pin. You can use this to make an -LED get brighter or dimmer, control a servomotor, etc. After a call to -pwmWrite(), the pin will output a steady square wave with the given -duty cycle. You can change the duty cycle later by calling pwmWrite() -again with the same pin and a different duty. - -.. contents:: Contents - :local: - -Library Documentation ---------------------- - -.. doxygenfunction:: pwmWrite - -Example -------- - -Sets the output to the LED proportional to the value read from the -potentiometer:: - - int ledPin = 13; // LED connected to pin 13 (Maple) - int analogPin = 3; // potentiometer connected to analog pin 3 - int val = 0; // variable to store the read value - - void setup() { - pinMode(ledPin, OUTPUT); // sets the LED pin as output - - pinMode(analogPin, PWM); // sets the potentiometer pin as PWM - // output - } - - void loop() { - val = analogRead(analogPin); // read the input pin - - analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, - // analogWrite values from 0 to 65535 - } - -See Also --------- - -- :ref:`Maple PWM tutorial ` diff --git a/docs/source/lang/random.rst b/docs/source/lang/random.rst deleted file mode 100644 index f2a9762..0000000 --- a/docs/source/lang/random.rst +++ /dev/null @@ -1,73 +0,0 @@ -.. highlight:: cpp - -.. _lang-random: - -random() -======== - -The ``random()`` function generates pseudo-random numbers. - -.. TODO keep tracking Sphinx/Breathe's ability to reference overloaded -.. functions so we can use doxygenfunction instead of manually -.. documenting this. - -Library Documentation ---------------------- - -.. 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() ` to differ, on subsequent executions of a -sketch, use :ref:`randomSeed() ` to initialize the -random number generator with a fairly random input, such as -:ref:`analogRead() ` on an unconnected pin. - -Conversely, it can occasionally be useful to use 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 -` reading of pin 0. If this pin is unconnected, the Sketch -should print different values to the :ref:`serial monitor -` each time it is run:: - - long randNumber; - - void setup() { - pinMode(0, INPUT_ANALOG); - randomSeed(analogRead(0)); - } - - void loop() { - randNumber = random(300); - SerialUSB.println(randNumber); - - delay(50); - } - -See Also --------- - -- :ref:`randomSeed() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/randomseed.rst b/docs/source/lang/randomseed.rst deleted file mode 100644 index d0a15b7..0000000 --- a/docs/source/lang/randomseed.rst +++ /dev/null @@ -1,60 +0,0 @@ -.. highlight:: cpp - -.. _lang-randomseed: - -randomSeed() -============ - -``randomSeed()`` initializes the `pseudorandom number generator -`_, -causing it to start at an arbitrary point in its random sequence. -This sequence, while very long, and random, is always the same. - - -Library Documentation ---------------------- - -.. doxygenfunction:: randomSeed - -Discussion ----------- - -If it is important for a sequence of values generated by -:ref:`random() ` to differ, on subsequent executions of a -sketch, use ``randomSeed()`` to initialize the random number generator -with a fairly random input, such as :ref:`analogRead() -` on an unconnected pin. - -Conversely, it can occasionally be useful to use 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 -` reading of pin 0. If this pin is unconnected, the Sketch -should print different values to the :ref:`serial monitor -` each time it is run:: - - long randNumber; - - void setup() { - pinMode(0, INPUT_ANALOG); - randomSeed(analogRead(0)); - } - - void loop() { - randNumber = random(300); - SerialUSB.println(randNumber); - - delay(50); - } - -See Also --------- - -- :ref:`random() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/return.rst b/docs/source/lang/return.rst deleted file mode 100644 index 7b5039e..0000000 --- a/docs/source/lang/return.rst +++ /dev/null @@ -1,61 +0,0 @@ -.. highlight:: cpp - -.. _lang-return: - -``return`` -========== - -Terminates a function and return a value from a function to the -calling function, if the function has non-``void`` return type. - -Syntax: -------- - -:: - - // from within a "void" function: - return; - - // from within a non-"void" function: - return value; - -In the second case, ``value`` should have a type which is the same as -the return type of the function, or be convertible to it (like an -``int`` to a ``long``, etc.; see :ref:`this note -` for some references). - -Examples: ---------- - -A function to compare a sensor input to a threshold:: - - // converts analog readings between 0 and 400 to 0, and 400 up to 1. - int checkSensor() { - if (analogRead(0) > 400) { - return 1; - else { - return 0; - } - } - -An early ``return`` is also useful when testing a section of code -without having to "comment out" large sections of possibly buggy code, -like so:: - - void loop() { - - // brilliant code idea to test here - - return; - - // the rest of a dysfunctional sketch here - // this code will never be executed - } - -See Also --------- - -- :ref:`comments ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/scope.rst b/docs/source/lang/scope.rst deleted file mode 100644 index 7b65bab..0000000 --- a/docs/source/lang/scope.rst +++ /dev/null @@ -1,120 +0,0 @@ -.. highlight:: cpp - -.. _lang-scope: - -Scope -===== - -Variables in the C++ programming language, which Maple uses (all of -your sketches are C++ programs in disguise), have a property called -*scope*. Simply put, a variable's scope is made up of all of the -lines where the variable can be used. - -Scope in C++ is a fairly complex topic, so we won't try to describe it -in full here. Instead, we present a simplified view, describing two -different kinds of scopes, *global* and *local*. For more detailed -information, consult a C++ reference. - -Global and Local Variables --------------------------- - -A global variable is one that can be "seen" by every function in a -program. In the :ref:`Maple IDE `, any variable declared outside -of a function (like :ref:`setup() ` and :ref:`loop() -`) is a global variable. - -A local variable can only be "seen" inside of a particular function. -You can declare a variable to be local to a function by declaring it -inside of the :ref:`curly braces ` which enclose -that function. - -When programs start to get larger and more complex, local variables -are a useful way to ensure that a function has exclusive access to its -own variables. This prevents programming errors when one function -mistakenly modifies variables used by another function. - -It is also sometimes useful to declare and initialize a variable -inside a :ref:`for ` loop. This creates a variable that -can only be accessed from inside the loop body. - -Example -------- - -Here is an example sketch (which you can copy into the Maple IDE and -run on your Maple) that illustrates the use of global and local -variables, as well as declaring variables inside of a ``for`` loop. -Be sure to open a :ref:`serial monitor ` after you -:ref:`verify ` and :ref:`upload ` the sketch:: - - int globalVar; // any function will see this variable - - void setup() { - // since "globalVar" is declared outside of any function, - // every function can "see" and use it: - globalVar = 50; - - // the variables "i" and "d" declared inside the "loop" function - // can't be seen here. see what happens when you uncomment the - // following lines, and try to Verify (compile) the sketch: - // - // i = 16; - // SerialUSB.print("i = "); - // SerialUSB.println(i); - // d = 26.5; - // SerialUSB.print("d = "); - // SerialUSB.println(d); - } - - void loop() { - // since "i" and "d" are declared inside of the "loop" function, - // they can only be seen and used from inside of it: - int i; - double d; - - for (int j = 0; j < 5; j++) { - // variable i can be used anywhere inside the "loop" function; - // variable j can only be accessed inside the for-loop brackets: - i = j * j; - SerialUSB.print("i = "); - SerialUSB.println(i); - } - - // globalVar can be accessed from anywhere. note how even - // though we set globalVar = 50 in the "setup" function, we can - // see that value here: - SerialUSB.print("globalVar = "); - SerialUSB.println(globalVar); - - // d can be accessed from anywhere inside the "loop" function: - d = 26.5; - SerialUSB.print("d = "); - SerialUSB.print(d); - SerialUSB.println(" (before separateFunction())"); - - separateFunction(); - - // notice how even though separateFunction() has a variable - // named "d", it didn't touch our (local) variable which has - // the same name: - SerialUSB.print("d = "); - SerialUSB.print(d); - SerialUSB.println(" (after separateFunction())"); - } - - void separateFunction() { - // variable "d" here has the same name as variable "d" inside of - // the "loop" function, but since they're both _local_ - // variables, they don't affect each other: - double d = 30.5; - SerialUSB.print("d = "); - SerialUSB.print(d); - SerialUSB.println(" (inside of separateFunction())"); - } - -See Also --------- - -- `C++ programming Wikibook `_. -- Wikipedia article on `scope `_ - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/semicolon.rst b/docs/source/lang/semicolon.rst deleted file mode 100644 index 8164616..0000000 --- a/docs/source/lang/semicolon.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. highlight:: cpp - -.. _lang-semicolon: - -Semicolon (``;``) -================= - -Used to end a line of code. Example:: - - int a = 13; - -Tip ---- - -Forgetting to end a line in a semicolon will result in a compiler -error. The error text may be obvious, and refer to a missing -semicolon, or it may not. If an impenetrable or seemingly illogical -compiler error comes up, one of the first things to check is a -missing semicolon, in the immediate vicinity, preceding the line at -which the compiler complained. - - - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/serial.rst b/docs/source/lang/serial.rst deleted file mode 100644 index ca89b31..0000000 --- a/docs/source/lang/serial.rst +++ /dev/null @@ -1,226 +0,0 @@ -.. _lang-serial: - -Serial Ports (``Serial1``, ``Serial2``, ``Serial3``) -==================================================== - -Used for communication between the Maple board and a computer or other -devices. - -.. contents:: Contents - :local: - -Introduction ------------- - -The Maple has three serial ports (also known as a UARTs or USARTs): -``Serial1``, ``Serial2``, and ``Serial3``. They communicate using the -pins summarized in the following table: - -.. list-table:: - :header-rows: 1 - - * - Serial port - - TX, RX, CK - - CTS, RTS (if present) - - * - ``Serial1`` - - 7, 8, 6 - - - - * - ``Serial2`` - - 1, 0, 10 - - 2, 3 - - * - ``Serial3`` - - 29, 30, 31 - - 32, 33 - -Thus, if you use a particular serial port, you cannot also use its -communication pins for other purposes at the same time. - -If you want to communicate with the Maple using the provided USB port, -use :ref:`SerialUSB ` instead. - -To use them to communicate with an external TTL serial device, connect -the TX pin to your device's RX pin, the RX to your device's TX pin, -and the ground of your Maple to your device's ground. - -.. warning:: Don't connect these pins directly to an RS232 serial - port; they operate at +/- 12V and can damage your board. - - -Library Documentation ---------------------- - -All of the ``Serial[1,2,3]`` objects are instances of the -``HardwareSerial`` class, which is documented in this section. (This -means that you can use any of these functions on any of ``Serial1``, -``Serial2``, and ``Serial3``). - -.. cpp:class:: HardwareSerial - - Serial port class. Predefined instances are ``Serial1``, - ``Serial2``, and ``Serial3``. - -.. cpp:function:: HardwareSerial::begin(unsigned int baud) - - Set up a ``HardwareSerial`` object for communications. This method - must be called before attempting to use the ``HardwareSerial`` - object (typically, you call this in your :ref:`setup() - ` function). - -.. cpp:function:: HardwareSerial::end() - - Disables the USART associated with this object, allowing any - associated 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 - `), the call will block until one - becomes available. - -.. cpp:function:: HardwareSerial::flush() - - Removes the contents of the Serial's associated USART RX FIFO. - That is, clears any buffered characters, so that the next character - read is guaranteed to be new. - -.. cpp:function:: HardwareSerial::print(unsigned char b) - - Print the given byte over the USART. - -.. cpp:function:: HardwareSerial::print(char c) - - Print the given character over the USART. 7-bit clean characters - are typically interpreted as ASCII text. - -.. cpp:function:: HardwareSerial::print(const char *str) - - Print the given null-terminated string over the USART. - -.. cpp:function:: HardwareSerial::print(int n) - - Print the argument's digits over the USART, in decimal format. - Negative values will be prefixed with a ``'-'`` character. - -.. cpp:function:: HardwareSerial::print(unsigned int n) - - Print the argument's digits over the USART, in decimal format. - -.. cpp:function:: HardwareSerial::print(long n) - - Print the argument's digits over the USART, in decimal format. - Negative values will be prefixed with a ``'-'`` character. - -.. cpp:function:: HardwareSerial::print(unsigned long n) - - Print the argument's digits over the USART, in decimal format. - -.. cpp:function:: HardwareSerial::print(long n, int base) - - Print the digits of ``n`` over the USART, in base ``base`` (which - may be between 2 and 16). The ``base`` value 2 corresponds to - binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. Negative - values will be prefixed with a ``'-'`` character. - -.. cpp:function:: HardwareSerial::print(double n) - - Print ``n``, accurate to 2 digits after the decimal point. - -.. _lang-serial-println: - -.. cpp:function:: HardwareSerial::println(char c) - - Like ``print(c)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(const char *c) - - Like ``print(c)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(unsigned char b) - - Like ``print(b)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(int n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(unsigned int n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(long n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(unsigned long n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(long n, int base) - - Like ``print(n, b)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println(double n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: HardwareSerial::println() - - Prints ``"\r\n"`` over the USART. - -.. cpp:function:: HardwareSerial::write(unsigned char ch) - - Sends one character over the USART. This function is currently - blocking, although nonblocking writes are a planned future - extension. - - This is a low-level function. One of the ``print()`` or - ``println()`` functions is likely to be more useful when printing - multiple characters, when formatting numbers for printing, etc. - -.. cpp:function:: HardwareSerial::write(const char* str) - - Send the given null-terminated character string over the USART. - - This is a low-level function. One of the ``print()`` or - ``println()`` functions is likely to be more useful when printing - multiple characters, when formatting numbers for printing, etc. - -.. cpp:function:: HardwareSerial::write(void *buf, unsigned int size) - - 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. - -Arduino Compatibility Note --------------------------- - -Unlike the Arduino, none of the Maple's serial ports is connected to -the USB port on the Maple board (for that, use :ref:`SerialUSB -`). Thus, to use these pins to communicate with your -personal computer, you will need an additional USB-to-serial adaptor. - -.. TODO LATER port these examples over - -.. Examples -.. -------- - -.. - `ASCII Table `_ -.. - `Dimmer `_ -.. - `Graph `_ -.. - `Physical Pixel `_ -.. - `Virtual Color Mixer `_ -.. - `Serial Call Response `_ -.. - `Serial Call Response ASCII `_ - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/serialusb.rst b/docs/source/lang/serialusb.rst deleted file mode 100644 index af3a7e0..0000000 --- a/docs/source/lang/serialusb.rst +++ /dev/null @@ -1,242 +0,0 @@ -.. 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 `, the Maple's -STM32 microprocessor includes a dedicated USB peripheral. This -peripheral is used to emulate a regular serial port for use as a -terminal (text read/write). The emulated terminal is relatively slow -and inefficient; it is best for transferring data at regular serial -speeds (kilobaud). - -Library access to the emulated serial port is provided through the -``SerialUSB`` object. You can mostly use ``SerialUSB`` as a drop-in -replacement for ``Serial1``, ``Serial2``, and ``Serial3``. - -.. warning:: The ``SerialUSB`` functionality includes a 50 millisecond - timeout for writes, and does not try to detect if the USB host is - "really" connected, or just enumerated and initialized. - - This means that if you have a number of calls to one of the - ``SerialUSB`` ``write()`` or ``print()`` functions in your code, - and you are not monitoring the emulated on a computer, your program - will run much, much slower than if it is being monitored or totally - disconnected (run off of a battery). - - You can avoid this behavior by :ref:`deciphering the port status - using the DTR and RTS line status `; the - behavior of these control lines is platform dependent and we no - longer interpret them by default. - -Library Documentation ---------------------- - -The ``SerialUSB`` object is an instance of the ``USBSerial`` class, -which is documented in this section. This means that you can use any -of these functions by writing -``SerialUSB.functionName(arguments...)``. For example, to print the -message "hello, world!", you can write ``USBSerial.println("hello, -world!")``. - -.. cpp:class:: USBSerial - - Emulated serial-over-USB class. ``SerialUSB`` is the predefined - instance. - -.. cpp:function:: USBSerial::begin() - - Set up the USB peripheral for emulated serial communication. The - peripheral is configured this way by default; calling this function - should only be necessary if you have disabled the peripheral using - ``SerialUSB.end()``. - -.. _lang-serialusb-end: - -.. cpp:function:: USBSerial::end() - - Disables the USB peripheral. - -.. cpp:function:: unsigned int USBSerial::available() - - Returns the number of bytes available for reading. - -.. _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 - `), the call will block until one - becomes available. - -.. cpp:function:: USBSerial::flush() - - Removes the contents of the Serial's associated input buffer. That - is, clears any buffered characters, so that the next character read - is guaranteed to be new. - -.. cpp:function:: USBSerial::print(unsigned char b) - - Print the given byte over the USB connection. - -.. cpp:function:: USBSerial::print(char c) - - Print the given character over the USB connection. 7-bit clean characters - are typically interpreted as ASCII text. - -.. cpp:function:: USBSerial::print(const char *str) - - Print the given null-terminated string over the USB connection. - -.. cpp:function:: USBSerial::print(int n) - - Print the argument's digits over the USB connection, in decimal format. - Negative values will be prefixed with a ``'-'`` character. - -.. cpp:function:: USBSerial::print(unsigned int n) - - Print the argument's digits over the USB connection, in decimal format. - -.. cpp:function:: USBSerial::print(long n) - - Print the argument's digits over the USB connection, in decimal - format. Negative values will be prefixed with a ``'-'`` character. - -.. cpp:function:: USBSerial::print(unsigned long n) - - Print the argument's digits over the USB connection, in decimal - format. - -.. cpp:function:: USBSerial::print(long n, int base) - - Print the digits of ``n`` over the USB connection, in base ``base`` - (which may be between 2 and 16). The ``base`` value 2 corresponds - to binary, 8 to octal, 10 to decimal, and 16 to hexadecimal. - Negative values will be prefixed with a ``'-'`` character. - -.. cpp:function:: USBSerial::print(double n) - - Print ``n``, accurate to 2 digits after the decimal point. - -.. _lang-serialusb-println: - -.. cpp:function:: USBSerial::println(char c) - - Like ``print(c)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(const char *c) - - Like ``print(c)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(unsigned char b) - - Like ``print(b)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(int n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(unsigned int n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(long n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(unsigned long n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(long n, int base) - - Like ``print(n, b)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println(double n) - - Like ``print(n)``, followed by ``"\r\n"``. - -.. cpp:function:: USBSerial::println() - - Prints ``"\r\n"`` over the USB connection. - -.. cpp:function:: USBSerial::write(unsigned char ch) - - Sends one character over the USB connection. This function is - currently blocking, although nonblocking writes are a planned - future extension. - - This is a low-level function. One of the ``print()`` or - ``println()`` functions is likely to be more useful when printing - multiple characters, when formatting numbers for printing, etc. - -.. cpp:function:: USBSerial::write(const char* str) - - Send the given null-terminated character string over the USB - connection. - - This is a low-level function. One of the ``print()`` or - ``println()`` functions is likely to be more useful when printing - multiple characters, when formatting numbers for printing, etc. - -.. cpp:function:: USBSerial::write(void *buf, unsigned int size) - - Writes the first ``size`` bytes of ``buf`` over the USB connection. - Each byte is transmitted as an individual character. - - This is a low-level function. One of the ``print()`` or - ``println()`` functions is likely to be more useful when printing - multiple characters, when formatting numbers for printing, etc. - -Examples --------- - -.. _lang-serialusb-safe-print: - -**Safe print**: This function should run smoothly and not block; the -LED should blink at roughly the same speed whether being monitored, -running from battery, or connected but not monitored. You may need to -experiment with the DTR/RTS logic for your platform and device -configuration. :: - - #define LED_PIN 13 - - void setup() { - /* Set up the LED to blink */ - pinMode(LED_PIN, OUTPUT); - } - - void loop() { - // LED will stay off if we are disconnected; - // will blink quickly if USB is unplugged (battery etc) - if(SerialUSB.isConnected()) { - digitalWrite(LED_PIN, 1); - } - delay(100); - - // If this logic fails to detect if bytes are going to - // be read by the USB host, then the println() will fully - // many times, causing a very slow LED blink. - // If the characters are printed and read, the blink will - // only slow a small amount when "really" connected, and fast - // when the virtual port is only configured. - if(SerialUSB.isConnected() && (SerialUSB.getDTR() || SerialUSB.getRTS())) { - for(int i=0; i<10; i++) { - SerialUSB.println(123456,BIN); - } - } - digitalWrite(LED_PIN, 0); - delay(100); - } - diff --git a/docs/source/lang/setup.rst b/docs/source/lang/setup.rst deleted file mode 100644 index 837ddd6..0000000 --- a/docs/source/lang/setup.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. highlight:: cpp - -.. _lang-setup: - -setup() -======= - -The ``setup()`` function is called when a sketch starts. Use it to -initialize :ref:`variables `, :ref:`pin modes -`, start using :ref:`libraries `, etc. The -``setup()`` function will only run once, after each power-up or reset -of the Maple board. - -Example -------- - -:: - - int buttonPin = 38; - - void setup() { - pinMode(buttonPin, INPUT); - } - - void loop() { - // ... - } - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/sin.rst b/docs/source/lang/sin.rst deleted file mode 100644 index 398b8f3..0000000 --- a/docs/source/lang/sin.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. _lang-sin: - -sin() -===== - -Calculates the `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 -`_\ , while Arduino's is that of -`avr-libc `_\ . - -See Also --------- - -- :ref:`cos ` -- :ref:`tan ` -- :ref:`float ` -- :ref:`double ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/sizeof.rst b/docs/source/lang/sizeof.rst deleted file mode 100644 index eae509c..0000000 --- a/docs/source/lang/sizeof.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. highlight:: cpp - -.. _lang-sizeof: - -``sizeof()`` -============ - -The ``sizeof`` operator on the Maple returns the number of bytes -needed to store a value of a given type\ [#fcharsize]_. This can be -an ordinary numeric type, like ``int``. It can be something more -complicated, like a ``struct`` or ``union``. If the argument to -``sizeof`` is an array, it returns the total number of bytes occupied -by the array. - -The general syntax looks like this:: - - sizeof(type) - sizeof(var) - -Example -------- - -The ``sizeof`` operator is useful for dealing with arrays (such as -strings) where it is convenient to be able to change the size of the -array without breaking other parts of the program. - -This program prints out a text string one character at a time. Try -changing the text phrase:: - - char myStr[] = "this is a test"; - int i; - - void setup() { - Serial.begin(9600); - } - - void loop() { - for (i = 0; i < sizeof(myStr) - 1; i++) { - Serial.print(i, DEC); - Serial.print(" = "); - Serial.println(myStr[i], BYTE); - } - } - - -Note that ``sizeof`` returns the total number of bytes. So for larger -variable types such as ``int``, the :ref:`for loop ` -would look something like this:: - - for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { - // do something with myInts[i] - } - -.. rubric:: Footnotes - -.. [#fcharsize] Technically (and pedantically) speaking, ``sizeof`` - returns a multiple of the number of bits a ``char`` occupies in - memory. However, on the Maple (this goes for most C++ - implementations), a ``char`` occupies 8 bits = 1 byte. All the C++ - standard guarantees, however, is that a ``char`` occupies at - *least* 8 bits. - -.. include:: cc-attribution.txt - diff --git a/docs/source/lang/sq.rst b/docs/source/lang/sq.rst deleted file mode 100644 index bd32648..0000000 --- a/docs/source/lang/sq.rst +++ /dev/null @@ -1,46 +0,0 @@ -.. 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:: cc-attribution.txt diff --git a/docs/source/lang/sqrt.rst b/docs/source/lang/sqrt.rst deleted file mode 100644 index 956a754..0000000 --- a/docs/source/lang/sqrt.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. _lang-sqrt: - -sqrt() -====== - -Calculates the square root of a number. - -Library Documentation ---------------------- - -.. doxygenfunction:: sqrt - -Arduino Compatibility ---------------------- - -The Maple versino of ``sqrt()`` is compatible with Arduino. - -See Also --------- - -- :ref:`pow ` -- :ref:`sq ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/static.rst b/docs/source/lang/static.rst deleted file mode 100644 index 5d1802e..0000000 --- a/docs/source/lang/static.rst +++ /dev/null @@ -1,57 +0,0 @@ -.. highlight:: cpp - -.. _lang-static: - -``static`` -========== - -The ``static`` keyword can be used to create variables that are -visible to only one function. However, unlike local variables that get -created and destroyed every time a function is called, ``static`` -variables persist beyond the function call, preserving their data -between function calls. - -Variables declared as ``static`` will only be created and initialized -the first time a function is called. - -.. note:: This is only one use of the ``static`` keyword in C++. It - has some other important uses that are not documented here; consult - a reliable C++ reference for details. - -Example -------- - -One use case for ``static`` variables is implementing counters that -last longer than the functions which need them, but shouldn't be -shared to other functions. Here's an example:: - - void setup() { - SerialUSB.begin(); - } - - void loop() { - int reading; - if (timeToReadSensors()) { - reading = readSensors(); - } - // do something with reading - } - - int readSensors() { - static int numSensorReadings = 0; - numSensorReadings++; - if (numSensorReadings % 100 == 0) { - SerialUSB.print("just got to another 100 sensor readings"); - } - return analogRead(...); - } - -In this example, the static variable ``numSensorReadings`` is -initialized to zero the first time ``readSensors()`` is called, and -then incremented, so it starts out at one. Subsequent calls to -``readSensors()`` won't reset ``numSensorReadings`` to zero, because -it was declared ``static``. Thus, ``numSensorReadings`` is a count of -the number of times that ``readSensors()`` has been called. - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/string.rst b/docs/source/lang/string.rst deleted file mode 100644 index 0a270da..0000000 --- a/docs/source/lang/string.rst +++ /dev/null @@ -1,128 +0,0 @@ -.. highlight:: cpp - -.. _lang-string: - -Strings -======= - -Text strings can be represented in two ways. You can - -1. Use the :ref:`String ` data type, which is -part of the core as of version 0.0.9, or - -2. You can make a string out of an array of type :ref:`char -` and null-terminate it. - -This page describes the second method. - -Examples --------- - -All of the following are valid declarations for strings:: - - char str1[15]; - char str2[6] = {'m', 'a', 'p', 'l', 'e'}; - char str3[6] = {'m', 'a', 'p', 'l', 'e', '\0'}; - char str4[ ] = "maple"; - char str5[6] = "maple"; - char str6[15] = "maple"; - -As you can see, there are several methods available for declaring and -initializing strings: - -- Declare an array of ``char`` without initializing it, as with ``str1``. - -- Declare an array of ``char`` (with one extra ``char``) and the - compiler will add the required null character, as with ``str2``. - -- Explicitly add the null character (``'\0'``), as with ``str3``. - -- Initialize with a string constant in quotation marks (``"..."``); - the compiler will size the array to fit the string constant and a - terminating null character (``str4``). - -- Initialize the array with an explicit size and string constant, - (``str5``). - -- Initialize the array, leaving extra space for a larger string - (``str6``). - -Null Termination ----------------- - -Generally, strings are terminated with a null character (`ASCII -`_ code 0). This allows functions -(like ``SerialUSB.print()``) to tell where the end of a string is. -Otherwise, they would continue reading subsequent bytes of memory that -aren't actually part of the string. - -This means that your string needs to have space for one more character -than the text you want it to contain. That is why ``str2`` and -``str5`` need to be six characters, even though "maple" is only five --- the last position is automatically filled with a NULL -character. ``str4`` will be automatically sized to six characters, one -for the extra null. In the case of ``str3``, we've explicitly included -the null character (written ``'\0'``) ourselves. - -Note that it's possible to have a string without a final null -character (e.g. if you had specified the length of ``str2`` as five -instead of six). This will break most functions that use strings, so -you shouldn't do it intentionally. If you notice something behaving -strangely (operating on characters not in the string), however, this -could be the problem. - -Single quotes or double quotes? -------------------------------- - -Strings are always defined inside double quotes (``"Abc"``) and -characters are always defined inside single quotes (``'A'``). - -Wrapping long strings ---------------------- - -You can wrap long strings like this:: - - char myString[] = "This is the first line" - " this is the second line" - " etcetera"; - -Arrays of Strings ------------------ - -It is often convenient, when working with large amounts of text, -such as a project with an LCD display, to setup an array of -strings. Because strings themselves are arrays, this is in actually -an example of a two-dimensional array. - -In the code below, the asterisk after the datatype char ``char *`` -indicates that this is an array of "pointers". All array names are -actually pointers, so this is required to make an array of arrays. -Pointers are one of the more esoteric parts of C for beginners to -understand, but it isn't necessary to understand pointers in detail to -use them effectively here:: - - char* myStrings[] = {"This is string 1", "This is string 2", - "This is string 3", "This is string 4", - "This is string 5", "This is string 6"}; - - void setup() { - SerialUSB.begin(); - } - - void loop() { - for (int i = 0; i < 6; i++) { - SerialUSB.println(myStrings[i]); - delay(500); - } - } - - -See Also --------- - -- :ref:`array ` -- :ref:`__attribute__ ` -- :ref:`Variables ` - - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/switchcase.rst b/docs/source/lang/switchcase.rst deleted file mode 100644 index b484bc5..0000000 --- a/docs/source/lang/switchcase.rst +++ /dev/null @@ -1,118 +0,0 @@ -.. highlight:: cpp - -.. _lang-switchcase: - -``switch``\ /\ ``case`` -======================= - -Like :ref:`if ` statements, A ``switch`` statement controls -program flow by allowing you to specify different code that should be -executed under various cases. - -The general syntax looks like this:: - - switch (var) { - case val1: - // statements - break; - case val2: - // statements - break; - ... - default: - // statements - } - -Where ``var`` is a variable whose value to investigate, and the -``val1``, ``val2`` after each ``case`` are constant values that -``var`` might be. - -Description ------------ - -A ``switch`` statement compares the value of a variable to the values -specified in ``case`` statements. When a ``case`` statement is found -whose value matches that of the variable, the code in that case -statement is run. - -Here's a more concrete example:: - - switch (var) { - case 1: - doThing1(); - break; - case 2: - doThing2(); - break; - } - afterTheSwitch(); - -In the above example, if ``var == 1``, then the code beginning on the -line after ``case 1`` gets executed. That is, if ``var`` is one, -``doThing1()`` gets called first, and then the ``break`` statement is -executed. - -The ``break`` keyword exits the ``switch`` statement, and is typically -used at the end of each ``case``. Since there is a ``break`` at the -end of ``case 1``, the ``switch`` statement exits, and the next line -to be run is the one which calls ``afterTheSwitch()``. - -Without a ``break``, the ``switch`` statement will continue executing -the following ``case`` expressions ("falling-through") until a -``break`` (or the end of the switch statement) is reached. Let's -pretend the ``switch`` looked like this instead:: - - switch (var) { - case 1: - doThing1(); - // no break statement anymore - case 2: - doThing2(); - break; - } - afterTheSwitch(); - -Now, if ``var`` is one, ``doThing1()`` gets executed like before. -However, without a ``break``, the code would continue to be executed -line-by-line, so ``doThing2()`` would be called next. At this point, -a ``break`` has been reached, so the program continues by calling -``afterTheSwitch()``. This is usually not what you want, which is why -each ``case`` usually has a ``break`` at the end. - -.. _lang-switchcase-default: - -Writing "``default:``" instead of a ``case`` statement allows you to -specify what to do if none of the ``case`` statements matches. Having -a ``default`` is optional (you can leave it out), but if you have one, -it must appear after all of the ``case`` statements. Let's add a -``default`` to the ``switch`` we've been discussing:: - - switch (var) { - case 1: - doThing1(); - break; - case 2: - doThing2(); - break; - default: - doSomethingElse(); - } - afterTheSwitch(); - -If ``var`` is one, then ``doThing1()`` gets called. If ``var`` is -two, ``doThing2()`` gets called. If ``var`` is anything else, -``doSomethingElse()`` gets called. As stated above, a ``default`` is -optional. If you're missing one and none of the ``case`` statements -match, the ``switch`` does nothing at all, as if it weren't there. - -``switch`` statements are often used with an :ref:`enum ` -value as the variable to compare. In this case, you can write down -all of the values the ``enum`` takes as ``case`` statements, and be -sure you've covered all the possibilities. - -See also: ---------- - -- :ref:`if/else ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/tan.rst b/docs/source/lang/tan.rst deleted file mode 100644 index 4bbe0db..0000000 --- a/docs/source/lang/tan.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. _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 -`_\ , while Arduino's is that of -`avr-libc `_\ . - -See Also --------- - - -- :ref:`sin ` -- :ref:`cos ` -- :ref:`float ` -- :ref:`double ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/unsignedchar.rst b/docs/source/lang/unsignedchar.rst deleted file mode 100644 index 5b946ed..0000000 --- a/docs/source/lang/unsignedchar.rst +++ /dev/null @@ -1,33 +0,0 @@ -.. highlight:: cpp - -.. _lang-unsignedchar: - -``unsigned char`` -================= - -An unsigned version of the :ref:`char ` data type. An -``unsigned char`` occupies 1 byte of memory; it stores an integer from -0 to 255. - -Like an :ref:`unsigned int `, an ``unsigned char`` -won't store negative numbers; it is also subject to the same -:ref:`overflow issues ` as any integral data type. - -Example -------- - -:: - - unsigned char c = 240; - -See Also --------- - - -- :ref:`byte ` -- :ref:`int ` -- :ref:`array ` -- :ref:`SerialUSB.println() ` -- :ref:`Serial.println() ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/unsignedint.rst b/docs/source/lang/unsignedint.rst deleted file mode 100644 index f6311da..0000000 --- a/docs/source/lang/unsignedint.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. highlight:: cpp - -.. _lang-unsignedint: - -``unsigned int`` -================ - -An ``unsigned int`` (unsigned integer) is the same as an :ref:`int -` in that it stores a 4 byte integer value. However, -Instead of storing both negative and positive numbers, an ``unsigned -int`` can only store nonnegative values, yielding a range of 0 to -4,294,967,295 (the positive value is 2^32 - 1). - -The difference between an ``unsigned int`` and a (signed) ``int`` lies -in the way the highest bit, sometimes referred to as the "sign" bit, -is interpreted. In the case of the Maple ``int`` type (which is -signed), if the high bit is a "1", the number is interpreted as a -negative number, using a technique known as `two's complement math -`_. The -bits in an an ``unsigned int`` are interpreted according to the usual -rules for converting `binary to decimal -`_. - -An ``unsigned int`` is subject to the same :ref:`overflow issues -` as a regular ``int``; the only difference is -that an ``unsigned int`` will "underflow" at 0, and "overflow" at -4,294,967,295. Here is some example code which illustrates this:: - - unsigned int x; - x = 0; - x--; // x now contains 4,294,967,295; rolled over "left to right" - x++; // x now contains 0; rolled over "right to left" - -Here is an example of declaring an ``unsigned int`` variable named -``ledPin``, then giving it value 13:: - - unsigned int ledPin = 13; - -The general syntax for declaring an ``unsigned int`` variable named -``var``, then giving it value ``val``, looks like:: - - unsigned int var = val; - -See Also --------- - -- :ref:`int ` -- :ref:`char ` -- :ref:`unsigned char ` -- :ref:`long ` -- :ref:`unsigned long ` -- :ref:`Integer Constants ` -- :ref:`Variables ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/unsignedlong.rst b/docs/source/lang/unsignedlong.rst deleted file mode 100644 index 14a4fc3..0000000 --- a/docs/source/lang/unsignedlong.rst +++ /dev/null @@ -1,41 +0,0 @@ -.. highlight:: cpp - -.. _lang-unsignedlong: - -``unsigned long`` -================= - -An unsigned version of the :ref:`long ` data type. An -``unsigned long`` occupies 8 bytes of memory; it stores an integer -from 0 to 2^64-1, which is approximately 1.8×10^19 (18 quintillion, or -18 billion billion). - -Like an :ref:`unsigned int `, an ``unsigned long`` -won't store negative numbers; it is also subject to the same -:ref:`overflow issues ` as any integral data type. - -Here is an example of declaring an ``unsigned long`` variable named -``c``, then giving it value 299,792,458,000,000,000 (see :ref:`integer -constants ` for an explanation of the "L" -at the end of the number):: - - // Speed of light in nanometers per second (approximate). - unsigned long c = 299792458000000000L; - -The general syntax for declaring an ``unsigned long`` variable named -``var``, then giving it value ``val``, looks like:: - - unsigned long var = val; - -See Also --------- - -- :ref:`long ` -- :ref:`int ` -- :ref:`unsigned ` -- :ref:`char ` -- :ref:`unsigned char ` -- :ref:`Integer Constants ` -- :ref:`Variables ` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/variables.rst b/docs/source/lang/variables.rst deleted file mode 100644 index 9094cd5..0000000 --- a/docs/source/lang/variables.rst +++ /dev/null @@ -1,170 +0,0 @@ -.. highlight:: cpp - -.. _lang-variables: - -Variables -========= - -A variable is a way of naming and storing a value for later use by -the program, such as data from a sensor or an intermediate value -used in a calculation. - -.. contents:: Contents - :local: - -.. _lang-variables-declaring: - -Declaring Variables -------------------- - -Before they are used, all variables have to be *declared*. Declaring a -variable means defining its type, giving it a name, and (optionally) -giving it an initial value (this is often referred to as -*initializing* the variable). Variables do not have to be initialized -(given a value) when they are declared, but it is good style to give -them an initial value whenever possible. - -Here is an example of declaring a variable named ``inputVariable1`` -with type :ref:`int ` (the ``int`` type is used to store -integers, like -2, -1, 0, 1, etc.):: - - int inputVariable1; - -In the above declaration, we did not give the variable an initial -value. Here is another example, where we declare an ``int`` variable -named ``inputVariable2``, with an initial value of ``0``:: - - int inputVariable2 = 0; - -The Maple environment comes ready to use with many useful types of -variables. See the :ref:`built-in types ` page -for more information. - -Here are a few examples of declaring variables of different types:: - - int lightSensVal; - char currentLetter; - unsigned long speedOfLight = 186000UL; - char errorMessage = {"choose another option"}; // see string - -Naming Variables ----------------- - -The rules for naming a variable are simple. Names for variables can -contain letters, numbers, and underscores (the underscore is the -:kbd:`_` character), and cannot begin with a number. So -``temperature_reading``, ``tempReading``, ``tempReading1``, and -``tempReading2`` are all valid variable names, but ``4_temp_readings`` -is not, because it begins with a number. - -You cannot choose a name for a variable that is one of the C++ -:ref:`keywords `. - -Variable names are case-sensitive, so "tempreading" and "tempReading" -are different variables. However, it is very bad style to write code -that chooses variables which are the same up to case. - -You should give your variables descriptive names, so as to make your -code more readable. Variable names like ``tiltSensor`` or -``pushButton`` help you (and anyone else reading your code) understand -what the variable represents. Variable names like ``var`` or -``value``, on the other hand, do little to make your code readable. - -.. _lang-variables-scope: - -Variable Scope --------------- - -An important choice that programmers face is where (in the program -text) to declare variables. The specific place that variables are -declared influences how various functions in a program will "see" the -variable. This is called variable *scope*. See the :ref:`scope -reference ` for more information. - -.. _lang-variables-initializing: - -Initializing Variables ----------------------- - -Variables may be *initialized* (assigned a starting value) when they -are declared or not. It is always good programming practice however to -double check that a variable has valid data in it before it is used. -Using a variable before you give it a value is a common source of -bugs. - -.. _lang-variables-rollover: - -Variable Rollover ------------------ - -Every (numeric) type has a valid *range*. The range of a type is the -smallest and largest value that a variable of that type can store. -For example, the :ref:`int ` type has a range of --2,147,483,648 to 2,147,483,647 [#frange]_. - -When variables are made to exceed their range's maximum value, they -"roll over" back to their minimum value. Note that this happens in -both directions. It's like in the game *Pac-Man* -- when Pac-Man goes -past the right edge of the screen, he reappears on the left, and when -he goes past the left side of the screen, he reappears on the right:: - - int x; - x = -2,147,483,648; - x = x - 1; // x now contains -2,147,483,647; rolled over "left to right" - - x = 2,147,483,647; - x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" - -Each numeric type's reference page includes its range. See the -:ref:`built-in types ` reference for links to each -type's reference page. - -Using Variables ---------------- - -Once variables have been declared, they are given values using the -:ref:`assignment operator `, which is a single equals -sign, ``=``. The assignment operator tells the program to store the -value on the right side of the equals sign into the variable on the -left side:: - - inputVariable1 = 7; // sets variable named inputVariable1 to 7 - inputVariable2 = analogRead(2); // sets variable named inputVariable2 to - // the (digitized) input voltage read from - // analog pin #2 - -Once a variable has been set (assigned a value), you can test its -value to see if it meets certain conditions, or you can use its value -directly. For instance, the following code tests whether the -inputVariable2 is less than 100, then sets a delay based on -inputVariable2 (which, at that point, is at least 100):: - - if (inputVariable2 < 100) { - inputVariable2 = 100; - } - - delay(inputVariable2); - -See Also --------- - -- :ref:`lang-scope` -- :ref:`lang-numeric-types` - -.. rubric:: Footnotes - -.. [#frange] This range might seem a little weird at first. The - reasons for this range of values have to do with the fact that an - ``int`` occupies 32 bits of memory, and the facts :: - - 2^31 = -2,147,483,648 - 2^31 - 1 = 2,147,483,647 - - - Why 2^31 instead of 2^32? Well, that has to do with `how ints are - (usually) stored - `_ on computers. - - -.. include:: cc-attribution.txt - diff --git a/docs/source/lang/void.rst b/docs/source/lang/void.rst deleted file mode 100644 index 88bd448..0000000 --- a/docs/source/lang/void.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. highlight:: cpp - -.. _lang-void: - -``void`` -======== - -The ``void`` keyword is used only in function declarations. It -indicates that the function is expected to return no information to -the function from which it was called, or that it expects no arguments -from its caller. - -Example -------- - -:: - - // actions are performed in the functions "setup" and "loop" - // but no information is reported to the larger program - - void setup() { - // ... - } - - void loop() { - // ... - } - -.. TODO doc page on function declaration? - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/volatile.rst b/docs/source/lang/volatile.rst deleted file mode 100644 index 276bb6a..0000000 --- a/docs/source/lang/volatile.rst +++ /dev/null @@ -1,65 +0,0 @@ -.. 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 `). - -Specifically, it directs the compiler to read the variable's value -fresh every time it is used, rather than "backing up" the value and -reading from its backup copy. (Compilers often "back up" a variable's -value in RAM into a storage location called a *register*; this is done -for efficiency). - -A variable should be declared ``volatile`` whenever its value can be -changed by something beyond the control of the code section in which -it appears, such as an :ref:`external interrupt -`. On the Maple, the only place that this is -likely to occur is in sections of code associated with interrupts. - -Example -------- - -:: - - // 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 ` -- :ref:`lang-attachinterrupt` -- :ref:`lang-detachinterrupt` - -.. include:: cc-attribution.txt diff --git a/docs/source/lang/while.rst b/docs/source/lang/while.rst deleted file mode 100644 index 9047d05..0000000 --- a/docs/source/lang/while.rst +++ /dev/null @@ -1,38 +0,0 @@ -.. highlight:: cpp - -.. _lang-while: - -``while`` -========= - -Syntax ------- - -:: - - while (expression) { - // block of code - } - -Description ------------ - -``while`` loops will repeat the statements inside their associated -block of code until the expression inside the parentheses becomes -:ref:`false `. Something must change the tested -expressions' value, or the ``while`` loop will never exit. This could -be in your code, such as an incremented variable, or an external -condition, such as testing a sensor. - -Example -------- - -:: - - var = 0; - while(var < 200) { - // do something repetitive 200 times - var++; - } - -.. include:: cc-attribution.txt -- cgit v1.2.3 From d744fb826f4a6d6ce560f3b78f2e63a1f9666d9e Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Wed, 15 Dec 2010 01:50:56 -0500 Subject: Finalized 0.0.9 documentation. --- docs/Doxyfile | 11 +- docs/source/_static/img/jtag-wiring.png | Bin 40550 -> 33637 bytes docs/source/bootloader.rst | 710 ++++++++++++------------ docs/source/compatibility.rst | 22 +- docs/source/cpp.rst | 13 - docs/source/external-interrupts.rst | 1 - docs/source/gpio.rst | 16 +- docs/source/home.rst | 32 -- docs/source/i2c.rst | 1 - docs/source/index.rst | 20 +- docs/source/jtag.rst | 27 +- docs/source/lang/api/analogread.rst | 35 -- docs/source/lang/api/analogwrite.rst | 50 +- docs/source/lang/api/constants.rst | 23 + docs/source/lang/api/hardwarespi.rst | 152 +++++ docs/source/lang/api/hardwaretimer.rst | 368 ++++++++++++ docs/source/lang/api/interrupts.rst | 47 ++ docs/source/lang/api/isbuttonpressed.rst | 17 + docs/source/lang/api/nointerrupts.rst | 47 ++ docs/source/lang/api/pinmode.rst | 2 + docs/source/lang/api/pwmwrite.rst | 15 +- docs/source/lang/api/serialusb.rst | 11 +- docs/source/lang/api/toggleled.rst | 17 + docs/source/lang/api/togglepin.rst | 17 + docs/source/lang/api/waitforbuttonpress.rst | 17 + docs/source/lang/cpp/built-in-types.rst | 95 ++++ docs/source/lang/cpp/keywords.rst | 2 +- docs/source/lang/cpp/numeric-types.rst | 79 --- docs/source/lang/cpp/variables.rst | 6 +- docs/source/lang/cpp/void.rst | 10 +- docs/source/lang/unimplemented/interrupts.rst | 59 -- docs/source/lang/unimplemented/nointerrupts.rst | 59 -- docs/source/language-index.rst | 40 +- docs/source/language.rst | 233 ++++---- docs/source/libraries.rst | 67 ++- docs/source/libs/servo.rst | 108 ++++ docs/source/pwm.rst | 103 +--- docs/source/spi.rst | 55 +- docs/source/timers.rst | 231 ++------ docs/source/troubleshooting.rst | 27 +- docs/source/usart.rst | 1 - docs/source/usb.rst | 1 - libmaple/libmaple_types.h | 2 + libmaple/timers.h | 109 ++-- support/scripts/copy-to-ide | 16 +- wirish/HardwareTimer.cpp | 1 - wirish/HardwareTimer.h | 69 ++- wirish/comm/HardwareSPI.h | 23 +- wirish/ext_interrupts.h | 4 +- wirish/io.h | 2 +- wirish/wirish_math.h | 6 +- 51 files changed, 1784 insertions(+), 1295 deletions(-) delete mode 100644 docs/source/cpp.rst delete mode 100644 docs/source/home.rst create mode 100644 docs/source/lang/api/hardwarespi.rst create mode 100644 docs/source/lang/api/hardwaretimer.rst create mode 100644 docs/source/lang/api/interrupts.rst create mode 100644 docs/source/lang/api/isbuttonpressed.rst create mode 100644 docs/source/lang/api/nointerrupts.rst create mode 100644 docs/source/lang/api/toggleled.rst create mode 100644 docs/source/lang/api/togglepin.rst create mode 100644 docs/source/lang/api/waitforbuttonpress.rst create mode 100644 docs/source/lang/cpp/built-in-types.rst delete mode 100644 docs/source/lang/cpp/numeric-types.rst delete mode 100644 docs/source/lang/unimplemented/interrupts.rst delete mode 100644 docs/source/lang/unimplemented/nointerrupts.rst create mode 100644 docs/source/libs/servo.rst (limited to 'docs/source/lang') diff --git a/docs/Doxyfile b/docs/Doxyfile index 88b8764..3290843 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -318,7 +318,7 @@ EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. -EXTRACT_STATIC = NO +EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. @@ -1335,13 +1335,13 @@ ENABLE_PREPROCESSING = YES # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. -MACRO_EXPANSION = NO +MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. -EXPAND_ONLY_PREDEF = NO +EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. @@ -1369,7 +1369,8 @@ INCLUDE_FILE_PATTERNS = # undefined via #undef or recursively expanded use the := operator # instead of the = operator. -PREDEFINED = __cplusplus +PREDEFINED = ALWAYS_INLINE= \ + __cplusplus # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. @@ -1462,7 +1463,7 @@ HIDE_UNDOC_RELATIONS = YES # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) -HAVE_DOT = YES +HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will diff --git a/docs/source/_static/img/jtag-wiring.png b/docs/source/_static/img/jtag-wiring.png index 9c63e82..8f31f99 100644 Binary files a/docs/source/_static/img/jtag-wiring.png and b/docs/source/_static/img/jtag-wiring.png differ diff --git a/docs/source/bootloader.rst b/docs/source/bootloader.rst index d42c050..57833ed 100644 --- a/docs/source/bootloader.rst +++ b/docs/source/bootloader.rst @@ -138,447 +138,447 @@ This time, however, no DFU transaction is initiated, and the bootloader gives way to user code, closing down the DFU pipe and bringing up the USB serial. -.. _bootloader-rev6: - -Maple Rev6 - The Serial Bootloader (Tentative) ----------------------------------------------- - -.. note:: This section documents an in-progress version of the Maple - bootloader. **No Maples yet sold use this bootloader protocol**. - It has not been yet been publicly released, and its interface is - not stable. - -The bootloader in Rev3/Rev5 works well on Linux, acceptably on Mac, -but was unsatisfactory on Windows. Unlike the other operating systems, -Windows needed to be manually pointed to both the driver to use for -programming (DFU, via `libusb `_) and the -driver to use for serial communication (usbser.sys, built in to -Windows). Since Maple operates in only one of these modes at a time, -driver installation was unnecessarily complicated. It was necessary to -bring Maple into the correct mode before installing each of the -drivers. Furthermore, because libusb is not bundled with Windows, and -its driver is not signed, Windows 7 users have been forced to -laboriously disable driver signing checks. Finally, Windows hates the -constant switching of the device between Serial and DFU modes (during -programming), and often prompts users to install drivers that are -already installed. We have therefore decided to abandon DFU. - -In our new bootloader scheme, Maple is simply a serial device. -Windows comes bundled with usbser.sys, so no driver signing is -required. The IDE installation process is greatly simplified, there -is no more switching back and forth between "modes", and we can build -in new functionality outside the DFU spec. - -The first incarnation of this serial-only bootloader leaves libmaple -and user code untouched. However, during programming, instead of -calling :command:`dfu-util` to upload code we will now call a newly -written utility script similar to `avr-dude -`_. The high level -operation of the bootloader will remain the same - come on at startup, -wait for an upload operation or timeout, and jump to user code. - -The second version of this bootloader will eliminate this dependence -on resetting and timing out by having the bootloader run in the -background. It will additionally own the serial port. In this scheme, -sending data over the COM port while DTR is pulled low results in that -packet being captured by the bootloader and interpreted as a -bootloader command. When the user uploads a new program, the -bootloader will overwrite the old one, reset the various peripheral -registers, and jump to user code. All of this will occur without -resetting the chip and thus causing Maple to connect and disconnect -from your computer (which seems to cause many problems). - -The final version of this bootloader scheme will involve a separate -microcontroller, whose responsibilities are to drive the USB port, -program the main processor, and offer some amount of debugging -capability. This will allow user sketches to run on the bare metal of -the main processor, without any bootloader hiding underneath. This -approach is similar to the approaches taken by mbed and the Arduino -Uno. - -Regardless of which generation of the new serial bootloader you are -working with, the command interface is the same. The low level -communication protocol is inspired by STK-500, the protocol used to -program many AVR-based development boards. The protocol is a -packetized query-response scheme. The host PC initiates every -transaction, and for every query sent to the bootloader, a single -response will be returned (or the system times out). Data is -transmitted over 115.2kbps, 8 data bits, 1 stop bit, no parity -bit. Every query or response follows the same packet format that looks -like this: - -.. _bootloader-packet-structure: - -Packet Structure -^^^^^^^^^^^^^^^^ - -A bootloader packet is composed of a sequence of fields, as follows. - -.. list-table:: - :header-rows: 1 - - * - Field - - Length (bytes) - - Value - - Description - - * - START - - 1 - - 0x1B - - Magic constant, indicates bootloader packet - - * - SEQUENCE_NUM - - 1 - - 0--0xFF - - Queries and responses must have the same sequence number; rolls - over to 0 after 0xFF - - * - MESSAGE_SIZE - - 2 - - 0--0xFFFF - - Size of message body, currently limited to a 1024B=1KB maximum - - * - TOKEN - - 1 - - 0x7F - - Differs from STK500 value of 0x0E - - * - MESSAGE_BODY - - Variable, determined by MESSAGE_SIZE field - - Command query or response - - See :ref:`next section ` - - * - CHECKSUM - - 4 - - XOR of all other 32-bit words in packet - - See :ref:`below ` - -.. _bootloader-checksum: - -.. highlight:: cpp - -.. note:: When computing the checksum, the words in a packet are - interpreted big-endian (as if the packet were a sequence of 32-bit, - big-endian unsigned integers). If the end of the MESSAGE_BODY is - not aligned with a four-byte boundary, then the checksum will treat - it as if it was padded with zero bytes to a four-byte boundary. - - As a concrete example, an entire GET_INFO query (see :ref:`below - `), including the packet structure, is - comprised of the byte sequence :: - - {0x1B, 0x7F, 0x00, 0x01, 0x7F, 0x00, 0x64, 0x7F, 0x00, 0x01} - - The SEQUENCE_NUM of this query is 0x7F. +.. .. _bootloader-rev6: + +.. Maple Rev6 - The Serial Bootloader (Tentative) +.. ---------------------------------------------- + +.. .. note:: This section documents an in-progress version of the Maple +.. bootloader. **No Maples yet sold use this bootloader protocol**. +.. It has not been yet been publicly released, and its interface is +.. not stable. + +.. The bootloader in Rev3/Rev5 works well on Linux, acceptably on Mac, +.. but was unsatisfactory on Windows. Unlike the other operating systems, +.. Windows needed to be manually pointed to both the driver to use for +.. programming (DFU, via `libusb `_) and the +.. driver to use for serial communication (usbser.sys, built in to +.. Windows). Since Maple operates in only one of these modes at a time, +.. driver installation was unnecessarily complicated. It was necessary to +.. bring Maple into the correct mode before installing each of the +.. drivers. Furthermore, because libusb is not bundled with Windows, and +.. its driver is not signed, Windows 7 users have been forced to +.. laboriously disable driver signing checks. Finally, Windows hates the +.. constant switching of the device between Serial and DFU modes (during +.. programming), and often prompts users to install drivers that are +.. already installed. We have therefore decided to abandon DFU. + +.. In our new bootloader scheme, Maple is simply a serial device. +.. Windows comes bundled with usbser.sys, so no driver signing is +.. required. The IDE installation process is greatly simplified, there +.. is no more switching back and forth between "modes", and we can build +.. in new functionality outside the DFU spec. + +.. The first incarnation of this serial-only bootloader leaves libmaple +.. and user code untouched. However, during programming, instead of +.. calling :command:`dfu-util` to upload code we will now call a newly +.. written utility script similar to `avr-dude +.. `_. The high level +.. operation of the bootloader will remain the same - come on at startup, +.. wait for an upload operation or timeout, and jump to user code. + +.. The second version of this bootloader will eliminate this dependence +.. on resetting and timing out by having the bootloader run in the +.. background. It will additionally own the serial port. In this scheme, +.. sending data over the COM port while DTR is pulled low results in that +.. packet being captured by the bootloader and interpreted as a +.. bootloader command. When the user uploads a new program, the +.. bootloader will overwrite the old one, reset the various peripheral +.. registers, and jump to user code. All of this will occur without +.. resetting the chip and thus causing Maple to connect and disconnect +.. from your computer (which seems to cause many problems). + +.. The final version of this bootloader scheme will involve a separate +.. microcontroller, whose responsibilities are to drive the USB port, +.. program the main processor, and offer some amount of debugging +.. capability. This will allow user sketches to run on the bare metal of +.. the main processor, without any bootloader hiding underneath. This +.. approach is similar to the approaches taken by mbed and the Arduino +.. Uno. + +.. Regardless of which generation of the new serial bootloader you are +.. working with, the command interface is the same. The low level +.. communication protocol is inspired by STK-500, the protocol used to +.. program many AVR-based development boards. The protocol is a +.. packetized query-response scheme. The host PC initiates every +.. transaction, and for every query sent to the bootloader, a single +.. response will be returned (or the system times out). Data is +.. transmitted over 115.2kbps, 8 data bits, 1 stop bit, no parity +.. bit. Every query or response follows the same packet format that looks +.. like this: + +.. .. _bootloader-packet-structure: + +.. Packet Structure +.. ^^^^^^^^^^^^^^^^ + +.. A bootloader packet is composed of a sequence of fields, as follows. + +.. .. list-table:: +.. :header-rows: 1 + +.. * - Field +.. - Length (bytes) +.. - Value +.. - Description + +.. * - START +.. - 1 +.. - 0x1B +.. - Magic constant, indicates bootloader packet + +.. * - SEQUENCE_NUM +.. - 1 +.. - 0--0xFF +.. - Queries and responses must have the same sequence number; rolls +.. over to 0 after 0xFF + +.. * - MESSAGE_SIZE +.. - 2 +.. - 0--0xFFFF +.. - Size of message body, currently limited to a 1024B=1KB maximum + +.. * - TOKEN +.. - 1 +.. - 0x7F +.. - Differs from STK500 value of 0x0E + +.. * - MESSAGE_BODY +.. - Variable, determined by MESSAGE_SIZE field +.. - Command query or response +.. - See :ref:`next section ` + +.. * - CHECKSUM +.. - 4 +.. - XOR of all other 32-bit words in packet +.. - See :ref:`below ` + +.. .. _bootloader-checksum: + +.. .. highlight:: cpp + +.. .. note:: When computing the checksum, the words in a packet are +.. interpreted big-endian (as if the packet were a sequence of 32-bit, +.. big-endian unsigned integers). If the end of the MESSAGE_BODY is +.. not aligned with a four-byte boundary, then the checksum will treat +.. it as if it was padded with zero bytes to a four-byte boundary. -.. highlight:: sh +.. As a concrete example, an entire GET_INFO query (see :ref:`below +.. `), including the packet structure, is +.. comprised of the byte sequence :: + +.. {0x1B, 0x7F, 0x00, 0x01, 0x7F, 0x00, 0x64, 0x7F, 0x00, 0x01} + +.. The SEQUENCE_NUM of this query is 0x7F. + +.. .. highlight:: sh -.. _bootloader-commands: +.. .. _bootloader-commands: -Commands -^^^^^^^^ +.. Commands +.. ^^^^^^^^ -The packet structure overhead is for reliability. The actual queries -and responses are transacted inside of the message body. Following -the STK-500 protocol, each query or response begins with the single -byte command field. For each query, the resultant response must begin -with the same CMD byte. For each type of command, the structure of -queries and responses is of fixed size. +.. The packet structure overhead is for reliability. The actual queries +.. and responses are transacted inside of the message body. Following +.. the STK-500 protocol, each query or response begins with the single +.. byte command field. For each query, the resultant response must begin +.. with the same CMD byte. For each type of command, the structure of +.. queries and responses is of fixed size. -Also following STK-500, fields longer than 1 byte are transmitted MSB -first (big-endian). However, READ and WRITE commands operate byte-wise -(not word-wise); it is up to the host PC to ensure that alignment and -ordering issues are handled appropriately. +.. Also following STK-500, fields longer than 1 byte are transmitted MSB +.. first (big-endian). However, READ and WRITE commands operate byte-wise +.. (not word-wise); it is up to the host PC to ensure that alignment and +.. ordering issues are handled appropriately. -.. _bootloader-get-info: +.. .. _bootloader-get-info: -GET_INFO -"""""""" +.. GET_INFO +.. """""""" -Used to query device characteristics. +.. Used to query device characteristics. -GET_INFO Query: +.. GET_INFO Query: -.. list-table:: - :header-rows: 1 +.. .. list-table:: +.. :header-rows: 1 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - GET_INFO - - 1 - - Value 0 +.. * - GET_INFO +.. - 1 +.. - Value 0 -GET_INFO Response: +.. GET_INFO Response: -.. list-table:: - :header-rows: 1 - :widths: 4 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - GET_INFO - - 1 - - Value 0 +.. * - GET_INFO +.. - 1 +.. - Value 0 - * - Endianness - - 1 - - 0 indicates little-endian, 1 indicates big-endian. - (Currently returns 0; this field allows for future - expansion). +.. * - Endianness +.. - 1 +.. - 0 indicates little-endian, 1 indicates big-endian. +.. (Currently returns 0; this field allows for future +.. expansion). - * - Available Ram - - 4 - - In bytes +.. * - Available Ram +.. - 4 +.. - In bytes - * - Available Flash - - 4 - - In bytes +.. * - Available Flash +.. - 4 +.. - In bytes - * - Flash Page Size - - 2 - - In bytes +.. * - Flash Page Size +.. - 2 +.. - In bytes - * - Starting Address (FLASH) - - 4 - - Usually 0x08005000 +.. * - Starting Address (FLASH) +.. - 4 +.. - Usually 0x08005000 - * - Starting Address (RAM) - - 4 - - Usually 0x200000C0 +.. * - Starting Address (RAM) +.. - 4 +.. - Usually 0x200000C0 - * - Bootloader Version - - 4 - - Current version 0x00060000 (MAJ,MIN) +.. * - Bootloader Version +.. - 4 +.. - Current version 0x00060000 (MAJ,MIN) -.. _bootloader-erase-page: +.. .. _bootloader-erase-page: -ERASE_PAGE -"""""""""" +.. ERASE_PAGE +.. """""""""" -Used to erase flash pages. +.. Used to erase flash pages. -ERASE_PAGE query: +.. ERASE_PAGE query: -.. list-table:: - :header-rows: 1 - :widths: 4 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - ERASE_PAGE - - 1 - - Value 1 +.. * - ERASE_PAGE +.. - 1 +.. - Value 1 - * - ADDRESS - - 4 - - Will erase whichever page contains ADDRESS +.. * - ADDRESS +.. - 4 +.. - Will erase whichever page contains ADDRESS -ERASE_PAGE response: +.. ERASE_PAGE response: -.. list-table:: - :header-rows: 1 - :widths: 3 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 3 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - ERASE_PAGE - - 1 - - Value 1 +.. * - ERASE_PAGE +.. - 1 +.. - Value 1 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success) +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success) -WRITE_BYTES -""""""""""" +.. WRITE_BYTES +.. """"""""""" -Used to write to RAM or flash. +.. Used to write to RAM or flash. -WRITE_BYTES query: +.. WRITE_BYTES query: -.. list-table:: - :header-rows: 1 - :widths: 4 4 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 4 4 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - WRITE_BYTES - - 1 - - Value 2 +.. * - WRITE_BYTES +.. - 1 +.. - Value 2 - * - Starting Address - - 4 - - Can address arbitrary RAM, or :ref:`cleared - ` flash pages. +.. * - Starting Address +.. - 4 +.. - Can address arbitrary RAM, or :ref:`cleared +.. ` flash pages. - * - DATA - - MESSAGE_SIZE - 5 - - See :ref:`Packet Structure ` +.. * - DATA +.. - MESSAGE_SIZE - 5 +.. - See :ref:`Packet Structure ` -WRITE_BYTES response: +.. WRITE_BYTES response: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - WRITE_BYTES - - 1 - - Value 2 +.. * - WRITE_BYTES +.. - 1 +.. - Value 2 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success). Will fail if writes were - made to uncleared pages. Does not clean up failed writes - (memory will be left in an undefined state). +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success). Will fail if writes were +.. made to uncleared pages. Does not clean up failed writes +.. (memory will be left in an undefined state). -READ_BYTES -"""""""""" +.. READ_BYTES +.. """""""""" -Used to read from RAM or flash. +.. Used to read from RAM or flash. -READ_BYTES query: +.. READ_BYTES query: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - READ_BYTES - - 1 - - Value 3 +.. * - READ_BYTES +.. - 1 +.. - Value 3 - * - ADDRESS - - 4 - - Start of block to read. Must be a multiple of 4. +.. * - ADDRESS +.. - 4 +.. - Start of block to read. Must be a multiple of 4. - * - LENGTH - - 2 - - Maximum number of bytes to read (currently, this may be at most - 1024 = 1KB). Must be a multiple of 4. +.. * - LENGTH +.. - 2 +.. - Maximum number of bytes to read (currently, this may be at most +.. 1024 = 1KB). Must be a multiple of 4. -READ_BYTES response: +.. READ_BYTES response: -.. list-table:: - :header-rows: 1 - :widths: 2 2 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 2 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - READ_BYTES - - 1 - - Value 3 +.. * - READ_BYTES +.. - 1 +.. - Value 3 - * - DATA - - MESSAGE_SIZE - 1 - - Contains read bytes. The actual number of bytes read may be - less than the LENGTH field of the corresponding READ_BYTES - query. If this section is of length 0, this should be - interpreted as a read failure. See - :ref:`bootloader-packet-structure`. +.. * - DATA +.. - MESSAGE_SIZE - 1 +.. - Contains read bytes. The actual number of bytes read may be +.. less than the LENGTH field of the corresponding READ_BYTES +.. query. If this section is of length 0, this should be +.. interpreted as a read failure. See +.. :ref:`bootloader-packet-structure`. -JUMP_TO_USER -"""""""""""" +.. JUMP_TO_USER +.. """""""""""" -Causes the bootloader to jump to user code's starting address. +.. Causes the bootloader to jump to user code's starting address. -JUMP_TO_USER query: +.. JUMP_TO_USER query: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - JUMP_TO_USER - - 1 - - Value 4 +.. * - JUMP_TO_USER +.. - 1 +.. - Value 4 - * - Location - - 1 - - 0 means jump to flash starting address, 1 means jump to RAM - starting address. See the :ref:`bootloader-get-info` command - for more information. +.. * - Location +.. - 1 +.. - 0 means jump to flash starting address, 1 means jump to RAM +.. starting address. See the :ref:`bootloader-get-info` command +.. for more information. -JUMP_TO_USER response: +.. JUMP_TO_USER response: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - JUMP_TO_USER - - 1 - - Value 4 +.. * - JUMP_TO_USER +.. - 1 +.. - Value 4 - * - SUCCESS - - 1 - - Either 0 (failure) or 1 (success). If successful, after the - response is sent, the bootloader ends this session and jumps to - the user code in flash or RAM as specified in the query's - Location field. +.. * - SUCCESS +.. - 1 +.. - Either 0 (failure) or 1 (success). If successful, after the +.. response is sent, the bootloader ends this session and jumps to +.. the user code in flash or RAM as specified in the query's +.. Location field. -SOFT_RESET -"""""""""" +.. SOFT_RESET +.. """""""""" -Engages a full software reset. +.. Engages a full software reset. -SOFT_RESET query: +.. SOFT_RESET query: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - SOFT_RESET - - 1 - - Value 5 +.. * - SOFT_RESET +.. - 1 +.. - Value 5 -SOFT_RESET response: +.. SOFT_RESET response: -.. list-table:: - :header-rows: 1 - :widths: 2 1 10 +.. .. list-table:: +.. :header-rows: 1 +.. :widths: 2 1 10 - * - Field - - Bytes - - Comments +.. * - Field +.. - Bytes +.. - Comments - * - SOFT_RESET - - 1 - - Value 5 +.. * - SOFT_RESET +.. - 1 +.. - Value 5 - * - SUCCESS - - 1 - - Either 0 or 1 (FAILED and OK, respectively). Will end this - bootloader session and reset the processor. +.. * - SUCCESS +.. - 1 +.. - Either 0 or 1 (FAILED and OK, respectively). Will end this +.. bootloader session and reset the processor. .. _bootloader-reflashing: diff --git a/docs/source/compatibility.rst b/docs/source/compatibility.rst index a070b42..848a3d3 100644 --- a/docs/source/compatibility.rst +++ b/docs/source/compatibility.rst @@ -119,8 +119,6 @@ differences, most of which are improvements: Shield and Device Compatibility ------------------------------- -.. TODO update for 0.0.9 - .. list-table:: :header-rows: 1 @@ -134,7 +132,7 @@ Shield and Device Compatibility * - WiFi Shield - Yes! - - Tested; no library yet (expected for 0.0.9) + - Tested; preliminary library support * - MIDI shield - Yes! @@ -146,7 +144,8 @@ Shield and Device Compatibility * - Bluetooth shield - Unknown - - + - Some Bluetooth <-> UART boards have been tested and are known + to work. * - Cellular shield - Unknown @@ -158,11 +157,12 @@ Library Porting Status The state of currently ported Arduino libraries is the :ref:`libraries`. -.. TODO update for 0.0.9; update as libraries are ported. +.. TODO Update as libraries are ported. .. list-table:: :header-rows: 1 + * - Library - Ported? - Notes @@ -180,9 +180,11 @@ The state of currently ported Arduino libraries is the - Planned * - EEPROM - - No - - The Maple doesn't have EEPROM; use flash instead. Perhaps this - library could be emulated? + - (Unsupported) third-party emulation + - The Maple doesn't have EEPROM; it uses flash instead. There is + an `EEPROM emulation library + `_ by + `x893 `_, but we haven't tested it. * - Firmata - Not yet @@ -192,6 +194,10 @@ The state of currently ported Arduino libraries is the - Not yet - Planned + * - Servo + - **Yes** + - :ref:`Included since IDE 0.0.9 ` + * - SoftwareSerial - Not yet - Planned diff --git a/docs/source/cpp.rst b/docs/source/cpp.rst deleted file mode 100644 index a20578e..0000000 --- a/docs/source/cpp.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. _cpp: - -============== -C++ for Maple -============== - -.. _index-language-index-cpp-index: - -.. toctree:: - :maxdepth: 1 - :glob: - - lang/cpp/* \ No newline at end of file diff --git a/docs/source/external-interrupts.rst b/docs/source/external-interrupts.rst index 79492ef..5187ca4 100644 --- a/docs/source/external-interrupts.rst +++ b/docs/source/external-interrupts.rst @@ -121,6 +121,5 @@ Recommended Reading * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/gpio.rst b/docs/source/gpio.rst index ee2b6eb..4017862 100644 --- a/docs/source/gpio.rst +++ b/docs/source/gpio.rst @@ -14,9 +14,9 @@ peripheral functions. This page documents those capabilities, by pin. The current and voltage limitations have not been copied over from the STM32 datasheet (see the :ref:`Recommended Reading ` for a link). In particular, a number of -GPIO pins are 5v tolerant (which means that applying 5v to a pin and -reading it as input or allowing it to drain to ground will not damage -that pin), while some are not. +GPIO pins are 5V tolerant (which means that applying 5 volts to a pin +and reading it as input or allowing it to drain to ground will not +damage that pin), while some are not. .. contents:: Contents :local: @@ -26,11 +26,10 @@ that pin), while some are not. Pin Mapping Mega Table ---------------------- -This huge reference table shows the available functionality on every -GPIO pin, by peripheral type. The "STM32" column refers to the port -and number that the header is connected to on the microcontroller. -The "5v?" column documents whether or not the pin is 5v tolerant (see -above). +This table shows the available functionality on every GPIO pin, by +peripheral type. The "STM32" column refers to the port and number that +the header is connected to on the microcontroller. The "5V?" column +documents whether or not the pin is 5 volt tolerant (see above). .. csv-table:: :header: "Pin", "STM32", ":ref:`ADC `", ":ref:`Timer `", ":ref:`I2C `", ":ref:`UART `", ":ref:`SPI `", "5v?" @@ -99,6 +98,5 @@ Recommended Reading STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/home.rst b/docs/source/home.rst deleted file mode 100644 index db5b56e..0000000 --- a/docs/source/home.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. _home: - -======================== -Maple Documentation Home -======================== - - -Welcome! - -Maple is a user-friendly prototyping platform developed by LeafLabs in Cambridge, MA. Using Maple, creators with any level of experience can implement beautiful ideas that require the power of a 32-bit processor. For more details about Maple's hardware, please see its :ref:`technical specifications `. To start using your Maple, keep reading - -.. _home-Getting-Started: - -Getting Started -^^^^^^^^^^^^^^^ - -:ref:`Quickstart ` - -:ref:`IDE Anatomy ` - -:ref:`Basic Language Reference ` - -:ref:`Tech Specs` - -.. _home-Problem-Solving: - -Problem Solving -^^^^^^^^^^^^^^^ - -Check out our :ref:`troubleshooting ` and :ref:`known problems` pages. - -If you don't find what you're looking for, hit the `forums `_ to ask the LeafLabs team and other Maple users questions. Good luck, and have fun! diff --git a/docs/source/i2c.rst b/docs/source/i2c.rst index 6e5b946..b4a996b 100644 --- a/docs/source/i2c.rst +++ b/docs/source/i2c.rst @@ -80,7 +80,6 @@ Recommended Reading * `Arduino i2c/TWI reference `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Application Note on Advanced I2C Usage diff --git a/docs/source/index.rst b/docs/source/index.rst index c552dd4..825ec81 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,7 +1,15 @@ .. _index: Maple Documentation Contents -============================= +============================ + +Welcome! This is the Maple documentation index. If you just bought a +Maple, you probably want to head to the :ref:`quickstart +`. If you're having problems, check out the +:ref:`troubleshooting ` and :ref:`known problems +` pages. + +Have fun! .. _index-usage: @@ -15,7 +23,7 @@ Maple Documentation Contents IDE Anatomy .. _index-maple-programming: - + **Maple Programming:** .. toctree:: @@ -29,7 +37,7 @@ Maple Documentation Contents Bootloader - Troubleshooting + Troubleshooting Known Problems .. _index-hardware: @@ -38,7 +46,7 @@ Maple Documentation Contents .. toctree:: :maxdepth: 1 - + i2c pwm gpio @@ -55,8 +63,8 @@ Maple Documentation Contents .. toctree:: :maxdepth: 1 - + Technical Specifications Complete Language Index - + diff --git a/docs/source/jtag.rst b/docs/source/jtag.rst index 7cfba5f..e3c8111 100644 --- a/docs/source/jtag.rst +++ b/docs/source/jtag.rst @@ -15,24 +15,24 @@ and hardware peripherals (we use it when working on :ref:`libmaple Note that the STM32 on the Maple has a built-in low level serial debugger which could also be used to flash bootloaders, and that the :ref:`ASSERT ` framework allows basic debugging over -a USART serial channel. We expect only advanced users to use this -feature. +a USART serial channel. We expect only fairly advanced users to use +this feature. .. contents:: Contents :local: - Wiring Diagram -------------- .. figure:: /_static/img/jtag-wiring.png :align: center :alt: JTAG wiring diagram + :width: 7.4in - JTAG wiring diagram to connect a standard 20-pin ARM JTAG device to - the 8-pin JTAG port on the Maple. - -.. FIXME jtag wiring diagram (above) looks terrible; replace it + JTAG wiring diagram (`large version + `_) + to connect a standard 20-pin ARM JTAG device to the 8-pin JTAG port + on the Maple. The Maple has holes for a 8-pin JTAG header but that header is not soldered on by default. If you know ahead of time that you'll be @@ -42,14 +42,7 @@ probably solder one on for no charge. Otherwise, you can simply attach standard 0.1" pitch male header pins (either the exact 4x2 block or two 4-pin pieces of breakaway straight header). For a one-off usage hack, the header can be jammed in the holes and twisted to -ensure electrical contact; this is what we do to flash our bootloader. - -The above schematic assumes that the header has been soldered on to -the *bottom* of the board, not the top; most ribbon cable connectors -will interfere with the power header. If you don't want a header -coming off the bottom, you can use a slim connector and invert this -diagram appropriately. - +ensure electrical contact. Compatible Devices ------------------ @@ -65,6 +58,8 @@ Recommended Reading * `STM32/gdb/OpenOCD HOWTO `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) +* There's a `thread on JTAG + `_ in our `forum`_ + which you may find useful. diff --git a/docs/source/lang/api/analogread.rst b/docs/source/lang/api/analogread.rst index c614aca..35c6fbc 100644 --- a/docs/source/lang/api/analogread.rst +++ b/docs/source/lang/api/analogread.rst @@ -32,11 +32,6 @@ Before calling analogRead() on a pin, that pin must first be configured for analog input, using :ref:`lang-pinMode` (you only have to do this once, so it's usually done in :ref:`lang-setup`\ ). -It takes about 0.8 microseconds (.0000008 seconds) to read an analog -input, so the maximum sample rate using this function is approximately -1.3 million samples per second\ [#fsamp]_. - - Parameter Discussion -------------------- @@ -115,40 +110,10 @@ Some basic tools to accomplish this are `resistor dividers . However, opamps and other powered components can also be used if greater precision is required. -Finally, On the Arduino, it takes significantly longer to read analog -input: about 100 microseconds (0.0001 s), so the maximum reading rate -is 10,000 times a second. - - See also -------- - :ref:`ADC note ` - `(Arduino) Tutorial: Analog Input Pins `_ - -.. rubric:: Footnotes - -.. [#fsamp] This is based on the current configuration of a 55.5 cycle - sample time, at 72 MHz. However, the minimum sample time *possible* - is 1.5 cycles, leading to a theoretical maximum of approximately 48 - million samples per second (of course, doing anything with the - readings also consumes cycles, so this maximum can't be reached in - practice). - - See the `STM32 Reference Manual `_, §§11.12.4--5 - (pp. 225--226), for more information on the low-level bit twiddling - currently necessary to change the sample time. For examples of how - the ADCs are configured in libmaple, see `adc.h - `_ - and `adc.c - `_\ - . Be aware that changing the sample time has important - consequences related to the impedance of the device connected to - the input pin. If you want to make changes, as a minimum, you - should first read ST's application notes on `ADC modes - `_ and `ADC oversampling - `_. - - .. include:: cc-attribution.txt diff --git a/docs/source/lang/api/analogwrite.rst b/docs/source/lang/api/analogwrite.rst index 01820ef..9147b96 100644 --- a/docs/source/lang/api/analogwrite.rst +++ b/docs/source/lang/api/analogwrite.rst @@ -11,19 +11,18 @@ analogWrite() .. note:: On the Maple, calling analogWrite() is the same as calling - :ref:`lang-pwmwrite`\ ; see that function's documentation for more - information. + :ref:`lang-pwmwrite`\ ; we recommend using that function directly + instead. This is because PWM is not true analog output (i.e., is not the output of a `DAC `_\ ), so - the function is badly named. For instance, **analogWrite() has + the function is badly named. For instance, analogWrite() **has absolutely nothing to do with** :ref:`lang-analogread`\ , which is potentially confusing. - The alias of analogWrite() to pwmWrite() is provided (sigh) for the - sake of compatibility with Arduino, but we recommend using - :ref:`lang-pwmwrite` when writing new software, for clarity. + The alias of analogWrite() to pwmWrite() is provided for the sake + of compatibility with Arduino only. .. contents:: Contents :local: @@ -97,23 +96,21 @@ Difference 3: No PWM on pin 10 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, -9, 11, 12, and 14, or twelve pins in total. That is at least as -*many* PWM pins as any Arduino board, but there are differences in -*which* pins support it. +9, 11, 12, 14, 24, 27, and 28 or fifteen pins in total. That's *more* +PWM-capable pins as any Arduino board, but there are differences in +*which* pins support PWM. * On **most Arduino boards** (those with the ATmega168 or ATmega328; this includes the **Arduino Uno**), this function works on pins 3, 5, 6, 9, 10, and 11, or six pins total. Note that these boards support PWM on pin 10, while Maple does not. -* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve pins - total. Note that this board supports PWM on pins 4, 10, and 13, - while the Maple does not. Maple supports PWM on pins 0, 1, and 14, - which the Mega does not, making the total number of pins supporting - PWM equal on these boards. +* On the **Arduino Mega**, PWM works on pins 2 through 13, or twelve + pins total. Note that this board supports PWM on pins 4, 10, and + 13, while the Maple does not. -* **Older Arduino boards** with an ATmega8 only support analogWrite() on - pins 9, 10, and 11. Maple does not support PWM on pin 10. +* **Older Arduino boards** with an ATmega8 only support analogWrite() + on pins 9, 10, and 11. Maple does not support PWM on pin 10. In all cases, Arduino boards support PWM on pin 10, unlike Maple. We did our best to make PWM as pin-compatible as possible; however, @@ -125,7 +122,8 @@ work on any Arduino board and on Maple. The "safe" pins, which work on most recent Arduino boards, the Arduino Mega and the Maple, are pins 3, 5, 6, 9, and 11. Thus, if you want your project to be as portable as possible between Maple and Arduino, we recommend using the -"safest" pins first, then the "safe" pins, as necessary. +"safest" pins first, then the "safe" pins, then any other pins, as +necessary. Difference 4: PWM frequency ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -138,17 +136,23 @@ Hz, or 1.1 KHz. This is because the PWM frequency is the frequency of the timer which controls PWM output on the particular pin (\ :ref:`the PWM tutorial has the details `\ ). -If your application absolutely requires Arduino's PWM frequency (it -probably doesn't), then the steps are: +If your application definitely requires Arduino's PWM frequency, then +the steps are: -1. Figure out which timer controls PWM output on your pin (\ :ref:`this table ` is your friend here). Let's say it's ``Timern``\ , where ``n`` is some number 1, 2, 3, or 4. +1. Figure out which :ref:`timer ` controls PWM + output on your pin (\ :ref:`this table ` is your + friend here). Let's say it's ``Timern``\ , where ``n`` is some + number 1, 2, 3, or 4. -2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's period to approximately 2041 microseconds, which is a frequency of approximately 490 Hz. +2. Call ``Timern.setPeriod(2041)``\ . This will set the timer's + period to approximately 2041 microseconds, which is a frequency of + approximately 490 Hz. Be aware that this will change the period for the **entire timer**\ , and will affect anything else in your program that depends on that -timer. One example is :ref:`interrupts `\ . -You've been :ref:`warned `\ . +timer. The important examples are :ref:`timer interrupts +` and :ref:`PWM +`\ . See also -------- diff --git a/docs/source/lang/api/constants.rst b/docs/source/lang/api/constants.rst index bc5c894..4426293 100644 --- a/docs/source/lang/api/constants.rst +++ b/docs/source/lang/api/constants.rst @@ -288,6 +288,29 @@ exponent indicators. Some examples are given in the following table: - 67.0×10\ :sup:`-12` - ``0.000000000067`` +.. _lang-constants-board: + +Board-Specific Constants +------------------------ + +This section documents constants whose value might change across +different LeafLabs boards. You can use these constants to help ensure +that your code will be portable across different boards. + +.. TODO replace "upcoming" when Mini, Native come out + +.. _lang-constants-led: + +- ``BOARD_LED_PIN``: the number of the pin which connects to the + built-in LED. On the Maple, this is pin 13, but it's not guaranteed + to be the same in upcoming boards like the Maple Mini. + +.. _lang-constants-but: + +- ``BOARD_BUTTON_PIN``: the number of the pin which connects to the + built-in button (labeled "BUT"). On the Maple, this is pin 38, but + it's not guaranteed to be the same in other boards. + See Also -------- diff --git a/docs/source/lang/api/hardwarespi.rst b/docs/source/lang/api/hardwarespi.rst new file mode 100644 index 0000000..c71b2c3 --- /dev/null +++ b/docs/source/lang/api/hardwarespi.rst @@ -0,0 +1,152 @@ +.. highlight:: cpp + +.. _lang-hardwarespi: + +HardwareSPI +=========== + +This class is used for creating objects to manage the Maple's built-in +SPI ports. The Maple has two SPI ports. The relevant pins +corresponding to each port's logic signals are documented in the +following table (and on the Maple silkscreen): + +.. _lang-hardwarespi-pinout: + +.. list-table:: + :header-rows: 1 + + * - Port number + - NSS + - MOSI + - MISO + - SCK + + * - 1 + - 10 + - 11 + - 12 + - 13 + + * - 2 + - 31 + - 32 + - 33 + - 34 + +If you use a SPI port, you cannot simultaneously use its associated +pins for other purposes. + +Library Documentation +--------------------- + +HardwareSPI Class Reference +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can use the SPI interface by including a declaration ``HardwareSPI +Spi(number);`` at the start of the sketch or program. The ``number`` +must be either 1 or 2 and specifies which port to use. Once this is +done, you can call any of the methods documented here using +``Spi.method(arguments)``; for example, ``Spi.send(0x13)`` would send +the value ``0x13`` into the port buffer to be transmitted as soon as +possible. + +.. cpp:class:: HardwareSPI + + Class for interacting with SPI. + +.. cpp:function:: HardwareSPI::HardwareSPI(uint32 spi_num) + + Construct an object for managing a SPI peripheral. ``spi_num`` + must be 1 or 2; see the :ref:`table above + ` for pinout information. + +.. cpp:function:: void HardwareSPI::begin(SPIFrequency freq, uint32 endianness, uint32 mode) + + Configure the baudrate of the given SPI port and set up the header + pins appropriately. + + Parameters: + + - ``freq``: one of the ``SPIFrequency`` values, given :ref:`below + `. + + - ``endianness``: either ``LSBFIRST`` (little-endian) or + ``MSBFIRST`` (big-endian). + + - ``mode``: one of 0, 1, 2, or 3, and specifies which SPI mode is + used. The mode number determines a combination of polarity and + phase according to the following table: + + .. list-table:: + :header-rows: 1 + + * - Mode + - Polarity + - Phase + + * - 0 + - 0 + - 0 + + * - 1 + - 0 + - 1 + + * - 2 + - 1 + - 0 + + * - 3 + - 1 + - 1 + + For more information on polarity and phase, see the + :ref:`external references, below `. + +.. cpp:function:: void HardwareSPI::begin() + + A convenience ``begin()``, equivalent to ``begin(SPI_1_125MHZ, + MSBFIRST, 0)``. + +.. cpp:function:: uint8 HardwareSpi::send(uint8 *data, uint32 length) + + Writes ``data`` into the port buffer to be transmitted as soon as + possible, where ``length`` is the number of bytes to send from + ``data``. Returns the last byte shifted back from slave. + +.. cpp:function:: uint8 HardwareSpi::send(uint8 data) + + Writes the single byte ``data`` into the port buffer to be + transmitted as soon as possible. Returns the data byte shifted + back from the slave. + +.. cpp:function:: uint8 HardwareSpi::recv() + + Reads a byte from the peripheral. Returns the next byte in the + buffer. + +SPI Speeds +^^^^^^^^^^ + +.. _lang-hardwarespi-spifrequency: + +The possible SPI speeds are configured using the ``SPIFrequency`` enum: + +.. doxygenenum:: SPIFrequency + +.. _lang-hardwarespi-seealso: + +See Also +-------- + +* `Wikipedia Article on Serial Peripheral Interface Bus (SPI) + `_ +* `Arduino reference on SPI + `_ +* `Hardcore SPI on Arduino `_ by kik64 +* STMicro documentation for STM32F103RB microcontroller: + + * `Datasheet `_ (pdf) + * `Reference Manual `_ (pdf) + + diff --git a/docs/source/lang/api/hardwaretimer.rst b/docs/source/lang/api/hardwaretimer.rst new file mode 100644 index 0000000..258471b --- /dev/null +++ b/docs/source/lang/api/hardwaretimer.rst @@ -0,0 +1,368 @@ +.. highlight:: cpp + +.. _lang-hardwaretimer: + +HardwareTimer +============= + +This class defines the public API for interfacing with the STM32's +built-in timer peripherals. More information on these peripherals +(including code examples) is available in the :ref:`timers reference +`. + +Library Documentation +--------------------- + +HardwareTimer Class Reference +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To interact with a particular timer, call one of the methods +documented below on one of the predefined ``HardwareTimer`` instances. +For example, to set the prescale factor on timer 1 to 5, call +``Timer1.setPrescaleFactor(5)``. + +.. cpp:class:: HardwareTimer + + Class for interacting with a timer. There are four predefined + instances available on the Maple: ``Timer1``, ``Timer2``, + ``Timer3``, and ``Timer4``. + +.. _lang-hardwaretimer-attachinterrupt: + +.. cpp:function:: void HardwareTimer::attachInterrupt(int channel, voidFuncPtr handler) + + Attach an interrupt handler to the given ``channel``. This + interrupt handler will be called when the timer's counter reaches + the given channel :ref:`compare ` + value. + + ``handler`` should be a function which takes no arguments and has + :ref:`void ` value; i.e. it should have signature :: + + void handler(void); + + You can later detach the interrupt using :ref:`detachInterrupt() + `. + + .. note:: The function (often called an *interrupt service + routine*, or ISR) should attempt to return as quickly as + possible. :ref:`Blinking the LED `, some + logic, :ref:`PWM ` updates, and :ref:`Serial + ` writes are fine; writing to + :ref:`SerialUSB ` or :ref:`waiting + ` for user input can take a long + time and prevent other interrupts from firing on time. + + Tip: if you have a :ref:`delay() ` in your + ISR, you're probably doing it wrong. + +.. cpp:function:: void HardwareTimer::attachCompare1Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(1, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare2Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(2, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare3Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(3, handler)``. + +.. cpp:function:: void HardwareTimer::attachCompare4Interrupt(voidFuncPtr handler) + + Equivalent to :ref:`attachInterrupt + `\ ``(4, handler)``. + +.. _lang-hardwaretimer-setchannelmode: + +.. cpp:function:: void HardwareTimer::setChannelMode(int channel, TimerMode mode) + + Set the given channel of this timer to the given :ref:`mode + `. The parameter ``channel`` is one of + 1, 2, 3, and 4, and corresponds to the compare channel you would + like to set. Refer to the full :ref:`pin mapping table + ` to match up timer channels and pin + numbers. + +.. cpp:function:: void HardwareTimer::setChannel1Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(1, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel2Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(2, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel3Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(3, mode)``. + +.. cpp:function:: void HardwareTimer::setChannel4Mode(TimerMode mode) + + Equivalent to :ref:`setChannelMode `\ + ``(4, mode)``. + +.. _lang-hardwaretimer-getcompare: + +.. cpp:function:: uint16 HardwareTimer::getCompare(int channel) + + Gets the compare value for the given ``channel``, from 1 to 4. See + :ref:`setCompare() `. + +.. cpp:function:: uint16 HardwareTimer::getCompare1() + + Equivalent to :ref:`getCompare `\ + ``(1, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare2() + + Equivalent to :ref:`getCompare `\ + ``(2, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare3() + + Equivalent to :ref:`getCompare `\ + ``(3, mode)``. + +.. cpp:function:: uint16 HardwareTimer::getCompare4() + + Equivalent to :ref:`getCompare `\ + ``(4, mode)``. + +.. _lang-hardwaretimer-setcompare: + +.. cpp:function:: void HardwareTimer::setCompare(int channel, uint16 compare) + + Sets the compare value for the given ``channel`` to ``compare``. + If ``compare`` is greater than this timer's overflow value, it will + be truncated to the overflow value. The default compare value is + 65,535 (the largest unsigned 16-bit integer value). + + When the counter reaches this value the interrupt for this channel + will fire if the given ``channel`` :ref:`mode + ` is ``TIMER_OUTPUTCOMPARE`` and + an interrupt is :ref:`attached + `. + + By default, this only changes the relative offsets between events + on a single timer ("phase"); they don't control the frequency with + which they occur. However, a common trick is to increment the + compare value manually in the interrupt handler so that the event + will fire again after the increment period. There can be a + different increment value for each channel, so this trick allows + events to be programmed at 4 different rates on a single + timer. Note that function call overheads mean that the smallest + increment rate is at least a few microseconds. + +.. cpp:function:: void HardwareTimer::setCompare1(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(1, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare2(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(2, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare3(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(3, compare)``. + +.. cpp:function:: void HardwareTimer::setCompare4(uint16 compare) + + Equivalent to :ref:`setCompare `\ + ``(4, compare)``. + +.. cpp:function:: uint16 HardwareTimer::getCount() + + Gets the current timer count. Due to function call overhead, the + return value will be increasingly accurate with smaller prescale + values. Also see :ref:`setCount() `. + +.. _lang-hardwaretimer-setcount: + +.. cpp:function:: void HardwareTimer::setCount(uint16 val) + + Set the timer's current count to ``val``. + + Note that there is some function call overhead associated with + calling this method, so using it is not a robust way to get + multiple timers to share a count value. + + If ``val`` exceeds the timer's :ref:`overflow value + `, it is truncated to the overflow + value. + + +.. _lang-hardwaretimer-detachinterrupt: + +.. cpp:function:: void HardwareTimer::detachInterrupt(int channel) + + Remove the interrupt handler attached to the given ``channel``, if + any. The handler will no longer be called by this timer. + +.. cpp:function:: void HardwareTimer::detachCompare1Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(1)``. + +.. cpp:function:: void HardwareTimer::detachCompare2Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(2)``. + +.. cpp:function:: void HardwareTimer::detachCompare3Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(3)``. + +.. cpp:function:: void HardwareTimer::detachCompare4Interrupt() + + Equivalent to :ref:`detachInterrupt + `\ ``(4)``. + +.. _lang-hardwaretimer-generateupdate: + +.. cpp:function:: void HardwareTimer::generateUpdate() + + Re-initializes the counter (to 0 in upcounting mode, which is the + default), and generates an update of the prescale and overflow + registers. + +.. _lang-hardwaretimer-getoverflow: + +.. cpp:function:: uint16 HardwareTimer::getOverflow() + + Gets the timer's overflow value. See :ref:`setOverflow() + `. + +.. _lang-hardwaretimer-setoverflow: + +.. cpp:function:: void HardwareTimer::setOverflow(uint16 val) + + Sets the timer overflow (or "reload") value to ``val``. + + When the timer's counter reaches this, value it resets to + zero. Its default value is 65535 (the largest unsigned 16-bit + integer); setting the overflow to anything lower will cause + interrupts to be called more frequently (see :ref:`setPeriod() + ` function for a shortcut). + + After the next :ref:`timer update + `, this number will be the + maximum value for the timer's channel compare values. + +.. _lang-hardwaretimer-pause: + +.. cpp:function:: void HardwareTimer::pause() + + Stop the timer's counter, without affecting its configuration. + + The timer will no longer count or fire interrupts after this + function is called, until it is resumed. This function is useful + during timer setup periods, in order to prevent interrupts from + firing before the timer is fully configured. + + Note that there is some function call overhead associated with this + method, so using it in concert with :ref:`resume() + ` is not a robust way to align multiple + timers to the same count value. + +.. _lang-hardwaretimer-setperiod: + +.. cpp:function:: uint16 HardwareTimer::setPeriod(uint32 microseconds) + + Configure the :ref:`prescaler + ` and :ref:`overflow + ` values to generate a timer reload + with a period as close to the given number of ``microseconds`` as + possible. + + The return value is the new overflow value, which may be used to + set channel compare values. However, if a clock that fires an + interrupt every given number of microseconds is all that is + desired, and the relative "phases" are unimportant, channel compare + values may all be set to 1. + +.. _lang-hardwaretimer-getprescalefactor: + +.. cpp:function:: uint16 HardwareTimer::getPrescaleFactor() + + Returns the timer's prescale factor. See + :ref:`setPrescaleFactor() `. + +.. _lang-hardwaretimer-setprescalefactor: + +.. cpp:function:: void HardwareTimer::setPrescaleFactor(uint16 factor) + + Set the timer's prescale factor to ``factor``. + + The prescaler acts as a clock divider to slow down the rate at + which the counter increments. + + For example, the system clock rate is 72MHz, so the counter will + reach 65535 in (13.89 nanoseconds) × (65535 counts) = (910.22 + microseconds), or about a thousand times a second. If the + prescaler equals 1098, then the clock rate is effectively 72MHz / + 1098 = 65.56KHz, and the counter will reach 65536 in (15.25 + microseconds) × (65536 counts) = (0.999 seconds), or about once + per second. + + The :ref:`setPeriod() ` method may + also be used as a convenient alternative. + +.. cpp:function:: void HardwareTimer::resume() + + Resume a paused timer, without affecting its configuration. + + The timer will resume counting and firing interrupts as + appropriate. + + Note that there is some function call overhead associated with + using this method, so using it in concert with :ref:`pause() + ` is not a robust way to align multiple + timers to the same count value. + +.. cpp:function:: timer_dev_num HardwareTimer::getTimerNum() + + Returns the :ref:`timer device number + ` associated with the timer. For + example, ``Timer1.getTimerNum()`` would return ``TIMER1``. + + In most cases, you should not need to use this function. If you do + use it, be careful; the constant ``TIMER1`` is *not equal* to the + number 1; similarly, ``TIMER2`` is *not* the number 2, etc. Be + sure to refer to the timer device number by name. + +.. _lang-hardwaretimer-modes: + +Timer Modes +^^^^^^^^^^^ +.. doxygenenum:: TimerMode + +.. _lang-hardwaretimer-timer-dev-num: + +Timer Device Numbers +^^^^^^^^^^^^^^^^^^^^ + +These provide a lower-level interface for interacting with timers. +They are mostly useful in context with the :ref:`getTimer() +` function. **Be careful** when using +these not to confuse e.g. ``TIMER1`` with the number 1; they are +different. + +.. doxygenenum:: timer_dev_num + +.. _lang-hardwaretimer-convenience: + +.. _lang-hardwaretimer-gettimer: + +Other Functions +^^^^^^^^^^^^^^^ +.. doxygenfunction:: getTimer diff --git a/docs/source/lang/api/interrupts.rst b/docs/source/lang/api/interrupts.rst new file mode 100644 index 0000000..58fd2cc --- /dev/null +++ b/docs/source/lang/api/interrupts.rst @@ -0,0 +1,47 @@ +.. highlight:: cpp + +.. _lang-interrupts: + +interrupts() +============ + +Re-enables interrupts (after they've been disabled by +:ref:`noInterrupts() `). Interrupts allow certain +important tasks to happen in the background, and certain interrupts +are enabled by default. + +Some functions will not work while interrupts are disabled, and both +incoming and outgoing communication may be ignored. Interrupts can +slightly disrupt the timing of code, however, and may be disabled for +particularly critical sections of code. + +Library Documentation +--------------------- + +.. doxygenfunction:: interrupts + +Example +------- + +:: + + void setup() {} + + void loop() { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + +See Also +-------- + +- :ref:`noInterrupts() ` +- :ref:`attachInterrupt() ` +- :ref:`detachInterrupt() ` +- :ref:`Timers reference ` +- :ref:`Timer API ` +- :ref:`External interrupts ` + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/api/isbuttonpressed.rst b/docs/source/lang/api/isbuttonpressed.rst new file mode 100644 index 0000000..dbff0c9 --- /dev/null +++ b/docs/source/lang/api/isbuttonpressed.rst @@ -0,0 +1,17 @@ +.. _lang-isbuttonpressed: + +isButtonPressed() +================= + +Check whether the board's built-in button (labeled BUT on the +silkscreen) is pressed. + +Library Documentation +--------------------- + +.. doxygenfunction:: isButtonPressed + +See Also +-------- + +- :ref:`lang-waitforbuttonpress` diff --git a/docs/source/lang/api/nointerrupts.rst b/docs/source/lang/api/nointerrupts.rst new file mode 100644 index 0000000..68f0498 --- /dev/null +++ b/docs/source/lang/api/nointerrupts.rst @@ -0,0 +1,47 @@ +.. highlight:: cpp + +.. _lang-nointerrupts: + +noInterrupts() +============== + +Description +----------- + +Disables interrupts. Interrupts allow certain important tasks to +happen in the background and are enabled by default. Some functions +will not work while interrupts are disabled, and incoming +communication may be ignored. Interrupts can slightly disrupt the +timing of code, however, and may be disabled for particularly critical +sections of code. + +Library Documentation +--------------------- + +.. doxygenfunction:: noInterrupts + +Example +------- + +:: + + void setup() {} + + void loop() { + noInterrupts(); + // critical, time-sensitive code here + interrupts(); + // other code here + } + +See Also +-------- + +- :ref:`interrupts() ` +- :ref:`attachInterrupt() ` +- :ref:`detachInterrupt() ` +- :ref:`Timers reference ` +- :ref:`Timer API ` +- :ref:`External interrupts ` + +.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/api/pinmode.rst b/docs/source/lang/api/pinmode.rst index b9095da..03cbcfa 100644 --- a/docs/source/lang/api/pinmode.rst +++ b/docs/source/lang/api/pinmode.rst @@ -13,6 +13,8 @@ Library Documentation .. doxygenfunction:: pinMode +.. _lang-pinmode-wiringpinmode: + .. doxygenenum:: WiringPinMode Discussion diff --git a/docs/source/lang/api/pwmwrite.rst b/docs/source/lang/api/pwmwrite.rst index 7a1d51f..2c858ab 100644 --- a/docs/source/lang/api/pwmwrite.rst +++ b/docs/source/lang/api/pwmwrite.rst @@ -11,6 +11,13 @@ pwmWrite(), the pin will output a steady square wave with the given duty cycle. You can change the duty cycle later by calling pwmWrite() again with the same pin and a different duty. +On the Maple, the pins which support PWM are: 0, 1, 2, 3, 5, 6, 7, 8, +9, 11, 12, 14, 24, 27, and 28. + +The Arduino function :ref:`analogWrite() ` is an +alias for ``pwmWrite()``, but it is badly named, and its use is +discouraged. + .. contents:: Contents :local: @@ -25,12 +32,11 @@ Example Sets the output to the LED proportional to the value read from the potentiometer:: - int ledPin = 13; // LED connected to pin 13 (Maple) int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { - pinMode(ledPin, OUTPUT); // sets the LED pin as output + pinMode(BOARD_LED_PIN, OUTPUT); // sets the LED pin as output pinMode(analogPin, PWM); // sets the potentiometer pin as PWM // output @@ -39,8 +45,9 @@ potentiometer:: void loop() { val = analogRead(analogPin); // read the input pin - analogWrite(ledPin, val / 16); // analogRead values go from 0 to 4095, - // analogWrite values from 0 to 65535 + analogWrite(BOARD_LED_PIN, val / 16); // analogRead values go from 0 + // to 4095, analogWrite values + // from 0 to 65535 } See Also diff --git a/docs/source/lang/api/serialusb.rst b/docs/source/lang/api/serialusb.rst index af3a7e0..e1d12bf 100644 --- a/docs/source/lang/api/serialusb.rst +++ b/docs/source/lang/api/serialusb.rst @@ -52,7 +52,9 @@ world!")``. .. cpp:class:: USBSerial Emulated serial-over-USB class. ``SerialUSB`` is the predefined - instance. + (singleton) instance. + +.. _lang-serialusb-begin: .. cpp:function:: USBSerial::begin() @@ -65,7 +67,12 @@ world!")``. .. cpp:function:: USBSerial::end() - Disables the USB peripheral. + Disables the USB peripheral. Note that using this function will + terminate all USB communications between the Maple and the USB + host; in particular, it implies that you won't be able to upload + any new programs without resetting the board or using + :ref:`perpetual bootloader mode + `. .. cpp:function:: unsigned int USBSerial::available() diff --git a/docs/source/lang/api/toggleled.rst b/docs/source/lang/api/toggleled.rst new file mode 100644 index 0000000..0cc20c2 --- /dev/null +++ b/docs/source/lang/api/toggleled.rst @@ -0,0 +1,17 @@ +.. _lang-toggleled: + +toggleLED() +=========== + +Switches the LED from off to on, or on to off. + +Library Documentation +--------------------- + +.. doxygenfunction:: toggleLED + +See Also +-------- + +- :ref:`BOARD_LED_PIN ` +- :ref:`togglePin() ` diff --git a/docs/source/lang/api/togglepin.rst b/docs/source/lang/api/togglepin.rst new file mode 100644 index 0000000..290718d --- /dev/null +++ b/docs/source/lang/api/togglepin.rst @@ -0,0 +1,17 @@ +.. _lang-togglepin: + +togglePin() +=========== + +Switches a digital output pin from :ref:`HIGH ` +to :ref:`LOW `, or from LOW to HIGH. + +Library Documentation +--------------------- + +.. doxygenfunction:: togglePin + +See Also +-------- + +- :ref:`toggleLED() ` diff --git a/docs/source/lang/api/waitforbuttonpress.rst b/docs/source/lang/api/waitforbuttonpress.rst new file mode 100644 index 0000000..34c5066 --- /dev/null +++ b/docs/source/lang/api/waitforbuttonpress.rst @@ -0,0 +1,17 @@ +.. _lang-waitforbuttonpress: + +waitForButtonPress() +==================== + +Wait for the board's built-in button (labeled BUT on the silkscreen) +to be pressed, possibly with timeout. + +Library Documentation +--------------------- + +.. doxygenfunction:: waitForButtonPress + +See Also +-------- + +- :ref:`lang-isbuttonpressed` diff --git a/docs/source/lang/cpp/built-in-types.rst b/docs/source/lang/cpp/built-in-types.rst new file mode 100644 index 0000000..1323db8 --- /dev/null +++ b/docs/source/lang/cpp/built-in-types.rst @@ -0,0 +1,95 @@ +.. highlight:: cpp + +.. _lang-built-in-types: + +================ + Built-in Types +================ + +This document serves as a reference for many of the built-in types +which are available when programming in the IDE. Programmers using +the :ref:`command-line tools ` will have access to +these types as long as they have imported `wirish.h +`_; +several are defined in in `libmaple_types.h +`_. + +.. _lang-built-in-types-integral: + +Integral types +-------------- + +.. cpp:type:: char + + 8-bit integer value. + +.. cpp:type:: short + + 16-bit integer value. + +.. cpp:type:: int + + 32-bit integer value. + +.. cpp:type:: long + + 64-bit integer value. + +.. cpp:type:: long long + + 64-bit integer value. + +.. cpp:type:: int8 + + Synonym for ``char``. + +.. cpp:type:: uint8 + + Synonym for ``unsigned char``. + +.. cpp:type:: int16 + + Synonym for ``short``. + +.. cpp:type:: uint16 + + Synonym for ``unsigned short``. + +.. cpp:type:: int32 + + Synonym for ``int``. + +.. cpp:type:: uint32 + + Synonym for ``unsigned int`` + +.. cpp:type:: int64 + + Synonym for ``long long`` + +.. cpp:type:: uint64 + + Synonym for ``unsigned long long``. + +Floating-Point Types +-------------------- + +.. cpp:type:: float + + 32-bit, IEEE 754 single-precision floating-point type. + +.. cpp:type:: double + + 64-bit, IEEE 754 double-precision floating-point type. + +Other Types +----------- + +.. cpp:type:: voidFuncPtr + + Pointer to a function that takes no arguments and returns nothing, i.e. + + :: + + typedef void (*voidFuncPtr)(void); + diff --git a/docs/source/lang/cpp/keywords.rst b/docs/source/lang/cpp/keywords.rst index e4ebe99..e3bc20d 100644 --- a/docs/source/lang/cpp/keywords.rst +++ b/docs/source/lang/cpp/keywords.rst @@ -94,7 +94,7 @@ The following keywords are used for built-in types. - :ref:`lang-float` - :ref:`lang-int` - :ref:`lang-long` -- :ref:`short ` +- :ref:`short ` - :ref:`void ` (not really a type, but used in the absence of one) diff --git a/docs/source/lang/cpp/numeric-types.rst b/docs/source/lang/cpp/numeric-types.rst deleted file mode 100644 index 9d2be48..0000000 --- a/docs/source/lang/cpp/numeric-types.rst +++ /dev/null @@ -1,79 +0,0 @@ -.. _lang-numeric-types: - -Numeric types -============= - -This document serves as a reference for all of the built-in numeric -types which are available when programming in the IDE. Programmers -using the :ref:`command-line tools ` will have access -to these types as long as they have imported ``wirish.h``; several are -defined in in `libmaple_types.h -`_. - -.. _lang-numeric-types-integral: - -Integral types --------------- - -.. cpp:type:: char - - 8-bit integer value. - -.. cpp:type:: short - - 16-bit integer value. - -.. cpp:type:: int - - 32-bit integer value. - -.. cpp:type:: long - - 64-bit integer value. - -.. cpp:type:: long long - - 64-bit integer value. - -.. cpp:type:: int8 - - Synonym for ``char``. - -.. cpp:type:: uint8 - - Synonym for ``unsigned char``. - -.. cpp:type:: int16 - - Synonym for ``short``. - -.. cpp:type:: uint16 - - Synonym for ``unsigned short``. - -.. cpp:type:: int32 - - Synonym for ``int``. - -.. cpp:type:: uint32 - - Synonym for ``unsigned int`` - -.. cpp:type:: int64 - - Synonym for ``long long`` - -.. cpp:type:: uint64 - - Synonym for ``unsigned long long``. - -Floating-Point Types --------------------- - -.. cpp:type:: float - - 32-bit, IEEE 754 single-precision floating-point type. - -.. cpp:type:: double - - 64-bit, IEEE 754 double-precision floating-point type. diff --git a/docs/source/lang/cpp/variables.rst b/docs/source/lang/cpp/variables.rst index 9094cd5..e6da0c9 100644 --- a/docs/source/lang/cpp/variables.rst +++ b/docs/source/lang/cpp/variables.rst @@ -37,7 +37,7 @@ named ``inputVariable2``, with an initial value of ``0``:: int inputVariable2 = 0; The Maple environment comes ready to use with many useful types of -variables. See the :ref:`built-in types ` page +variables. See the :ref:`built-in types ` page for more information. Here are a few examples of declaring variables of different types:: @@ -116,7 +116,7 @@ he goes past the left side of the screen, he reappears on the right:: x = x + 1; // x now contains -2,147,483,648; rolled over "right to left" Each numeric type's reference page includes its range. See the -:ref:`built-in types ` reference for links to each +:ref:`built-in types ` reference for links to each type's reference page. Using Variables @@ -149,7 +149,7 @@ See Also -------- - :ref:`lang-scope` -- :ref:`lang-numeric-types` +- :ref:`lang-built-in-types` .. rubric:: Footnotes diff --git a/docs/source/lang/cpp/void.rst b/docs/source/lang/cpp/void.rst index 88bd448..88c9c64 100644 --- a/docs/source/lang/cpp/void.rst +++ b/docs/source/lang/cpp/void.rst @@ -5,10 +5,12 @@ ``void`` ======== -The ``void`` keyword is used only in function declarations. It -indicates that the function is expected to return no information to -the function from which it was called, or that it expects no arguments -from its caller. +.. cpp:type:: void + + The ``void`` keyword is used in function declarations. It indicates + that the function is expected to return no information to the + function from which it was called, or that it expects no arguments + from its caller. Example ------- diff --git a/docs/source/lang/unimplemented/interrupts.rst b/docs/source/lang/unimplemented/interrupts.rst deleted file mode 100644 index 55b8e93..0000000 --- a/docs/source/lang/unimplemented/interrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-interrupts: - -interrupts() -============ - -Re-enables interrupts (after they've been disabled by -`noInterrupts `_\ ()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None - - - -Returns -------- - -None - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `noInterrupts `_\ () -- `attachInterrupt `_\ () -- `detachInterrupt `_\ () - - - - -.. include:: /lang/cc-attribution.txt diff --git a/docs/source/lang/unimplemented/nointerrupts.rst b/docs/source/lang/unimplemented/nointerrupts.rst deleted file mode 100644 index fb2e5f9..0000000 --- a/docs/source/lang/unimplemented/nointerrupts.rst +++ /dev/null @@ -1,59 +0,0 @@ -.. _lang-nointerrupts: - -noInterrupts() -============== - -Description ------------ - -Disables interrupts (you can re-enable them with interrupts()). -Interrupts allow certain important tasks to happen in the -background and are enabled by default. Some functions will not work -while interrupts are disabled, and incoming communication may be -ignored. Interrupts can slightly disrupt the timing of code, -however, and may be disabled for particularly critical sections of -code. - - - -Parameters ----------- - -None. - - - -Returns -------- - -None. - - - -Example -------- - -:: - - void setup() {} - - void loop() - { - noInterrupts(); - // critical, time-sensitive code here - interrupts(); - // other code here - } - - - -See Also --------- - - -- `interrupts `_\ () - - - - -.. include:: /lang/cc-attribution.txt diff --git a/docs/source/language-index.rst b/docs/source/language-index.rst index 7843cb0..e160e2b 100644 --- a/docs/source/language-index.rst +++ b/docs/source/language-index.rst @@ -4,37 +4,37 @@ Complete Language Index ======================= -This is the index of Maple's :ref:`language reference ` documentation. The 'Maple API' column includes language specific to Maple as a microcontroller development platform, while the language in 'C++ for Maple' is more generally applied. - -# Fix above explanation +This is the index of Maple's :ref:`language reference +` documentation. The "Maple API" column provides +API references for documented libmaple functionality. The "C++ for +Maple".. pages are adaptations of the Arduino C++ documentation to the +.. Maple, and are intended as a minimal reference/refresher for +.. programmers familiar with the Arduino language. .. _index-language-index-cpp: .. _index-language-index-api: -+--------------------------------------------+----------------------------------------------+ -| Maple API | :ref:`C++ for Maple ` | -| | | -+============================================+==============================================+ -| | | -| .. toctree:: | .. toctree:: | -| :maxdepth: 1 | :maxdepth: 1 | -| :glob: | :glob: | -| | | -| lang/api/* | lang/cpp/* | -| | | -+--------------------------------------------+----------------------------------------------+ - -.. Unfinished, unimplemented in libmaple: ++----------------------------------+------------------------------------+ +| Maple API | C++ for Maple | +| | | ++==================================+====================================+ +| | | +| .. toctree:: | .. toctree:: | +| :maxdepth: 1 | :maxdepth: 1 | +| :glob: | :glob: | +| | | +| lang/api/* | lang/cpp/* | +| | | ++----------------------------------+------------------------------------+ + +.. Unimplemented in libmaple or not part of current release: .. toctree:: :hidden: - lang/unimplemented/interrupts.rst - lang/unimplemented/nointerrupts.rst lang/unimplemented/notone.rst lang/unimplemented/pulsein.rst lang/unimplemented/shiftout.rst lang/unimplemented/stringclass.rst lang/unimplemented/stringobject.rst lang/unimplemented/tone.rst - diff --git a/docs/source/language.rst b/docs/source/language.rst index 8e5d454..018eb8c 100644 --- a/docs/source/language.rst +++ b/docs/source/language.rst @@ -52,8 +52,8 @@ Unique Maple Additions Maple Language Reference ------------------------ -The following table summarizes the available language features. A -more exhaustive index is available at the :ref:`language-index`. +The following table summarizes the available core language features. +A more exhaustive index is available at the :ref:`language-index`. +--------------------------------------------+----------------------------------------------+---------------------------------------------------+ | Structure | Variables | Functions | @@ -67,129 +67,129 @@ more exhaustive index is available at the :ref:`language-index`. |**Control Structures** |* :ref:`INPUT ` | | | | | :ref:`OUTPUT ` |* :ref:`digitalRead() ` | |* :ref:`if/else ` | | | -| |* :ref:`true ` | | | -|* :ref:`for ` | :ref:`false ` |**Analog I/O** | +| |* :ref:`true ` | |* :ref:`togglePin() ` | +|* :ref:`for ` | :ref:`false ` | | +| | |* :ref:`toggleLED() ` | +|* :ref:`switch/case ` |* :ref:`BOARD_LED_PIN ` | | | +| | :ref:`BOARD_BUTTON_PIN `|* :ref:`isButtonPressed() ` | +|* :ref:`while ` | | | +| |* :ref:`Constants |* :ref:`waitForButtonPress() | +|* :ref:`do...while ` | ` (:ref:`integers | ` | +| | `, :ref:`floating | | +|* :ref:`break ` | point `) |**Analog I/O** | | | | | -|* :ref:`switch/case ` |* :ref:`Constants |* :ref:`analogRead() ` | -| | ` (:ref:`integers | | -|* :ref:`while ` | `, :ref:`floating |* :ref:`pwmWrite() ` | -| | point `) | (:ref:`analogWrite() ` is | -|* :ref:`do...while ` | | also available, though its use is discouraged) | -| |**Data Types** | | -|* :ref:`break ` | | | -| | The size of each datatype, in bytes, is |**Advanced I/O** | -|* :ref:`continue ` | given in parentheses where appropriate. | | -| | |* tone(): TODO | -|* :ref:`return ` | *Note*: The ``word`` type is (deliberately) | | -| | :ref:`not supported `. |* noTone(): TODO | -|* :ref:`goto ` | | | -| |* :ref:`void ` |* shiftOut(): TODO | +|* :ref:`continue ` |**Data Types** |* :ref:`analogRead() ` | | | | | -|**Further syntax** |* :ref:`boolean ` (1 byte) |* pulseIn(): TODO | +|* :ref:`return ` | The size of each datatype, in bytes, is |* :ref:`pwmWrite() ` | +| | given in parentheses where appropriate. | (:ref:`analogWrite() ` is | +|* :ref:`goto ` | | also available, though its use is discouraged) | +| | *Note*: The ``word`` type is (deliberately) | | +| | :ref:`not supported `. | | +|**Further syntax** | |**Advanced I/O** | +| |* :ref:`void ` | | +|* :ref:`; (semicolon) ` | |* tone(): TODO | +| |* :ref:`boolean ` (1 byte) | | +|* :ref:`{} (curly braces) | |* noTone(): TODO | +| ` |* :ref:`char ` (1 byte) | | +| | |* shiftOut(): TODO | +|* :ref:`// (single-line comment) |* :ref:`unsigned char | | +| ` | ` (1 byte) |* pulseIn(): TODO | | | | | -|* :ref:`; (semicolon) ` |* :ref:`char ` (1 byte) | | -| | |**Time** | -|* :ref:`{} (curly braces) |* :ref:`unsigned char | | -| ` | ` (1 byte) |* :ref:`millis() ` | +|* :ref:`/\* \*/ (multi-line comment) |* :ref:`byte ` (1 byte) | | +| ` | |**Time** | +| |* :ref:`int ` (4 bytes) | | +|* :ref:`#define ` | |* :ref:`millis() ` | +| |* :ref:`unsigned int ` | | +|* :ref:`#include ` | (4 bytes) |* :ref:`micros() ` | | | | | -|* :ref:`// (single-line comment) |* :ref:`byte ` (1 byte) |* :ref:`micros() ` | -| ` | | | -| |* :ref:`int ` (4 bytes) |* :ref:`delay() ` | -|* :ref:`/\* \*/ (multi-line comment) | | | -| ` |* :ref:`unsigned int ` |* :ref:`delayMicroseconds() | -| | (4 bytes) | ` | -|* :ref:`#define ` | | | -| |* :ref:`long ` (8 bytes) | | -|* :ref:`#include ` | |**Math** | -| |* :ref:`unsigned long ` | | -| | (8 bytes) |* :ref:`min() ` | +| |* :ref:`long ` (8 bytes) |* :ref:`delay() ` | |**Arithmetic Operators** | | | -| |* :ref:`float ` (4 bytes) |* :ref:`max() ` | -|* :ref:`= ` | | | -| (assignment operator) |* :ref:`double ` (8 bytes) |* :ref:`abs() ` | +| |* :ref:`unsigned long ` |* :ref:`delayMicroseconds() | +|* :ref:`= ` | (8 bytes) | ` | +| (assignment operator) | | | +| |* :ref:`float ` (4 bytes) | | +|* :ref:`+ ` (addition) | |**Math** | +| |* :ref:`double ` (8 bytes) | | +|* :ref:`- ` | |* :ref:`min() ` | +| (subtraction) |* :ref:`Strings ` | | +| | |* :ref:`max() ` | +|* :ref:`* ` |* :ref:`Arrays ` | | +| (multiplication) | |* :ref:`abs() ` | +| |* :ref:`enum ` | | +|* :ref:`/ ` (division) | |* :ref:`constrain() ` | +| |* :ref:`Numeric types ` | | +|* :ref:`% ` (modulo) | |* :ref:`map() ` | +| |**Conversion** | | +| | |* :ref:`pow() ` | +|**Comparison Operators** |* :ref:`char() ` | | +| | |* :ref:`sqrt() ` | +|* :ref:`== ` (equal to) |* :ref:`byte() ` | | | | | | -|* :ref:`+ ` (addition) |* :ref:`Strings ` |* :ref:`constrain() ` | +|* :ref:`\!= ` |* :ref:`int() ` |**Trigonometry** | +| (not equal to) | | | +| |* :ref:`long() ` |* :ref:`sin() ` | +|* :ref:`< ` (less than) | | | +| |* :ref:`float() ` |* :ref:`cos() ` | +|* :ref:`> ` | | | +| (greater than) |* :ref:`double() ` |* :ref:`tan() ` | | | | | -|* :ref:`- ` |* :ref:`Arrays ` |* :ref:`map() ` | -| (subtraction) | | | -| |* :ref:`enum ` |* :ref:`pow() ` | -|* :ref:`* ` | | | -| (multiplication) |* :ref:`Numeric types ` |* :ref:`sqrt() ` | +|* :ref:`<= ` | | | +| (less than or equal to) |**Variable Scope & Qualifiers** |**Random Numbers** | | | | | -|* :ref:`/ ` (division) |**Conversion** | | -| | |**Trigonometry** | -|* :ref:`% ` (modulo) |* :ref:`char() ` | | -| | |* :ref:`sin() ` | -| |* :ref:`byte() ` | | -|**Comparison Operators** | |* :ref:`cos() ` | -| |* :ref:`int() ` | | -|* :ref:`== ` (equal to) | |* :ref:`tan() ` | -| |* :ref:`long() ` | | -|* :ref:`\!= ` | | | -| (not equal to) |* :ref:`float() ` |**Random Numbers** | +|* :ref:`>= ` |* :ref:`variables `, |* :ref:`randomSeed() ` | +| (greater than or equal to) | :ref:`scope ` | | +| | |* :ref:`random() ` | +| |* :ref:`static ` | | +|**Boolean Operators** | | | +| |* :ref:`volatile ` |**Bits and Bytes** | +|* :ref:`&& ` (and) | | | +| |* :ref:`const ` |* :ref:`lowByte() ` | +|* :ref:`|| ` (or) | | | +| | |* :ref:`highByte() ` is | +|* :ref:`\! ` (not) |**Utilities** | provided, though its use is discouraged. | | | | | -|* :ref:`< ` (less than) |* :ref:`double() ` |* :ref:`randomSeed() ` | -| | | | -|* :ref:`> ` | |* :ref:`random() ` | -| (greater than) |**Variable Scope & Qualifiers** | | -| | | | -|* :ref:`<= ` |* :ref:`variables `, |**Bits and Bytes** | -| (less than or equal to) | :ref:`scope ` | | -| | |* :ref:`lowByte() ` | -|* :ref:`>= ` |* :ref:`static ` | | -| (greater than or equal to) | |* :ref:`highByte() ` is | -| |* :ref:`volatile ` | provided, though its use is discouraged. | -| | | | -|**Boolean Operators** |* :ref:`const ` |* :ref:`bitRead() ` | -| | | | -|* :ref:`&& ` (and) | |* :ref:`bitWrite() ` | -| |**Utilities** | | -|* :ref:`|| ` (or) | |* :ref:`bitSet() ` | -| |* :ref:`sizeof() ` | | -|* :ref:`\! ` (not) | |* :ref:`bitClear() ` | -| | | | -| | |* :ref:`bit() ` | +| |* :ref:`sizeof() ` |* :ref:`bitRead() ` | |**Pointer Operators** | | | +| | |* :ref:`bitWrite() ` | +|* :ref:`* dereference operator | | | +| ` | |* :ref:`bitSet() ` | | | | | -|* :ref:`* dereference operator | |**External Interrupts** | +|* :ref:`& reference operator | |* :ref:`bitClear() ` | | ` | | | -| | |* :ref:`Reference Page ` | -|* :ref:`& reference operator | | | -| ` | |* :ref:`attachInterrupt() | -| | | ` | +| | |* :ref:`bit() ` | | | | | -|**Bitwise Operators** | |* :ref:`detachInterrupt() | -| | | ` | +|**Bitwise Operators** | | | +| | |**External Interrupts** | |* :ref:`& ` | | | -| (bitwise and) | | | -| | |**Interrupts** | -|* :ref:`| ` | | | -| (bitwise or) | |* interrupts(): TODO | +| (bitwise and) | |* :ref:`Reference Page ` | | | | | -|* :ref:`^ ` | |* noInterrupts(): TODO | -| (bitwise xor) | | | +|* :ref:`| ` | |* :ref:`attachInterrupt() | +| (bitwise or) | | ` | | | | | -|* :ref:`~ ` | |**Communication** | -| (bitwise not) | | | -| | |* :ref:`SerialUSB ` | -|* :ref:`\<\< ` | | | -| (shift left) | |* :ref:`Serial ` | +|* :ref:`^ ` | |* :ref:`detachInterrupt() | +| (bitwise xor) | | ` | | | | | -|* :ref:`>> ` | |**Looking for something else?** | -| (shift right) | | | -| | | See the :ref:`libraries` page for interfacing with| -| | | particular types of hardware. Maple links | -|**Compound Operators** | | against `newlib `_ | -| | | and allows the use of any of its functions; see | -|* :ref:`++ ` | | its documentation for more details. | -| (increment) | | | +|* :ref:`~ ` | | | +| (bitwise not) | |**Interrupts** | | | | | -|* :ref:`- - ` | | | -| (decrement) | | | +|* :ref:`\<\< ` | |* :ref:`interrupts() ` | +| (shift left) | | | +| | |* :ref:`noInterrupts() ` | +|* :ref:`>> ` | | | +| (shift right) | | | +| | |**Communication** | | | | | -|* :ref:`+= ` | | | -| (compound add) | | | +|**Compound Operators** | |* :ref:`SerialUSB ` | | | | | +|* :ref:`++ ` | |* :ref:`Serial ` | +| (increment) | | | +| | |**Looking for something else?** | +|* :ref:`- - ` | | | +| (decrement) | | See the :ref:`libraries` page for interfacing with| +| | | particular types of hardware. Maple links | +|* :ref:`+= ` | | against `newlib `_ | +| (compound add) | | and allows the use of any of its functions; see | +| | | its documentation for more details. | |* :ref:`-= | | | | ` (compound | | | | subtract) | | | @@ -222,6 +222,8 @@ more exhaustive index is available at the :ref:`language-index`. Missing Arduino Features ------------------------ +.. _langage-missing-analogreference: + **analogReference()** It is not possible to implement this function on the Maple @@ -256,8 +258,6 @@ Unimplemented Arduino Features The following Wiring/Arduino features are currently unimplemented on the Maple. However, they will be present in future versions: -- `interrupts() `_ -- `noInterrupts() `_ - `noTone() `_ - `pulseIn() `_ - `shiftOut() `_ @@ -272,7 +272,11 @@ the Maple. However, they will be present in future versions: C++ for Maple -------------- -If you haven't programmed in C++, or if you just need to jog your memory, you may want to check out our :ref:`C++ for Maple Index`. It covers programming ideas and C++ that will definitely come in handy. + +If you haven't programmed in C++, or if you just need to jog your +memory, you may want to check out our :ref:`Language Index +`. It provides some introductory coverage of +programming ideas and C++. .. _arduino_c_for_c_hackers: @@ -366,9 +370,7 @@ contains ``setup()`` and ``loop()``:: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } The second file contains the (not very useful) implementation for @@ -388,9 +390,7 @@ Then the results of the concatenation process might be :: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } int choose_a_pin(void); @@ -415,9 +415,7 @@ Which could plausibly be turned into the final source file :: } void loop() { - static int toggle = 0; - toggle ^= 1; - digitalWrite(the_pin, toggle); + togglePin(the_pin); } int choose_a_pin(void); @@ -441,7 +439,6 @@ Recommended Reading * `newlib Documentation `_ * STMicro documentation for STM32F103RB microcontroller: - * `All documents `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Programming Manual `_ (assembly language and register reference) diff --git a/docs/source/libraries.rst b/docs/source/libraries.rst index 567aec8..7623963 100644 --- a/docs/source/libraries.rst +++ b/docs/source/libraries.rst @@ -21,13 +21,69 @@ in the description of the library. .. contents:: Contents :local: +.. toctree:: + :hidden: + + libs/servo.rst + +.. _libraries-servo: + +Servo +----- + +The Servo library is provided for convenient control of RC +servomotors. For more information, see the :ref:`Servo ` +reference. + +**Compatibility Note** + +The Servo class provides a public interface identical to the Arduino +version's documented functionality (as of Arduino 0021), so in most +cases, this library will be a drop-in replacement. + +However, there are some differences, essentially at the level of +implementation details. + +The major difference is that while the Arduino implementation drives +the servos with "bit-banged" :ref:`PWM `, the Maple +implementation uses :ref:`timers ` to drive the PWM directly. + +Consequently, **the Maple implementation only allows Servo instances +to** :ref:`attach ` **to pins that support PWM**. + +To determine if a pin supports PWM (15 Maple pins do), you can either +check if "PWM" appears next to its number on the Maple silkscreen, or +consult the :ref:`pwmWrite() ` documentation. + +RC Servos expect a pulse approximately every 20ms. In the Maple +implementation, :ref:`periods ` are set +for entire timers, rather than individual channels. Thus, +``attach()``\ ing a Servo to a pin can interfere with other pins +associated with the same timer\ [#fard-servo]_. + +Because of this, we recommend connecting multiple servomotors to pins +which share a timer, in order to keep as many timers free for other +purposes as possible. Consult the :ref:`table provided in the timers +reference ` to match up pins and timer +channels. + +Another difference: although it is not publicly documented to do so, +the Arduino implementation of `attach() +`_ returns the timer +channel associated with the newly-attached pin, or 0 on failure (as of +Arduino 0021). The Maple implementation returns true on success, and +false on failure (and this is its documented behavior). + .. _libraries-liquid-crystal: LiquidCrystal ------------- +.. TODO 0.0.10 make our own LiquidCrystal docs + The LiquidCrystal library allows Maple to control LCD screens. For -more information, see the Arduino LiquidCrystal documentation. +more information, see the `Arduino LiquidCrystal documentation +`_. **Compatibility Note** @@ -57,6 +113,8 @@ the hardware i2c peripheral on the stm32 as well as the DMA for performance. Support for slave, smBUS, and multimaster modes are also slated for inclusion in the enhanced Wire port. +.. TODO 0.0.10 Wire docs in the cpp domain in own page under /libs/ + Wire Function Reference ^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,3 +185,10 @@ Wire Function Reference Returns the number of bytes which are still available for reading (with ``Wire.receive()``) from the last call to ``Wire.requestFrom(uint8, int)``. + +.. rubric:: Footnotes + +.. [#fard-servo] The Arduino implementation also captures timer + channels in groups as more Servo objects are attached, but the + details of which channels have their periods reset when are + slightly different. diff --git a/docs/source/libs/servo.rst b/docs/source/libs/servo.rst new file mode 100644 index 0000000..f92fd91 --- /dev/null +++ b/docs/source/libs/servo.rst @@ -0,0 +1,108 @@ +.. highlight:: cpp + +.. _libs-servo: + +======= + Servo +======= + +This documents the Servo library for controlling RC servomotors. It +is implemented as a thin layer over the built-in :ref:`timer +peripherals `. + +You can use this library in the :ref:`IDE ` by choosing the Servo +item under the Sketch > Import Library... menu. + +If you are using the :ref:`Unix toolchain `, the +library is located in ``$LIB_MAPLE_HOME/libraries/Servo/``. + +Servo Class Reference +--------------------- + +You can construct a Servo object by including the declaration :: + + Servo servo; + +in your sketch. This will create a Servo object called ``servo``. +You can then use any of its methods; for instance, to control a +servomotor attached to pin 9, you could write :: + + servo.attach(9); + +.. cpp:class:: Servo + + Class for controlling RC servomotors via :ref:`timers `. + +.. _libs-servo-attach: + +.. cpp:function:: bool Servo::attach(uint8 pin, uint16 min, uint16 max) + + Attach this Servo object to the given ``pin``. The pin must be + capable of PWM. You can check this by seeing if "PWM" is written + next to its number on the Maple silkscreen, or by consulting the + :ref:`pwmWrite() ` documentation. + + Sets this pin's :ref:`mode ` to :ref:`PWM + `, and returns true if successful. + Does nothing and returns false if the pin doesn't support PWM. + + Parameter ``min`` is the pulse width corresponding to 0 degrees; + ``max`` is the pulse width corresponding to 180 degrees (both are + in microseconds). + +.. cpp:function:: bool Servo::attach(uint8 pin) + + Equivalent to :ref:`attach(pin, 544, 2400) `. + +.. _libs-servo-attached: + +.. cpp:function:: int Servo::attached() const + + If currently attached (via :ref:`attach() `) to + a pin, returns that pin's number. Returns ``NOT_ATTACHED`` + otherwise. + +.. cpp:function:: bool Servo::detach() + + If this Servo object is currently attached to pin, stops driving + the servo by setting a zero pulse width (this is accomplished by + setting the associated :ref:`channel mode + ` to ``TIMER_DISABLED``). + + Subsequently, calling :ref:`attached() ` will + return ``NOT_ATTACHED``. + +.. cpp:function:: void Servo::write(unsigned int value) + + If ``value`` is less than ``SERVO_MAX_WRITE_ANGLE`` (which, for + Arduino compatibility, is 200), it's interpreted as an angle in + degrees. Otherwise, it's treated as a pulse width in microseconds. + + Drives the servo to target the given angle, based on a linear + interpolation of the ``min`` and ``max`` pulse widths determined + when :ref:`attach() ` was called. + + Be aware that some (especially lower-cost) servos have fairly + non-linear maps between pulse width and target angle. Make sure to + test your motor before relying on this method. + +.. cpp:function:: void Servo::writeMicroseconds(uint16 pulseWidth) + + Drives the servo using a ``pulseWidth``-microsecond pulse. + + If ``pulseWidth`` is outside of the [``min``, ``max``\ ] pulse + width range set during :ref:`attach() `, it will + be clamped to lie in this range. + +.. cpp:function:: int Servo::read() const + + Returns the servo's target angle, in degrees. This will be clamped + to lie between 0 (when the pulse width is at most ``min``) and 180 + (when the pulse width is at least ``max``). + +.. cpp:function:: uint16 Servo::readMicroseconds() const + + Returns the pulse width of the wave currently driving the servo, in + microseconds. This will be clamped to lie in the [``min``, + ``max``\ ] pulse width range set during :ref:`attach() + `. diff --git a/docs/source/pwm.rst b/docs/source/pwm.rst index fd72842..1a8f4df 100644 --- a/docs/source/pwm.rst +++ b/docs/source/pwm.rst @@ -28,9 +28,9 @@ Note that unlike the Arduino, the Maple does not have PWM functionality on pin D10; all other pins are :ref:`compatible `. -The following table shows which :ref:`timer ` generates which -PWM outputs. See the :ref:`pin mapping table ` -to track down exactly which timer *channel* corresponds to each pin. +The following table shows which timer can generate which PWM +outputs. See the :ref:`pin mapping table ` to +track down exactly which timer *channel* corresponds to each pin. .. _pwm-timer-table: @@ -65,12 +65,13 @@ The Maple has 16-bit PWM resolution, which means that the counter and variables can be as large as 65535, as opposed to 255 with 8-bit resolution. With a 72MHz clock rate, a PWM output could have maximum period of about one millisecond; using a :ref:`prescaler -` (clock divider) in front of the counter can increase -this maximum period. Setting the :ref:`period ` to -something other than the maximum value gives further control over the -total length of the waveform. However, this effectively limits the -resolution with which the duty can be modified: the duty must be less -than or equal to the period. +` (clock divider) in front of +the counter can increase this maximum period. Setting the +:ref:`period ` to something other than +the maximum value gives further control over the total length of the +waveform. However, this effectively limits the resolution with which +the duty can be modified: the duty must be less than or equal to the +period. Here are some commonly used PWM configurations (note that servos are notoriously variable, especially the lower cost models): @@ -93,82 +94,13 @@ notoriously variable, especially the lower cost models): Function Reference ------------------ -``pinMode(pin_num, PWM)`` - - This command is usually called from :ref:`setup() ` to - tell the microcontroller that pin_num should be configured to PWM - output. ``PWM`` implies regular driven OUTPUT; ``PWM_OPEN_DRAIN`` - is also available (see the list of :ref:`GPIO modes ` - for more information). - -.. _pwm-pwmwrite: - -``pwmWrite(pin_num, value)`` - - This command sets the PWM duty. User code is expected to determine - and honor the maximum value (based on the configured period). As a - convenience, ``analogWrite`` is an alias for ``pwmWrite`` to ease - porting Arduino code, though period and duty will have to be - recalibrated (see :ref:`compatibility `). - -.. _pwm-overflow: - -``Timer[1,2,3,4].setOverflow(overflow)`` - - This function sets the period ("reload" or "overflow") value for - an entire PWM timer bank. The value is 16bit (0 to 65535) and - determines the maximum value that can be written with - :ref:`pwmWrite() ` corresponding to 100% duty - cycle. This also affects the PWM frequency: the higher reload is, - the lower the PWM frequency will be. - - The PWM output pin starts HIGH, then the timer begins counting up - from zero (with frequency equal to 72MHz/:ref:`prescaler - `) until it hits the duty value, at which point it - drops to LOW. The timer then continues counting up until it hits - the total period (set with this function), at which point the - cycle starts again. - -.. _pwm-prescaler: - -``Timer[1,2,3,4].setPrescaleFactor(prescale)`` - - Find the appropriate timer for a given PWM header using the table - :ref:`above `, then set the prescaler. A - prescaler is a clock divider. The timer will normally count with - frequency equal to the STM32's normal clock (72MHz); this - corresponds to setting ``prescale`` to 1 (which is the default). - - If a longer frequency is desired, use a larger ``prescale`` value. - For instance, an 8MHz frequency can be achieved by setting - ``prescale`` to 9, since 72MHz / 9 = 8MHz. - - This function is normally called once from, :ref:`lang-setup`, but - the timer can be reconfigured with a new prescaler at any time. - - * Configure the prescaler and overflow values to generate a timer - * reload with a period as close to the given number of - * microseconds as possible. - * - * The return value is the overflow, which may be used to set - * channel compare values. However, if a clock that fires an - * interrupt every given number of microseconds is all that is - * desired, and the relative "phases" are unimportant, channel - * compare values may all be set to 1. - -``Timer[1,2,3,4].setPeriod(period_in_microseconds)`` - - Configure the prescaler and overflow values to generate a timer - reload with a period as close to the given number of microseconds - as possible. - - The return value is the overflow, which may be used to set channel - compare values. However, if a clock that fires an interrupt every - given number of microseconds is all that is desired, and the - relative "phases" are unimportant, channel compare values may all - be set to 1. - - +- :ref:`lang-pinmode` +- :ref:`lang-pwmwrite` +- :ref:`Timer API` (especially :ref:`setOverflow() + `, :ref:`setPrescaleFactor() + `, and :ref:`setPeriod() + `). +- :ref:`Timers reference `. Recommended Reading ------------------- @@ -182,6 +114,5 @@ Recommended Reading * `So You Want To Use PWM, Eh? `_ at Non-Lexical Vocables * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/spi.rst b/docs/source/spi.rst index ca9415c..ba43eef 100644 --- a/docs/source/spi.rst +++ b/docs/source/spi.rst @@ -4,54 +4,16 @@ SPI ===== -The Maple has two SPI ports. The first has NSS on D10, MOSI on D11, -MISO on D12, and SCK on D13. The second has NSS on D31, SCK on D32, -MISO on D33, and MOSI on D34. +The Serial Peripheral Interface Bus (SPI) is a serial data transfer +protocol useful for interacting with a wide variety of hardware +peripherals. -.. _spi-speeds: +The Maple has two SPI ports. The first has NSS on D10, MOSI on +D11, MISO on D12, and SCK on D13. The second has NSS on D31, SCK on +D32, MISO on D33, and MOSI on D34. -Each port can be configured at one of the following speeds: - -* ``SPI_18MHZ``: 18 MHz -* ``SPI_9MHZ``: 9 MHz -* ``SPI_4_5MHZ``: 4.5 MHz -* ``SPI_2_25MHZ``: 2.25 MHz -* ``SPI_1_125MHZ``: 1.124 MHz -* ``SPI_562_500KHZ``: 562.500 KHz -* ``SPI_281_250KHZ``: 281.250 KHz -* ``SPI_140_625KHZ``: 140.625 KHz - -.. contents:: Contents - :local: - -Function Reference ------------------- - -``HardwareSPI Spi(number);`` - - This declaration must be included at the start of any sketch or - program that uses the SPI interface. The argument number is either - 1 or 2 and specifies which port to use. - -``Spi.begin(freq, endianness, mode)`` - - ``begin`` is usually called in :ref:`lang-setup` to configure the - baudrate of the given SPI port and to set up the header pins - appropriately. ``freq`` is one of the set listed :ref:`above - `; ``endianness`` is either ``LSBFIRST`` or - ``MSBFIRST``; mode is one of 0, 1, 2, 3, and specifies which "SPI - Mode" is used (see specification docs linked below). - -``Spi.begin()`` - - A default ``begin`` with no arguments is provided for the lazy; it - is equivalent to ``Spi.begin(SPI_1_125MHZ, MSBFIRST, 0)``. - -``Spi.send(data, size)`` - - Writes data into the port buffer to be transmitted as soon as - possible. ``data`` should be an array of type ``byte*``; ``size`` - should be the number of elements in ``data``. +The public libmaple API for managing the SPI ports is the +:ref:`HardwareSpi ` class. Recommended Reading ------------------- @@ -63,7 +25,6 @@ Recommended Reading * `Hardcore SPI on Arduino `_ by kik64 * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/timers.rst b/docs/source/timers.rst index 948805b..56dd686 100644 --- a/docs/source/timers.rst +++ b/docs/source/timers.rst @@ -8,25 +8,46 @@ Timers There are four general purpose timers in the Maple microcontroller that can be configured to generate periodic or delayed events with minimal work done by the microcontroller. For example, the :ref:`PWM -` channels, once enabled, generate regular square-wave signals on -specific output pins that will continue even if the microcontroller is -busy crunching numbers or handling communications interrupts. By -attaching interrupt handlers to these channels (instead of just -changing the voltage on an external pin), more complex events like -printing to a serial port, updating a variable, or emitting a whale -mating call can be scheduled. You can even modify the configuration of -the timer itself at a regular interval; the possibilities are endless! - -The four timers each have four separate compare channels. Each timer -is a single 16-bit counter that can be configured with both a -prescaler and an overflow value. The prescaler acts as a divider of -the 72MHz system clock; without prescaling the counter would get up to -65536 (2 to the 16th power) and roll over more than a thousand times a -second; even with the full prescaler it rolls over about once a -minute. The overflow value is the maximum value the counter will go up -to. It defaults to the full 65535; smaller values will cause the -counter to reset to zero more frequently. +` channels can generate regular square-wave signals on specific +output pins without consuming extra clock cycles. By attaching +interrupt handlers to these channels (instead of just changing the +voltage on an external pin), more complex events can be scheduled. + +.. contents:: Contents + :local: + +Introduction +------------ + +.. _timers-prescale: + +The four timers each have four separate compare channels. Each channel +has an associated 16-bit counter that can be configured with a 16-bit +prescaler and a 16-bit overflow value. The prescaler determines how +fast the counter changes, while the overflow value determines when it +gets reset. + +The prescaler acts as a divider of the 72MHz system clock. That is, +with a prescaler of 1, the channel's counter increments with a +frequency of 72MHz, rolling over (passing the maximum 16-bit unsigned +integer value of 65,535) more than a thousand times a second. With a +prescaler of 7200, it has a frequency of (72/7200) MHz = 10 KHz, +rolling over approximately every 6.55 seconds. + +The overflow value is the maximum value the counter will go up to. It +defaults to the full 65,535; smaller values will cause the counter to +reset to zero more frequently. + +Whenever a channel's counter reaches its overflow value, an "update +event" interrupt is generated. You can configure the Maple to notify +you when this takes place, by registering an interrupt handler, which +is a function that will be called when the update event occurs. + +libmaple Reference +------------------ +The libmaple API for interacting with timers is documented at the +:ref:`HardwareTimer reference `. Caveats ------- @@ -36,9 +57,18 @@ Caveats **PWM Conflicts:** Because PWM functionality on a given pin depends on the configuration of the timer and channel, you must chose your channels carefully if you want to use both timer interrupts and PWM in -the same program. Refer to the full :ref:`pin mapping table -` to match up timer channels and Maple header -pin numbers. +the same program. Refer to the following table to match up timer +channels and Maple header pin numbers: + +.. _timers-pin-channel-map: + +.. csv-table:: + :header: Timer, Ch. 1 pin, Ch. 2 pin, Ch. 3 pin, Ch. 4 pin + + ``Timer1``, 6, 7, 8, -- + ``Timer2``, 2, 3, 1, 0 + ``Timer3``, 12, 11, 27, 28 + ``Timer4``, 5, 9, 14, 24 **Overhead:** there is some overhead associated with function and interrupt calls (loading and unloading the stack, preparing state, @@ -59,7 +89,8 @@ configuration being the same. auto-reset and communications functionality. This will require that you put your Maple into :ref:`perpetual bootloader mode ` before uploading a new - program to it. + program to it (or somehow causing your program to re-enable serial + over USB using :ref:`SerialUSB.begin() `). Disabling SysTick with ``systick_disable()`` helps as well. However, calling this function will break the ``micros()`` and @@ -73,33 +104,6 @@ a handler isn't going to block other interrupts from firing (e.g. USB, Serial, SysTick) if those other interrupts are important for your program. -.. _timers-modes: - -General Timer Modes -------------------- - -``TIMER_DISABLED`` - - Exactly what it sounds like: the timer stops counting, interrupts - are not called, and no state changes are output. - -``TIMER_PWM`` - - This is the default mode for pins after initialization. See the - :ref:`PWM docs ` for more information on this mode. - - .. note:: - - ``Timer1.setChannel1Mode(TIMER_PWM)`` may not work as expected; - if you want PWM functionality on a channel, make sure you don't - set it to something else. - -``TIMER_OUTPUTCOMPARE`` - - In this mode, the timer counts from 0 to the overflow value - repeatedly; every time the counter value reaches one of the - channel compare values, the corresponding interrupt is fired. - SysTick Peripheral ------------------ @@ -111,136 +115,22 @@ VGA code, where the timing jitters are transformed into visual jags in the image. The SysTick peripheral can be disabled by calling ``systick_disable()``, and re-enabled using ``systick_resume()``. -Function Reference ------------------- - -For all of these functions, ``Timer1`` can be replaced with -``Timer2``, ``Timer3``, or ``Timer4``; the channel numbers also range -from 1 to 4. - -``Timer1.pause()``/\ ``Timer1.resume()`` - - These functions start and stop the counter without affecting the - rest of the configuration. These functions can be used during the - setup period to prevent interrupts from firing before they are - completely configured. Note that there is some function call - overhead with these functions, so they are not a perfect way to - align multiple timers to the same count value. - -``Timer1.setOverflow(val)`` - - Sets the overflow (or "reload") value for the whole timer; when - the counter reaches this value it resets to zero. Defaults to - 65535 (the largest unsigned 16bit integer); setting it to anything - lower will cause interrupts to be called more frequently (see the - setPeriod function below for a shortcut). This number sets the - maximum value for the channel compare values. - -``Timer1.setPrescaleFactor(val)`` - - The prescaler acts as a clock divider to slow down the rate at - which the counter increments. For example, the system clock rate - is 72MHz, so the counter will reach 65535 in (13.89 nanoseconds) * - (65535 counts) = (910.22 microseconds), or about a thousand times - a second. If you set the prescaler to 1098, then the clock rate is - effectively 65.56KHz, and the counter will reach 65536 in (15.25 - microseconds) * (65536 counts) = (0.999 seconds), or just about - once a second. Use the :ref:`setPeriod ` - function below if you are allergic to math! - -.. _timers-set-period: - -``Timer1.setPeriod(val)`` - - This tricky trick will configure the prescaler and overflow values - to generate a timer reload with a period as close to val - microseconds as possible. It returns the chosen overflow value, - which you can then use to set the channel compare values - appropriately: if you just want the interrupts to fire when the - clock rolls over and you don't care about the relative "phase", - you can always set the channel compare values to 1. - - Remember: a microsecond is 1/1,000,000th of a second, or 1/1,000 - of a millisecond. The prescaler itself is 16bit, so the longest - period that can be configured is 1/(72MHz) * (2^32) = (59.65 - seconds) or about a minute. You can get around this by creating an - interrupt that increments a 32-bit variable, by using the - ``millis()`` function, or by interfacing with an external - real-time-clock chip. - -``Timer1.setCount(val)``/\ ``Timer1.getCount()`` - - These functions let you mess with the counter's brains - directly. You can probably make it not work if you try! The timer - is 16bit, so ``val`` and the return value of ``getCount`` are - ``uint16``. - -``Timer1.setChannel1Mode(MODE)`` - - This sets the given channel (here 1) of the given timer (here 1) - to the given mode. See the :ref:`list above ` for - possible values; for interrupts you want ``TIMER_OUTPUTCOMPARE``. - -``Timer1.setCompare1(val)`` - - Sets the compare value for the given channel; when the counter - reaches this value the interrupt for this channel will fire if the - channel is in output compare mode and an interrupt is attached. - - By default this only changes the relative offsets between events - on a single timer ("phase"); they don't control the frequency with - which they occur. However, a common trick is to increment the - compare value manually in the interrupt handler so that the event - will fire again after the increment period. There can be a - different increment value for each channel, so this trick allows - events to be programmed at 4 different rates on a single timer! - Note that function call overhead means that the smallest increment - rate is a couple microseconds. - -.. _timers-attachinterrupt: -.. _timers-detachinterrupt: - -``Timer1.attachCompare1Interrupt(function)``/\ ``Timer1.detachCompare1Interrupt()`` - - This is how to attach or disable an interrupt handlers to timer - channels; this what will get called when the counter reaches the - compare value set with ``setCompareN(val)``. ``function`` - (sometimes referred to as an ISR: "interrupt service routine") - should be of a type that does not accept or return any values - (C/C++ programmers: ``void (function*)(void)``). They are just - like any other function in your sketch/program and must be - initialized at the top of the file and defined below. - - ``function`` should try to do what it has to do as fast as - possible. Blinking the LED, some logic, PWM updates, and Serial - writes are fine; writing to SerialUSB or waiting for user input - can take a long time and other compare interrupts won't fire. Tip: - if you have a ``delay()`` in your ISR, you're probably doing it - wrong. - - Stay vigilant here... function pointers are serious business, and - once you go down that path you'll find yourself in a `forest of - parentheses `_ before you know it. - Code Examples ------------- LED blink ^^^^^^^^^ -\ :: +:: - #define LED_PIN 13 #define LED_RATE 500000 // in microseconds; should give 0.5Hz toggles void handler_led(void); - int toggle = 0; - void setup() { // Set up the LED to blink - pinMode(LED_PIN, OUTPUT); + pinMode(BOARD_LED_PIN, OUTPUT); // Setup Timer Timer2.setChannel1Mode(TIMER_OUTPUTCOMPARE); @@ -254,16 +144,13 @@ LED blink } void handler_led(void) { - toggle ^= 1; - digitalWrite(LED_PIN, toggle); + toggleLED(); } Racing Counters ^^^^^^^^^^^^^^^ -\ :: - - #define BUTTON_PIN 38 +:: void handler_count1(void); void handler_count2(void); @@ -274,7 +161,7 @@ Racing Counters void setup() { // Set up BUT for input - pinMode(BUTTON_PIN, INPUT_PULLUP); + pinMode(BOARD_BUTTON_PIN, INPUT_PULLUP); // Setup Counting Timers Timer3.setChannel1Mode(TIMER_OUTPUTCOMPARE); @@ -302,7 +189,7 @@ Racing Counters // Run... while BUT is held, pause Count2 for(int i = 0; i<1000; i++) { - if(digitalRead(BUTTON_PIN)) { + if(digitalRead(BOARD_BUTTON_PIN)) { Timer4.pause(); } else { Timer4.resume(); diff --git a/docs/source/troubleshooting.rst b/docs/source/troubleshooting.rst index 0c10d01..f3052d9 100644 --- a/docs/source/troubleshooting.rst +++ b/docs/source/troubleshooting.rst @@ -150,7 +150,11 @@ is several times more FLASH memory available for user programs. ``No DFU capable USB device found`` ----------------------------------- -This probably means you don't have a Maple plugged in or powered on! +This probably means you don't have a Maple plugged in or powered on. +Try unplugging and plugging your Maple or pressing the RESET button. + +This can also happen if you disable the USB peripheral, e.g. using +:ref:`SerialUSB.end() `. I have multiple Maples installed; how do I know which one will get flashed? --------------------------------------------------------------------------- @@ -161,19 +165,26 @@ board. There's no solution to this problem for now: you'll have to just plug in the Maples one at a time. If this is a real problem let us know and we'll see if we can come up with a better solution. +My flash programs don't seem to stick; they behave like they are RAM! +--------------------------------------------------------------------- + +If you have uploaded a program to RAM, this will take priority over +any program subsequently uploaded to flash. We'll be removing this +bug in a later version of the bootloader. For now, you can fix this +by unplugging your Maple to clear the contents of RAM, then plugging +it back in. + +If you are using the :ref:`Unix toolchain `, Make sure +you :command:`make clean` when switching between FLASH and RAM +targets; :command:`make` isn't smart enough to rebuild everything that +needs to be for the new target. + .. _troubleshooting-shell: ===================== Command-line issues ===================== -My flash programs don't seem to stick; they behave like they are RAM! ---------------------------------------------------------------------- - -Make sure you :command:`make clean` when switching between FLASH and -RAM targets; :command:`make` isn't smart enough to rebuild everything -that needs to be for the new target. - [Linux] ``cdc_acm 3-1:1.0: no more free acm devices`` ----------------------------------------------------- diff --git a/docs/source/usart.rst b/docs/source/usart.rst index c0334a9..3beb3fc 100644 --- a/docs/source/usart.rst +++ b/docs/source/usart.rst @@ -30,6 +30,5 @@ Recommended Reading * `Arduino reference on Serial `_ * STMicro documentation for STM32F103RB microcontroller: - * `All `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) diff --git a/docs/source/usb.rst b/docs/source/usb.rst index 5494b06..f502f31 100644 --- a/docs/source/usb.rst +++ b/docs/source/usb.rst @@ -39,7 +39,6 @@ Recommended Reading * Linux Kernel documentation for `USB ACM `_ and `USB Serial `_ * STMicro documentation for STM32F103RB microcontroller: - * `All documents `_ * `Datasheet `_ (pdf) * `Reference Manual `_ (pdf) * `Programming Manual `_ (pdf; assembly diff --git a/libmaple/libmaple_types.h b/libmaple/libmaple_types.h index a976a9e..8d216a8 100644 --- a/libmaple/libmaple_types.h +++ b/libmaple/libmaple_types.h @@ -45,6 +45,8 @@ typedef void (*voidFuncPtr)(void); #define __io volatile +#define ALWAYS_INLINE inline __attribute__((always_inline)) + #ifndef NULL #define NULL 0 #endif diff --git a/libmaple/timers.h b/libmaple/timers.h index 7589283..8d28f60 100644 --- a/libmaple/timers.h +++ b/libmaple/timers.h @@ -228,16 +228,16 @@ extern struct timer_dev timer_dev_table[]; /** * Initializes timer with prescale as the clock divisor. * - * @param timer Timer number. Valid values are TIMER1, TIMER2, - * TIMER3, TIMER4, and (on high-density devices) TIMER5, TIMER8. + * @param timer_num Timer number. * * @param prescale value in the range 1--65535 to use as a prescaler * for timer counter increment frequency. * + * @see timer_dev_num * @see timer_set_prescaler() * @see timer_set_mode() */ -void timer_init(timer_dev_num, uint16); +void timer_init(timer_dev_num timer_num, uint16 prescale); /** * Quickly disable all timers. Calling this function is faster than, @@ -250,34 +250,34 @@ void timer_disable_all(void); * this value is likely to be inaccurate if the counter is running * with a low prescaler. * - * @param timer the timer whose counter to return. + * @param timer_num the timer whose counter to return. * * @pre Timer has been initialized. */ -uint16 timer_get_count(timer_dev_num); +uint16 timer_get_count(timer_dev_num timer_num); /** * Sets the counter value for the given timer. * - * @param timer the timer whose counter to set. + * @param timer_num the timer whose counter to set. * * @param value the new counter value. * * @pre Timer has been initialized. */ -void timer_set_count(timer_dev_num,uint16); +void timer_set_count(timer_dev_num timer_num, uint16 value); /** * Stops the timer's counter from incrementing. Does not modify the * timer's mode or settings. * - * @param timer the timer to pause. + * @param timer_num the timer to pause. * * @see timer_resume() * * @pre Timer has been initialized. */ -void timer_pause(timer_dev_num); +void timer_pause(timer_dev_num timer_num); /** * Starts the counter for the given timer. Does not modify the @@ -285,17 +285,19 @@ void timer_pause(timer_dev_num); * first rising clock cycle after it has been re-enabled using this * function. * - * @param timer the timer to resume. + * @param timer_num the timer to resume. * * @see timer_pause() * * @pre Timer has been initialized. */ -void timer_resume(timer_dev_num); +void timer_resume(timer_dev_num timer_num); /** * Returns the prescaler for the given timer. * + * @param timer_num the timer whose prescaler to return. + * * @see timer_set_prescaler() * * @pre Timer has been initialized. @@ -308,7 +310,7 @@ uint16 timer_get_prescaler(timer_dev_num timer_num); * per clock cycle). This prescale does not take effect until the * next update event. * - * @param timer the timer whose prescaler to set. + * @param timer_num the timer whose prescaler to set. * * @param prescale the new prescaler. * @@ -331,10 +333,6 @@ uint16 timer_get_reload(timer_dev_num timer_num); * After this function returns, the timer's counter will reset to 0 * after it has reached the value max_reload. * - * @param timer the timer whose reload to set. - * - * @param max_reload the new reload value. - * * @pre Timer has been initialized. */ void timer_set_reload(timer_dev_num timer_num, uint16 max_reload); @@ -344,52 +342,32 @@ void timer_set_reload(timer_dev_num timer_num, uint16 max_reload); /** * Set the mode of an individual timer channel. * - * @param timer the timer whose channel mode to set. - * - * @param channel the channel whose mode to set (1 <= channel <= 4). - * - * @param mode the new mode value. Currently acceptable values - * include TIMER_DISABLED, TIMER_PWM, and TIMER_OUTPUTCOMPARE. Note - * that timer_disable_all() will disable all timers and all channels - * much more quickly than repeated calls to this function with mode - * TIMER_DISABLED. - * - * @see TimerMode - * * @see timer_disable_all() - * + * @see TimerMode + * @see timer_dev_num * @pre Timer has been initialized. */ -void timer_set_mode(timer_dev_num timer_num, uint8 channel_num, uint8 mode); +void timer_set_mode(timer_dev_num timer_num, uint8 channel, TimerMode mode); /** * Get the compare value for the given timer channel. * @see timer_set_compare_value() - * + * @see timer_dev_num * @pre Timer has been initialized. */ -uint16 timer_get_compare_value(timer_dev_num timer_num, uint8 channel_num); +uint16 timer_get_compare_value(timer_dev_num timer_num, uint8 channel); /** * Sets the compare value for a given timer channel. Useful for * scheduling when interrupt handlers will be called. * - * @param timer the timer whose channel compare to set. - * - * @param channel the channel whose compare to set (1 <= channel <= 4). - * - * @param compare the new compare value. This new value must be less - * than or equal to the timer's reload value. - * * @see timer_attach_interrupt() - * * @see timer_detach_interrupt() - * * @see timer_set_reload() - * + * @see timer_dev_num * @pre Timer has been initialized. */ -void timer_set_compare_value(timer_dev_num timer_num, uint8 channel_num, +void timer_set_compare_value(timer_dev_num timer_num, uint8 channel, uint16 value); /** @@ -397,44 +375,27 @@ void timer_set_compare_value(timer_dev_num timer_num, uint8 channel_num, * After this function returns, any handler attached to the given * channel will no longer be called. * - * @param timer the timer whose channel to detach the interrupt - * handler from. - * - * @param channel the channel from which to detach the interrupt handler. - * * @see timer_attach_interrupt() - * * @pre Timer has been initialized. + * @see timer_dev_num */ -void timer_detach_interrupt(timer_dev_num timer_num, uint8 channel_num); +void timer_detach_interrupt(timer_dev_num timer_num, uint8 channel); /** * Attach an interrupt handler for the given timer and channel. The - * handler will be called whenever the timer's counter reaches the - * compare value for the given timer and channel. - * - * @param timer the timer whose channel to register with an interrupt handler. - * - * @param channel the channel with which the new handler will be - * associated. timer_set_compare_value() can be used to set the value - * which the timer's counter must reach before handler is called (1 <= - * channel <= 4). - * - * @param handler the interrupt handler to call once the timer reaches - * the given channel's compare value. - * - * @pre The channel's mode must be set to TIMER_OUTPUTCOMPARE, or the - * interrupt handler will not get called. + * given ISR, handler, will be called whenever the timer's counter + * reaches the compare value for the given timer and channel. * * @see timer_set_compare_value() - * * @see timer_detach_interrupt() - * * @see timer_set_mode() - * + * @see timer_dev_num + * @see voidFuncPtr * @pre Timer has been initialized. + * @pre The channel's mode must be set to TIMER_OUTPUTCOMPARE, or the + * interrupt handler will not get called. */ -void timer_attach_interrupt(timer_dev_num timer_num, uint8 channel_num, +void timer_attach_interrupt(timer_dev_num timer_num, uint8 channel, voidFuncPtr handler); /** @@ -449,18 +410,18 @@ void timer_generate_update(timer_dev_num timer_num); /** * Turn on PWM with duty_cycle. * - * @param channel TIMERx_CHn_CCR, where x goes from 1 to NR_TIMERS, + * @param ccr TIMERx_CHn_CCR, where x goes from 1 to NR_TIMERS, * and n goes from 1 to 4. * - * @param duty_cycle 0--65535. duty_cycle=0 means always off; - * duty_cycle=65535 means always on. + * @param duty_cycle: A number between 0 and + * timer_get_compare_value(TIMERx, y), where x and y are as above. * * @pre Pin has been set to alternate function output. * * @pre Timer has been initialized. */ -static inline void timer_pwm_write_ccr(TimerCCR CCR, uint16 duty_cycle) { - *CCR = duty_cycle; +static inline void timer_pwm_write_ccr(TimerCCR ccr, uint16 duty_cycle) { + *ccr = duty_cycle; } #ifdef __cplusplus diff --git a/support/scripts/copy-to-ide b/support/scripts/copy-to-ide index 5bf52a4..c6b4c16 100755 --- a/support/scripts/copy-to-ide +++ b/support/scripts/copy-to-ide @@ -4,9 +4,7 @@ # repository. # Change this -DEST=`pwd`/../maple-ide/hardware/leaflabs/cores/maple/ - -ARCH=`uname -a` +DEST=`pwd`/../maple-ide-java/hardware/leaflabs/cores/maple FILES="LICENSE ./libmaple/*.h @@ -21,8 +19,8 @@ FILES="LICENSE ./wirish/*.cpp ./wirish/comm/*.cpp ./wirish/comm/*.h - ./support/ld/maple/ - ./support/ld/maple_native/ + ./support/ld/maple + ./support/ld/maple_native ./support/ld/libcs3-lanchon-stm32.a ./support/ld/names.inc" @@ -34,9 +32,9 @@ then exit -1 fi -echo "Then delete the old files..." -rm -r $DEST/*.c $DEST/*.cpp $DEST/*.h $DEST/*.cxx $DEST/*.ld $DEST/*.inc $DEST/*.a $DEST/maple/ $DEST/maple_native/ +echo "\nThen delete the old files..." +rm -r $DEST/*.c $DEST/*.cpp $DEST/*.h $DEST/*.cxx $DEST/*.inc $DEST/*.a $DEST/maple $DEST/maple_native -echo "Finally copy the new source files!" -cp -r $FILES $DEST +echo "\nFinally copy the new source files!" +cp -R $FILES $DEST echo "Done." diff --git a/wirish/HardwareTimer.cpp b/wirish/HardwareTimer.cpp index 92c6adf..354663e 100644 --- a/wirish/HardwareTimer.cpp +++ b/wirish/HardwareTimer.cpp @@ -221,7 +221,6 @@ HardwareTimer* getTimer(timer_dev_num timerNum) { return &Timer8; #endif default: - ASSERT(0); return 0; } } diff --git a/wirish/HardwareTimer.h b/wirish/HardwareTimer.h index c72175f..4034b1f 100644 --- a/wirish/HardwareTimer.h +++ b/wirish/HardwareTimer.h @@ -89,7 +89,7 @@ class HardwareTimer { * * Note that there is some function call overhead associated with * using this method, so using it in concert with - * HardwareTimer::resume() is not a robust way to align multiple + * HardwareTimer::pause() is not a robust way to align multiple * timers to the same count value. * * @see HardwareTimer::pause() @@ -103,7 +103,7 @@ class HardwareTimer { uint16 getPrescaleFactor(); /** - * Set the timer prescale. + * Set the timer's prescale factor. * * The prescaler acts as a clock divider to slow down the rate at * which the counter increments. @@ -155,7 +155,7 @@ class HardwareTimer { * Set the current timer count. * * Note that there is some function call overhead associated with - * callign this method, so using it is not a robust way to get + * calling this method, so using it is not a robust way to get * multiple timers to share a count value. * * @param val The new count value to set. If this value exceeds @@ -184,10 +184,6 @@ class HardwareTimer { /** * Set the given channel of this timer to the given mode. * - * Note: Timer1.setChannel1Mode(TIMER_PWM) may not work as - * expected; if you want PWM functionality on a channel make sure - * you don't set it to something else! - * * @param channel Timer channel, from 1 to 4 * @param mode Mode to set */ @@ -228,24 +224,24 @@ class HardwareTimer { */ uint16 getCompare(int channel); - /** Like getCompare(1) */ + /** Equivalent to getCompare(1) */ uint16 getCompare1(); - /** Like getCompare(2) */ + /** Equivalent to getCompare(2) */ uint16 getCompare2(); - /** Like getCompare(3) */ + /** Equivalent to getCompare(3) */ uint16 getCompare3(); - /** Like getCompare(4) */ + /** Equivalent to getCompare(4) */ uint16 getCompare4(); /** * Sets the compare value for the given channel. * * When the counter reaches this value the interrupt for this - * channel will fire if channel 1 mode is TIMER_OUTPUTCOMPARE and - * an interrupt is attached. + * channel will fire if the channel mode is TIMER_OUTPUTCOMPARE + * and an interrupt is attached. * * By default, this only changes the relative offsets between * events on a single timer ("phase"); they don't control the @@ -259,32 +255,33 @@ class HardwareTimer { * few microseconds. * * @param channel the channel whose compare to set, from 1 to 4. - * @param val The compare value to set. If greater than this - * timer's overflow value, it will be truncated to the - * overflow value. + * @param compare The compare value to set. If greater than this + * timer's overflow value, it will be truncated to + * the overflow value. * * @see TimerMode * @see HardwareTimer::setChannelMode() + * @see HardwareTimer::attachInterrupt() */ void setCompare(int channel, uint16 compare); /** - * Like setCompare(1, compare). + * Equivalent to setCompare(1, compare). */ void setCompare1(uint16 compare); /** - * Like setCompare(2, compare). + * Equivalent to setCompare(2, compare). */ void setCompare2(uint16 compare); /** - * Like setCompare(3, compare). + * Equivalent to setCompare(3, compare). */ void setCompare3(uint16 compare); /** - * Like setCompare(4, compare). + * Equivalent to setCompare(4, compare). */ void setCompare4(uint16 compare); @@ -313,25 +310,25 @@ class HardwareTimer { void attachInterrupt(int channel, voidFuncPtr handler); /** - * Like attachCompareInterrupt(1, handler). + * Equivalent to attachCompareInterrupt(1, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare1Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(2, handler). + * Equivalent to attachCompareInterrupt(2, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare2Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(3, handler). + * Equivalent to attachCompareInterrupt(3, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare3Interrupt(voidFuncPtr handler); /** - * Like attachCompareInterrupt(4, handler). + * Equivalent to attachCompareInterrupt(4, handler). * @see HardwareTimer::attachCompareInterrupt() */ void attachCompare4Interrupt(voidFuncPtr handler); @@ -346,25 +343,25 @@ class HardwareTimer { void detachInterrupt(int channel); /** - * Like detachInterrupt(1). + * Equivalent to detachInterrupt(1). * @see HardwareTimer::detachInterrupt() */ void detachCompare1Interrupt(void); /** - * Like detachInterrupt(2). + * Equivalent to detachInterrupt(2). * @see HardwareTimer::detachInterrupt() */ void detachCompare2Interrupt(void); /** - * Like detachInterrupt(3). + * Equivalent to detachInterrupt(3). * @see HardwareTimer::detachInterrupt() */ void detachCompare3Interrupt(void); /** - * Like detachInterrupt(4). + * Equivalent to detachInterrupt(4). * @see HardwareTimer::detachInterrupt() */ void detachCompare4Interrupt(void); @@ -394,6 +391,22 @@ extern HardwareTimer Timer5; extern HardwareTimer Timer8; #endif +/** + * Get one of the pre-instantiated HardwareTimer instances, given a + * timer device number. + * + * Be careful not to pass an actual number to this function. For + * example, getTimer(1) will not return Timer1. Use a real + * timer_dev_num, e.g. TIMER1, TIMER2, etc. + * + * @param timerNum the timer device number, e.g. TIMER1. + * + * @return Pointer to the HardwareTimer instance corresponding to the + * given timer device number. If timerNum is TIMER_INVALID, returns a + * null pointer. + * + * @see timer_dev_num + */ HardwareTimer* getTimer(timer_dev_num timerNum); #endif diff --git a/wirish/comm/HardwareSPI.h b/wirish/comm/HardwareSPI.h index 03d1ea1..7241d0b 100644 --- a/wirish/comm/HardwareSPI.h +++ b/wirish/comm/HardwareSPI.h @@ -29,18 +29,23 @@ #ifndef _HARDWARESPI_H_ #define _HARDWARESPI_H_ +/** + * Defines the possible SPI communication speeds. + */ typedef enum SPIFrequency { - SPI_18MHZ = 0, - SPI_9MHZ = 1, - SPI_4_5MHZ = 2, - SPI_2_25MHZ = 3, - SPI_1_125MHZ = 4, - SPI_562_500KHZ = 5, - SPI_281_250KHZ = 6, - SPI_140_625KHZ = 7, - MAX_SPI_FREQS = 8, + SPI_18MHZ = 0, /**< 18 MHz */ + SPI_9MHZ = 1, /**< 9 MHz */ + SPI_4_5MHZ = 2, /**< 4.5 MHz */ + SPI_2_25MHZ = 3, /**< 2.25 MHZ */ + SPI_1_125MHZ = 4, /**< 1.125 MHz */ + SPI_562_500KHZ = 5, /**< 562.500 KHz */ + SPI_281_250KHZ = 6, /**< 281.250 KHz */ + SPI_140_625KHZ = 7, /**< 140.625 KHz */ + MAX_SPI_FREQS = 8, /**< The number of SPI frequencies. */ } SPIFrequency; +/* Documented by hand in docs/source/lang/api/hardwarespi.rst; if you + make any changes, make sure to update this document. */ class HardwareSPI { private: uint32 spi_num; diff --git a/wirish/ext_interrupts.h b/wirish/ext_interrupts.h index 057c0d3..304e267 100644 --- a/wirish/ext_interrupts.h +++ b/wirish/ext_interrupts.h @@ -86,7 +86,7 @@ void detachInterrupt(uint8 pin); * * @see noInterrupts() */ -static inline __attribute__((always_inline)) void interrupts() { +static ALWAYS_INLINE void interrupts() { nvic_globalirq_enable(); } @@ -100,7 +100,7 @@ static inline __attribute__((always_inline)) void interrupts() { * * @see interrupts() */ -static inline __attribute__((always_inline)) void noInterrupts() { +static ALWAYS_INLINE void noInterrupts() { nvic_globalirq_disable(); } diff --git a/wirish/io.h b/wirish/io.h index 547dc8e..2d22dcd 100644 --- a/wirish/io.h +++ b/wirish/io.h @@ -145,7 +145,7 @@ void digitalWrite(uint8 pin, uint8 value); * @return LOW or HIGH. * @see pinMode() */ -uint32 digitalRead(uint8); +uint32 digitalRead(uint8 pin); /** * Read an analog value from pin. This function blocks during ADC diff --git a/wirish/wirish_math.h b/wirish/wirish_math.h index 4156722..14614ba 100644 --- a/wirish/wirish_math.h +++ b/wirish/wirish_math.h @@ -79,8 +79,10 @@ long random(long min, long max); * @return the mapped value. */ /* TODO: profile code bloat due to inlining this */ -inline long map(long x, long in_min, long in_max, long out_min, long out_max) { - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +inline long map(long value, long fromStart, long fromEnd, + long toStart, long toEnd) { + return (value - fromStart) * (toEnd - toStart) / (fromEnd - fromStart) + + toStart; } #define PI 3.1415926535897932384626433832795 -- cgit v1.2.3 From d5ad2a27f4e69e6cc9324331945937c983c30366 Mon Sep 17 00:00:00 2001 From: Marti Bolivar Date: Tue, 21 Dec 2010 03:58:22 -0500 Subject: removed flush() from SerialUSB docs. --- docs/source/lang/api/serialusb.rst | 6 ------ 1 file changed, 6 deletions(-) (limited to 'docs/source/lang') diff --git a/docs/source/lang/api/serialusb.rst b/docs/source/lang/api/serialusb.rst index e1d12bf..3bb8c00 100644 --- a/docs/source/lang/api/serialusb.rst +++ b/docs/source/lang/api/serialusb.rst @@ -87,12 +87,6 @@ world!")``. `), the call will block until one becomes available. -.. cpp:function:: USBSerial::flush() - - Removes the contents of the Serial's associated input buffer. That - is, clears any buffered characters, so that the next character read - is guaranteed to be new. - .. cpp:function:: USBSerial::print(unsigned char b) Print the given byte over the USB connection. -- cgit v1.2.3