diff --git a/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Parent_Of_Entities.adoc b/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Parent_Of_Entities.adoc index c0c06e710..4fdc98960 100644 --- a/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Parent_Of_Entities.adoc +++ b/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Parent_Of_Entities.adoc @@ -85,7 +85,7 @@ http://arduino.cc[serialEvent()] [role="language"] // Whenever you want to link to another Reference term, or more in general to a relative link, -// use the syntax shown below. Please note that the file format is subsituted by attribute. +// use the syntax shown below. Please note that the file format is substituted by attribute. // Please note that you always need to replace spaces that you might find in folder/file names with %20 // The entire link to Reference pages must be lower case, regardless of the case of the folders and files in this repository. * #LANGUAGE# link:../AsciiDoc_Template-Single_Entity[Single Entity] diff --git a/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Single_Entity.adoc b/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Single_Entity.adoc index aa4f95051..a9e23d242 100644 --- a/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Single_Entity.adoc +++ b/AsciiDoc_sample/Reference_Terms/AsciiDoc_Template-Single_Entity.adoc @@ -110,7 +110,7 @@ image::http://arduino.cc/en/uploads/Main/ArduinoUno_R3_Front_450px.jpg[caption=" [role="language"] // Whenever you want to link to another Reference term, or more in general to a relative link, -// use the syntax shown below. Please note that the file format is subsituted by attribute. +// use the syntax shown below. Please note that the file format is substituted by attribute. // Please note that you always need to replace spaces that you might find in folder/file names with %20 // The entire link to Reference pages must be lower case, regardless of the case of the folders and files in this repository. // For language tag, items will be automatically generated for any other item of the same subcategory, diff --git a/LICENSE.md b/LICENSE.md index c90487cb0..53764dac4 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -264,7 +264,7 @@ subject to and limited by the following restrictions: UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, -INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, +INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION diff --git a/Language/Functions/Advanced IO/pulseIn.adoc b/Language/Functions/Advanced IO/pulseIn.adoc index 964cb7a4f..5252f6814 100644 --- a/Language/Functions/Advanced IO/pulseIn.adoc +++ b/Language/Functions/Advanced IO/pulseIn.adoc @@ -20,6 +20,8 @@ subCategories: [ "Advanced I/O" ] Reads a pulse (either `HIGH` or `LOW`) on a pin. For example, if `value` is `HIGH`, `pulseIn()` waits for the pin to go from `LOW` to `HIGH`, starts timing, then waits for the pin to go `LOW` and stops timing. Returns the length of the pulse in microseconds or gives up and returns 0 if no complete pulse was received within the timeout. 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. + +NOTE: if the optional timeout is used code will execute faster. [%hardbreaks] @@ -32,7 +34,7 @@ The timing of this function has been determined empirically and will probably sh [float] === Parameters `pin`: the number of the Arduino pin on which you want to read the pulse. Allowed data types: `int`. + -`value`: type of pulse to read: either link:../../../variables/constants/constants[HIGH] or link:../../../variables/constants/constants[LOW]. Allowed data types: `int`. + +`value`: type of pulse to read: either link:../../../variables/constants/highlow/[HIGH] or link:../../../variables/constants/highlow/[LOW]. Allowed data types: `int`. + `timeout` (optional): the number of microseconds to wait for the pulse to start; default is one second. Allowed data types: `unsigned long`. diff --git a/Language/Functions/Advanced IO/pulseInLong.adoc b/Language/Functions/Advanced IO/pulseInLong.adoc index 2517f6533..1fdc88a1c 100644 --- a/Language/Functions/Advanced IO/pulseInLong.adoc +++ b/Language/Functions/Advanced IO/pulseInLong.adoc @@ -34,7 +34,7 @@ The timing of this function has been determined empirically and will probably sh [float] === Parameters `pin`: the number of the Arduino pin on which you want to read the pulse. Allowed data types: `int`. + -`value`: type of pulse to read: either link:../../../variables/constants/constants[HIGH] or link:../../../variables/constants/constants[LOW]. Allowed data types: `int`. + +`value`: type of pulse to read: either link:../../../variables/constants/highlow/[HIGH] or link:../../../variables/constants/highlow/[LOW]. Allowed data types: `int`. + `timeout` (optional): the number of microseconds to wait for the pulse to start; default is one second. Allowed data types: `unsigned long`. diff --git a/Language/Functions/Advanced IO/tone.adoc b/Language/Functions/Advanced IO/tone.adoc index 56c65bbc5..3468cd109 100644 --- a/Language/Functions/Advanced IO/tone.adoc +++ b/Language/Functions/Advanced IO/tone.adoc @@ -17,7 +17,7 @@ subCategories: [ "Advanced I/O" ] [float] === 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 link:../noTone[noTone()]. The pin can be connected to a piezo buzzer or other speaker to play tones. +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 link:../notone[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. @@ -56,7 +56,10 @@ Nothing [float] === Notes and Warnings -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. + +* 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. +* This function is non-blocking, which means that even if you provide the `duration` parameter the sketch execution will continue immediately even if the tone hasn't finished playing. + [%hardbreaks] -- @@ -75,11 +78,11 @@ If you want to play different pitches on multiple pins, you need to call `noTone [role="example"] -* #EXAMPLE# http://arduino.cc/en/Tutorial/Tone[Tone Melody^] -* #EXAMPLE# http://arduino.cc/en/Tutorial/tonePitchFollower[Pitch Follower^] -* #EXAMPLE# http://arduino.cc/en/Tutorial/Tone3[Tone Keyboard^] -* #EXAMPLE# http://arduino.cc/en/Tutorial/Tone4[Tone Multiple^] -* #EXAMPLE# http://arduino.cc/en/Tutorial/PWM[PWM^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody[Tone Melody^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/tonePitchFollower[Pitch Follower^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneKeyboard[Tone Keyboard^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMultiple[Tone Multiple^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/PWM[PWM^] -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Analog IO/analogRead.adoc b/Language/Functions/Analog IO/analogRead.adoc index 929b1cc8a..8eac217a5 100644 --- a/Language/Functions/Analog IO/analogRead.adoc +++ b/Language/Functions/Analog IO/analogRead.adoc @@ -20,19 +20,23 @@ On ATmega based boards (UNO, Nano, Mini, Mega), it takes about 100 microseconds [options="header"] |=================================================== -|Board |Operating voltage |Usable pins |Max resolution -|Uno |5 Volts |A0 to A5 |10 bits -|Mini, Nano |5 Volts |A0 to A7 |10 bits -|Mega, Mega2560, MegaADK |5 Volts |A0 to A14 |10 bits -|Micro |5 Volts |A0 to A11* |10 bits -|Leonardo |5 Volts |A0 to A11* |10 bits -|Zero |3.3 Volts |A0 to A5 |12 bits** -|Due |3.3 Volts |A0 to A11 |12 bits** -|MKR Family boards |3.3 Volts |A0 to A6 |12 bits** +|Board |Operating voltage |Usable pins |Max resolution +|UNO R3 |5 Volts |A0 to A5 |10 bits +|UNO R4 (Minima, WiFi) |5 Volts |A0 to A5 |14 bits** +|Mini |5 Volts |A0 to A7 |10 bits +|Nano, Nano Every |5 Volts |A0 to A7 |10 bits +|Nano 33 (IoT, BLE, RP2040, ESP32)|3.3 Volts |A0 to A7 |12 bits** +|Mega, Mega2560, MegaADK |5 Volts |A0 to A14 |10 bits +|Micro |5 Volts |A0 to A11* |10 bits +|Leonardo |5 Volts |A0 to A11* |10 bits +|Zero |3.3 Volts |A0 to A5 |12 bits** +|Due |3.3 Volts |A0 to A11 |12 bits** +|GIGA R1 |3.3 Volts |A0 to A11 |16 bits** +|MKR Family boards |3.3 Volts |A0 to A6 |12 bits** |=================================================== *A0 through A5 are labelled on the board, A6 through A11 are respectively available on pins 4, 6, 8, 9, 10, and 12 + -**The default `analogRead()` resolution for these boards is 10 bits, for compatibility. You need to use link:../../zero-due-mkr-family/analogreadresolution[analogReadResolution()] to change it to 12 bits. +**The default `analogRead()` resolution for these boards is 10 bits, for compatibility. You need to use link:../../zero-due-mkr-family/analogreadresolution[analogReadResolution()] to change it to a higher resolution. [%hardbreaks] @@ -43,7 +47,7 @@ On ATmega based boards (UNO, Nano, Mini, Mega), it takes about 100 microseconds [float] === Parameters -`pin`: the name of the analog input pin to read from (A0 to A5 on most boards, A0 to A6 on MKR boards, A0 to A7 on the Mini and Nano, A0 to A15 on the Mega). +`pin`: the name of the analog input pin to read from. [float] diff --git a/Language/Functions/Zero, Due, MKR Family/analogReadResolution.adoc b/Language/Functions/Analog IO/analogReadResolution.adoc similarity index 84% rename from Language/Functions/Zero, Due, MKR Family/analogReadResolution.adoc rename to Language/Functions/Analog IO/analogReadResolution.adoc index 8dbf51d92..8a935374e 100644 --- a/Language/Functions/Zero, Due, MKR Family/analogReadResolution.adoc +++ b/Language/Functions/Analog IO/analogReadResolution.adoc @@ -1,7 +1,7 @@ --- title: analogReadResolution() categories: [ "Functions" ] -subCategories: [ "Zero, Due & MKR Family" ] +subCategories: [ "Analog I/O" ] --- @@ -16,11 +16,12 @@ subCategories: [ "Zero, Due & MKR Family" ] [float] === Description -analogReadResolution() is an extension of the Analog API for the Arduino Due, Zero and MKR Family. +analogReadResolution() is an extension of the Analog API for the Zero, Due, MKR family, Nano 33 (BLE and IoT) and Portenta. Sets the size (in bits) of the value returned by `analogRead()`. It defaults to 10 bits (returns values between 0-1023) for backward compatibility with AVR based boards. -The *Due, Zero and MKR Family* boards have 12-bit ADC capabilities that can be accessed by changing the resolution to 12. This will return values from `analogRead()` between 0 and 4095. +The *Zero, Due, MKR family and Nano 33 (BLE and IoT)* boards have 12-bit ADC capabilities that can be accessed by changing the resolution to 12. This will return values from `analogRead()` between 0 and 4095. + +The *Portenta H7* has a 16 bit ADC, which will allow values between 0 and 65535. [%hardbreaks] @@ -31,7 +32,7 @@ The *Due, Zero and MKR Family* boards have 12-bit ADC capabilities that can be a [float] === Parameters -`bits`: determines the resolution (in bits) of the value returned by the `analogRead()` function. You can set this between 1 and 32. You can set resolutions higher than 12 but values returned by `analogRead()` will suffer approximation. See the note below for details. +`bits`: determines the resolution (in bits) of the value returned by the `analogRead()` function. You can set this between 1 and 32. You can set resolutions higher than the supported 12 or 16 bits, but values returned by `analogRead()` will suffer approximation. See the note below for details. [float] diff --git a/Language/Functions/Analog IO/analogReference.adoc b/Language/Functions/Analog IO/analogReference.adoc index 31ae3d39c..0e44b5881 100644 --- a/Language/Functions/Analog IO/analogReference.adoc +++ b/Language/Functions/Analog IO/analogReference.adoc @@ -22,11 +22,20 @@ Configures the reference voltage used for analog input (i.e. the value used as t Arduino AVR Boards (Uno, Mega, Leonardo, etc.) * DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards) -* INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328P and 2.56 volts on the ATmega32U4 and ATmega8 (not available on the Arduino Mega) +* INTERNAL: a built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328P and 2.56 volts on the ATmega32U4 and ATmega8 (not available on the Arduino Mega) * INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only) * INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only) * EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference. +Arduino Renesas Boards (UNO R4, Portenta C33) + +* AR_DEFAULT: the default analog reference of 5 volts. +* AR_INTERNAL: A built-in reference, equal to 1.5 Volts on the RA4M1 of the UNO R4 +* AR_INTERNAL_1_5V: A built-in reference, equal to 1.5 V on the R7FA6M5 of the Portenta C33 +* AR_INTERNAL_2_0V: A built-in reference, equal to 2.0 V on the R7FA6M5 of the Portenta C33 +* AR_INTERNAL_2_5V: A built-in reference, equal to 2.5 V on the R7FA6M5 of the Portenta C33 +* AR_EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference. + Arduino SAMD Boards (Zero, etc.) * AR_DEFAULT: the default analog reference of 3.3V @@ -52,6 +61,13 @@ Arduino SAM Boards (Due) * AR_DEFAULT: the default analog reference of 3.3V. This is the only supported option for the Due. +Arduino Mbed OS Nano Boards (Nano 33 BLE), Arduino Mbed OS Edge Boards (Edge Control) + +* AR_VDD: the default 3.3 V reference +* AR_INTERNAL: built-in 0.6 V reference +* AR_INTERNAL1V2: 1.2 V reference (internal 0.6 V reference with 2x gain) +* AR_INTERNAL2V4: 2.4 V reference (internal 0.6 V reference with 4x gain) + [%hardbreaks] diff --git a/Language/Functions/Analog IO/analogWrite.adoc b/Language/Functions/Analog IO/analogWrite.adoc index 28daf1085..36894922e 100644 --- a/Language/Functions/Analog IO/analogWrite.adoc +++ b/Language/Functions/Analog IO/analogWrite.adoc @@ -17,22 +17,31 @@ subCategories: [ "Analog I/O" ] [float] === Description -Writes an analog value (http://arduino.cc/en/Tutorial/PWM[PWM wave]) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to `analogWrite()`, the pin will generate a steady rectangular wave of the specified duty cycle until the next call to `analogWrite()` (or a call to `digitalRead()` or `digitalWrite()`) on the same pin. +Writes an analog value (http://arduino.cc/en/Tutorial/PWM[PWM wave]) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to `analogWrite()`, the pin will generate a steady rectangular wave of the specified duty cycle until the next call to `analogWrite()` (or a call to `digitalRead()` or `digitalWrite()`) on the same pin. + [options="header"] -|==================================================================================================== -| Board | PWM Pins | PWM Frequency -| Uno, Nano, Mini | 3, 5, 6, 9, 10, 11 | 490 Hz (pins 5 and 6: 980 Hz) -| Mega | 2 - 13, 44 - 46 | 490 Hz (pins 4 and 13: 980 Hz) -| Leonardo, Micro, Yún | 3, 5, 6, 9, 10, 11, 13 | 490 Hz (pins 3 and 11: 980 Hz) -| Uno WiFi Rev.2 | 3, 5, 6, 9, 10 | 976 Hz -| MKR boards * | 0 - 8, 10, A3 (18), A4 (19) | 732 Hz -| MKR1000 WiFi * | 0 - 8, 10, 11, A3 (18), A4 (19) | 732 Hz -| Zero * | 3 - 13, A0 (14), A1 (15) | 732 Hz -| Due ** | 2-13 | 1000 Hz -| 101 | 3, 5, 6, 9 | pins 3 and 9: 490 Hz, pins 5 and 6: 980 Hz -|==================================================================================================== -{empty}* In addition to PWM capabilities on the pins noted above, the MKR and Zero boards have true analog output when using `analogWrite()` on the `DAC0` (`A0`) pin. + -{empty}** In addition to PWM capabilities on the pins noted above, the Due has true analog output when using `analogWrite()` on pins `DAC0` and `DAC1`. + +|========================================================================================================================= +| Board | PWM Pins +*+ | PWM Frequency +| UNO (R3 and earlier), Nano, Mini | 3, 5, 6, 9, 10, 11 | 490 Hz (pins 5 and 6: 980 Hz) +| UNO R4 (Minima, WiFi) +*+ | 3, 5, 6, 9, 10, 11 | 490 Hz +| Mega | 2 - 13, 44 - 46 | 490 Hz (pins 4 and 13: 980 Hz) +| GIGA R1 +**+ | 2 - 13 | 500 Hz +| Leonardo, Micro, Yún | 3, 5, 6, 9, 10, 11, 13 | 490 Hz (pins 3 and 11: 980 Hz) +| UNO WiFi Rev2, Nano Every | 3, 5, 6, 9, 10 | 976 Hz +| MKR boards +*+ | 0 - 8, 10, A3, A4 | 732 Hz +| MKR1000 WiFi +**+ | 0 - 8, 10, 11, A3, A4 | 732 Hz +| Zero +**+ | 3 - 13, A0, A1 | 732 Hz +| Nano 33 IoT +**+ | 2, 3, 5, 6, 9 - 12, A2, A3, A5 | 732 Hz +| Nano 33 BLE/BLE Sense +****+ | 1 - 13, A0 - A7 | 500 Hz +| Due +***+ | 2-13 | 1000 Hz +| 101 | 3, 5, 6, 9 | pins 3 and 9: 490 Hz, pins 5 and 6: 980 Hz +|========================================================================================================================= + ++*+ These pins are officially supported PWM pins. While some boards have additional pins capable of PWM, using them is recommended only for advanced users that can account for timer availability and potential conflicts with other uses of those pins. + ++**+ In addition to PWM capabilities on the pins noted above, the MKR, Nano 33 IoT, Zero and UNO R4 boards have true analog output when using `analogWrite()` on the `DAC0` (`A0`) pin. + ++***+ In addition to PWM capabilities on the pins noted above, the Due and GIGA R1 boards have true analog output when using `analogWrite()` on pins `DAC0` and `DAC1`. + ++****+ Only 4 different pins can be used at the same time. Enabling PWM on more than 4 pins will abort the running sketch and require resetting the board to upload a new sketch again. + [%hardbreaks] diff --git a/Language/Functions/Zero, Due, MKR Family/analogWriteResolution.adoc b/Language/Functions/Analog IO/analogWriteResolution.adoc similarity index 99% rename from Language/Functions/Zero, Due, MKR Family/analogWriteResolution.adoc rename to Language/Functions/Analog IO/analogWriteResolution.adoc index 3ef4e482f..649eb171c 100644 --- a/Language/Functions/Zero, Due, MKR Family/analogWriteResolution.adoc +++ b/Language/Functions/Analog IO/analogWriteResolution.adoc @@ -1,7 +1,7 @@ --- title: analogWriteResolution() categories: [ "Functions" ] -subCategories: [ "Zero, Due & MKR Family" ] +subCategories: [ "Analog I/O" ] --- diff --git a/Language/Functions/Bits and Bytes/bit.adoc b/Language/Functions/Bits and Bytes/bit.adoc index 7b4636411..3aaeda82b 100644 --- a/Language/Functions/Bits and Bytes/bit.adoc +++ b/Language/Functions/Bits and Bytes/bit.adoc @@ -28,7 +28,7 @@ Computes the value of the specified bit (bit 0 is 1, bit 1 is 2, bit 2 is 4, etc [float] === Parameters -`n`: the bit whose value to compute +`n`: the bit whose value to compute. Note that `n` needs to be between 0-31 (32 bit). [float] diff --git a/Language/Functions/Bits and Bytes/bitClear.adoc b/Language/Functions/Bits and Bytes/bitClear.adoc index c81e359fe..7c8594c8f 100644 --- a/Language/Functions/Bits and Bytes/bitClear.adoc +++ b/Language/Functions/Bits and Bytes/bitClear.adoc @@ -34,12 +34,45 @@ Clears (writes a 0 to) a bit of a numeric variable. [float] === Returns -Nothing +`x`: the value of the numeric variable after the bit at position `n` is cleared. -- // OVERVIEW SECTION ENDS + +// HOW TO USE SECTION STARTS +[#howtouse] +-- + +[float] +=== Example Code +// Describe what the example code is all about and add relevant code +Prints the output of `bitClear(x,n)` on two given integers. The binary representation of 6 is 0110, so when `n=1`, the second bit from the right is set to 0. After this we are left with 0100 in binary, so 4 is returned. + +[source,arduino] +---- +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + int x = 6; + int n = 1; + Serial.print(bitClear(x, n)); // print the output of bitClear(x,n) +} + +void loop() { +} +---- +[%hardbreaks] + +-- +// HOW TO USE SECTION ENDS + + + // SEE ALSO SECTION [#see_also] -- diff --git a/Language/Functions/Bits and Bytes/bitRead.adoc b/Language/Functions/Bits and Bytes/bitRead.adoc index b6c324c15..53c190c6a 100644 --- a/Language/Functions/Bits and Bytes/bitRead.adoc +++ b/Language/Functions/Bits and Bytes/bitRead.adoc @@ -17,7 +17,7 @@ subCategories: [ "Bits and Bytes" ] [float] === Description -Reads a bit of a number. +Reads a bit of a variable, e.g. `bool`, `int`. Note that `float` & `double` are not supported. You can read the bit of variables up to an `unsigned long long` (64 bits / 8 bytes). [%hardbreaks] @@ -36,6 +36,55 @@ Reads a bit of a number. === Returns The value of the bit (0 or 1). +[float] +=== Example Code + +This example code demonstrates how to read two variables, one increasing counter, one decreasing counter, and print out both the binary and decimal values of the variables. + +The `readBit()` function loops through each bit of the variable (starting from the rightmost bit), and prints it out. + +[source,arduino] +---- +long negative_var = -0; // +unsigned long long positive_var = 0; + +//predefined sizes when looping through bits +//e.g. long_size is 32 bit (which is 0-31). Therefore, we subtract "1". +const int bool_size = (1 - 1); +const int int_size = (8 - 1); +const int long_size = (32 - 1); + +void setup() { + Serial.begin(9600); +} + +void loop() { + //run readBit function, passing the pos/neg variables + readBit("Positive ", positive_var); + readBit("Negative ", negative_var); + Serial.println(); + + //increase and decrease the variables + negative_var--; + positive_var++; + + delay(1000); +} + +/*this function takes a variable, prints it out bit by bit (starting from the right) +then prints the decimal number for comparison.*/ +void readBit(String direction, long counter) { + Serial.print(direction + "Binary Number: "); + //loop through each bit + for (int b = long_size; b >= 0; b--) { + byte bit = bitRead(counter, b); + Serial.print(bit); + } + Serial.print(" Decimal Number: "); + Serial.println(counter); +} +---- + -- // OVERVIEW SECTION ENDS diff --git a/Language/Functions/Bits and Bytes/bitSet.adoc b/Language/Functions/Bits and Bytes/bitSet.adoc index d5c49a018..94c52a797 100644 --- a/Language/Functions/Bits and Bytes/bitSet.adoc +++ b/Language/Functions/Bits and Bytes/bitSet.adoc @@ -34,12 +34,43 @@ Sets (writes a 1 to) a bit of a numeric variable. [float] === Returns -Nothing +`x`: the value of the numeric variable after the bit at position `n` is set. -- // OVERVIEW SECTION ENDS + +// HOW TO USE SECTION STARTS +[#howtouse] +-- + +[float] +=== Example Code +Prints the output of `bitSet(x,n)` on two given integers. The binary representation of 4 is 0100, so when `n=1`, the second bit from the right is set to 1. After this we are left with 0110 in binary, so 6 is returned. + +[source,arduino] +---- +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + int x = 4; + int n = 1; + Serial.print(bitSet(x, n)); // print the output of bitSet(x,n) +} + +void loop() { +} +---- +[%hardbreaks] + +-- +// HOW TO USE SECTION ENDS + + // SEE ALSO SECTION [#see_also] -- @@ -47,5 +78,8 @@ Nothing [float] === See also +[role="language"] +* #LANGUAGE# link:../bitclear[bitClear()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Bits and Bytes/bitWrite.adoc b/Language/Functions/Bits and Bytes/bitWrite.adoc index b12982ed5..b0e5ef723 100644 --- a/Language/Functions/Bits and Bytes/bitWrite.adoc +++ b/Language/Functions/Bits and Bytes/bitWrite.adoc @@ -17,7 +17,7 @@ subCategories: [ "Bits and Bytes" ] [float] === Description -Writes a bit of a numeric variable. +Writes to a bit of a variable, e.g. `bool`, `int`, `long`. Note that `float` & `double` are not supported. You can write to a bit of variables up to an `unsigned long` (32 bits / 4 bytes). [%hardbreaks] diff --git a/Language/Functions/Communication/Print.adoc b/Language/Functions/Communication/Print.adoc new file mode 100644 index 000000000..a6b7a142d --- /dev/null +++ b/Language/Functions/Communication/Print.adoc @@ -0,0 +1,61 @@ +--- +title: Print +categories: [ "Functions" ] +subCategories: [ "Communication" ] +--- + + + + += Print + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +The Print class is an abstract base class that provides a common interface for printing data to different output devices. It defines several methods that allow printing data in different formats. + +Print class is related to several libraries in Arduino that use the printing functionality to interact with devices such as Serial Monitor, LCD Screen, printers, etc. + +Some of the libraries that use the Print class are: + +* link:https://www.arduino.cc/en/Reference/serial[Serial] +* link:https://reference.arduino.cc/reference/en/libraries/liquidcrystal/[LiquidCrystal] +* link:https://www.arduino.cc/en/Reference/Ethernet[Ethernet] +* link:https://reference.arduino.cc/reference/en/libraries/wifi/wificlient/[Wifi] + + +-- +// OVERVIEW SECTION ENDS + + +// FUNCTIONS SECTION STARTS +[#functions] +-- + +''' + +[float] +=== Functions +link:https://www.arduino.cc/reference/en/language/functions/communication/wire/write/[write()] + +link:https://www.arduino.cc/en/Reference/serial/print/[print()] + +link:https://www.arduino.cc/en/Reference/serial/println/[println()] + +''' + +-- +// FUNCTIONS SECTION ENDS + + +// SEE ALSO SECTION +[#see_also] +-- + +[float] +=== See also + +-- +// SEE ALSO SECTION ENDS diff --git a/Language/Functions/Communication/SPI.adoc b/Language/Functions/Communication/SPI.adoc new file mode 100644 index 000000000..a448778cf --- /dev/null +++ b/Language/Functions/Communication/SPI.adoc @@ -0,0 +1,71 @@ +--- +title: SPI +categories: [ "Functions" ] +subCategories: [ "Communication" ] +--- + + += SPI + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + + +This library allows you to communicate with SPI devices, with the Arduino as the controller device. This library is bundled with every Arduino platform (avr, megaavr, mbed, samd, sam, arc32), so *you do not need to install* the library separately. + +To use this library + +`#include ` + +To read more about Arduino and SPI, you can visit the https://docs.arduino.cc/learn/communication/spi[Arduino & Serial Peripheral Interface (SPI)] guide. + +-- +// OVERVIEW SECTION ENDS + +// HOW TO USE SECTION STARTS +[#howtouse] +-- +|================================================================================================================================================ +| Boards | Default SPI Pins | Additional SPI Pins | Notes +| UNO R3, UNO R3 SMD, UNO WiFi Rev2, UNO Mini Ltd| 10(CS), 11(COPI), 12(CIPO), 13(SCK) | | SPI pins available on ICSP header +| UNO R4 Minima, UNO R4 WiFi| 10(CS), 11(COPI), 12(CIPO), 13(SCK) | | SPI pins available on ICSP header +| Leonardo, Yún Rev2, Zero| 10(CS), 11(COPI), 12(CIPO), 13(SCK) | | SPI pins available on ICSP header +| Micro | 14(CIPO), 15(SCK), 16(COPI) | | +| Nano boards | 11(COPI), 12(CIPO), 13(SCK) | | +| MKR boards | 8(COPI), 9(SCK), 10(CIPO) | | +| Due | 74(CIPO), 75(MOSI), 76(SCK) | SPI pins available on dedicated SPI header | +| GIGA R1 WiFi | 89(CIPO), 90(COPI), 91(SCK) | 12(CIPO), 11(COPI), 13(SCK), 10(CS) | Note that pin 89,90,91 are located on the SPI header +| Mega 2560 Rev3 | 50(CIPO), 51(COPI), 52(SCK), 53(CS) | | SPI pins available on ICSP header +|================================================================================================================================================ + +-- +// HOW TO USE SECTION ENDS + +// FUNCTIONS SECTION STARTS +[#functions] +-- + +''' + +[float] +=== Functions +link:../spi/spisettings[SPISettings] + +link:../spi/begin[begin()] + +link:../spi/begintransaction[beginTransaction()] + +link:../spi/endtransaction[endTransaction()] + +link:../spi/end[end()] + +link:../spi/setbitorder[setBitOrder()] + +link:../spi/setclockdivider[setClockDivider()] + +link:../spi/setdatamode[setDataMode()] + +link:../spi/transfer[transfer()] + +link:../spi/usinginterrupt[usingInterrupt()] + +''' + +-- +// SEEALSO SECTION ENDS diff --git a/Language/Functions/Communication/SPI/SPISettings.adoc b/Language/Functions/Communication/SPI/SPISettings.adoc new file mode 100644 index 000000000..a0586c8b6 --- /dev/null +++ b/Language/Functions/Communication/SPI/SPISettings.adoc @@ -0,0 +1,43 @@ +--- +title: SPISettings +--- + += SPISettings + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +The `SPISettings` object is used to configure the SPI port for your SPI device. All 3 parameters are combined to a single `SPISettings` object, which is given to `SPI.beginTransaction()`. + +When all of your settings are constants, SPISettings should be used directly in `SPI.beginTransaction()`. See the syntax section below. For constants, this syntax results in smaller and faster code. + +If any of your settings are variables, you may create a SPISettings object to hold the 3 settings. Then you can give the object name to SPI.beginTransaction(). Creating a named SPISettings object may be more efficient when your settings are not constants, especially if the maximum speed is a variable computed or configured, rather than a number you type directly into your sketch. + +[float] +=== Syntax +`SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0))` +Note: Best if all 3 settings are constants + +`SPISettings mySetting(speedMaximum, dataOrder, dataMode)` +Note: Best when any setting is a variable'' + + +[float] +=== Parameters + +`speedMaximum`: The maximum speed of communication. For a SPI chip rated up to 20 MHz, use 20000000. + +`dataOrder`: MSBFIRST or LSBFIRST + +`dataMode`: SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3 + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/begin.adoc b/Language/Functions/Communication/SPI/begin.adoc new file mode 100644 index 000000000..757e57c6c --- /dev/null +++ b/Language/Functions/Communication/SPI/begin.adoc @@ -0,0 +1,33 @@ +--- +title: SPI.begin() +--- + += SPI.begin() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high. + + +[float] +=== Syntax +`SPI.begin()` + + +[float] +=== Parameters +None. + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/beginTransaction.adoc b/Language/Functions/Communication/SPI/beginTransaction.adoc new file mode 100644 index 000000000..ae299ca02 --- /dev/null +++ b/Language/Functions/Communication/SPI/beginTransaction.adoc @@ -0,0 +1,33 @@ +--- +title: SPI.beginTransaction() +--- + += SPI.beginTransaction() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +Initializes the SPI bus. Note that calling link:../begin[SPI.begin()] is required before calling this one. + + +[float] +=== Syntax +`SPI.beginTransaction(mySettings)` + + +[float] +=== Parameters +mySettings: the chosen settings (see link:../spisettings[SPISettings]). + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/end.adoc b/Language/Functions/Communication/SPI/end.adoc new file mode 100644 index 000000000..76eef8025 --- /dev/null +++ b/Language/Functions/Communication/SPI/end.adoc @@ -0,0 +1,33 @@ +--- +title: SPI.end() +--- + += SPI.end() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +Disables the SPI bus (leaving pin modes unchanged). + + +[float] +=== Syntax +`SPI.end()` + + +[float] +=== Parameters +None. + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/endTransaction.adoc b/Language/Functions/Communication/SPI/endTransaction.adoc new file mode 100644 index 000000000..4bf8ec891 --- /dev/null +++ b/Language/Functions/Communication/SPI/endTransaction.adoc @@ -0,0 +1,33 @@ +--- +title: SPI.endTransaction() +--- + += SPI.endTransaction() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +Stop using the SPI bus. Normally this is called after de-asserting the chip select, to allow other libraries to use the SPI bus. + + +[float] +=== Syntax +`SPI.endTransaction()` + + +[float] +=== Parameters +None. + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/setBitOrder.adoc b/Language/Functions/Communication/SPI/setBitOrder.adoc new file mode 100644 index 000000000..c67d40c1e --- /dev/null +++ b/Language/Functions/Communication/SPI/setBitOrder.adoc @@ -0,0 +1,35 @@ +--- +title: SPI.setBitOrder() +--- + += SPI.setBitOrder() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function should not be used in new projects. Use link:../spisettings[SPISettings]. with link:../begintransaction[SPI.beginTransaction()]. to configure SPI parameters. + +Sets the order of the bits shifted out of and into the SPI bus, either LSBFIRST (least-significant bit first) or MSBFIRST (most-significant bit first). + + +[float] +=== Syntax +`SPI.setBitOrder(order)` + + +[float] +=== Parameters +order: either LSBFIRST or MSBFIRST + + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/setClockDivider.adoc b/Language/Functions/Communication/SPI/setClockDivider.adoc new file mode 100644 index 000000000..edb835c99 --- /dev/null +++ b/Language/Functions/Communication/SPI/setClockDivider.adoc @@ -0,0 +1,48 @@ +--- +title: SPI.setClockDivider() +--- + += SPI.setClockDivider() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function should not be used in new projects. Use link:../spisettings[SPISettings]. with link:../begintransaction[SPI.beginTransaction()]. to configure SPI parameters. + +Sets the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter the frequency of the system clock (4 Mhz for the boards at 16 MHz). + +*For Arduino Due:* On the Due, the system clock can be divided by values from 1 to 255. The default value is 21, which sets the clock to 4 MHz like other Arduino boards. + + +[float] +=== Syntax +`SPI.setClockDivider(divider)` + + +[float] +=== Parameters + +divider (only AVR boards): + +* SPI_CLOCK_DIV2 +* SPI_CLOCK_DIV4 +* SPI_CLOCK_DIV8 +* SPI_CLOCK_DIV16 +* SPI_CLOCK_DIV32 +* SPI_CLOCK_DIV64 +* SPI_CLOCK_DIV128 + +*chipSelectPin*: peripheral device CS pin (Arduino Due only) +*divider*: a number from 1 to 255 (Arduino Due only) + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/setDataMode.adoc b/Language/Functions/Communication/SPI/setDataMode.adoc new file mode 100644 index 000000000..4089e5e89 --- /dev/null +++ b/Language/Functions/Communication/SPI/setDataMode.adoc @@ -0,0 +1,41 @@ +--- +title: SPI.setDataMode() +--- + += SPI.setDataMode() + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function should not be used in new projects. Use link:../spisettings[SPISettings]. with link:../begintransaction[SPI.beginTransaction()]. to configure SPI parameters. + +Sets the SPI data mode: that is, clock polarity and phase. See the Wikipedia article on http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus:[SPI] for details. + +[float] +=== Syntax +`SPI.setDataMode(mode)` + + +[float] +=== Parameters + +mode: + +* SPI_MODE0 +* SPI_MODE1 +* SPI_MODE2 +* SPI_MODE3 + + +chipSelectPin - peripheral device CS pin (Arduino Due only) + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/transfer.adoc b/Language/Functions/Communication/SPI/transfer.adoc new file mode 100644 index 000000000..ff59a3b3c --- /dev/null +++ b/Language/Functions/Communication/SPI/transfer.adoc @@ -0,0 +1,40 @@ +--- +title: SPI.transfer() +--- + += SPI.transfer() + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal (or receivedVal16). In case of buffer transfers the received data is stored in the buffer in-place (the old data is replaced with the data received). + +[float] +=== Syntax + +`receivedVal = SPI.transfer(val)` + +`receivedVal16 = SPI.transfer16(val16)` + +`SPI.transfer(buffer, size)` + + +[float] +=== Parameters + +* val: the byte to send out over the bus +* val16: the two bytes variable to send out over the bus +* buffer: the array of data to be transferred + + +[float] +=== Returns +The received data. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/SPI/usingInterrupt.adoc b/Language/Functions/Communication/SPI/usingInterrupt.adoc new file mode 100644 index 000000000..7769ba39d --- /dev/null +++ b/Language/Functions/Communication/SPI/usingInterrupt.adoc @@ -0,0 +1,33 @@ +--- +title: SPI.usingInterrupt() +--- + += SPI.usingInterrupt() + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +If your program will perform SPI transactions within an interrupt, call this function to register the interrupt number or name with the SPI library. This allows `SPI.beginTransaction()` to prevent usage conflicts. Note that the interrupt specified in the call to usingInterrupt() will be disabled on a call to `beginTransaction()` and re-enabled in `endTransaction().` + +[float] +=== Syntax + +`SPI.usingInterrupt(interruptNumber)` + + +[float] +=== Parameters + +interruptNumber: the associated interrupt number. + +[float] +=== Returns +None. + +-- +// OVERVIEW SECTION ENDS + diff --git a/Language/Functions/Communication/Serial.adoc b/Language/Functions/Communication/Serial.adoc index 21fb67ce1..9b47ddbff 100644 --- a/Language/Functions/Communication/Serial.adoc +++ b/Language/Functions/Communication/Serial.adoc @@ -4,9 +4,6 @@ categories: [ "Functions" ] subCategories: [ "Communication" ] --- - - - = Serial() @@ -18,19 +15,38 @@ subCategories: [ "Communication" ] === Description 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), and some have several. [options="header"] + |================================================================================================================================================ -| Board | USB CDC name | Serial pins | Serial1 pins | Serial2 pins | Serial3 pins -| Uno, Nano, Mini | | 0(RX), 1(TX) | | | -| Mega | | 0(RX), 1(TX) | 19(RX), 18(TX) | 17(RX), 16(TX) | 15(RX), 14(TX) -| Leonardo, Micro, Yún | Serial | | 0(RX), 1(TX) | | -| Uno WiFi Rev.2 | | Connected to USB | 0(RX), 1(TX) | Connected to NINA | -| MKR boards | Serial | | 13(RX), 14(TX) | | -| Zero | SerialUSB (Native USB Port only) | Connected to Programming Port | 0(RX), 1(TX) | | -| Due | SerialUSB (Native USB Port only) | 0(RX), 1(TX) | 19(RX), 18(TX) | 17(RX), 16(TX) | 15(RX), 14(TX) -| 101 | Serial | | 0(RX), 1(TX) | | +| Board | Serial pins | Serial1 pins | Serial2 pins | Serial3 pins | Serial4 pins +| UNO R3, UNO R3 SMD Mini | 0(RX), 1(TX) | | | | +| Nano (classic) | 0(RX), 1(TX) | | | | +| UNO R4 Minima, UNO R4 WiFi| | 0(RX0), 1(TX0) | | | +| Leonardo, Micro, Yún Rev2 | | 0(RX), 1(TX) | | | +| Uno WiFi Rev.2 | | 0(RX), 1(TX) | | | +| MKR boards | | 13(RX), 14(TX) | | | +| Zero | | 0(RX), 1(TX) | | | +| GIGA R1 WiFi | | 0(RX), 1(TX) | 19(RX1), 18(TX1) | 17(RX2), 16(TX2) | 15(RX3), 14(TX3) +| Due | 0(RX), 1(TX) | 19(RX1), 18(TX1) | 17(RX2), 16(TX2) | 15(RX3), 14(TX3) | +| Mega 2560 Rev3 | 0(RX), 1(TX) | 19(RX1), 18(TX1) | 17(RX2), 16(TX2) | 15(RX3), 14(TX3) | +| Nano 33 IoT | | 0(RX0), 1(TX0) | | | +| Nano RP2040 Connect | | 0(RX0), 1(TX0) | | | +| Nano BLE / BLE Sense | | 0(RX0), 1(TX0) | | | |================================================================================================================================================ -On Uno, Nano, Mini, and Mega, pins 0 and 1 are used for communication with the computer. Connecting anything to these pins can interfere with that communication, including causing failed uploads to the board. + +[options="header"] + +The Nano ESP32 board is an exception due to being based on the ESP32 core. Here, `Serial0` refers to `RX0` and `TX0`, while `Serial1` and `Serial2` are additional ports that can be assigned to any free GPIO. + +|================================================================================================================================================ +| Board | Serial0 pins | Serial1 pins | Serial2 pins | Serial3 pins | Serial4 pins +| Nano ESP32 | 0(RX0), 1(TX0) | Any free GPIO | Any free GPIO | | +|================================================================================================================================================ + +You can read more about configuring the Nano ESP32's additional serial ports in https://docs.arduino.cc/tutorials/nano-esp32/cheat-sheet/#uart[this article]. + +[%hardbreaks] +On older boards (Uno, Nano, Mini, and Mega), pins 0 and 1 are used for communication with the computer. Connecting anything to these pins can interfere with that communication, including causing failed uploads to the board. [%hardbreaks] 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()`. [%hardbreaks] diff --git a/Language/Functions/Communication/Serial/available.adoc b/Language/Functions/Communication/Serial/available.adoc index 4c6d7a60f..14b8ab166 100644 --- a/Language/Functions/Communication/Serial/available.adoc +++ b/Language/Functions/Communication/Serial/available.adoc @@ -24,7 +24,7 @@ Get the number of bytes (characters) available for reading from the serial port. [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/availableForWrite.adoc b/Language/Functions/Communication/Serial/availableForWrite.adoc index 9989dfb66..fe76f5407 100644 --- a/Language/Functions/Communication/Serial/availableForWrite.adoc +++ b/Language/Functions/Communication/Serial/availableForWrite.adoc @@ -25,7 +25,7 @@ Get the number of bytes (characters) available for writing in the serial buffer [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/begin.adoc b/Language/Functions/Communication/Serial/begin.adoc index f5701a75a..ed0bf8270 100644 --- a/Language/Functions/Communication/Serial/begin.adoc +++ b/Language/Functions/Communication/Serial/begin.adoc @@ -28,7 +28,7 @@ An optional second argument configures the data, parity, and stop bits. The defa [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `speed`: in bits per second (baud). Allowed data types: `long`. + `config`: sets data, parity, and stop bits. Valid values are: + `SERIAL_5N1` + @@ -112,7 +112,9 @@ Thanks to Jeff Gray for the mega example [float] === Notes and Warnings -For USB CDC serial ports (e.g. `Serial` on the Leonardo), `Serial.begin()` is irrelevant. You can use any baud rate and configuration for serial communication with these ports. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +For USB CDC serial ports (e.g. `Serial` on the Leonardo), `Serial.begin()` is irrelevant. You can use any baud rate and configuration for serial communication with these ports. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + +The only `config` value supported for `Serial1` on the Arduino Nano 33 BLE and Nano 33 BLE Sense boards is `SERIAL_8N1`. [%hardbreaks] -- diff --git a/Language/Functions/Communication/Serial/end.adoc b/Language/Functions/Communication/Serial/end.adoc index b13b78ff5..a3b101c79 100644 --- a/Language/Functions/Communication/Serial/end.adoc +++ b/Language/Functions/Communication/Serial/end.adoc @@ -25,7 +25,7 @@ Disables serial communication, allowing the RX and TX pins to be used for genera [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/find.adoc b/Language/Functions/Communication/Serial/find.adoc index b36efdc63..9f454de0a 100644 --- a/Language/Functions/Communication/Serial/find.adoc +++ b/Language/Functions/Communication/Serial/find.adoc @@ -28,7 +28,7 @@ title: Serial.find() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `target`: the string to search for. Allowed data types: `char`. + `length`: length of the target. Allowed data types: `size_t`. diff --git a/Language/Functions/Communication/Serial/findUntil.adoc b/Language/Functions/Communication/Serial/findUntil.adoc index f19bfa6ef..a2e9fc0d6 100644 --- a/Language/Functions/Communication/Serial/findUntil.adoc +++ b/Language/Functions/Communication/Serial/findUntil.adoc @@ -29,7 +29,7 @@ The function returns true if the target string is found, false if it times out. [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `target`: the string to search for. Allowed data types: `char`. + `terminal`: the terminal string in the search. Allowed data types: `char`. diff --git a/Language/Functions/Communication/Serial/flush.adoc b/Language/Functions/Communication/Serial/flush.adoc index c3c6f43b8..fb7027f6a 100644 --- a/Language/Functions/Communication/Serial/flush.adoc +++ b/Language/Functions/Communication/Serial/flush.adoc @@ -14,9 +14,9 @@ title: Serial.flush() [float] === Description -Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.) +Waits for the transmission of outgoing serial data to complete. -`flush()` inherits from the link:../flush[Stream] utility class. +`flush()` inherits from the link:../../stream/streamflush[Stream] utility class. [%hardbreaks] @@ -27,7 +27,7 @@ Waits for the transmission of outgoing serial data to complete. (Prior to Arduin [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/ifSerial.adoc b/Language/Functions/Communication/Serial/ifSerial.adoc index d5a0fa29f..a41c1ec88 100644 --- a/Language/Functions/Communication/Serial/ifSerial.adoc +++ b/Language/Functions/Communication/Serial/ifSerial.adoc @@ -18,7 +18,6 @@ Indicates if the specified Serial port is ready. On the boards with native USB, `if (Serial)` (or `if(SerialUSB)` on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true. -This was introduced in Arduino IDE 1.0.1. [%hardbreaks] @@ -36,6 +35,7 @@ None === Returns Returns true if the specified serial port is available. This will only return false if querying the Leonardo's USB CDC serial connection before it is ready. Data type: `bool`. + -- // OVERVIEW SECTION ENDS @@ -66,5 +66,9 @@ void loop() { } ---- +[float] +=== Notes and Warnings +This function adds a delay of 10ms in an attempt to solve "open but not quite" situations. Don't use it in tight loops. + -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/Communication/Serial/parseFloat.adoc b/Language/Functions/Communication/Serial/parseFloat.adoc index b9b0cde79..6c1f01bcd 100644 --- a/Language/Functions/Communication/Serial/parseFloat.adoc +++ b/Language/Functions/Communication/Serial/parseFloat.adoc @@ -29,7 +29,7 @@ title: Serial.parseFloat() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `lookahead`: the mode used to look ahead in the stream for a floating point number. Allowed data types: `LookaheadMode`. Allowed `lookahead` values: * `SKIP_ALL`: all characters other than a minus sign, decimal point, or digits are ignored when scanning the stream for a floating point number. This is the default mode. diff --git a/Language/Functions/Communication/Serial/parseInt.adoc b/Language/Functions/Communication/Serial/parseInt.adoc index 962b48cbd..93c6e1563 100644 --- a/Language/Functions/Communication/Serial/parseInt.adoc +++ b/Language/Functions/Communication/Serial/parseInt.adoc @@ -35,7 +35,7 @@ In particular: [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `lookahead`: the mode used to look ahead in the stream for an integer. Allowed data types: `LookaheadMode`. Allowed `lookahead` values: * `SKIP_ALL`: all characters other than digits or a minus sign are ignored when scanning the stream for an integer. This is the default mode. diff --git a/Language/Functions/Communication/Serial/peek.adoc b/Language/Functions/Communication/Serial/peek.adoc index 7209996be..557c729af 100644 --- a/Language/Functions/Communication/Serial/peek.adoc +++ b/Language/Functions/Communication/Serial/peek.adoc @@ -27,7 +27,7 @@ Returns the next byte (character) of incoming serial data without removing it fr [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/print.adoc b/Language/Functions/Communication/Serial/print.adoc index ff3cbe14a..8f09302a0 100644 --- a/Language/Functions/Communication/Serial/print.adoc +++ b/Language/Functions/Communication/Serial/print.adoc @@ -30,7 +30,7 @@ An optional second parameter specifies the base (format) to use; permitted value * `_Serial_.print(78, HEX)` gives "4E" + * `_Serial_.print(1.23456, 0)` gives "1" + * `_Serial_.print(1.23456, 2)` gives "1.23" + -* `_Serial_.print(1.23456, 4)` gives "1.2345" +* `_Serial_.print(1.23456, 4)` gives "1.2346" You can pass flash-memory based strings to `_Serial_.print()` by wrapping them with link:../../../../variables/utilities/progmem[F()]. For example: @@ -48,7 +48,7 @@ To send data without conversion to its representation as characters, use link:.. [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `val`: the value to print. Allowed data types: any data type. @@ -100,7 +100,7 @@ void loop() { for (int x = 0; x < 64; x++) { // only part of the ASCII chart, change to suit // print it out in many formats: Serial.print(x); // print as an ASCII-encoded decimal - same as "DEC" - Serial.print("\t\t"); // prints two tabs to accomodate the label lenght + Serial.print("\t\t"); // prints two tabs to accommodate the label length Serial.print(x, DEC); // print as an ASCII-encoded decimal Serial.print("\t"); // prints a tab diff --git a/Language/Functions/Communication/Serial/println.adoc b/Language/Functions/Communication/Serial/println.adoc index 15ef923c0..49dc2aaa1 100644 --- a/Language/Functions/Communication/Serial/println.adoc +++ b/Language/Functions/Communication/Serial/println.adoc @@ -26,7 +26,7 @@ Prints data to the serial port as human-readable ASCII text followed by a carria [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `val`: the value to print. Allowed data types: any data type. + `format`: specifies the number base (for integral data types) or number of decimal places (for floating point types). diff --git a/Language/Functions/Communication/Serial/read.adoc b/Language/Functions/Communication/Serial/read.adoc index 2a781fc7e..b721f2322 100644 --- a/Language/Functions/Communication/Serial/read.adoc +++ b/Language/Functions/Communication/Serial/read.adoc @@ -27,7 +27,7 @@ Reads incoming serial data. [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] diff --git a/Language/Functions/Communication/Serial/readBytes.adoc b/Language/Functions/Communication/Serial/readBytes.adoc index da566d64b..eee28340b 100644 --- a/Language/Functions/Communication/Serial/readBytes.adoc +++ b/Language/Functions/Communication/Serial/readBytes.adoc @@ -29,7 +29,7 @@ title: Serial.readBytes() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `buffer`: the buffer to store the bytes in. Allowed data types: array of `char` or `byte`. + `length`: the number of bytes to read. Allowed data types: `int`. diff --git a/Language/Functions/Communication/Serial/readBytesUntil.adoc b/Language/Functions/Communication/Serial/readBytesUntil.adoc index d35ff46c2..50775c471 100644 --- a/Language/Functions/Communication/Serial/readBytesUntil.adoc +++ b/Language/Functions/Communication/Serial/readBytesUntil.adoc @@ -29,7 +29,7 @@ Serial.readBytesUntil() reads characters from the serial buffer into an array. T [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `character`: the character to search for. Allowed data types: `char`. + `buffer`: the buffer to store the bytes in. Allowed data types: array of `char` or `byte`. + `length`: the number of bytes to read. Allowed data types: `int`. diff --git a/Language/Functions/Communication/Serial/readString.adoc b/Language/Functions/Communication/Serial/readString.adoc index 3e6822e2a..496787c8e 100644 --- a/Language/Functions/Communication/Serial/readString.adoc +++ b/Language/Functions/Communication/Serial/readString.adoc @@ -27,17 +27,56 @@ title: Serial.readString() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. [float] === Returns A `String` read from the serial buffer + -- // OVERVIEW SECTION ENDS +// HOW TO USE SECTION STARTS +[#howtouse] +-- + +[float] +=== Example Code +Demonstrate Serial.readString() + +[source,arduino] +---- +void setup() { + Serial.begin(9600); +} + +void loop() { + Serial.println("Enter data:"); + while (Serial.available() == 0) {} //wait for data available + String teststr = Serial.readString(); //read until timeout + teststr.trim(); // remove any \r \n whitespace at the end of the String + if (teststr == "red") { + Serial.println("A primary color"); + } else { + Serial.println("Something else"); + } +} +---- +[%hardbreaks] + + +[float] +=== Notes and Warnings +The function does not terminate early if the data contains end of line characters. The returned `String` may contain carriage return and/or line feed characters if they were received. +[%hardbreaks] + +-- +// HOW TO USE SECTION ENDS + + // SEE ALSO SECTION [#see_also] -- @@ -46,7 +85,7 @@ A `String` read from the serial buffer === See also [role="language"] -* #LANGUAGE# link:../../serial[Serial] +* #LANGUAGE# link:https://www.arduino.cc/en/Reference/serial[Serial] * #LANGUAGE# link:../begin[begin()] * #LANGUAGE# link:../end[end()] * #LANGUAGE# link:../available[available()] diff --git a/Language/Functions/Communication/Serial/readStringUntil.adoc b/Language/Functions/Communication/Serial/readStringUntil.adoc index 53990e334..54f24540f 100644 --- a/Language/Functions/Communication/Serial/readStringUntil.adoc +++ b/Language/Functions/Communication/Serial/readStringUntil.adoc @@ -27,13 +27,14 @@ title: Serial.readStringUntil() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `terminator`: the character to search for. Allowed data types: `char`. [float] === Returns -The entire `String` read from the serial buffer, up to the terminator character +The entire `String` read from the serial buffer, up to the terminator character. +If the terminator character can't be found, or if there is no data before the terminator character, it will return `NULL`. -- // OVERVIEW SECTION ENDS @@ -46,6 +47,7 @@ The entire `String` read from the serial buffer, up to the terminator character [float] === Notes and Warnings The terminator character is discarded from the serial buffer. +If the terminator character can't be found, all read characters will be discarded. [%hardbreaks] -- @@ -60,7 +62,7 @@ The terminator character is discarded from the serial buffer. === See also [role="language"] -* #LANGUAGE# link:../../serial[Serial] +* #LANGUAGE# link:https://www.arduino.cc/en/Reference/serial[Serial] * #LANGUAGE# link:../begin[begin()] * #LANGUAGE# link:../end[end()] * #LANGUAGE# link:../available[available()] diff --git a/Language/Functions/Communication/Serial/serialEvent.adoc b/Language/Functions/Communication/Serial/serialEvent.adoc index e554fb882..80475fe00 100644 --- a/Language/Functions/Communication/Serial/serialEvent.adoc +++ b/Language/Functions/Communication/Serial/serialEvent.adoc @@ -14,7 +14,9 @@ title: serialEvent() [float] === Description -Called when data is available. Use `Serial.read()` to capture this data. +Called at the end of link:../../../../structure/sketch/loop[`loop()`] when data is available. Use `Serial.read()` to capture this data. + +*Please note:* most modern boards do not support this method. See "Notes and Warnings" further below this article. [%hardbreaks] @@ -27,7 +29,9 @@ void serialEvent() { //statements } ---- -For boards with additional serial ports (see the list of available serial ports for each board on the link:../../serial[Serial main page]): + +The Mega 2560 R3 and Due boards have additional serial ports which can be accessed by adding the corresponding number at the end of the function. + [source,arduino] ---- void serialEvent1() { @@ -63,11 +67,9 @@ Nothing [float] === Notes and Warnings -`serialEvent()` doesn't work on the Leonardo, Micro, or Yún. - -`serialEvent()` and `serialEvent1()` don't work on the Arduino SAMD Boards +Please note that `serialEvent()` *does not work* on any modern Arduino boards. The only recognized boards to have support as of 2023/12/06 are the *UNO R3*, *Nano*, *Mega 2560 R3* and *Due*. -`serialEvent()`, `serialEvent1()``serialEvent2()`, and `serialEvent3()` don't work on the Arduino Due. +Instead, you can use the link:../available[`available()`] method. Examples in this page demonstrates how to read serial data only when it is available, similarly to how `Serial.event()` is implemented. [%hardbreaks] -- diff --git a/Language/Functions/Communication/Serial/setTimeout.adoc b/Language/Functions/Communication/Serial/setTimeout.adoc index 76e73dff1..41d5f224c 100644 --- a/Language/Functions/Communication/Serial/setTimeout.adoc +++ b/Language/Functions/Communication/Serial/setTimeout.adoc @@ -27,7 +27,7 @@ title: Serial.setTimeout() [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `time`: timeout duration in milliseconds. Allowed data types: `long`. diff --git a/Language/Functions/Communication/Serial/write.adoc b/Language/Functions/Communication/Serial/write.adoc index aa2117dfb..cfcd0b944 100644 --- a/Language/Functions/Communication/Serial/write.adoc +++ b/Language/Functions/Communication/Serial/write.adoc @@ -24,7 +24,7 @@ Writes binary data to the serial port. This data is sent as a byte or series of [float] === Parameters -`_Serial_`: serial port object. See the list of available serial ports for each board on the link:../../serial[Serial main page]. + +`_Serial_`: serial port object. See the list of available serial ports for each board on the link:https://www.arduino.cc/en/Reference/serial[Serial main page]. + `val`: a value to send as a single byte. + `str`: a string to send as a series of bytes. + `buf`: an array to send as a series of bytes. + @@ -65,7 +65,7 @@ void loop() { [float] === Notes and Warnings -As of Arduino IDE 1.0, serial transmission is asynchronous. If there is enough empty space in the transmit buffer, `Serial.write()` will return before any characters are transmitted over serial. If the transmit buffer is full then `Serial.write()` will block until there is enough space in the buffer. To avoid blocking calls to `Serial.write()`, you can first check the amount of free space in the transmit buffer using link:../availableforwrite[availableForWrite()]. +Serial transmission is asynchronous. If there is enough empty space in the transmit buffer, `Serial.write()` will return before any characters are transmitted over serial. If the transmit buffer is full then `Serial.write()` will block until there is enough space in the buffer. To avoid blocking calls to `Serial.write()`, you can first check the amount of free space in the transmit buffer using link:../availableforwrite[availableForWrite()]. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/Communication/Stream/streamReadBytesUntil.adoc b/Language/Functions/Communication/Stream/streamReadBytesUntil.adoc index 1baf1ff02..e417058be 100644 --- a/Language/Functions/Communication/Stream/streamReadBytesUntil.adoc +++ b/Language/Functions/Communication/Stream/streamReadBytesUntil.adoc @@ -16,7 +16,7 @@ title: Stream.readBytesUntil() === Description `readBytesUntil()` reads characters from a stream into a buffer. The function terminates if the terminator character is detected, the determined length has been read, or it times out (see link:../streamsettimeout[setTimeout()]). The function returns the characters up to the last character before the supplied terminator. The terminator itself is not returned in the buffer. -`readBytesUntil()` returns the number of bytes placed in the buffer. A 0 means no valid data was found. +`readBytesUntil()` returns the number of bytes placed in the buffer. A 0 means the terminator character can't be found or there is no data before it. This function is part of the Stream class, and can be called by any class that inherits from it (Wire, Serial, etc). See the link:../../stream[Stream class] main page for more information. [%hardbreaks] @@ -37,7 +37,7 @@ This function is part of the Stream class, and can be called by any class that i [float] === Returns -The number of bytes placed in the buffer. +The number of bytes (excluding the terminator character) placed in the buffer if the terminator character has been found. -- // OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Stream/streamReadStringUntil.adoc b/Language/Functions/Communication/Stream/streamReadStringUntil.adoc index 79b818a9d..fea1400ab 100644 --- a/Language/Functions/Communication/Stream/streamReadStringUntil.adoc +++ b/Language/Functions/Communication/Stream/streamReadStringUntil.adoc @@ -33,7 +33,8 @@ This function is part of the Stream class, and can be called by any class that i [float] === Returns -The entire String read from a stream, up to the terminator character +The entire String read from a stream, up to the terminator character. +If the terminator character can't be found, or if there is no data before the terminator character, it will return `NULL`. -- // OVERVIEW SECTION ENDS @@ -46,6 +47,7 @@ The entire String read from a stream, up to the terminator character [float] === Notes and Warnings The terminator character is discarded from the stream. +If the terminator character can't be found, all read characters will be discarded. [%hardbreaks] -- diff --git a/Language/Functions/Communication/Wire.adoc b/Language/Functions/Communication/Wire.adoc new file mode 100644 index 000000000..50ee777b7 --- /dev/null +++ b/Language/Functions/Communication/Wire.adoc @@ -0,0 +1,78 @@ +--- +title: Wire +categories: [ "Functions" ] +subCategories: [ "Communication" ] +--- + + += Wire + + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + + +This library allows you to communicate with I2C devices, a feature that is present on all Arduino boards. I2C is a very common protocol, primarily used for reading/sending data to/from external I2C components. To learn more, visit link:https://docs.arduino.cc/learn/communication/wire[this article for Arduino & I2C]. + +Due to the hardware design and various architectural differences, the I2C pins are located in different places. The pin map just below highlights the default pins, as well as additional ports available on certain boards. + + +|================================================================================================================================================ +| Board | I2C Default | I2C1 | I2C2 | Notes +| UNO R3, UNO R3 SMD, UNO Mini Ltd | A4(SDA), A5(SCL) | | | I2C also available on the SDA / SCL pins (digital header). +| UNO R4 Minima, UNO R4 WiFi | A4(SDA), A5(SCL) | Qwiic: D27(SDA), D26(SCL) | | I2C also available on the SDA / SCL pins (digital header). +| UNO WiFi Rev2, Zero | 20(SDA), 21(SCL) | | | +| Leonardo, Micro, Yùn Rev2 | D2(SDA), D3(SCL) | | | +| Nano boards | A4(SDA), A5(SCL) | | | +| MKR boards | D11(SDA), D12(SCL) | | | +| GIGA R1 WiFi | 20(SDA), 21(SCL) | D102(SDA1), D101 (SCL1) | D9(SDA2), D8 (SCL2) | Use `Wire1.begin()` for I2C1, and `Wire2.begin()` for I2C2. +| Due | 20(SDA), 21(SCL) | D70(SDA1), D71(SCL1) | | Use `Wire1.begin()` for I2C1 +| Mega 2560 Rev3 | D20(SDA), D21(SCL) | | | +|================================================================================================================================================ + + +This library inherits from the Stream functions, making it consistent with other read/write libraries. Because of this, `send()` and `receive()` have been replaced with `read()` and `write()`. + +Recent versions of the Wire library can use timeouts to prevent a lockup in the face of certain problems on the bus, but this is not enabled by default (yet) in current versions. It is recommended to always enable these timeouts when using the Wire library. See the Wire.setWireTimeout function for more details. + +*Note:* There are both 7 and 8-bit versions of I2C addresses. 7 bits identify the device, and the eighth bit determines if it's being written to or read from. The Wire library uses 7 bit addresses throughout. If you have a datasheet or sample code that uses 8-bit address, you'll want to drop the low bit (i.e. shift the value one bit to the right), yielding an address between 0 and 127. However the addresses from 0 to 7 are not used because are reserved so the first address that can be used is 8. Please note that a pull-up resistor is needed when connecting SDA/SCL pins. Please refer to the examples for more information. MEGA 2560 board has pull-up resistors on pins 20 and 21 onboard. + +*The Wire library implementation uses a 32 byte buffer, therefore any communication should be within this limit. Exceeding bytes in a single transmission will just be dropped.* + +To use this library: + +`#include ` + +-- +// OVERVIEW SECTION ENDS + +//FUNCTION SECTION STARTS +[#functions] +-- + +''' +[float] +=== Functions +link:../wire/begin[begin()] + +link:../wire/end[end()] + +link:../wire/requestfrom[requestFrom()] + +link:../wire/begintransmission[beginTransmission()] + +link:../wire/endtransmission[endTransmission()] + +link:../wire/write[write()] + +link:../wire/available[available()] + +link:../wire/read[read()] + +link:../wire/setclock[setClock()] + +link:../wire/onreceive[onReceive()] + +link:../wire/onrequest[onRequest()] + +link:../wire/setwiretimeout[setWireTimeout()] + +link:../wire/clearwiretimeoutflag[clearWireTimeoutFlag()] + +link:../wire/getwiretimeoutflag[getWireTimeoutFlag()] + +''' + +-- +// FUNCTION SECTION ENDS diff --git a/Language/Functions/Communication/Wire/available.adoc b/Language/Functions/Communication/Wire/available.adoc new file mode 100644 index 000000000..db375e9ee --- /dev/null +++ b/Language/Functions/Communication/Wire/available.adoc @@ -0,0 +1,30 @@ +--- +title: available() +--- + += available + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function returns the number of bytes available for retrieval with `read()`. This function should be called on a controller device after a call to `requestFrom()` or on a peripheral inside the `onReceive()` handler. `available()` inherits from the Stream utility class. + +[float] +=== Syntax +`Wire.available()` + +[float] +=== Parameters + +None. + +[float] +=== Returns + +The number of bytes available for reading. + +-- +//OVERVIEW SECTION STARTS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/begin.adoc b/Language/Functions/Communication/Wire/begin.adoc new file mode 100644 index 000000000..cbd0dea14 --- /dev/null +++ b/Language/Functions/Communication/Wire/begin.adoc @@ -0,0 +1,31 @@ +--- +title: begin() +--- += begin + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +This function initializes the Wire library and join the I2C bus as a controller or a peripheral. This function should normally be called only once. + +[float] +=== Syntax + +`Wire.begin()` + +`Wire.begin(address)` + +[float] +=== Parameters +* _address_: the 7-bit slave address (optional); if not specified, join the bus as a controller device. + +[float] +=== Returns +None. +-- + +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/beginTransmission.adoc b/Language/Functions/Communication/Wire/beginTransmission.adoc new file mode 100644 index 000000000..ffc686af5 --- /dev/null +++ b/Language/Functions/Communication/Wire/beginTransmission.adoc @@ -0,0 +1,28 @@ +--- +title: beginTransmission() +--- + += beginTransmission + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function begins a transmission to the I2C peripheral device with the given address. Subsequently, queue bytes for transmission with the `write()` function and transmit them by calling `endTransmission()`. + +[float] +=== Syntax + +`Wire.beginTransmission(address)` + +[float] +=== Parameters +* _address_: the 7-bit address of the device to transmit to. + +[float] +=== Returns +None. +-- +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Wire/clearWireTimeoutFlag.adoc b/Language/Functions/Communication/Wire/clearWireTimeoutFlag.adoc new file mode 100644 index 000000000..66bb41466 --- /dev/null +++ b/Language/Functions/Communication/Wire/clearWireTimeoutFlag.adoc @@ -0,0 +1,37 @@ +--- +title: clearWireTimeoutFlag() +--- += clearWireTimeoutFlag + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +Clears the timeout flag. + +Timeouts might not be enabled by default. See the documentation for `Wire.setWireTimeout()` for more information on how to configure timeouts and how they work. + + +[float] +=== Syntax + +`Wire.clearTimeout()` + +[float] +=== Parameters +None. + +[float] +=== Returns +None. + +[float] +=== Portability Notes +This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the `WIRE_HAS_TIMEOUT` macro, which is only defined when `Wire.setWireTimeout()`, `Wire.getWireTimeoutFlag()` and `Wire.clearWireTimeout()` are all available. + +-- + +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/end.adoc b/Language/Functions/Communication/Wire/end.adoc new file mode 100644 index 000000000..74871fba4 --- /dev/null +++ b/Language/Functions/Communication/Wire/end.adoc @@ -0,0 +1,31 @@ +--- +title: end() +--- += end + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +Disable the Wire library, reversing the effect of `Wire.begin()`. To use the Wire library again after this, call `Wire.begin()` again. + +*Note:* This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the `WIRE_HAS_END` macro, which is only defined when `Wire.end()` is available. + +[float] +=== Syntax + +`Wire.end()` + +[float] +=== Parameters +None. + +[float] +=== Returns +None. +-- + +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/endTransmission.adoc b/Language/Functions/Communication/Wire/endTransmission.adoc new file mode 100644 index 000000000..5687ed70a --- /dev/null +++ b/Language/Functions/Communication/Wire/endTransmission.adoc @@ -0,0 +1,34 @@ +--- +title: endTransmission() +--- + += endTransmission + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function ends a transmission to a peripheral device that was begun by `beginTransmission()` and transmits the bytes that were queued by `write()`. The `endTransmission()` method accepts a boolean argument changing its behavior for compatibility with certain I2C devices. If true, `endTransmission()` sends a stop message after transmission, releasing the I2C bus. If false, `endTransmission()` sends a restart message after transmission. The bus will not be released, which prevents another controller device from transmitting between messages. This allows one controller device to send multiple transmissions while in control. The default value is true. + +[float] +=== Syntax +`Wire.endTransmission()` +`Wire.endTransmission(stop)` + +[float] +=== Parameters + +* _stop_: true or false. True will send a stop message, releasing the bus after transmission. False will send a restart, keeping the connection active. +[float] +=== Returns + +* _0_: success. +* _1_: data too long to fit in transmit buffer. +* _2_: received NACK on transmit of address. +* _3_: received NACK on transmit of data. +* _4_: other error. +* _5_: timeout +-- +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Wire/getWireTimeoutFlag.adoc b/Language/Functions/Communication/Wire/getWireTimeoutFlag.adoc new file mode 100644 index 000000000..c50449a63 --- /dev/null +++ b/Language/Functions/Communication/Wire/getWireTimeoutFlag.adoc @@ -0,0 +1,37 @@ +--- +title: getWireTimeoutFlag() +--- += getWireTimeoutFlag + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +Checks whether a timeout has occurred since the last time the flag was cleared. + +This flag is set is set whenever a timeout occurs and cleared when `Wire.clearWireTimeoutFlag()` is called, or when the timeout is changed using `Wire.setWireTimeout()`. + + +[float] +=== Syntax + +`Wire.getWireTimeoutFlag()` + +[float] +=== Parameters +None. + +[float] +=== Returns +* bool: The current value of the flag + +[float] +=== Portability Notes +This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the `WIRE_HAS_TIMEOUT` macro, which is only defined when `Wire.setWireTimeout()`, `Wire.getWireTimeoutFlag()` and `Wire.clearWireTimeout()` are all available. + +-- + +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Wire/onReceive.adoc b/Language/Functions/Communication/Wire/onReceive.adoc new file mode 100644 index 000000000..2ca8d60dd --- /dev/null +++ b/Language/Functions/Communication/Wire/onReceive.adoc @@ -0,0 +1,30 @@ +--- +title: onReceive() +--- + += onReceive + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +This function registers a function to be called when a peripheral device receives a transmission from a controller device. + +[float] +=== Syntax +`Wire.onReceive(handler)` + +[float] +=== Parameters + +* _handler_: the function to be called when the peripheral device receives data; this should take a single int parameter (the number of bytes read from the controller device) and return nothing. + +[float] +=== Returns + +None. +-- +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Wire/onRequest.adoc b/Language/Functions/Communication/Wire/onRequest.adoc new file mode 100644 index 000000000..3b56c9a8d --- /dev/null +++ b/Language/Functions/Communication/Wire/onRequest.adoc @@ -0,0 +1,30 @@ +--- +title: onRequest() +--- + += onRequest + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function registers a function to be called when a controller device requests data from a peripheral device. + +[float] +=== Syntax +`Wire.onRequest(handler)` + +[float] +=== Parameters + +* _handler_: the function to be called, takes no parameters and returns nothing. + +[float] +=== Returns + +None. + +-- +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/read.adoc b/Language/Functions/Communication/Wire/read.adoc new file mode 100644 index 000000000..73f56240f --- /dev/null +++ b/Language/Functions/Communication/Wire/read.adoc @@ -0,0 +1,54 @@ +--- +title: read() +--- + += read + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function reads a byte that was transmitted from a peripheral device to a controller device after a call to `requestFrom()` or was transmitted from a controller device to a peripheral device. `read()` inherits from the Stream utility class. + +[float] +=== Syntax +`Wire.read()` + +[float] +=== Parameters + +None. + +[float] +=== Returns + +The next byte received. + +[float] +=== Example + +``` +#include + +void setup() { + Wire.begin(); // Join I2C bus (address is optional for controller device) + Serial.begin(9600); // Start serial for output +} + +void loop() { + Wire.requestFrom(2, 6); // Request 6 bytes from slave device number two + + // Slave may send less than requested + while(Wire.available()) { + char c = Wire.read(); // Receive a byte as character + Serial.print(c); // Print the character + } + + delay(500); +} +``` + +-- +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/requestFrom.adoc b/Language/Functions/Communication/Wire/requestFrom.adoc new file mode 100644 index 000000000..342dc54da --- /dev/null +++ b/Language/Functions/Communication/Wire/requestFrom.adoc @@ -0,0 +1,33 @@ +--- +title: requestFrom() +--- + += requestFrom + +// OVERVIEW SECTION STARTS +[#overview] + +-- + +[float] +=== Description +This function is used by the controller device to request bytes from a peripheral device. The bytes may then be retrieved with the `available()` and `read()` functions. The `requestFrom()` method accepts a boolean argument changing its behavior for compatibility with certain I2C devices. If true, `requestFrom()` sends a stop message after the request, releasing the I2C bus. If false, `requestFrom()` sends a restart message after the request. The bus will not be released, which prevents another master device from requesting between messages. This allows one master device to send multiple requests while in control. The default value is true. + +[float] +=== Syntax +`Wire.requestFrom(address, quantity)` + +`Wire.requestFrom(address, quantity, stop)` + +[float] +=== Parameters +* _address_: the 7-bit slave address of the device to request bytes from. +* _quantity_: the number of bytes to request. +* _stop_: true or false. true will send a stop message after the request, releasing the bus. False will continually send a restart after the request, keeping the connection active. + +[float] +=== Returns +* _byte_ : the number of bytes returned from the peripheral device. + +-- +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/setClock.adoc b/Language/Functions/Communication/Wire/setClock.adoc new file mode 100644 index 000000000..f47de0c20 --- /dev/null +++ b/Language/Functions/Communication/Wire/setClock.adoc @@ -0,0 +1,28 @@ +--- +title: setClock() +--- + += setClock + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function modifies the clock frequency for I2C communication. I2C peripheral devices have no minimum working clock frequency, however 100KHz is usually the baseline. + +[float] +=== Syntax +`Wire.setClock(clockFrequency)` + +[float] +=== Parameters +* _clockFrequency_: the value (in Hertz) of the desired communication clock. Accepted values are 100000 (standard mode) and 400000 (fast mode). Some processors also support 10000 (low speed mode), 1000000 (fast mode plus) and 3400000 (high speed mode). Please refer to the specific processor documentation to make sure the desired mode is supported. + +[float] +=== Returns + +None. +-- +//OVERVIEW SECTION ENDS \ No newline at end of file diff --git a/Language/Functions/Communication/Wire/setWireTimeout.adoc b/Language/Functions/Communication/Wire/setWireTimeout.adoc new file mode 100644 index 000000000..3cfe18b8e --- /dev/null +++ b/Language/Functions/Communication/Wire/setWireTimeout.adoc @@ -0,0 +1,105 @@ +--- +title: setWireTimeout() +--- += setWireTimeout + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description + +Sets the timeout for Wire transmissions in master mode. + +*Note:* these timeouts are almost always an indication of an underlying problem, such as misbehaving devices, noise, insufficient shielding, or other electrical problems. These timeouts will prevent your sketch from locking up, but not solve these problems. In such situations there will often (also) be data corruption which doesn't result in a timeout or other error and remains undetected. So when a timeout happens, it is likely that some data previously read or written is also corrupted. Additional measures might be needed to more reliably detect such issues (e.g. checksums or reading back written values) and recover from them (e.g. full system reset). This timeout and such additional measures should be seen as a last line of defence, when possible the underlying cause should be fixed instead. + +[float] +=== Syntax + +`Wire.setWireTimeout(timeout, reset_on_timeout)` + +`Wire.setWireTimeout()` + +[float] +=== Parameters +* `timeout a timeout`: timeout in microseconds, if zero then timeout checking is disabled +* `reset_on_timeout`: if true then Wire hardware will be automatically reset on timeout + +When this function is called without parameters, a default timeout is configured that should be sufficient to prevent lockups in a typical single-master configuration. + +[float] +=== Returns +None. + +[float] +=== Example Code + +``` +#include + +void setup() { + Wire.begin(); // join i2c bus (address optional for master) + #if defined(WIRE_HAS_TIMEOUT) + Wire.setWireTimeout(3000 /* us */, true /* reset_on_timeout */); + #endif +} + +byte x = 0; + +void loop() { + /* First, send a command to the other device */ + Wire.beginTransmission(8); // transmit to device #8 + Wire.write(123); // send command + byte error = Wire.endTransmission(); // run transaction + if (error) { + Serial.println("Error occurred when writing"); + if (error == 5) + Serial.println("It was a timeout"); + } + + delay(100); + + /* Then, read the result */ + #if defined(WIRE_HAS_TIMEOUT) + Wire.clearWireTimeoutFlag(); + #endif + byte len = Wire.requestFrom(8, 1); // request 1 byte from device #8 + if (len == 0) { + Serial.println("Error occurred when reading"); + #if defined(WIRE_HAS_TIMEOUT) + if (Wire.getWireTimeoutFlag()) + Serial.println("It was a timeout"); + #endif + } + + delay(100); +} +``` + +[float] +=== Notes and Warnings + +How this timeout is implemented might vary between different platforms, but typically a timeout condition is triggered when waiting for (some part of) the transaction to complete (e.g. waiting for the bus to become available again, waiting for an ACK bit, or maybe waiting for the entire transaction to be completed). + +When such a timeout condition occurs, the transaction is aborted and `endTransmission()` or `requestFrom()` will return an error code or zero bytes respectively. While this will not resolve the bus problem by itself (i.e. it does not remove a short-circuit), it will at least prevent blocking potentially indefinitely and allow your software to detect and maybe solve this condition. + +If `reset_on_timeout` was set to true and the platform supports this, the Wire hardware is also reset, which can help to clear any incorrect state inside the Wire hardware module. For example, on the AVR platform, this can be required to restart communications after a noise-induced timeout. + +When a timeout is triggered, a flag is set that can be queried with `getWireTimeoutFlag()` and must be cleared manually using `clearWireTimeoutFlag()` (and is also cleared when `setWireTimeout()` is called). + +Note that this timeout can also trigger while waiting for clock stretching or waiting for a second master to complete its transaction. So make sure to adapt the timeout to accommodate for those cases if needed. A typical timeout would be 25ms (which is the maximum clock stretching allowed by the SMBus protocol), but (much) shorter values will usually also work. + + +[float] +=== Portability Notes + +This function was not available in the original version of the Wire library and might still not be available on all platforms. Code that needs to be portable across platforms and versions can use the `WIRE_HAS_TIMEOUT` macro, which is only defined when `Wire.setWireTimeout()`, `Wire.getWireTimeoutFlag()` and `Wire.clearWireTimeout()` are all available. + +When this timeout feature was introduced on the AVR platform, it was initially kept disabled by default for compatibility, expecting it to become enabled at a later point. This means the default value of the timeout can vary between (versions of) platforms. The default timeout settings are available from the `WIRE_DEFAULT_TIMEOUT` and `WIRE_DEFAULT_RESET_WITH_TIMEOUT` macro. + +If you require the timeout to be disabled, it is recommended you disable it by default using `setWireTimeout(0)`, even though that is currently the default. + +-- + +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/Wire/write.adoc b/Language/Functions/Communication/Wire/write.adoc new file mode 100644 index 000000000..3bd29962d --- /dev/null +++ b/Language/Functions/Communication/Wire/write.adoc @@ -0,0 +1,61 @@ +--- +title: write() +--- + += write + +//OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +This function writes data from a peripheral device in response to a request from a controller device, or queues bytes for transmission from a controller to peripheral device (in-between calls to `beginTransmission()` and `endTransmission()`). + +[float] +=== Syntax +`Wire.write(value)` +`Wire.write(string)` +`Wire.write(data, length)` + +[float] +=== Parameters +* _value_: a value to send as a single byte. +* _string_: a string to send as a series of bytes. +* _data_: an array of data to send as bytes. +* _length_: the number of bytes to transmit. + +[float] +=== Returns + +The number of bytes written (reading this number is optional). +[float] +=== Example + +``` +#include + +byte val = 0; + +void setup() { + Wire.begin(); // Join I2C bus +} + +void loop() { + Wire.beginTransmission(44); // Transmit to device number 44 (0x2C) + + Wire.write(val); // Sends value byte + Wire.endTransmission(); // Stop transmitting + + val++; // Increment value + + // if reached 64th position (max) + if(val == 64) { + val = 0; // Start over from lowest value + } + + delay(500); +} +``` +-- +//OVERVIEW SECTION ENDS diff --git a/Language/Functions/Communication/stream.adoc b/Language/Functions/Communication/stream.adoc index 8950da800..7258a219e 100644 --- a/Language/Functions/Communication/stream.adoc +++ b/Language/Functions/Communication/stream.adoc @@ -22,8 +22,8 @@ Stream defines the reading functions in Arduino. When using any core functionali Some of the libraries that rely on Stream include : -* link:../serial[Serial] -* link:https://www.arduino.cc/en/Reference/Wire[Wire] +* link:https://www.arduino.cc/en/Reference/serial[Serial] +* link:https://www.arduino.cc/en/Reference/wire[Wire] * link:https://www.arduino.cc/en/Reference/Ethernet[Ethernet] * link:https://www.arduino.cc/en/Reference/SD[SD] diff --git a/Language/Functions/Digital IO/pinMode.adoc b/Language/Functions/Digital IO/pinMode.adoc index 882e8c221..46daae777 100644 --- a/Language/Functions/Digital IO/pinMode.adoc +++ b/Language/Functions/Digital IO/pinMode.adoc @@ -19,7 +19,7 @@ subCategories: [ "Digital I/O" ] === Description Configures the specified pin to behave either as an input or an output. See the http://arduino.cc/en/Tutorial/DigitalPins[Digital Pins] page for details on the functionality of the pins. [%hardbreaks] -As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode `INPUT_PULLUP`. Additionally, the `INPUT` mode explicitly disables the internal pullups. +It is possible to enable the internal pullup resistors with the mode `INPUT_PULLUP`. Additionally, the `INPUT` mode explicitly disables the internal pullups. [%hardbreaks] diff --git a/Language/Functions/External Interrupts/attachInterrupt.adoc b/Language/Functions/External Interrupts/attachInterrupt.adoc index 0a618e52c..05fa3b70c 100644 --- a/Language/Functions/External Interrupts/attachInterrupt.adoc +++ b/Language/Functions/External Interrupts/attachInterrupt.adoc @@ -19,17 +19,21 @@ The first parameter to `attachInterrupt()` is an interrupt number. Normally you [options="header"] |=================================================== -|Board |Digital Pins Usable For Interrupts -|Uno, Nano, Mini, other 328-based |2, 3 -|Uno WiFi Rev.2, Nano Every |all digital pins -|Mega, Mega2560, MegaADK |2, 3, 18, 19, 20, 21 -|Micro, Leonardo, other 32u4-based |0, 1, 2, 3, 7 -|Zero |all digital pins, except 4 -|MKR Family boards |0, 1, 4, 5, 6, 7, 8, 9, A1, A2 -|Nano 33 IoT |2, 3, 9, 10, 11, 13, 15, A5, A7 -|Nano 33 BLE, Nano 33 BLE Sense |all pins -|Due |all digital pins -|101 |all digital pins (Only pins 2, 5, 7, 8, 10, 11, 12, 13 work with *CHANGE*) +|Board |Digital Pins Usable For Interrupts| Notes +|Uno Rev3, Nano, Mini, other 328-based |2, 3| +|UNO R4 Minima, UNO R4 WiFi |2, 3| +|Uno WiFi Rev2, Nano Every |All digital pins| +|Mega, Mega2560, MegaADK |2, 3, 18, 19, 20, 21 |(*pins 20 & 21* are not available to use for interrupts while they are used for I2C communication; they also have external pull-ups that cannot be disabled) +|Micro, Leonardo |0, 1, 2, 3, 7| +|Zero |0-3, 5-13, A0-A5| Pin 4 cannot be used as an interrupt. +|MKR Family boards |0, 1, 4, 5, 6, 7, 8, 9, A1, A2| +|Nano 33 IoT |2, 3, 9, 10, 11, 13, A1, A5, A7| +|Nano 33 BLE, Nano 33 BLE Sense (rev 1 & 2) |all pins| +|Nano RP2040 Connect |0-13, A0-A5| +|Nano ESP32 |all pins| +|GIGA R1 WiFi |all pins| +|Due |all digital pins| +|101 |all digital pins | (Only pins 2, 5, 7, 8, 10, 11, 12, 13 work with *CHANGE*)) |=================================================== [%hardbreaks] @@ -133,8 +137,8 @@ Note that in the table below, the interrupt numbers refer to the number to be pa |Mega2560 | 2 | 3 | 21 | 20 | 19 | 18 |32u4 based (e.g Leonardo, Micro) | 3 | 2 | 0 | 1 | 7 | |=================================================== -For Uno WiFiRev.2, Due, Zero, MKR Family and 101 boards the *interrupt number = pin number*. +For Uno WiFi Rev2, Due, Zero, MKR Family and 101 boards the *interrupt number = pin number*. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/External Interrupts/detachInterrupt.adoc b/Language/Functions/External Interrupts/detachInterrupt.adoc index f9e7cc395..84fa30978 100644 --- a/Language/Functions/External Interrupts/detachInterrupt.adoc +++ b/Language/Functions/External Interrupts/detachInterrupt.adoc @@ -23,9 +23,9 @@ Turns off the given interrupt. [float] === Syntax -`detachInterrupt(digitalPinToInterrupt(pin))` (recommended) + -`detachInterrupt(interrupt)` (not recommended) + -`detachInterrupt(pin)` (Not recommended. Additionally, this syntax only works on Arduino SAMD Boards, Uno WiFi Rev2, Due, and 101.) +- `detachInterrupt(digitalPinToInterrupt(pin))` (recommended) + +- `detachInterrupt(interrupt)` (not recommended) + +- `detachInterrupt(pin)` (Not recommended. Additionally, this only works on a specific set of boards.) [float] diff --git a/Language/Functions/External Interrupts/digitalPinToInterrupt.adoc b/Language/Functions/External Interrupts/digitalPinToInterrupt.adoc new file mode 100644 index 000000000..a5077725f --- /dev/null +++ b/Language/Functions/External Interrupts/digitalPinToInterrupt.adoc @@ -0,0 +1,92 @@ +--- +title: digitalPinToInterrupt() +categories: [ "Functions" ] +subCategories: [ "External Interrupts" ] +--- + + + + + += digitalPinToInterrupt() + + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +=== Description +The `digitalPinToInterrupt()` function takes a pin as an argument, and returns the same pin *if* it can be used as an interrupt. For example, `digitalPinToInterrupt(4)` on an Arduino UNO will not work, as interrupts are only supported on pins 2,3. + +See link:../../external-interrupts/attachinterrupt[attachInterrupt()] for a full list of supported interrupt pins on all boards. + +[%hardbreaks] + + +[float] +=== Syntax +`digitalPinToInterrupt(pin)` + + +[float] +=== Parameters +- `pin` - the pin we want to use for an interrupt. + + +[float] +=== Returns +- The pin to interrupt (e.g. `2`)+ +- If pin is not available for interrupt, returns `-1`. + +-- +// OVERVIEW SECTION ENDS + + + + +// HOW TO USE SECTION STARTS +[#howtouse] +-- + +[float] +=== Example Code +// Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄ +This example checks if a pin can be used as an interrupt. + +[source,arduino] +---- +int pin = 2; + +void setup() { + Serial.begin(9600); + int checkPin = digitalPinToInterrupt(pin); + + if (checkPin == -1) { + Serial.println("Not a valid interrupt pin!"); + } else { + Serial.println("Valid interrupt pin."); + } +} + +void loop() { +} +---- + +-- +// HOW TO USE SECTION ENDS + + +// SEE ALSO SECTION +[#see_also] +-- + +[float] +=== See also + +[role="language"] +* #LANGUAGE# link:../../external-interrupts/attachinterrupt[attachInterrupts()] +* #LANGUAGE# link:../../external-interrupts/detachinterrupt[detachInterrupts()] + +-- +// SEE ALSO SECTION ENDS diff --git a/Language/Functions/Interrupts/interrupts.adoc b/Language/Functions/Interrupts/interrupts.adoc index 251ecced8..2158aeed6 100644 --- a/Language/Functions/Interrupts/interrupts.adoc +++ b/Language/Functions/Interrupts/interrupts.adoc @@ -17,7 +17,7 @@ subCategories: [ "Interrupts" ] [float] === Description -Re-enables interrupts (after they've been disabled by link:../nointerrupts[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. +Re-enables interrupts (after they've been disabled by link:../nointerrupts[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. [%hardbreaks] diff --git a/Language/Functions/Interrupts/noInterrupts.adoc b/Language/Functions/Interrupts/noInterrupts.adoc index c7e413dba..b925094d7 100644 --- a/Language/Functions/Interrupts/noInterrupts.adoc +++ b/Language/Functions/Interrupts/noInterrupts.adoc @@ -17,7 +17,7 @@ subCategories: [ "Interrupts" ] [float] === 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. +Disables interrupts (you can re-enable them with link:../interrupts[`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. [%hardbreaks] @@ -61,6 +61,13 @@ void loop() { // other code here } ---- +[%hardbreaks] + + +[float] +=== Notes and Warnings +Note that disabling interrupts on the Arduino boards with native USB capabilities (e.g., link:https://docs.arduino.cc/hardware/leonardo[Leonardo^]) will make the board +not appear in the Port menu, since this disables its USB capability. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/Math/abs.adoc b/Language/Functions/Math/abs.adoc index c24610f7a..5e575abb2 100644 --- a/Language/Functions/Math/abs.adoc +++ b/Language/Functions/Math/abs.adoc @@ -45,7 +45,34 @@ Calculates the absolute value of a number. // HOW TO USE SECTION STARTS [#howtouse] -- +[float] +=== Example Code +// Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄ +Prints the absolute value of variable `x` to the Serial Monitor. +[source,arduino] +---- +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + int x = 42; + Serial.print("The absolute value of "); + Serial.print(x); + Serial.print(" is "); + Serial.println(abs(x)); + x = -42; + Serial.print("The absolute value of "); + Serial.print(x); + Serial.print(" is "); + Serial.println(abs(x)); +} + +void loop() { +} +---- +[%hardbreaks] [float] === Notes and Warnings @@ -72,5 +99,14 @@ a++; // keep other math outside the function [float] === See also +[role="language"] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/constrain.adoc b/Language/Functions/Math/constrain.adoc index 5ba9436ee..7abb8f2f4 100644 --- a/Language/Functions/Math/constrain.adoc +++ b/Language/Functions/Math/constrain.adoc @@ -88,5 +88,14 @@ int constrainedInput = constrain(input, minimumValue, maximumValue); [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/map.adoc b/Language/Functions/Math/map.adoc index bc69e9ba8..ee97cf762 100644 --- a/Language/Functions/Math/map.adoc +++ b/Language/Functions/Math/map.adoc @@ -51,7 +51,7 @@ The `map()` function uses integer math so will not generate fractions, when the [float] === Returns -The mapped value. +The mapped value. Data type: `long`. -- // OVERVIEW SECTION ENDS @@ -109,5 +109,14 @@ As previously mentioned, the map() function uses integer math. So fractions migh [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/max.adoc b/Language/Functions/Math/max.adoc index b3ec6d8d1..1ea570a59 100644 --- a/Language/Functions/Math/max.adoc +++ b/Language/Functions/Math/max.adoc @@ -83,5 +83,15 @@ a--; // keep other math outside the function [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/min.adoc b/Language/Functions/Math/min.adoc index 77054141b..fc8c663c8 100644 --- a/Language/Functions/Math/min.adoc +++ b/Language/Functions/Math/min.adoc @@ -82,5 +82,14 @@ a++; // use this instead - keep other math outside the function [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/pow.adoc b/Language/Functions/Math/pow.adoc index 4beded9a1..feda5a6d9 100644 --- a/Language/Functions/Math/pow.adoc +++ b/Language/Functions/Math/pow.adoc @@ -66,9 +66,15 @@ See the (http://arduino.cc/playground/Main/Fscale[fscale]) sketch for a more com [float] === See also -[role="definition"] -* #DEFINITION# link:../../../variables/data-types/float[float] -* #DEFENITION# link:../../../variables/data-types/double[double] +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../sq[sq()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/sq.adoc b/Language/Functions/Math/sq.adoc index 484d523e3..ac403498d 100644 --- a/Language/Functions/Math/sq.adoc +++ b/Language/Functions/Math/sq.adoc @@ -72,5 +72,14 @@ int inputSquared = sq(input); [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sqrt[sqrt()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Math/sqrt.adoc b/Language/Functions/Math/sqrt.adoc index 25a918575..00f601091 100644 --- a/Language/Functions/Math/sqrt.adoc +++ b/Language/Functions/Math/sqrt.adoc @@ -46,5 +46,14 @@ The number's square root. Data type: `double`. [float] === See also +[role="language"] +* #LANGUAGE# link:../abs[abs()] +* #LANGUAGE# link:../constrain[constrain()] +* #LANGUAGE# link:../map[map()] +* #LANGUAGE# link:../max[max()] +* #LANGUAGE# link:../min[min()] +* #LANGUAGE# link:../pow[pow()] +* #LANGUAGE# link:../sq[sq()] + -- // SEE ALSO SECTION ENDS diff --git a/Language/Functions/Random Numbers/randomSeed.adoc b/Language/Functions/Random Numbers/randomSeed.adoc index 6e9292223..13ee2ad5e 100644 --- a/Language/Functions/Random Numbers/randomSeed.adoc +++ b/Language/Functions/Random Numbers/randomSeed.adoc @@ -32,7 +32,7 @@ Conversely, it can occasionally be useful to use pseudo-random sequences that re [float] === Parameters -`seed`: number to initialize the pseudo-random sequence. Allowed data types: `unsigned long`. +`seed`: non-zero number to initialize the pseudo-random sequence. Allowed data types: `unsigned long`. [float] @@ -69,6 +69,11 @@ void loop() { delay(50); } ---- +[%hardbreaks] + +[float] +=== Notes and Warnings +If the `seed` is 0, `randomSeed(seed)` will have no effect. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/Time/delayMicroseconds.adoc b/Language/Functions/Time/delayMicroseconds.adoc index 0fbf57d84..7b57914da 100644 --- a/Language/Functions/Time/delayMicroseconds.adoc +++ b/Language/Functions/Time/delayMicroseconds.adoc @@ -19,7 +19,7 @@ subCategories: [ "Time" ] === Description Pauses the program for the amount of time (in microseconds) specified by the parameter. There are a thousand microseconds in a millisecond and a million microseconds in a second. -Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use `delay()` instead. +Currently, the largest value that will produce an accurate delay is 16383; larger values can produce an extremely short delay. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use `delay()` instead. [%hardbreaks] @@ -71,9 +71,7 @@ void loop() { [float] === Notes and Warnings -This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times. - -As of Arduino 0018, delayMicroseconds() no longer disables interrupts. +This function works very accurately in the range 3 microseconds and up to 16383. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times. Larger delay times may actually delay for an extremely brief time. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/Time/micros.adoc b/Language/Functions/Time/micros.adoc index 92f274ab6..22fc13962 100644 --- a/Language/Functions/Time/micros.adoc +++ b/Language/Functions/Time/micros.adoc @@ -17,7 +17,7 @@ subCategories: [ "Time" ] [float] === 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. +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 the boards from the Arduino Portenta family this function has a resolution of one microsecond on all cores. 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. [%hardbreaks] diff --git a/Language/Functions/Time/millis.adoc b/Language/Functions/Time/millis.adoc index d031efded..cecb109dd 100644 --- a/Language/Functions/Time/millis.adoc +++ b/Language/Functions/Time/millis.adoc @@ -47,16 +47,16 @@ This example code prints on the serial port the number of milliseconds passed si [source,arduino] ---- -unsigned long time; +unsigned long myTime; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time: "); - time = millis(); + myTime = millis(); - Serial.println(time); //prints time since program started + Serial.println(myTime); // prints time since program started delay(1000); // wait a second so as not to send massive amounts of data } ---- @@ -64,7 +64,11 @@ void loop() { [float] === Notes and Warnings -Please note that the return value for millis() is of type `unsigned long`, logic errors may occur if a programmer tries to do arithmetic with smaller data types such as `int`. Even signed `long` may encounter errors as its maximum value is half that of its unsigned counterpart. + +* The return value for millis() is of type `unsigned long`, logic errors may occur if a programmer tries to do arithmetic with smaller data types such as `int`. Even signed `long` may encounter errors as its maximum value is half that of its unsigned counterpart. +* millis() is incremented (for 16 MHz AVR chips and some others) every 1.024 milliseconds, then incrementing by 2 (rather than 1) every 41 or 42 ticks, to pull it back into synch; thus some millis() values are skipped. For accurate timing over short intervals, consider using micros(). +* millis() will wrap around to 0 after about 49 days (micros in about 71 minutes). +* Reconfiguration of the microcontroller's timers may result in inaccurate `millis()` readings. The "Arduino AVR Boards" and "Arduino megaAVR Boards" cores use Timer0 to generate `millis()`. The "Arduino ARM (32-bits) Boards" and "Arduino SAMD (32-bits ARM Cortex-M0+) Boards" cores use the SysTick timer. -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/USB/Keyboard.adoc b/Language/Functions/USB/Keyboard.adoc index 20a1ac7df..6773f0e69 100644 --- a/Language/Functions/USB/Keyboard.adoc +++ b/Language/Functions/USB/Keyboard.adoc @@ -24,6 +24,23 @@ The library supports the use of modifier keys. Modifier keys change the behavior -- // OVERVIEW SECTION ENDS +[float] +=== Compatible Hardware +HID is supported on the following boards: +[options="header"] +|================================================================================================= +| Board | Supported Pins +| link:https://docs.arduino.cc/hardware/leonardo[Leonardo] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/micro[Micro] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/due[Due] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/zero[Zero] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/uno-r4-minima[UNO R4 Minima] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/uno-r4-wifi[UNO R4 WiFi] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/giga-r1-wifi[Giga R1] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/nano-esp32[Nano ESP32] | All digital & analog pins +| link:https://docs.arduino.cc/#mkr-family[MKR Family] | All digital & analog pins +|================================================================================================= + [float] === Notes and Warnings These core libraries allow the 32u4 and SAMD based boards (Leonardo, Esplora, Zero, Due and MKR Family) to appear as a native Mouse and/or Keyboard to a connected computer. diff --git a/Language/Functions/USB/Keyboard/keyboardBegin.adoc b/Language/Functions/USB/Keyboard/keyboardBegin.adoc index 1a36f3f90..52e352203 100644 --- a/Language/Functions/USB/Keyboard/keyboardBegin.adoc +++ b/Language/Functions/USB/Keyboard/keyboardBegin.adoc @@ -20,12 +20,28 @@ When used with a Leonardo or Due board, `Keyboard.begin()` starts emulating a ke [float] === Syntax -`Keyboard.begin()` +`Keyboard.begin()` + +`Keyboard.begin(layout)` [float] === Parameters -None +`layout`: the keyboard layout to use. This parameter is optional and defaults to `KeyboardLayout_en_US`. + + +[float] +=== Keyboard layouts +Currently, the library supports the following national keyboard layouts: + +* `KeyboardLayout_da_DK`: Denmark +* `KeyboardLayout_de_DE`: Germany +* `KeyboardLayout_en_US`: USA +* `KeyboardLayout_es_ES`: Spain +* `KeyboardLayout_fr_FR`: France +* `KeyboardLayout_hu_HU`: Hungary +* `KeyboardLayout_it_IT`: Italy +* `KeyboardLayout_pt_PT`: Portugal +* `KeyboardLayout_sv_SE`: Sweden [float] @@ -68,5 +84,10 @@ void loop() { } ---- + +[float] +=== Notes and Warnings +Custom layouts can be created by copying and modifying an existing layout. See the instructions in the Keyboard library's KeyboardLayout.h file. + -- // HOW TO USE SECTION ENDS diff --git a/Language/Functions/USB/Keyboard/keyboardModifiers.adoc b/Language/Functions/USB/Keyboard/keyboardModifiers.adoc index 6ff0b9c75..3ecd403df 100644 --- a/Language/Functions/USB/Keyboard/keyboardModifiers.adoc +++ b/Language/Functions/USB/Keyboard/keyboardModifiers.adoc @@ -1,11 +1,11 @@ --- -title: Keyboard Modifiers +title: Keyboard Modifiers and Special Keys --- -= Keyboard Modifiers += Keyboard modifiers and special keys // OVERVIEW SECTION STARTS @@ -14,44 +14,108 @@ title: Keyboard Modifiers [float] === Description -The `Keyboard.write()` and `Keyboard.press()` and `Keyboard.release()` commands don’t work with every possible ASCII character, only those that correspond to a key on the keyboard. For example, backspace works, but many of the other non-printable characters produce unpredictable results. For capital letters (and other keys), what’s sent is shift plus the character (i.e. the equivalent of pressing both of those keys on the keyboard). -[%hardbreaks] -A modifier key is a special key on a computer keyboard that modifies the normal action of another key when the two are pressed in combination. -[%hardbreaks] -For more on ASCII values and the characters or functions they represent, see http://www.asciitable.com/[asciitable.com] -[%hardbreaks] -For multiple key presses use link:../keyboardpress[Keyboard.press]() -[%hardbreaks] -The definitions of the modifier keys are listed below: +When given a printable ASCII character as an argument, the functions `Keyboard.write()`, `Keyboard.press()` and `Keyboard.release()` simulate actuations on the corresponding keys. These functions can also handle ASCII characters that require pressing a key in combination with Shift or, on international keyboards, AltGr. For example: +[source,arduino] +---- +Keyboard.write('a'); // press and release the 'A' key +Keyboard.write('A'); // press Shift and 'A', then release both +---- +A typical keyboard, however, has many keys that do not match a printable ASCII character. In order to simulate those keys, the library provides a set of macros that can be passed as arguments to `Keyboard.write()`, `Keyboard.press()` and `Keyboard.release()`. For example, the key combination Shift+F2 can be generated by: +[source,arduino] +---- +Keyboard.press(KEY_LEFT_SHIFT); // press and hold Shift +Keyboard.press(KEY_F2); // press and hold F2 +Keyboard.releaseAll(); // release both +---- +Note that, in order to press multiple keys simultaneously, one has to use link:../keyboardpress[`Keyboard.press()`] rather than link:../keyboardwrite[`Keyboard.write()`], as the latter just “hits” the keys (it presses and immediately releases them). [%hardbreaks] +The available macros are listed below: +[float] +=== Keyboard modifiers +These keys are meant to modify the normal action of another key when the two are pressed in combination. + +|=== +|Key |Hexadecimal value |Decimal value |Notes + +|KEY_LEFT_CTRL |0x80 |128 | +|KEY_LEFT_SHIFT |0x81 |129 | +|KEY_LEFT_ALT |0x82 |130 |Option (⌥) on Mac +|KEY_LEFT_GUI |0x83 |131 |OS logo, Command (⌘) on Mac +|KEY_RIGHT_CTRL |0x84 |132 | +|KEY_RIGHT_SHIFT |0x85 |133 | +|KEY_RIGHT_ALT |0x86 |134 |also AltGr, Option (⌥) on Mac +|KEY_RIGHT_GUI |0x87 |135 |OS logo, Command (⌘) on Mac +|=== + +[float] +=== Special keys +These are all the keys that do not match a printable ASCII character and are not modifiers. + +[float] +==== Within the alphanumeric cluster |=== |Key |Hexadecimal value |Decimal value -|KEY_LEFT_CTRL |0x80 |128 -|KEY_LEFT_SHIFT |0x81 |129 -|KEY_LEFT_ALT |0x82 |130 -|KEY_LEFT_GUI |0x83 |131 -|KEY_RIGHT_CTRL |0x84 |132 -|KEY_RIGHT_SHIFT |0x85 |133 -|KEY_RIGHT_ALT |0x86 |134 -|KEY_RIGHT_GUI |0x87 |135 -|KEY_UP_ARROW |0xDA |218 -|KEY_DOWN_ARROW |0xD9 |217 -|KEY_LEFT_ARROW |0xD8 |216 -|KEY_RIGHT_ARROW |0xD7 |215 -|KEY_BACKSPACE |0xB2 |178 |KEY_TAB |0xB3 |179 +|KEY_CAPS_LOCK |0xC1 |193 +|KEY_BACKSPACE |0xB2 |178 |KEY_RETURN |0xB0 |176 -|KEY_ESC |0xB1 |177 +|KEY_MENU |0xED |237 +|=== + +[float] +==== Navigation cluster + +|=== +|Key |Hexadecimal value |Decimal value + |KEY_INSERT |0xD1 |209 |KEY_DELETE |0xD4 |212 -|KEY_PAGE_UP |0xD3 |211 -|KEY_PAGE_DOWN |0xD6 |214 |KEY_HOME |0xD2 |210 |KEY_END |0xD5 |213 -|KEY_CAPS_LOCK |0xC1 |193 +|KEY_PAGE_UP |0xD3 |211 +|KEY_PAGE_DOWN |0xD6 |214 +|KEY_UP_ARROW |0xDA |218 +|KEY_DOWN_ARROW |0xD9 |217 +|KEY_LEFT_ARROW |0xD8 |216 +|KEY_RIGHT_ARROW |0xD7 |215 +|=== + +[float] +==== Numeric keypad + +|=== +|Key |Hexadecimal value |Decimal value + +|KEY_NUM_LOCK |0xDB |219 +|KEY_KP_SLASH |0xDC |220 +|KEY_KP_ASTERISK |0xDD |221 +|KEY_KP_MINUS |0xDE |222 +|KEY_KP_PLUS |0xDF |223 +|KEY_KP_ENTER |0xE0 |224 +|KEY_KP_1 |0xE1 |225 +|KEY_KP_2 |0xE2 |226 +|KEY_KP_3 |0xE3 |227 +|KEY_KP_4 |0xE4 |228 +|KEY_KP_5 |0xE5 |229 +|KEY_KP_6 |0xE6 |230 +|KEY_KP_7 |0xE7 |231 +|KEY_KP_8 |0xE8 |232 +|KEY_KP_9 |0xE9 |233 +|KEY_KP_0 |0xEA |234 +|KEY_KP_DOT |0xEB |235 +|=== + +[float] +==== Escape and function keys +The library can simulate function keys up to F24. + +|=== +|Key |Hexadecimal value |Decimal value + +|KEY_ESC |0xB1 |177 |KEY_F1 |0xC2 |194 |KEY_F2 |0xC3 |195 |KEY_F3 |0xC4 |196 @@ -78,5 +142,37 @@ The definitions of the modifier keys are listed below: |KEY_F24 |0xFB |251 |=== +[float] +==== Function control keys +These are three keys that sit above the navigation cluster. + +|=== +|Key |Hexadecimal value |Decimal value |Notes + +|KEY_PRINT_SCREEN |0xCE |206 |Print Screen or PrtSc / SysRq +|KEY_SCROLL_LOCK |0xCF |207 | +|KEY_PAUSE |0xD0 |208 |Pause / Break +|=== + +[float] +==== International keyboard layouts + +Some national layouts define extra keys. For example, the Swedish and Danish layouts define `KEY_A_RING` as `0xB7`, which is the key to the right of “P”, labeled “Å” on those layouts and “{”/“[” on the US layout. In order to use those definitions, one has to include the proper Keyboard_*.h file. For example: + +[source,arduino] +---- +#include +#include // extra key definitions from Swedish layout + +void setup() { + Keyboard.begin(KeyboardLayout_sv_SE); // use the Swedish layout + Keyboard.write(KEY_A_RING); +} + +void loop() {} // do-nothing loop +---- + +For the list of layout-specific key definitions, see the respective Keyboard_*.h file within the library sources. + -- // OVERVIEW SECTION ENDS diff --git a/Language/Functions/USB/Keyboard/keyboardPrint.adoc b/Language/Functions/USB/Keyboard/keyboardPrint.adoc index 1f5014d73..f93530145 100644 --- a/Language/Functions/USB/Keyboard/keyboardPrint.adoc +++ b/Language/Functions/USB/Keyboard/keyboardPrint.adoc @@ -14,7 +14,7 @@ title: Keyboard.print() [float] === Description -Sends a keystroke to a connected computer. +Sends one or more keystrokes to a connected computer. `Keyboard.print()` must be called after initiating link:../keyboardbegin[Keyboard.begin()]. [%hardbreaks] @@ -29,12 +29,12 @@ Sends a keystroke to a connected computer. [float] === Parameters `character`: a char or int to be sent to the computer as a keystroke. + -`characters`: a string to be sent to the computer as a keystroke. +`characters`: a string to be sent to the computer as keystrokes. [float] === Returns -Number of bytes sent. Data type: `size_t`. +Number of keystrokes sent. Data type: `size_t`. -- // OVERVIEW SECTION ENDS diff --git a/Language/Functions/USB/Keyboard/keyboardPrintln.adoc b/Language/Functions/USB/Keyboard/keyboardPrintln.adoc index 1ae3551ce..062b9c92f 100644 --- a/Language/Functions/USB/Keyboard/keyboardPrintln.adoc +++ b/Language/Functions/USB/Keyboard/keyboardPrintln.adoc @@ -14,7 +14,7 @@ title: Keyboard.println() [float] === Description -Sends a keystroke to a connected computer, followed by a newline and carriage return. +Sends one or more keystrokes to a connected computer, followed by a keystroke on the Enter key. `Keyboard.println()` must be called after initiating link:../keyboardbegin[Keyboard.begin()]. [%hardbreaks] @@ -23,19 +23,19 @@ Sends a keystroke to a connected computer, followed by a newline and carriage re [float] === Syntax `Keyboard.println()` + -`Keyboard.println(character)`+ +`Keyboard.println(character)` + `Keyboard.println(characters)` [float] === Parameters -`character`: a char or int to be sent to the computer as a keystroke, followed by newline and carriage return. + -`characters`: a string to be sent to the computer as a keystroke, followed by a newline and carriage return. +`character`: a char or int to be sent to the computer as a keystroke, followed by Enter. + +`characters`: a string to be sent to the computer as keystrokes, followed by Enter. [float] === Returns -Number of bytes sent. Data type: `size_t`. +Number of keystrokes sent. Data type: `size_t`. -- // OVERVIEW SECTION ENDS diff --git a/Language/Functions/USB/Mouse.adoc b/Language/Functions/USB/Mouse.adoc index adab1e421..b4a8400b8 100644 --- a/Language/Functions/USB/Mouse.adoc +++ b/Language/Functions/USB/Mouse.adoc @@ -23,6 +23,22 @@ The mouse functions enable 32u4 or SAMD micro based boards to control cursor mov -- // OVERVIEW SECTION ENDS +[float] +=== Compatible Hardware +HID is supported on the following boards: +[options="header"] +|================================================================================================= +| Board | Supported Pins +| link:https://docs.arduino.cc/hardware/leonardo[Leonardo] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/micro[Micro] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/due[Due] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/zero[Zero] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/uno-r4-minima[UNO R4 Minima] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/uno-r4-wifi[UNO R4 WiFi] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/giga-r1-wifi[Giga R1] | All digital & analog pins +| link:https://docs.arduino.cc/hardware/nano-esp32[Nano ESP32] | All digital & analog pins +| link:https://docs.arduino.cc/#mkr-family[MKR Family] | All digital & analog pins +|================================================================================================= [float] === Notes and Warnings diff --git a/Language/Functions/USB/Mouse/mouseMove.adoc b/Language/Functions/USB/Mouse/mouseMove.adoc index 852938b29..f4214f85a 100644 --- a/Language/Functions/USB/Mouse/mouseMove.adoc +++ b/Language/Functions/USB/Mouse/mouseMove.adoc @@ -110,7 +110,7 @@ int readAxis(int axisNumber) { } // the Y axis needs to be inverted in order to - // map the movemment correctly: + // map the movement correctly: if (axisNumber == 1) { distance = -distance; } diff --git a/Language/Functions/Zero, Due, MKR Family/.gitkeep b/Language/Functions/Zero, Due, MKR Family/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/Language/Structure/Bitwise Operators/bitshiftRight.adoc b/Language/Structure/Bitwise Operators/bitshiftRight.adoc index f2f98b840..444665f96 100644 --- a/Language/Structure/Bitwise Operators/bitshiftRight.adoc +++ b/Language/Structure/Bitwise Operators/bitshiftRight.adoc @@ -29,8 +29,8 @@ The right shift operator `>>` causes the bits of the left operand to be shifted [float] === Parameters -`variable`: Allowed data types: `byte`, `int`, `long`. + -`number_of_bits`: a number that is < = 32. Allowed data types: `int`. +`variable`: Allowed data types: any integer type (`byte`, `short`, `int`, `long`, `unsigned short`...). + +`number_of_bits`: a positive number smaller than the bit-width of `variable`. Allowed data types: `int`. -- // OVERVIEW SECTION ENDS @@ -47,34 +47,41 @@ The right shift operator `>>` causes the bits of the left operand to be shifted [source,arduino] ---- int a = 40; // binary: 0000000000101000 -int b = a >> 3; // binary: 0000000000000101, or 5 in decimal +int b = a >> 3; // binary: 0000000000000101, decimal: 5 ---- [%hardbreaks] [float] === Notes and Warnings -When you shift x right by y bits (x >> y), and the highest bit in x is a 1, the behavior depends on the exact data type of x. If x is of type int, the highest bit is the sign bit, determining whether x is negative or not, as we have discussed above. In that case, the sign bit is copied into lower bits, for esoteric historical reasons: +When you shift `x` right by `y` bits (`x >> y`), the `y` rightmost bits of `x` “fall off” and are discarded. If `x` has an unsigned type (e.g. `unsigned int`), the `y` leftmost bits of the result are filled with zeroes. If `x` has a signed type (e.g. `int`), its leftmost bit is the sign bit, which determines whether it is positive or negative. In this case, the `y` leftmost bits of the result are filled with copies of the sign bit. This behavior, called “sign extension”, ensures the result has the same sign as `x`. [source,arduino] ---- -int x = -16; // binary: 1111111111110000 +int x = -16; // binary: 1111111111110000 int y = 3; -int result = x >> y; // binary: 1111111111111110 +int result = x >> y; // binary: 1111111111111110, decimal: -2 ---- -This behavior, called sign extension, is often not the behavior you want. Instead, you may wish zeros to be shifted in from the left. It turns out that the right shift rules are different for unsigned int expressions, so you can use a typecast to suppress ones being copied from the left: +This may not be the behavior you want. If you instead want zeros to be shifted in from the left, you can use a typecast to suppress sign extension: [source,arduino] ---- -int x = -16; // binary: 1111111111110000 +int x = -16; // binary: 1111111111110000 int y = 3; -int result = (unsigned int)x >> y; // binary: 0001111111111110 +int result = (unsigned int)x >> y; // binary: 0001111111111110, decimal: 8190 ---- -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: +Sign extension causes the right-shift operator `>>` to perform a division by powers of 2, even with negative numbers. For example: [source,arduino] ---- -int x = 1000; -int y = x >> 3; // integer division of 1000 by 8, causing y = 125. +int x = -1000; +int y = x >> 3; // integer division of -1000 by 8, causing y = -125. +---- +But be aware of the rounding with negative numbers: +[source,arduino] +---- +int x = -1001; +int y = x >> 3; // division by shifting always rounds down, causing y = -126 +int z = x / 8; // division operator rounds towards zero, causing z = -125 ---- -- diff --git a/Language/Structure/Bitwise Operators/bitwiseAnd.adoc b/Language/Structure/Bitwise Operators/bitwiseAnd.adoc index 986a37fcc..eb8a2067b 100644 --- a/Language/Structure/Bitwise Operators/bitwiseAnd.adoc +++ b/Language/Structure/Bitwise Operators/bitwiseAnd.adoc @@ -58,7 +58,7 @@ One of the most common uses of bitwise AND is to select a particular bit (or bit [source,arduino] ---- -PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins PD0 and PD1 untouched (xx & 11 == xx) +PORTD = PORTD & 0b00000011; // clear out bits 2 - 7, leave pins PD0 and PD1 untouched (xx & 11 == xx) ---- -- diff --git a/Language/Structure/Bitwise Operators/bitwiseOr.adoc b/Language/Structure/Bitwise Operators/bitwiseOr.adoc index 14d894b8a..c0297fea7 100644 --- a/Language/Structure/Bitwise Operators/bitwiseOr.adoc +++ b/Language/Structure/Bitwise Operators/bitwiseOr.adoc @@ -56,7 +56,7 @@ One of the most common uses of the Bitwise OR is to set multiple bits in a bit-p // Note: This code is AVR architecture specific // set direction bits for pins 2 to 7, leave PD0 and PD1 untouched (xx | 00 == xx) // same as pinMode(pin, OUTPUT) for pins 2 to 7 on Uno or Nano -DDRD = DDRD | B11111100; +DDRD = DDRD | 0b11111100; ---- -- diff --git a/Language/Structure/Bitwise Operators/bitwiseXor.adoc b/Language/Structure/Bitwise Operators/bitwiseXor.adoc index d4677dbf9..995040657 100644 --- a/Language/Structure/Bitwise Operators/bitwiseXor.adoc +++ b/Language/Structure/Bitwise Operators/bitwiseXor.adoc @@ -56,12 +56,12 @@ The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some // Note: This code uses registers specific to AVR microcontrollers (Uno, Nano, Leonardo, Mega, etc.) // it will not compile for other architectures void setup() { - DDRB = DDRB | B00100000; // set PB5 (pin 13 on Uno/Nano, pin 9 on Leonardo/Micro, pin 11 on Mega) as OUTPUT + DDRB = DDRB | 0b00100000; // set PB5 (pin 13 on Uno/Nano, pin 9 on Leonardo/Micro, pin 11 on Mega) as OUTPUT Serial.begin(9600); } void loop() { - PORTB = PORTB ^ B00100000; // invert PB5, leave others untouched + PORTB = PORTB ^ 0b00100000; // invert PB5, leave others untouched delay(100); } ---- diff --git a/Language/Structure/Compound Operators/compoundBitwiseAnd.adoc b/Language/Structure/Compound Operators/compoundBitwiseAnd.adoc index 2e33d7317..aa31bb88a 100644 --- a/Language/Structure/Compound Operators/compoundBitwiseAnd.adoc +++ b/Language/Structure/Compound Operators/compoundBitwiseAnd.adoc @@ -54,22 +54,22 @@ Bits that are "bitwise ANDed" with 0 are cleared to 0 so, if myByte is a byte va [source,arduino] ---- -myByte & B00000000 = 0; +myByte & 0b00000000 = 0; ---- Bits that are "bitwise ANDed" with 1 are unchanged so, [source,arduino] ---- -myByte & B11111111 = myByte; +myByte & 0b11111111 = myByte; ---- [%hardbreaks] [float] === Notes and Warnings -Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, B00000000 is shown for clarity, but zero in any number format is zero (hmmm something philosophical there?) +Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, 0b00000000 is shown for clarity, but zero in any number format is zero (hmmm something philosophical there?) -Consequently - to clear (set to zero) bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise AND operator (&=) with the constant B11111100 +Consequently - to clear (set to zero) bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise AND operator (&=) with the constant 0b11111100 1 0 1 0 1 0 1 0 variable 1 1 1 1 1 1 0 0 mask @@ -93,8 +93,8 @@ So if: [source,arduino] ---- -myByte = B10101010; -myByte &= B11111100; // results in B10101000 +myByte = 0b10101010; +myByte &= 0b11111100; // results in 0b10101000 ---- [%hardbreaks] diff --git a/Language/Structure/Compound Operators/compoundBitwiseOr.adoc b/Language/Structure/Compound Operators/compoundBitwiseOr.adoc index 815d98771..5cae450f2 100644 --- a/Language/Structure/Compound Operators/compoundBitwiseOr.adoc +++ b/Language/Structure/Compound Operators/compoundBitwiseOr.adoc @@ -49,22 +49,22 @@ A review of the Bitwise OR `|` operator: Bits that are "bitwise ORed" with 0 are unchanged, so if myByte is a byte variable, [source,arduino] ---- -myByte | B00000000 = myByte; +myByte | 0b00000000 = myByte; ---- Bits that are "bitwise ORed" with 1 are set to 1 so: [source,arduino] ---- -myByte | B11111111 = B11111111; +myByte | 0b11111111 = 0b11111111; ---- [%hardbreaks] [float] === Notes and Warnings -Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, B00000000 is shown for clarity, but zero in any number format is zero. +Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, 0b00000000 is shown for clarity, but zero in any number format is zero. [%hardbreaks] -Consequently - to set bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise OR operator (|=) with the constant B00000011 +Consequently - to set bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise OR operator (|=) with the constant 0b00000011 1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask @@ -88,8 +88,8 @@ Here is the same representation with the variables bits replaced with the symbol So if: [source,arduino] ---- -myByte = B10101010; -myByte |= B00000011 == B10101011; +myByte = 0b10101010; +myByte |= 0b00000011 == 0b10101011; ---- -- diff --git a/Language/Structure/Compound Operators/compoundBitwiseXor.adoc b/Language/Structure/Compound Operators/compoundBitwiseXor.adoc index 267d44fd9..8ddecc915 100644 --- a/Language/Structure/Compound Operators/compoundBitwiseXor.adoc +++ b/Language/Structure/Compound Operators/compoundBitwiseXor.adoc @@ -49,22 +49,22 @@ A review of the Bitwise XOR `^` operator: Bits that are "bitwise XORed" with 0 are left unchanged. So if myByte is a byte variable, [source,arduino] ---- -myByte ^ B00000000 = myByte; +myByte ^ 0b00000000 = myByte; ---- Bits that are "bitwise XORed" with 1 are toggled so: [source,arduino] ---- -myByte ^ B11111111 = ~myByte; +myByte ^ 0b11111111 = ~myByte; ---- [%hardbreaks] [float] === Notes and Warnings -Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, B00000000 is shown for clarity, but zero in any number format is zero. +Because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, 0b00000000 is shown for clarity, but zero in any number format is zero. [%hardbreaks] -Consequently - to toggle bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise XOR operator (^=) with the constant B00000011 +Consequently - to toggle bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise XOR operator (^=) with the constant 0b00000011 1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask @@ -88,8 +88,8 @@ Here is the same representation with the variables bits replaced with the symbol So if: [source,arduino] ---- -myByte = B10101010; -myByte ^= B00000011 == B10101001; +myByte = 0b10101010; +myByte ^= 0b00000011 == 0b10101001; ---- -- diff --git a/Language/Structure/Compound Operators/compoundMultiplication.adoc b/Language/Structure/Compound Operators/compoundMultiplication.adoc index b2ec543ab..cd5f56582 100644 --- a/Language/Structure/Compound Operators/compoundMultiplication.adoc +++ b/Language/Structure/Compound Operators/compoundMultiplication.adoc @@ -47,7 +47,7 @@ This is a convenient shorthand to perform multiplication of a variable with anot [source,arduino] ---- x = 2; -x *= 2; // x now contains 4 +x *= 3; // x now contains 6 ---- diff --git a/Language/Structure/Compound Operators/increment.adoc b/Language/Structure/Compound Operators/increment.adoc index b9dd49b7b..7419f1ff6 100644 --- a/Language/Structure/Compound Operators/increment.adoc +++ b/Language/Structure/Compound Operators/increment.adoc @@ -24,8 +24,8 @@ Increments the value of a variable by 1. [float] === Syntax -`x++; // increment x by one and returns the old value of x` + -`++x; // increment x by one and returns the new value of x` +`x{plus}{plus}; // increment x by one and returns the old value of x` + +`{plus}{plus}x; // increment x by one and returns the new value of x` [float] diff --git a/Language/Structure/Control Structure/doWhile.adoc b/Language/Structure/Control Structure/doWhile.adoc index c79421917..033d32b9c 100644 --- a/Language/Structure/Control Structure/doWhile.adoc +++ b/Language/Structure/Control Structure/doWhile.adoc @@ -32,7 +32,7 @@ do { [float] === Parameters -`condition`: a boolean expression that evaluates to `link:../../../variables/constants/constants[true]` or `link:../../../variables/constants/constants[false]`. +`condition`: a boolean expression that evaluates to `link:../../../variables/constants/truefalse[true]` or `link:../../../variables/constants/truefalse[false]`. -- // OVERVIEW SECTION ENDS @@ -49,11 +49,15 @@ do { [source,arduino] ---- +// initialize x and i with a value of 0 int x = 0; +int i = 0; + do { delay(50); // wait for sensors to stabilize x = readSensors(); // check the sensors -} while (x < 100); + i++; // increase i by 1 +} while (i < 100); // repeat 100 times ---- diff --git a/Language/Structure/Control Structure/for.adoc b/Language/Structure/Control Structure/for.adoc index 7e02a21f7..3ddf86d4f 100644 --- a/Language/Structure/Control Structure/for.adoc +++ b/Language/Structure/Control Structure/for.adoc @@ -34,8 +34,8 @@ for (initialization; condition; increment) { [float] === Parameters `initialization`: happens first and exactly once. + -`condition`: each time through the loop, `condition` is tested; if it's `link:../../../variables/constants/constants[true]`, the statement block, and the *increment* is executed, then the *condition* is tested again. When the *condition* becomes `link:../../../variables/constants/constants[false]`, the loop ends. + -`increment`: executed each time through the loop when `condition` is link:../../../variables/constants/constants[`true`]. +`condition`: each time through the loop, `condition` is tested; if it's `link:../../../variables/constants/truefalse[true]`, the statement block, and the *increment* is executed, then the *condition* is tested again. When the *condition* becomes `link:../../../variables/constants/truefalse[false]`, the loop ends. + +`increment`: executed each time through the loop when `condition` is link:../../../variables/constants/truefalse[`true`]. -- // OVERVIEW SECTION ENDS @@ -51,8 +51,8 @@ for (initialization; condition; increment) { === Example Code [source,arduino] ---- -// Dim an LED using a PWM pin -int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10 +// Brighten an LED using a PWM pin +int PWMpin = 10; // LED in series with 470 ohm resistor from pin 10 to ground void setup() { // no setup needed diff --git a/Language/Structure/Control Structure/if.adoc b/Language/Structure/Control Structure/if.adoc index f1a79934e..45ad2da20 100644 --- a/Language/Structure/Control Structure/if.adoc +++ b/Language/Structure/Control Structure/if.adoc @@ -16,7 +16,7 @@ subCategories: [ "Control Structure" ] -- [float] === Description -The `if` statement checks for a condition and executes the proceeding statement or set of statements if the condition is 'true'. +The `if` statement checks for a condition and executes the following statement or set of statements if the condition is 'true'. [%hardbreaks] [float] @@ -101,6 +101,7 @@ This is because C++ evaluates the statement `if (x=10)` as follows: 10 is assign === See also [role="language"] +* #LANGUAGE# link:../else[else] -- // SEE ALSO SECTION ENDS diff --git a/Language/Structure/Control Structure/switchCase.adoc b/Language/Structure/Control Structure/switchCase.adoc index faa4a60a7..7b2fad04d 100644 --- a/Language/Structure/Control Structure/switchCase.adoc +++ b/Language/Structure/Control Structure/switchCase.adoc @@ -44,9 +44,12 @@ switch (var) { [float] === Parameters -`var`: a variable whose value to compare with various cases. Allowed data types: `int`, `char`. + -`label1`, `label2`: constants. Allowed data types: `int`, `char`. +`var`: an *integer* variable whose value to compare with various cases. Any integer data type is allowed*, such as `byte`, `char`, `int`, `long`. +`label1`, `label2`: constants. Any integer data type here is also allowed. +*You can also use the `bool` data type when you specify just two switch cases. + +Note that you can also use negative values as input. [float] === Returns @@ -69,10 +72,10 @@ Nothing ---- switch (var) { case 1: - //do something when var equals 1 + // do something when var equals 1 break; case 2: - //do something when var equals 2 + // do something when var equals 2 break; default: // if nothing else matches, do the default @@ -89,7 +92,7 @@ switch (var) { -// SEE ALSO SECTIN BEGINS +// SEE ALSO SECTION BEGINS [#see_also] -- diff --git a/Language/Structure/Control Structure/while.adoc b/Language/Structure/Control Structure/while.adoc index 491cceb88..09b25192c 100644 --- a/Language/Structure/Control Structure/while.adoc +++ b/Language/Structure/Control Structure/while.adoc @@ -71,7 +71,7 @@ while (var < 200) { [role="language"] [role="example"] -* #EXAMPLE# https://arduino.cc/en/Tutorial/WhileLoop[While Loop^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/BuiltInExamples/WhileStatementConditional[While Loop^] -- // SEE ALSO SECTION ENDS diff --git a/Language/Structure/Further Syntax/define.adoc b/Language/Structure/Further Syntax/define.adoc index 561a6d7e8..c04df008f 100644 --- a/Language/Structure/Further Syntax/define.adoc +++ b/Language/Structure/Further Syntax/define.adoc @@ -24,7 +24,7 @@ subCategories: [ "Further Syntax" ] This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text). [%hardbreaks] -In general, the `link:../../../variables/variable-scope\--qualifiers/const[const]` keyword is preferred for defining constants and should be used instead of `#define`. +In general, the `link:../../../variables/variable-scope-qualifiers/const[const]` keyword is preferred for defining constants and should be used instead of `#define`. [%hardbreaks] [float] @@ -88,8 +88,7 @@ Similarly, including an equal sign after the #define statement will also generat === See also [role="language"] -* #LANGUAGE# link:../../../variables/variable-scope\--qualifiers/const[const] -* #LANGUAGE# link:../../../variables/constants/constants[Constants] +* #LANGUAGE# link:../../../variables/variable-scope-qualifiers/const[const] -- // SEE ALSO SECTION ENDS diff --git a/Language/Structure/Further Syntax/include.adoc b/Language/Structure/Further Syntax/include.adoc index e4020e65e..478a1ab28 100644 --- a/Language/Structure/Further Syntax/include.adoc +++ b/Language/Structure/Further Syntax/include.adoc @@ -27,6 +27,18 @@ The main reference page for AVR C libraries (AVR is a reference to the Atmel chi Note that `#include`, similar to `link:../define[#define]`, has no semicolon terminator, and the compiler will yield cryptic error messages if you add one. [%hardbreaks] + +[float] +=== Syntax +`#include ` + +`#include "LocalFile.h"` + + +[float] +=== Parameters +`LibraryFile.h`: when the angle brackets syntax is used, the libraries paths will be searched for the file. + +`LocalFile.h`: When the double quotes syntax is used, the folder of the file using the `#include` directive will be searched for the specified file, then the libraries paths if it was not found in the local path. Use this syntax for header files in the sketch's folder. + -- // OVERVIEW SECTION ENDS diff --git a/Language/Variables/Constants/constants.adoc b/Language/Variables/Constants/constants.adoc deleted file mode 100644 index 6bbff458b..000000000 --- a/Language/Variables/Constants/constants.adoc +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: constants -categories: [ "Variables" ] -subCategories: [ "Constants" ] ---- - -= Constants - - -// OVERVIEW SECTION STARTS -[#overview] --- - -[float] -== Description -Constants are predefined expressions in the Arduino language. They are used to make the programs easier to read. We classify constants in groups: - -[float] -== Defining Logical Levels: true and false (Boolean Constants) -There are two constants used to represent truth and falsity in the Arduino language: `true`, and `false`. - -[float] -=== false -`false` is the easier of the two to define. false is defined as 0 (zero). -[%hardbreaks] - -[float] -=== 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. -[%hardbreaks] - -Note that the `true` and `false` constants are typed in lowercase unlike `HIGH`, `LOW`, `INPUT`, and `OUTPUT`. -[%hardbreaks] - -[float] -== 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`. - -[float] -=== 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 `link:../../../functions/digital-io/pinmode[pinMode()]`, and read with `link:../../../functions/digital-io/digitalread[digitalRead()]`, the Arduino (ATmega) will report `HIGH` if: - - - a voltage greater than 3.0V is present at the pin (5V boards) - - a voltage greater than 2.0V volts is present at the pin (3.3V boards) -[%hardbreaks] - -A pin may also be configured as an INPUT with link:../../../functions/digital-io/pinmode[`pinMode()`], and subsequently made HIGH with `link:../../../functions/digital-io/digitalwrite[digitalWrite()]`. This will enable the internal 20K pullup resistors, which will _pull up_ the input pin to a `HIGH` reading unless it is pulled `LOW` by external circuitry. This can done alternatively by passing `INPUT_PULLUP` as argument to the link:../../../functions/digital-io/pinmode[`pinMode()`] funtion, as explained in more detail in the section "Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT" further below. -[%hardbreaks] - -When a pin is configured to OUTPUT with link:../../../functions/digital-io/pinmode[`pinMode()`], and set to `HIGH` with link:../../../functions/digital-io/digitalwrite[`digitalWrite()`], the pin is at: - - - 5 volts (5V boards) - - 3.3 volts (3.3V boards) - -In this state it can source current, e.g. light an LED that is connected through a series resistor to ground. -[%hardbreaks] - -[float] -=== 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 link:../../../functions/digital-io/pinmode[`pinMode()`], and read with link:../../../functions/digital-io/digitalread[`digitalRead()`], the Arduino (ATmega) will report LOW if: - - - a voltage less than 1.5V is present at the pin (5V boards) - - a voltage less than 1.0V (Approx) is present at the pin (3.3V boards) - -When a pin is configured to `OUTPUT` with link:../../../functions/digital-io/pinmode[`pinMode()`], and set to `LOW` with link:../../../functions/digital-io/digitalwrite[`digitalWrite()`], the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts). -[%hardbreaks] - -[float] -== Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT -Digital pins can be used as `INPUT`, `INPUT_PULLUP`, or `OUTPUT`. Changing a pin with link:../../../functions/digital-io/pinmode[`pinMode()`] changes the electrical behavior of the pin. - -[float] -=== Pins Configured as INPUT -Arduino (ATmega) pins configured as `INPUT` with link:../../../functions/digital-io/pinmode[`pinMode()`] are said to be in a _high-impedance_ state. Pins configured as `INPUT` make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 Megohms in front of the pin. This makes them useful for reading a sensor. -[%hardbreaks] - -If you have your pin configured as an `INPUT`, and are reading a switch, when the switch is in the open state the input pin will be "floating", resulting in unpredictable results. In order to assure a proper reading when the switch is open, a pull-up or pull-down resistor must be used. The purpose of this resistor is to pull the pin to a known state when the switch is open. A 10 K ohm resistor is usually chosen, as it is a low enough value to reliably prevent a floating input, and at the same time a high enough value to not draw too much current when the switch is closed. See the http://arduino.cc/en/Tutorial/DigitalReadSerial[Digital Read Serial^] tutorial for more information. -[%hardbreaks] - -If a pull-down resistor is used, the input pin will be `LOW` when the switch is open and `HIGH` when the switch is closed. -[%hardbreaks] - -If a pull-up resistor is used, the input pin will be `HIGH` when the switch is open and `LOW` when the switch is closed. -[%hardbreaks] - -[float] -=== Pins Configured as INPUT_PULLUP -The ATmega microcontroller on the Arduino has internal pull-up resistors (resistors that connect to power internally) that you can access. If you prefer to use these instead of external pull-up resistors, you can use the `INPUT_PULLUP` argument in link:../../../functions/digital-io/pinmode[`pinMode()`]. -[%hardbreaks] - -See the http://arduino.cc/en/Tutorial/InputPullupSerial[Input Pullup Serial^] tutorial for an example of this in use. -[%hardbreaks] - -Pins configured as inputs with either `INPUT` or `INPUT_PULLUP` can be damaged or destroyed if they are connected to voltages below ground (negative voltages) or above the positive power rail (5V or 3V). -[%hardbreaks] - -[float] -=== Pins Configured as OUTPUT -Pins configured as `OUTPUT` with link:../../../functions/digital-io/pinmode[`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 current) or sink (absorb current) up to 40 mA (milliamps) of current to other devices/circuits. This makes them useful for powering LEDs because LEDs typically use less than 40 mA. Loads greater than 40 mA (e.g. motors) will require a transistor or other interface circuitry. -[%hardbreaks] - -Pins configured as outputs can be damaged or destroyed if they are connected to either the ground or positive power rails. -[%hardbreaks] - -[float] -== Defining built-ins: LED_BUILTIN -Most Arduino boards have a pin connected to an on-board LED in series with a resistor. The constant `LED_BUILTIN` is the number of the pin to which the on-board LED is connected. Most boards have this LED connected to digital pin 13. - --- -// OVERVIEW SECTION ENDS - - - -// HOW TO USE SECTION STARTS -[#howtouse] --- - --- -// HOW TO USE SECTION ENDS - -// SEE ALSO SECTION BEGINS -[#see_also] --- - -[float] -=== See also - -[role="language"] - --- -// SEE ALSO SECTION ENDS diff --git a/Language/Variables/Constants/floatingPointConstants.adoc b/Language/Variables/Constants/floatingPointConstants.adoc index 43e248203..2d3defe04 100644 --- a/Language/Variables/Constants/floatingPointConstants.adoc +++ b/Language/Variables/Constants/floatingPointConstants.adoc @@ -34,7 +34,7 @@ Similar to integer constants, floating point constants are used to make code mor [source,arduino] ---- -n = 0.005; // 0.005 is a floating point constant +float n = 0.005; // 0.005 is a floating point constant ---- [%hardbreaks] diff --git a/Language/Variables/Constants/highLow.adoc b/Language/Variables/Constants/highLow.adoc new file mode 100644 index 000000000..1bec2b54e --- /dev/null +++ b/Language/Variables/Constants/highLow.adoc @@ -0,0 +1,61 @@ +--- +title: HIGH | LOW +categories: [ "Variables" ] +subCategories: [ "Constants" ] +--- + += HIGH | LOW + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +== 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`. These are the same as `true` and `false`, as well as `1` and `0`. + +[float] +=== 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 `link:../../../functions/digital-io/pinmode[pinMode()]`, and read with `link:../../../functions/digital-io/digitalread[digitalRead()]`, the Arduino (ATmega) will report `HIGH` if: + + - a voltage greater than 3.0V is present at the pin (5V boards) + - a voltage greater than 2.0V is present at the pin (3.3V boards) +[%hardbreaks] + +A pin may also be configured as an INPUT with link:../../../functions/digital-io/pinmode[`pinMode()`], and subsequently made HIGH with `link:../../../functions/digital-io/digitalwrite[digitalWrite()]`. This will enable the internal 20K pullup resistors, which will _pull up_ the input pin to a `HIGH` reading unless it is pulled `LOW` by external circuitry. This can be done alternatively by passing `INPUT_PULLUP` as argument to the link:../../../functions/digital-io/pinmode[`pinMode()`] function, as explained in more detail in the section "Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT" further below. +[%hardbreaks] + +When a pin is configured to OUTPUT with link:../../../functions/digital-io/pinmode[`pinMode()`], and set to `HIGH` with link:../../../functions/digital-io/digitalwrite[`digitalWrite()`], the pin is at: + + - 5 volts (5V boards) + - 3.3 volts (3.3V boards) + +In this state it can source current, e.g. light an LED that is connected through a series resistor to ground. +[%hardbreaks] + +[float] +=== 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 Arduino (ATmega) will report LOW if: + +a voltage less than 1.5V is present at the pin (5V boards) + +a voltage less than 1.0V (Approx) is present at the pin (3.3V boards) + +When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts). + +-- +// OVERVIEW SECTION ENDS + + +// SEE ALSO SECTION BEGINS +[#see_also] +-- + +[float] +=== See also + +[role="language"] + +-- +// SEE ALSO SECTION ENDS diff --git a/Language/Variables/Constants/inputOutputPullup.adoc b/Language/Variables/Constants/inputOutputPullup.adoc new file mode 100644 index 000000000..5cf653401 --- /dev/null +++ b/Language/Variables/Constants/inputOutputPullup.adoc @@ -0,0 +1,73 @@ +--- +title: INPUT | INPUT_PULLUP | OUTPUT +categories: [ "Variables" ] +subCategories: [ "Constants" ] +--- + += INPUT | INPUT_PULLUP | OUTPUT + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +== Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT +Digital pins can be used as `INPUT`, `INPUT_PULLUP`, or `OUTPUT`. Changing a pin with link:../../../functions/digital-io/pinmode[`pinMode()`] changes the electrical behavior of the pin. + +-- +// OVERVIEW SECTION ENDS + +// HOW TO USE SECTION STARTS +[#howtouse] +-- + +[float] +=== INPUT +Arduino (ATmega) pins configured as `INPUT` with link:../../../functions/digital-io/pinmode[`pinMode()`] are said to be in a _high-impedance_ state. Pins configured as `INPUT` make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 Megohms in front of the pin. This makes them useful for reading a sensor. +[%hardbreaks] + +If you have your pin configured as an `INPUT`, and are reading a switch, when the switch is in the open state the input pin will be "floating", resulting in unpredictable results. In order to assure a proper reading when the switch is open, a pull-up or pull-down resistor must be used. The purpose of this resistor is to pull the pin to a known state when the switch is open. A 10 K ohm resistor is usually chosen, as it is a low enough value to reliably prevent a floating input, and at the same time a high enough value to not draw too much current when the switch is closed. See the http://arduino.cc/en/Tutorial/DigitalReadSerial[Digital Read Serial^] tutorial for more information. +[%hardbreaks] + +If a pull-down resistor is used, the input pin will be `LOW` when the switch is open and `HIGH` when the switch is closed. +[%hardbreaks] + +If a pull-up resistor is used, the input pin will be `HIGH` when the switch is open and `LOW` when the switch is closed. +[%hardbreaks] + +[float] +=== INPUT_PULLUP +The ATmega microcontroller on the Arduino has internal pull-up resistors (resistors that connect to power internally) that you can access. If you prefer to use these instead of external pull-up resistors, you can use the `INPUT_PULLUP` argument in link:../../../functions/digital-io/pinmode[`pinMode()`]. +[%hardbreaks] + +See the http://arduino.cc/en/Tutorial/InputPullupSerial[Input Pullup Serial^] tutorial for an example of this in use. +[%hardbreaks] + +Pins configured as inputs with either `INPUT` or `INPUT_PULLUP` can be damaged or destroyed if they are connected to voltages below ground (negative voltages) or above the positive power rail (5V or 3V). +[%hardbreaks] + +[float] +=== OUTPUT +Pins configured as `OUTPUT` with link:../../../functions/digital-io/pinmode[`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 current) or sink (absorb current) up to 40 mA (milliamps) of current to other devices/circuits. This makes them useful for powering LEDs because LEDs typically use less than 40 mA. Loads greater than 40 mA (e.g. motors) will require a transistor or other interface circuitry. +[%hardbreaks] + +Pins configured as outputs can be damaged or destroyed if they are connected to either the ground or positive power rails. +[%hardbreaks] + + +-- +// HOW TO USE SECTION ENDS + + + +// SEE ALSO SECTION BEGINS +[#see_also] +-- + +[float] +=== See also + +[role="language"] + +-- +// SEE ALSO SECTION ENDS \ No newline at end of file diff --git a/Language/Variables/Constants/integerConstants.adoc b/Language/Variables/Constants/integerConstants.adoc index d34e50370..71e93ed15 100644 --- a/Language/Variables/Constants/integerConstants.adoc +++ b/Language/Variables/Constants/integerConstants.adoc @@ -32,9 +32,9 @@ Normally, integer constants are treated as base 10 (decimal) integers, but speci | |2 (binary) -|B1111011 -|leading 'B' -|only works with 8 bit values (0 to 255) characters 0&1 valid +|0b1111011 +|leading "0b" +|characters 0&1 valid |8 (octal) |0173 @@ -76,13 +76,7 @@ Only the characters 0 and 1 are valid. === Example Code: [source,arduino] ---- -n = 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: -[source,arduino] ----- -myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte` +n = 0b101; // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1) ---- [%hardbreaks] diff --git a/Language/Variables/Constants/ledbuiltin.adoc b/Language/Variables/Constants/ledbuiltin.adoc new file mode 100644 index 000000000..7ff780510 --- /dev/null +++ b/Language/Variables/Constants/ledbuiltin.adoc @@ -0,0 +1,31 @@ +--- +title: LED_BUILTIN +categories: [ "Variables" ] +subCategories: [ "Constants" ] +--- + += LED_BUILTIN + +// OVERVIEW SECTION STARTS +[#overview] +-- + +[float] +== Defining built-ins: LED_BUILTIN +Most Arduino boards have a pin connected to an on-board LED in series with a resistor. The constant `LED_BUILTIN` is the number of the pin to which the on-board LED is connected. Most boards have this LED connected to digital pin 13. + +-- +// OVERVIEW SECTION ENDS + + +// SEE ALSO SECTION BEGINS +[#see_also] +-- + +[float] +=== See also + +[role="language"] + +-- +// SEE ALSO SECTION ENDS \ No newline at end of file diff --git a/Language/Variables/Constants/trueFalse.adoc b/Language/Variables/Constants/trueFalse.adoc new file mode 100644 index 000000000..fe260f872 --- /dev/null +++ b/Language/Variables/Constants/trueFalse.adoc @@ -0,0 +1,47 @@ +--- +title: 'true | false' +categories: [ "Variables" ] +subCategories: [ "Constants" ] +--- + += true | false + +// OVERVIEW SECTION STARTS +[#overview] +-- + +There are two constants used to represent truth and falsity in the Arduino language: `true`, and `false`. + +[float] +=== 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. +[%hardbreaks] + +Note that the `true` and `false` constants are typed in lowercase unlike `HIGH`, `LOW`, `INPUT`, and `OUTPUT`. +[%hardbreaks] + + +[float] +=== false +`false` is the easier of the two to define. false is defined as 0 (zero). +[%hardbreaks] + +Note that the `true` and `false` constants are typed in lowercase unlike `HIGH`, `LOW`, `INPUT`, and `OUTPUT`. +[%hardbreaks] + +-- +// OVERVIEW SECTION ENDS + + + +// SEE ALSO SECTION BEGINS +[#see_also] +-- + +[float] +=== See also + +[role="language"] + +-- +// SEE ALSO SECTION ENDS \ No newline at end of file diff --git a/Language/Variables/Data Types/String/Functions/charAt.adoc b/Language/Variables/Data Types/String/Functions/charAt.adoc index a546ddd01..cb571e95a 100644 --- a/Language/Variables/Data Types/String/Functions/charAt.adoc +++ b/Language/Variables/Data Types/String/Functions/charAt.adoc @@ -35,7 +35,7 @@ Access a particular character of the String. [float] === Returns -The n'th character of the String. +The character at index n of the String. -- // OVERVIEW SECTION ENDS diff --git a/Language/Variables/Data Types/String/Functions/length.adoc b/Language/Variables/Data Types/String/Functions/length.adoc index a0b644b42..d3703282e 100644 --- a/Language/Variables/Data Types/String/Functions/length.adoc +++ b/Language/Variables/Data Types/String/Functions/length.adoc @@ -34,7 +34,7 @@ Returns the length of the String, in characters. (Note that this doesn't include [float] === Returns -The length of the String in characters. +The length of the String in characters. Data type: `unsigned int`. -- // OVERVIEW SECTION ENDS diff --git a/Language/Variables/Data Types/String/Functions/reserve.adoc b/Language/Variables/Data Types/String/Functions/reserve.adoc index 10d76d6ec..de64fdd0d 100644 --- a/Language/Variables/Data Types/String/Functions/reserve.adoc +++ b/Language/Variables/Data Types/String/Functions/reserve.adoc @@ -35,7 +35,7 @@ The String reserve() function allows you to allocate a buffer in memory for mani [float] === Returns -Nothing +`1` on success, `0` on failure. -- // OVERVIEW SECTION ENDS diff --git a/Language/Variables/Data Types/String/Functions/toLowerCase.adoc b/Language/Variables/Data Types/String/Functions/toLowerCase.adoc index 9fe9a2fb5..2d1ba3b57 100644 --- a/Language/Variables/Data Types/String/Functions/toLowerCase.adoc +++ b/Language/Variables/Data Types/String/Functions/toLowerCase.adoc @@ -17,7 +17,7 @@ subCategories: [ "StringObject Function" ] [float] === Description -Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the String in place rather than returning a new one. +Get a lower-case version of a String. The `toLowerCase()` function modifies the String in place rather than returning a new one. [%hardbreaks] diff --git a/Language/Variables/Data Types/String/Functions/toUpperCase.adoc b/Language/Variables/Data Types/String/Functions/toUpperCase.adoc index 81ef0dd79..231dcc27c 100644 --- a/Language/Variables/Data Types/String/Functions/toUpperCase.adoc +++ b/Language/Variables/Data Types/String/Functions/toUpperCase.adoc @@ -17,7 +17,7 @@ subCategories: [ "StringObject Function" ] [float] === Description -Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the String in place rather than returning a new one. +Get an upper-case version of a String. The `toUpperCase()` modifies the String in place rather than returning a new one. [%hardbreaks] diff --git a/Language/Variables/Data Types/String/Functions/trim.adoc b/Language/Variables/Data Types/String/Functions/trim.adoc index f5a3fb27d..3714c4f87 100644 --- a/Language/Variables/Data Types/String/Functions/trim.adoc +++ b/Language/Variables/Data Types/String/Functions/trim.adoc @@ -17,7 +17,7 @@ subCategories: [ "StringObject Function" ] [float] === Description -Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the String in place rather than returning a new one. +Get a version of the String with any leading and trailing whitespace removed. The `trim()` function modifies the String in place rather than returning a new one. [%hardbreaks] diff --git a/Language/Variables/Data Types/String/Operators/differentFrom.adoc b/Language/Variables/Data Types/String/Operators/differentFrom.adoc index c26fe47d4..7cb1ce0d7 100644 --- a/Language/Variables/Data Types/String/Operators/differentFrom.adoc +++ b/Language/Variables/Data Types/String/Operators/differentFrom.adoc @@ -7,8 +7,6 @@ subCategories: [ "StringObject Operator" ] - - = != Different From @@ -30,7 +28,7 @@ Compares two Strings for difference. The comparison is case-sensitive, meaning t [float] === Parameters -`myString1: a String variable. + +`myString1`: a String variable. + `myString2`: a String variable. diff --git a/Language/Variables/Data Types/array.adoc b/Language/Variables/Data Types/array.adoc index b038a83db..d9b781b61 100644 --- a/Language/Variables/Data Types/array.adoc +++ b/Language/Variables/Data Types/array.adoc @@ -19,16 +19,21 @@ An array is a collection of variables that are accessed with an index number. Ar All of the methods below are valid ways to create (declare) an array. [source,arduino] ---- + // Declare an array of a given length without initializing the values: int myInts[6]; - int myPins[] = {2, 4, 8, 3, 6}; - int mySensVals[6] = {2, 4, -8, 3, 2}; + + // Declare an array without explicitly choosing a size (the compiler + // counts the elements and creates an array of the appropriate size): + int myPins[] = {2, 4, 8, 3, 6, 4}; + + // Declare an array of a given length and initialize its values: + int mySensVals[5] = {2, 4, -8, 3, 2}; + + // When declaring an array of type char, you'll need to make it longer + // by one element to hold the required the null termination character: char message[6] = "hello"; ---- -You can declare an array without initializing it as in myInts. -{empty} + -In myPins we declare an array without explicitly choosing a size. The compiler counts the elements and creates an array of the appropriate size. -{empty} + -Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character. + [%hardbreaks] [float] @@ -83,7 +88,7 @@ for (byte i = 0; i < 5; i = i + 1) { [float] === Example Code -For a complete program that demonstrates the use of arrays, see the (http://www.arduino.cc/en/Tutorial/KnightRider[Knight Rider example]) from the (http://www.arduino.cc/en/Main/LearnArduino[Tutorials]). +For a complete program that demonstrates the use of arrays, see the (https://docs.arduino.cc/built-in-examples/control-structures/Arrays[How to Use Arrays example]) from the (https://docs.arduino.cc/built-in-examples[Built-in Examples]). -- // HOW TO USE SECTION ENDS diff --git a/Language/Variables/Data Types/bool.adoc b/Language/Variables/Data Types/bool.adoc index 6145dab3a..b6e0cb199 100644 --- a/Language/Variables/Data Types/bool.adoc +++ b/Language/Variables/Data Types/bool.adoc @@ -12,7 +12,7 @@ subCategories: [ "Data Types" ] [float] === Description -A `bool` holds one of two values, `link:../../constants/constants[true]` or `link:../../constants/constants[false]`. (Each `bool` variable occupies one byte of memory.) +A `bool` holds one of two values, `link:../../constants/truefalse[true]` or `link:../../constants/truefalse[false]`. (Each `bool` variable occupies one byte of memory.) [%hardbreaks] @@ -77,8 +77,6 @@ void loop() { [float] === See also -[role="language"] -* #LANGUAGE# link:../../../variables/constants/constants[constants] -- // SEE ALSO SECTION ENDS diff --git a/Language/Variables/Data Types/float.adoc b/Language/Variables/Data Types/float.adoc index 8882397ed..fd89b97a5 100644 --- a/Language/Variables/Data Types/float.adoc +++ b/Language/Variables/Data Types/float.adoc @@ -67,7 +67,7 @@ If doing math with floats, you need to add a decimal point, otherwise it will be The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float. -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 numbers are not exact, and may yield strange results when compared. For example 9.0 / 0.3 may not quite equal 30.0. You should instead check that the absolute value of the difference between the numbers is less than some small number. Conversion from floating point to integer math results in truncation: [source,arduino] diff --git a/Language/Variables/Data Types/long.adoc b/Language/Variables/Data Types/long.adoc index 061c9c2c9..07462b014 100644 --- a/Language/Variables/Data Types/long.adoc +++ b/Language/Variables/Data Types/long.adoc @@ -19,7 +19,7 @@ subCategories: [ "Data Types" ] === Description Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647. -If doing math with integers, at least one of the numbers must be followed by an L, forcing it to be a long. See the link:../../constants/integerconstants[Integer Constants] page for details. +If doing math with integers at least one of the values must be of type long, either an integer constant followed by an L or a variable of type long, forcing it to be a long. See the link:../../constants/integerconstants[Integer Constants] page for details. [%hardbreaks] [float] @@ -49,7 +49,7 @@ If doing math with integers, at least one of the numbers must be followed by an [source,arduino] ---- -long speedOfLight = 186000L; // see the Integer Constants page for explanation of the 'L' +long speedOfLight_km_s = 300000L; // see the Integer Constants page for explanation of the 'L' ---- -- diff --git a/Language/Variables/Data Types/string.adoc b/Language/Variables/Data Types/string.adoc index c19ab743e..29d4f97ad 100644 --- a/Language/Variables/Data Types/string.adoc +++ b/Language/Variables/Data Types/string.adoc @@ -12,7 +12,7 @@ subCategories: [ "Data Types" ] [float] === Description -Text strings can be represented in two ways. you can use the String data type, which is part of the core as of version 0019, or you can make a string out of an array of type char and null-terminate it. This page described the latter method. For more details on the String object, which gives you more functionality at the cost of more memory, see the link:../stringobject[String object] page. +Text strings can be represented in two ways. you can use the String data type, or you can make a string out of an array of type char and null-terminate it. This page described the latter method. For more details on the String object, which gives you more functionality at the cost of more memory, see the link:../stringobject[String object] page. [%hardbreaks] [float] diff --git a/Language/Variables/Data Types/stringObject.adoc b/Language/Variables/Data Types/stringObject.adoc index 396582b3d..b3b04a498 100644 --- a/Language/Variables/Data Types/stringObject.adoc +++ b/Language/Variables/Data Types/stringObject.adoc @@ -36,7 +36,7 @@ gives you the String "13". You can use other bases, however. For example, String thisString = String(13, HEX); ---- -gives you the String "D", which is the hexadecimal representation of the decimal value 13. Or if you prefer binary, +gives you the String "d", which is the hexadecimal representation of the decimal value 13. Or if you prefer binary, [source,arduino] ---- diff --git a/Language/Variables/Utilities/PROGMEM.adoc b/Language/Variables/Utilities/PROGMEM.adoc index b483ad5fe..0728741c6 100644 --- a/Language/Variables/Utilities/PROGMEM.adoc +++ b/Language/Variables/Utilities/PROGMEM.adoc @@ -17,16 +17,22 @@ subCategories: [ "Utilities" ] [float] === Description -Store data in flash (program) memory instead of SRAM. There's a description of the various http://www.arduino.cc/playground/Learning/Memory[types of memory] available on an Arduino board. -The `PROGMEM` keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go. +Keep constant data in flash (program) memory only, instead of copying it to SRAM when the program starts. There's a description of the various https://www.arduino.cc/en/Tutorial/Foundations/Memory[types of memory] available on an Arduino board. -PROGMEM is part of the link:http://www.nongnu.org/avr-libc/user-manual/group\__avr__pgmspace.html[pgmspace.h] library. It is included automatically in modern versions of the IDE. However, if you are using an IDE version below 1.0 (2011), you'll first need to include the library at the top of your sketch, like this: +The `PROGMEM` keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "keep this information in flash memory only", instead of copying it to SRAM at start up, like it would normally do. + +PROGMEM is part of the link:http://www.nongnu.org/avr-libc/user-manual/group\__avr__pgmspace.html[pgmspace.h] library. It is included automatically in the Arduino IDE. -`#include ` While `PROGMEM` could be used on a single variable, it is really only worth the fuss if you have a larger block of data that needs to be stored, which is usually easiest in an array, (or another C++ data structure beyond our present discussion). -Using `PROGMEM` is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the link:http://www.nongnu.org/avr-libc/user-manual/group\__avr__pgmspace.html[pgmspace.h] library, to read the data from program memory back into SRAM, so we can do something useful with it. +Using `PROGMEM` is a two-step procedure. Once a variable has been defined with `PROGMEM`, it cannot be read like a regular SRAM-based variable: you have to read it using specific functions, also defined in link:http://www.nongnu.org/avr-libc/user-manual/group\__avr__pgmspace.html[pgmspace.h]. + +==== Important Note! + +`PROGMEM` is useful _only_ when working with AVR boards (Uno Rev3, Leonardo etc.). Newer boards (Due, MKR WiFi 1010, GIGA R1 WiFi etc.) automatically use the program space when a variable is declared as a `const`. However, for retro compatibility, `PROGMEM` can still be used with newer boards. This implementation currently lives link:https://github.com/arduino/ArduinoCore-API/blob/master/api/deprecated-avr-comp/avr/pgmspace.h[here]. + + [%hardbreaks] @@ -86,7 +92,8 @@ void setup() { Serial.println(); // read back a char - for (byte k = 0; k < strlen_P(signMessage); k++) { + int signMessageLength = strlen_P(signMessage); + for (byte k = 0; k < signMessageLength; k++) { myChar = pgm_read_byte_near(signMessage + k); Serial.print(myChar); } @@ -151,7 +158,7 @@ void loop() { for (int i = 0; i < 6; i++) { - strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy. + strcpy_P(buffer, (char *)pgm_read_ptr(&(string_table[i]))); // Necessary casts and dereferencing, just copy. Serial.println(buffer); delay(500); } @@ -187,7 +194,7 @@ When an instruction like : Serial.print("Write something on the Serial Monitor"); ---- -is used, the string to be printed is normally saved in RAM. If your sketch prints a lot of stuff on the Serial Monitor, you can easily fill the RAM. If you have free FLASH memory space, you can easily indicate that the string must be saved in FLASH using the syntax: +is used, the string to be printed is normally saved in RAM. If your sketch prints a lot of stuff on the Serial Monitor, you can easily fill the RAM. This can be avoided by not loading strings from the FLASH memory space until they are needed. You can easily indicate that the string is not to be copied to RAM at start up using the syntax: [source,arduino] ---- @@ -205,7 +212,7 @@ Serial.print(F("Write something on the Serial Monitor that is stored in FLASH")) === See also [role="example"] -* #EXAMPLE# https://www.arduino.cc/playground/Learning/Memory[Types of memory available on an Arduino board^] +* #EXAMPLE# https://www.arduino.cc/en/Tutorial/Foundations/Memory[Types of memory available on an Arduino board^] [role="definition"] * #DEFINITION# link:../../data-types/array[array] diff --git a/Language/Variables/Variable Scope & Qualifiers/volatile.adoc b/Language/Variables/Variable Scope & Qualifiers/volatile.adoc index 20fbd6fbd..8845e1100 100644 --- a/Language/Variables/Variable Scope & Qualifiers/volatile.adoc +++ b/Language/Variables/Variable Scope & Qualifiers/volatile.adoc @@ -55,34 +55,47 @@ There are several ways to do this: === Example Code // Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄ +The `volatile` modifier ensures that changes to the `changed` variable are immediately visible in `loop()`. Without the `volatile` modifier, the `changed` variable may be loaded into a register when entering the function and would not be updated anymore until the function ends. [source,arduino] ---- -// toggles LED when interrupt pin changes state +// Flashes the LED for 1 s if the input has changed +// in the previous second. -int pin = 13; -volatile byte state = LOW; +volatile byte changed = 0; void setup() { - pinMode(pin, OUTPUT); - attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE); + pinMode(LED_BUILTIN, OUTPUT); + attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE); } void loop() { - digitalWrite(pin, state); + if (changed == 1) { + // toggle() has been called from interrupts! + + // Reset changed to 0 + changed = 0; + + // Blink LED for 200 ms + digitalWrite(LED_BUILTIN, HIGH); + delay(200); + digitalWrite(LED_BUILTIN, LOW); + } } -void blink() { - state = !state; +void toggle() { + changed = 1; } ---- +To access a variable with size greater than the microcontroller’s 8-bit data bus, use the `ATOMIC_BLOCK` macro. The macro ensures that the variable is read in an atomic operation, i.e. its contents cannot be altered while it is being read. [source,arduino] ---- #include // this library includes the ATOMIC_BLOCK macro. volatile int input_from_interrupt; +// Somewhere in the code, e.g. inside loop() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { // code with interrupts blocked (consecutive atomic operations will not get interrupted) int result = input_from_interrupt; diff --git a/README.adoc b/README.adoc index cbe8fde78..90010049d 100644 --- a/README.adoc +++ b/README.adoc @@ -47,7 +47,7 @@ reference-en │ ├── Functions │ ├── Structure │ └── Variables -├── LICENCE.md +├── LICENSE.md └── README.adoc ----