Year End 2024 Sale
Skip to main content

Arduino API

warning

With version V4.1.1 of RUI3, the LoRa P2P functions are separated into a new class and API calls for LoRa have a changed syntax:

OldNewComment
api.lorawan.pXXXapi.lora.pXXXAll LoRa P2P API calls change.
api.lorawan.registerPyyyapi.lora.registerPyyyAll LoRa P2P callback register API calls change.
api.lorawan.nwm.set(1)api.lorawan.nwm.set()Set device to LoRaWAN mode.
api.lorawan.nwm.set(0)api.lora.nwm.set()Set device to LoRa P2P mode.

RUI Arduino Data Type

Typedefs

typedef enum _eAnalogReference eAnalogReference

Enumerations

RAK_SERIAL_MODE

enum RAK_SERIAL_MODE
Enumerator
RAK_AT_MODEAT command mode.
RAK_CUSTOM_MODECustom mode
RAK_DEFAULT_MODEDefault mode which depends on platform

RAK_ADC_RESOLUTION

enum RAK_ADC_RESOLUTION
Enumerator
RAK_ADC_RESOLUTION_8BIT8 bit resolution
RAK_ADC_RESOLUTION_10BIT10 bit resolution
RAK_ADC_RESOLUTION_12BIT12 bit resolution
RAK_ADC_RESOLUTION_14BIT14 bit resolution

RAK_ADC_MODE

enum RAK_ADC_MODE
Enumerator
RAK_ADC_MODE_DEFAULTdefault range which depends on platform
RAK_ADC_MODE_3_0maximum 3.0 V
RAK_ADC_MODE_2_4maximum 2.4 V
RAK_ADC_MODE_1_8maximum 1.8 V
RAK_ADC_MODE_1_2maximum 1.2 V

RAK_PWM_RESOLUTION

enum RAK_PWM_RESOLUTION
Enumerator
RAK_PWM_RESOLUTION_8BIT8 bit resolution
RAK_PWM_RESOLUTION_10BIT10 bit resolution
RAK_PWM_RESOLUTION_12BIT12 bit resolution
RAK_PWM_RESOLUTION_14BIT14 bit resolution

Serial

begin()

Sets the data rate in bits per second (baud) for serial data transmission.

Serial.begin(baud);
Serial.begin(baud, mode);
Functionvoid begin (uint32_t baud, RAK_SERIAL_MODE mode = RAK_DEFAULT_MODE)
Parametersbaud - The baudrate to set for the Serial.
mode(optional) - The mode that use UART in different way (if not assigned, RAK_DEFAULT_MODE is chosen).
List:
RAK_AT_MODE
RAK_API_MODE
RAK_CUSTOM_MODE
RAK_DEFAULT_MODE
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);
Serial1.begin(9600, RAK_CUSTOM_MODE);
}

void loop() {
}
NOTE

For RAK4630 and RAK11720 with BLE, the BLE UART is assigned to Serial6.

end()

End connection of the Serial with flushing all data.

Serial.end();
Functionvoid end(void)
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);
}

void loop() {
Serial.end();
}

getBaudrate()

Gets the data rate in bits per second (baud) for serial data transmission.

Serial.getBaudrate(void);
Functionuint32_t getBaudrate(void)
ReturnsBaud rate in bits per second
Click to view the code
void setup() {
uint32_t baudrate = Serial.getBaudrate();
Serial.begin(baudrate);
}

void loop() {
}

lock()

To lock the Serial port of the device.

NOTE
  1. If you never set a password successfully, the default password will be 00000000.
  2. Serial.lock can only lock the Serial which is in AT Command mode.
  3. Serial.lock will lock all Serial that is on AT Command mode.
  4. Due that Serial lock and unlock is system-wise operation for all Serial ports in AT Command mode, the Serial could be unlocked from either one or more Serial ports which are in AT Command mode.
Serial.lock(locked);
Functionvoid lock(bool locked)
Parameterslocked - true to lock the device, false to unlock the device
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);

//Lock Serial(USB) with password => 12345678
String password = "12345678";
Serial.password(password);
Serial.lock(true);
}

void loop() {
}

password()

Set up the password to unlock the device when locked.

Serial.password(str);
Serial.password(new_passwd, len);
Functionbool password(char * new_passwd, size_t len)
Parametersstr - a string to set for unlocking the device
new_passwd - a char array to set for unlocking the device
len - the length of your password
ReturnsTRUE - for success
FALSE - for failure
Click to view the code

Example:

void setup() {
Serial.begin(115200);

//Lock Serial(USB) with password => 12345678
String password = "12345678";
Serial.password(password);
Serial.lock(true);
}

void loop() {
}

write()

Writes a byte sequence to a specified serial port.

Serial.write(val);
Serial.write(buf, size);
NOTE

This function is a virtual function declared in Print.h.

Functionvirtual size_t write( uint8_t val)
Parametersval - a value to send as a single byte
Returnsnumber of bytes sent successfully (Type: size_t)
Functionvirtual size_t write(const uint8_t* buf, size_t size)
Parametersbuf - an array to send as a series of bytes
size - the number of bytes to be sent from the array
Returnsnumber of bytes sent successfully (Type: size_t)
Click to view the code
void setup() {
Serial.begin(115200);
}

void loop() {
Serial.write(45);
Serial.write("Hello");
}

available()

Gets the number of bytes available for reading from the specified serial port.

Serial.available();
NOTE
  • Serial.available() inherits from the Stream utility class.
Functionvirtual int available(void)
ReturnsThe number of bytes available for reading from the specified serial port (Type: int)
Click to view the code
void setup() {
Serial.begin(115200, RAK_CUSTOM_MODE);
}

void loop() {
//print if you receive data
if (Serial.available() > 0) {
Serial.print("Return Byte = ");
Serial.println(Serial.read());
}
}

read()

Reads incoming serial data.

Serial.read();
NOTE

Serial.read() inherits from the Stream utility class.

Functionvirtual int read(void)
ReturnsThe first byte of incoming serial data available (Type: int32_t)
Return Values-1 Read fail, received nothing from the specified serial port
Click to view the code
void setup() {
Serial.begin(115200, RAK_CUSTOM_MODE);
}

void loop() {
//print if you receive data
if (Serial.available() > 0) {
Serial.print("Return Byte = ");
Serial.println(Serial.read());
}
}

peek()

Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer. That is, successive calls to peek() will return the same character, as will the next call to read().

Serial.peek();
Functionvirtual int peek(void)
ReturnsThe first byte of incoming serial data available (or -1 if no data is available) (Type: int)
Click to view the code
void setup() {
Serial.begin(115200, RAK_CUSTOM_MODE);
}

void loop() {
//print if you receive data
if (Serial.available() > 0) {

//Peek the data first
Serial.print("Peek the Byte = ");
Serial.println(Serial.peek());

//Read the data you peeked
Serial.print("Return Byte = ");
Serial.println(Serial.read());
}
}

flush()

Waits for the transmission of outgoing serial data to complete.

Serial.flush();
Functionvirtual void flush(void)
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);
}

void loop() {
Serial.write(45);
Serial.write("Hello");
Serial.flush();
}

print()

Prints data to the serial port as human-readable ASCII text. This command can take many forms. Numbers are printed using an ASCII character for each digit. Floats are similarly printed as ASCII digits, defaulting to two decimal places. Bytes are sent as a single character. Characters and strings are sent as is.

Serial.print(val);
Serial.print(val,format);
Functionsize_t print(long, int=DEC)
Parametersval - the value to print, allows any data type
ReturnsReturns the number of bytes written, though reading that number is optional (Type: size_t)
Click to view the code
void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
}

void loop() {
// print labels
Serial.print("NO FORMAT"); // prints a label
Serial.print("\t"); // prints a tab

Serial.print("DEC");
Serial.print("\t");

Serial.print("HEX");
Serial.print("\t");

Serial.print("OCT");
Serial.print("\t");

Serial.print("BIN");
Serial.println(); // carriage return after the last label

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 accommodate the label length

Serial.print(x, DEC); // print as an ASCII-encoded decimal
Serial.print("\t"); // prints a tab

Serial.print(x, HEX); // print as an ASCII-encoded hexadecimal
Serial.print("\t"); // prints a tab

Serial.print(x, OCT); // print as an ASCII-encoded octal
Serial.print("\t"); // prints a tab

Serial.println(x, BIN); // print as an ASCII-encoded binary
// then adds the carriage return with "println"
delay(200); // delay 200 milliseconds
}
Serial.println(); // prints another carriage return
}

println()

Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '') and a newline character (ASCII 10, or ''). This command takes the same form as Serial.print().

Serial.print(val);
Serial.print(val,format);
Functionsize_t println(int, int=DEC)
Parametersval - the value to print, allows any data type
ReturnsReturns the number of bytes written, though reading that number is optional (Type: size_t)
Click to view the code
int analogValue = 0;    // variable to hold the analog value

void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);

// print it out in many formats:
Serial.println(analogValue); // print as an ASCII-encoded decimal
Serial.println(analogValue, DEC); // print as an ASCII-encoded decimal
Serial.println(analogValue, HEX); // print as an ASCII-encoded hexadecimal
Serial.println(analogValue, OCT); // print as an ASCII-encoded octal
Serial.println(analogValue, BIN); // print as an ASCII-encoded binary

// delay 10 milliseconds before the next reading:
delay(10);
}

printf()

To output formatted text over Serial without the need to create a char array first, fill it with snprintf() and then send it with Serial.println.

Serial.printf(val);
Functionsize_t printf(const char * val, ...)
Parametersval
ReturnsReturns the number of bytes written, though reading that number is optional (Type: size_t)
Click to view the code
int exampleNum = 123;

void setup()
{
Serial.begin(115200);
}

void loop()
{
Serial.printf("The example number = %d\r\n", exampleNum);
}

setTimeout()

This API is used to set the timeout value for read/write/flush API.

Serial.setTimeout(timeout);
Functionvoid setTimeout(unsigned long timeout)
Parameterstimeout - the timeout value
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);

//Set Timeout to 5000
Serial.setTimeout(5000);
Serial.print("Time out = ");
Serial.println(Serial.getTimeout());
}

void loop() {
}

getTimeout()

This API is used to get the timeout value for read/write/flush API.

Serial.getTimeout(timeout);
Functionunsigned long getTimeout(void)
ReturnsThe value of timeout (Type: unsigned long)
Click to view the code
void setup() {
Serial.begin(115200);

//Set Timeout to 5000
Serial.setTimeout(5000);
Serial.print("Time out = ");
Serial.println(Serial.getTimeout());
}

void loop() {
}

readBytes()

Read characters from Stream into buffer terminates if length characters have been read, or timeout (see setTimeout).

Serial.readBytes(buffer, length);
NOTE

Serial.readBytes() inherits from the Stream utility class.

Functionsize_t readBytes(char* buffer,size_t length)
Parametersbuffer - The buffer to store the bytes in.
length - The number of bytes to read.
ReturnsThe number of bytes placed in the buffer (Type: size_t)
Click to view the code
void setup() {
Serial.begin(11500, RAK_CUSTOM_MODE);
}

void loop() {
int returnBytes = 0;
char readBuf[256];

if (Serial.available > 0) {

//Read 5 characters in 1 second
returnBytes = Serial.readBytes(readBuf, 5);

if (returnBytes == 0)
Serial.print("read nothing");
else {
Serial.print("read: ");
for (int i=0; i<returnBytes; i++) {
Serial.print(readBuf[i]);
}
}

Serial.println("");
}
}

readBytesUntil()

As readBytes with terminator character Terminates if length characters have been read, timeout, or if the terminator character detected.

Serial.readBytesUntil(terminator, buffer, length);
NOTE

Serial.readBytesUntil() inherits from the Stream utility class

Functionsize_t readBytesUntil(char terminator, char* buffer, size_t length)
Parametersterminator - The character to search for
buffer - The buffer to store the bytes in
length - The number of bytes to read
Returnssize_t
Click to view the code
void setup() {
Serial.begin(11500,RAK_CUSTOM_MODE);
}

void loop() {
int returnBytes = 0;
char readBuf[256];

if (Serial.available > 0) {

//Read 5 characters in 1 second,or Press ENTER to end reading
returnBytes = Serial.readBytesUntil('\r', readBuf, 5);

if (returnBytes == 0)
Serial.print("read nothing");
else {
Serial.print("read: ");
for (int i=0; i<returnBytes; i++) {
Serial.print(readBuf[i]);
}
}

Serial.println("");
}
}

readString

Reads characters from a Stream into a String. The function terminates if it times out (see setTimeout()).

Serial.readString();
NOTE

Serial.readString() inherits from the Stream utility class.

FunctionString readString()
ReturnsA String read from a Stream (Type: String)
Click to view the code
void setup() {
Serial.begin(11500,RAK_CUSTOM_MODE);
}

void loop() {
String returnString = "";

if (Serial.available > 0) {

//Read 5 characters in 1 second
returnString = Serial.readString();

if (returnString == "")
Serial.print("read nothing");
else {
Serial.print("read: ");
Serial.println(returnString);
}

Serial.println("");
}
}

readStringUntil()

Reads characters from the serial buffer into a String until the terminator is found or a timeout occurs (see setTimeout()).

Serial.readStringUntil(terminator);
NOTE

Serial.readStringUntil() inherits from the Stream utility class.

FunctionString readStringUntil(char terminator)
ReturnsThe entire String read from the serial buffer, up to the terminator character(Type: String).
Click to view the code
void setup() {
Serial.begin(11500,RAK_CUSTOM_MODE);
}

void loop() {
String returnString = "";

if (Serial.available > 0) {

//Read 5 characters in 1 second,or Press ENTER to end reading
returnString = Serial.readStringUntil('\r');

if (returnString == "")
Serial.print("read nothing");
else {
Serial.print("read: ");
Serial.println(returnString);
}

Serial.println("");
}
}

Wire

begin()

Initiate the Wire library and join the I2C bus as a master.

Wire.begin();
Functionvoid begin(void)
Returnsvoid
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
}

end()

End the I2C bus

Wire.end();
Functionvoid end(void)
Returnsvoid
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.end();
}

setClock()

This function modifies the clock frequency for I2C communication. I2C slave devices have no minimum working clock frequency, however 100 kHz is usually the baseline.

Wire.setClock(freq);
Functionvoid setClock(uint32_t freq)
Parametersfreq - The value (in Hertz) of desired communication clock. Accepted values are 100000 (standard mode) and 400000 (fast mode).
Returnsvoid
Click to view the code
void setup() {
Wire.begin();
Wire.setClock(400000);
}

void loop() {
}

beginTransmission()

Begin a transmission to the I2C slave device with the given address. Subsequently, queue bytes for transmission with the write() function and transmit them by calling endTransmission().

Wire.beginTransmission(address);
Functionvoid beginTransmission(uint8_t address)
Parametersaddress - The 7-bit address of the device to transmit to
Returnsvoid
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();
}

endTransmission()

Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().

Wire.endTransmission();
Wire.endTransmission(sendStop);
Functionuint32_t endTransmission(uint8_t sendStop = false)
ParameterssendStop(optional)
true will send a stop message, releasing the bus after transmission.
false will send a restart, keeping the connection active (default = false).
Returns0 - success
1- fail
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();
}

requestFrom()

Used by the master to request bytes from a slave device. The bytes may then be retrieved with the available() and read() functions.

Wire.requestFrom(address, quantity);
Wire.requestFrom(address, quantity, sendStop);
Functionuint8_t requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
Parametersaddress - The 7-bit address of the device to request bytes from
quantity - The number of bytes to request
sendStop
- 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(default = false)
ReturnsThe number of bytes returned from the slave device (Type: byte)
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();

Wire.requestFrom(0b1110000, 6);

while(Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
delay(5000);

}

write()

Writes data to a slave device.

Wire.write(value);
Wire.write(data, size);
NOTE

In-between calls to beginTransmission() and endTransmission().

Functionvirtual size_t write(const uint8_t* data, size_t size)
Parametersvalue - A value to send as a single byte
data - An array of data to send as bytes
size - The number of bytes to transmit
Returnswrite() will return the number of bytes written, though reading that number is optional (Type: byte)
Click to view the code
  void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();

Wire.requestFrom(0b1110000, 6);

while(Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
delay(5000);

}

available()

Returns the number of bytes available for retrieval with read().

Wire.available();
Functionvirtual int available(void)
ReturnsThe number of bytes available for reading
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();

Wire.requestFrom(0b1110000, 6);

while(Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
delay(5000);

}

read()

Reads a byte that was transmitted from a slave device to a master

Wire.read();
Functionvirtual int read(void)
ReturnsThe next byte received
NOTE
  • read() inherits from the Stream utility class.
Click to view the code
void setup() {
Wire.begin();
}

void loop() {
Wire.beginTransmission(0b1110000);
Wire.write(0x35);
Wire.endTransmission();

Wire.requestFrom(0b1110000, 6);

while(Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
delay(5000);

}

SPI

begin()

Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.

SPI.begin()
Functionvoid begin()
Returnsvoid

end()

Disables the SPI bus.

SPI.end()
Functionvoid end()
Returnsvoid

transfer16()

SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal16.

receivedVal16 = SPI.transfer16(val16)
Functionuint16_t transfer16 (uint16_t data)
Parametersval16 - the two bytes variable to send out over the bus
ReturnsThe received data

transfer()

SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal. In case of buffer transfers the received data is stored in the buffer in-place.

receivedVal = SPI.transfer(val)
SPI.transfer(buffer, size)
Functionvoid transfer(void* buf, size_t count)
Parametersval - the byte to send out over the bus
buffer - the array of data to be transferred
ReturnsThe received data

beginTransaction()

Initializes the SPI bus using the defined SPISettings.

SPI.beginTransactions(mySetting)
Functionvoid beginTransaction(SPISettings settings)
ParametersmySetting - the chosen settings according to SPISettings
Returnsvoid

endTransaction()

Stops using the SPI bus.

SPI.endTransaction()
Functionvoid endTransaction()
Returnsvoid

setBitOrder()

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).

SPI.setBitOrder(order)
Functionvoid setBitOrder(BitOrder order)
Parametersorder - either LSBFIRST or MSBFIRST
Returnsvoid

setDataMode()

Sets the SPI data mode: that is, clock polarity and phase.

SPI.setDataMode(mode)
Functionvoid setDataMode(uint8_t mode)
Parametersmode
- SPI_MODE0
- SPI_MODE1
- SPI_MODE2
- SPI_MODE3
Returnsvoid

setClockDivider()

Sets the SPI clock divider relative to the system clock.

SPI.setClockDivider(divider)
Functionvoid setClockDivider(uint32_t uc_div)
Parametersdivider
- SPI_CLOCK_DIV2
- SPI_CLOCK_DIV4
- SPI_CLOCK_DIV8
- SPI_CLOCK_DIV16
- SPI_CLOCK_DIV32
- SPI_CLOCK_DIV64
- SPI_CLOCK_DIV128
- SPI_CLOCK_DIV256
Returnsvoid

Time

delay

Pauses the program for the amount of time (in milliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

delay(ms);
Functionvoid delay(uint32_t ms)
Parametersms - The number of milliseconds to pause
Click to view the code
unsigned long myTime;

void setup() {
Serial.begin(115200);
}
void loop() {
Serial.print("Time: ");
myTime = millis();

Serial.println(myTime); // prints time since program started
delay(1000); // wait a second so as not to send massive amounts of data
}

delayMicroseconds

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.

delayMicroSeconds(us);
Functionvoid delayMicroseconds(uint32_t us)
Parametersus - The number of microseconds to pause
Click to view the code
unsigned long time;

void setup() {
Serial.begin(115200);
}
void loop() {
Serial.print("Time: ");
time = micros();

Serial.println(time); //prints time since program started
delayMicroseconds(1000); // wait a second so as not to send massive amounts of data
}

millis

Returns the number of milliseconds passed since the device began running the current program.

millis();
Functionunsigned long millis()
ReturnsThe number of milliseconds since the device began running the current program (Type: unsigned long).
Click to view the code
unsigned long myTime;

void setup() {
Serial.begin(115200);
}
void loop() {
Serial.print("Time: ");
myTime = millis();

Serial.println(myTime); // prints time since program started
delay(1000); // wait a second so as not to send massive amounts of data
}

micros

Returns the number of microseconds since the device began running the current program.

unsigned long micros()
Functionmicros();
ReturnsNumber of microseconds since the device began running the current program (Type: unsigned long)
Click to view the code
unsigned long time;

void setup() {
Serial.begin(115200);
}
void loop() {
Serial.print("Time: ");
time = micros();

Serial.println(time); //prints time since program started
delayMicrosecond(1000); // wait a second so as not to send massive amounts of data
}

AdvancedIO

tone()

Generates a square wave of the specified frequency (and 50% duty cycle) on a pin. A duration can be specified, otherwise the wave continues until a call to noTone(). 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.

tone(pin, frequency);
tone(pin, frequency, duration);
Functionvoid tone(uint8_t pin, uint32_t frequency, uint64_t duration = 0)
Parameterspin - The device pin on which to generate the tone
frequency - The frequency of the tone in hertz
duration(optional) - The duration of the tone in milliseconds (default = no timeout)
Returnsvoid
Click to view the code
uint8_t ledPin = 36;
uint8_t pulsePin = 13;
unsigned long duration;

void setup() {
Serial.begin(115200);
pinMode(pulsePin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}

void loop() {
duration = pulseIn(pulsePin, LOW);
Serial.print("Pulse duration = ");
Serial.print((float)duration/1000000);
Serial.println(" sec");

if(duration >= 15000000)
noTone(ledPin);
else if(duration >= 10000000)
tone(ledPin, 494, 5000);
else if(duration >= 5000000)
tone(ledPin, 494);
}

noTone()

Stops the generation of a square wave triggered by tone().

noTone(pin);
Functionvoid noTone(uint8_t pin)
Parameterspin - The device pin on which to stop generating the tone
Returnsvoid
Click to view the code
uint8_t ledPin = 36;
uint8_t pulsePin = 13;
unsigned long duration;

void setup() {
Serial.begin(115200);
pinMode(pulsePin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}

void loop() {
duration = pulseIn(pulsePin, LOW);
Serial.print("Pulse duration = ");
Serial.print((float)duration/1000000);
Serial.println(" sec");

if(duration >= 15000000)
noTone(ledPin);
else if(duration >= 10000000)
tone(ledPin, 494, 5000);
else if(duration >= 5000000)
tone(ledPin, 494);
}

shiftOut()

Shifts out a byte of data one bit at a time. Starts from either the most (That it the leftmost) or least (rightmost) significant bit. Each bit is written in turn to a data pin, after which a clock pin is pulsed (taken high, then low) to indicate that the bit is available.

shiftOut(dataPin, clockPin, bitOrder, val);
Functionvoid shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
ParametersdataPin - The pin on which to output each bit
clockPin - The pin to toggle once the dataPin has been set to the correct value
bitOrder - Which order to shift out the bits, either MSBFIRST or LSBFIRST
val - The data to shift out
Returnsvoid

shiftIn()

Shifts in a byte of data one bit at a time. Starts from either the most (That is the leftmost) or least (rightmost) significant bit. For each bit, the clock pin is pulled high, the next bit is read from the data line, and then the clock pin is taken low.

byte incoming = shiftIn(dataPin, clockPin, bitOrder);
Functionuint32_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
ParametersdataPin - The pin on which to output each bit
clockPin - The pin to toggle once the dataPin has been set to the correct value
bitOrder - Which order to shift out the bits, either MSBFIRST or LSBFIRST
ReturnsThe value read(Type: byte);

pulseIn()

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.

pulseIn(pin, state);
pulseIn(pin, state, timeout);
Functionunsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L)
Parameterspin - The pin on which you want to read a pulse
state - Type of pulse to read: either HIGH or LOW
timeout(optional) - The number of microseconds to wait for the pulse to start; default is one second
ReturnsThe length of the pulse (in microseconds) or 0 if no pulse started before the timeout(Type: unsigned long)
Click to view the code
uint8_t ledPin = 36;
uint8_t pulsePin = 13;
unsigned long duration;

void setup() {
Serial.begin(115200);
pinMode(pulsePin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}

void loop() {
duration = pulseIn(pulsePin, LOW);
Serial.print("Pulse duration = ");
Serial.print((float)duration/1000000);
Serial.println(" sec");

if(duration >= 15000000)
noTone(ledPin);
else if(duration >= 10000000)
tone(ledPin, 494, 5000);
else if(duration >= 5000000)
tone(ledPin, 494);
}

pulseInLong()

pulseInLong() is an alternative to pulseIn() which is better at handling long pulse and interrupt affected scenarios

pulseInLong(pin, state);
pulseInLong(pin, state, timeout);
Functionunsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L)
Parameterspin - The pin on which you want to read a pulse
state - Type of pulse to read: either HIGH or LOW
timeout(optional) - The number of microseconds to wait for the pulse to start; default is one second.
ReturnsThe length of the pulse (in microseconds) or 0 if no pulse started before the timeout(Type: unsigned long).

Characters

isAlphaNumeric()

Analyze if a char is alphanumeric (that is a letter or a numbers). Returns true if thisChar contains either a number or a letter.

isAlphaNumeric(thisChar);
Functionboolean isAlphaNumeric(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is alphanumeric
FALSE: The character is not alphanumeric
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isAlphaNumeric(myChar)) { // tests if myChar isa letter or a number
Serial.println("The character is alphanumeric");
}
else {
Serial.println("The character is not alphanumeric");
}
}

void loop() {
}

isAlpha()

Analyze if a char is alpha (that is a letter). Returns true if thisChar contains a letter.

isAlpha(thisChar);
Functionboolean isAlpha(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is a letter
FALSE : The character is not a letter
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isAlpha(myChar)) { // tests if myChar is a letter
Serial.println("The character is a letter");
}
else {
Serial.println("The character is not a letter");
}
}

void loop() {
}

isAscii()

Analyze if a char is Ascii. Returns true if thisChar contains an Ascii character.

isAscii(thisChar);
Functionboolean isAscii(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is Ascii
FALSE : The character is not Ascii
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isAscii(myChar)) { // tests if myChar is an Ascii character
Serial.println("The character is Ascii");
}
else {
Serial.println("The character is not Ascii");
}
}

void loop() {
}

isWhitespace

Analyze if a char is a space character. Returns true if the argument is a space or horizontal tab ('').

isWhitespace(thisChar);
Functionboolean isWhitespace(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is a space or tab
FALSE: The character is not a space or tab
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isWhitespace(myChar)) { // tests if myChar is a space character
Serial.println("The character is a space or tab");
}
else {
Serial.println("The character is not a space or tab");
}
}

void loop() {
}

isControl()

Analyze if a char is a control character. Returns true if thisChar is a control character.

isControl(thisChar);
Functionboolean isControl(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is a control character
FALSE: The character is not a control character
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isControl(myChar)) { // tests if myChar is a control character
Serial.println("The character is a control character");
}
else {
Serial.println("The character is not a control character");
}
}

void loop() {
}

isDigit()

Analyze if a char is a digit (that is a number). Returns true if thisChar is a number.

isDigit(thisChar);
Functionboolean isDigit(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is a number
FALSE: The character is not a number
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isDigit(myChar)) { // tests if myChar is a digit
Serial.println("The character is a number");
}
else {
Serial.println("The character is not a number");
}
}

void loop() {
}

isGraph()

Analyze if a char is printable with some content (space is printable but has no content). Returns true if thisChar is printable.

isGraph(thisChar);
Functionboolean isGraph(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is printable
FALSE: The character is not printable
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isGraph(myChar)) { // tests if myChar is a printable character but not a blank space.
Serial.println("The character is printable");
}
else {
Serial.println("The character is not printable");
}
}

void loop() {
}

isLowerCase()

Analyze if a char is lower case (that is a letter in lower case). Returns true if thisChar contains a letter in lower case.

isLowerCase(thisChar);
Functionboolean isLowerCase(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is lower case
FALSE: The character is not lower case
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isLowerCase(myChar)) { // tests if myChar is a lower case letter
Serial.println("The character is lower case");
}
else {
Serial.println("The character is not lower case");
}
}

void loop() {
}

isPrintable()

Analyze if a char is printable (that is any character that produces an output, even a blank space). Returns true if thisChar is printable

isPrintable(thisChar);
Functionboolean isPrintable(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is printable
FALSE: The character is not printable
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isPrintable(myChar)) { // tests if myChar is printable char
Serial.println("The character is printable");
}
else {
Serial.println("The character is not printable");
}
}

void loop() {
}

isPunct()

Analyze if a char is punctuation (that is a comma, a semicolon, an exclamation mark and so on). Returns true if thisChar is punctuation.

isPunct(thisChar);
Functionboolean isPunct(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is a punctuation
FALSE: The character is not a punctuation
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isPunct(myChar)) { // tests if myChar is a punctuation character
Serial.println("The character is a punctuation");
}
else {
Serial.println("The character is not a punctuation");
}
}

void loop() {
}

isSpace()

Analyze if a char is a white-space character. Returns true if the argument is a space, form feed (''), newline (''), carriage return (''), horizontal tab (''), or vertical tab ('').

isSpace(thisChar);
Functionboolean isSpace(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is white-space
FALSE: The character is not white-space
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isSpace(myChar)) { // tests if myChar is a white-space character
Serial.println("The character is white-space");
}
else {
Serial.println("The character is not white-space");
}
}

void loop() {
}

isUpperCase()

Analyze if a char is upper case (that is a letter in upper case). Returns true if thisChar is upper case.

isUpperCase(thisChar);
Functionboolean isUpperCase(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is upper case
FALSE: The character is not upper case
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isUpperCase(myChar)) { // tests if myChar is an upper case letter
Serial.println("The character is upper case");
}
else {
Serial.println("The character is not upper case");
}
}

void loop() {
}

isHexadecimalDigit()

Analyze if a char is an hexadecimal digit (A-F, 0-9). Returns true if thisChar contains an hexadecimal digit.

isHexadecimalDigit(thisChar);
Functionboolean isHexadecimalDigit(int thisChar)
ParametersthisChar variable(Type: char)
ReturnsTRUE: The character is an hexadecimal digit
FALSE: The character is not an hexadecimal digit
Click to view the code
char mychar = 'A';

void setup() {
Serial.begin(115200);

if (isHexadecimalDigit(myChar)) { // tests if myChar is an hexadecimal digit
Serial.println("The character is an hexadecimal digit");
}
else {
Serial.println("The character is not an hexadecimal digit");
}
}

void loop() {
}

Bit and Byte

bitRead

Reads a bit of a number.

bitRead(value, bit);
Functionuint8_t bitRead(value, bit)
Parametersvalue - The number from which to read
bit - Which bit to read, starting at 0 for the least-significant (rightmost) bit
ReturnsThe value of the bit (0 or 1)
Click to view the code
void setup() {
Serial.begin(115200);
Serial.println("Read the bits of 6(0110)");

Serial.print("bitRead(6, 0) = ");
Serial.println(bitRead(6, 0)); //print the first bit of 6

Serial.print("bitRead(6, 1) = ");
Serial.println(bitRead(6, 1)); //print the second bit of 6

Serial.print("bitRead(6, 2) = ");
Serial.println(bitRead(6, 2)); //print the third bit of 6

Serial.print("bitRead(6, 3) = ");
Serial.println(bitRead(6, 3)); //print the fourth bit of 6
}

void loop() {
}

bitSet

Sets (writes a 1 to) a bit of a numeric variable.

bitSet(value, bit);
Functionvoid bitSet(value, bit)
Parametersvalue - The numeric variable whose bit to set
bit - Which bit to set, starting at 0 for the least-significant (rightmost) bit
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);

Serial.print("Before bitSet(): 6 => ");
Serial.println(6, BIN);

Serial.print("After bitSet(6, 0) => ");
int value = 6;
int pos = 0;
Serial.println(bitSet(value,pos), BIN); //set the first bit of 6(0110) to 1
}

void loop() {
}

bitClear

Clears (writes a 0 to) a bit of a numeric variable.

bitClear(value, bit);
Functionvoid bitClear(value, bit)
Parametersvalue - The numeric variable whose bit to clear
bit - Which bit to clear, starting at 0 for the least-significant (rightmost) bit
ReturnsThe value of the numeric variable after the bit at position n is cleared
Click to view the code
void setup() {
Serial.begin(115200);

Serial.print("Before bitClear(): 6 => ");
Serial.println(6, BIN);

Serial.print("After bitClear(6, 1) => ");
int value = 6;
int pos = 1;
Serial.println(bitClear(value,ipos), BIN); // set the second bit of 6(0110) to 0
}

void loop() {
}

bitWrite

Writes a bit of a numeric variable.

bitWrite(value, bit, bitvalue);
Functionvoid bitWrite(value, bit, bitvalue)
Parametersvalue - The numeric variable to which to write
bit - Which bit of the number to write, starting at 0 for the least-significant (rightmost) bit
bitvalue - The value to write to the bit (0 or 1)
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);

int target = 6; // set the bitWrite target to 6
Serial.print("Before bitWrite(): 6 => ");
Serial.println(target, BIN);

Serial.print("After bitWrite(target, 0, 1) => "); // Set the first bit of target to 1
Serial.println(bitWrite(target, 0,1), BIN);

Serial.print("After bitWrite(target, 1, 0) => "); // Set the second bit of target to 0
Serial.println(bitWrite(target, 1,0), BIN);

Serial.print("After bitWrite(target, 2, 0) => "); // Set the third bit of target to 0
Serial.println(bitWrite(target, 2,0), BIN);

Serial.print("After bitWrite(target, 3, 1) => "); // Set the fourth bit of target to 1
Serial.println(bitWrite(target, 3,1), BIN);

Serial.println("");
Serial.println("target now should be 9(1001)");
Serial.print("target = ");
Serial.println(target);
}

void loop() {
}

bit

Computes the value of the specified bit. (bit 0 is 1, bit 1 is 2, bit 2 is 4, etc.)

bit(b);
Functionuint8_t bit(b)
Parametersb - The bit whose value to compute
ReturnsThe value of the bit
Click to view the code
void setup() {
Serial.begin(115200);

Serial.print("bit 0: ");
Serial.println(bit(0));
Serial.print("bit 3: ");
Serial.println(bit(3));
}

void loop() {
}

lowByte

Extracts the low-order (rightmost) byte of a variable (e.g. a word).

lowByte(w);
Functionuint8_t lowByte(w)
Parametersw - A value of any type
Returnsbyte
Click to view the code
void setup() {
Serial.begin(115200);
Serial.println("Test target 0xABCD");

uint16_t target = 0xABCD;

Serial.print("lowByte() of 0xABCD = "); // extract the low-order byte of the target
Serial.println(lowByte(target), HEX);

Serial.print("highByte() of 0xABCD = "); // extract the low-order byte of the target
Serial.println(highByte(target), HEX);
}

void loop() {
}

highByte

Extracts the high-order (leftmost) byte of a word (or the second lowest byte of a larger data type).

highByte(w);
Functionuint8_t highByte(w)
Parametersw - A value of any type
Returnsbyte
Click to view the code
void setup() {
Serial.begin(115200);
Serial.println("Test target 0xABCD");

uint16_t target = 0xABCD;

Serial.print("lowByte() of 0xABCD = "); // extract the low-order byte of the target
Serial.println(lowByte(target), HEX);

Serial.print("highByte() of 0xABCD = "); // extract the low-order byte of the target
Serial.println(highByte(target), HEX);
}

void loop() {
}

DigitalIO

pinMode()

Configures the specified pin to behave either as an input or an output.

pinMode(pin, mode);
Functionvoid pinMode(uint8_t pin, uint8_t mode)
Parameterspin - The pin which you want to set
mode
- INPUT
- OUTPUT
- INPUT_PULLUP
- INPUT_PULLDOWN
Returnsvoid
Click to view the code
uint8_t ledPin = 36;   // LED connected to digital pin 36
uint8_t inputPin = 13; // input connected to digital pin 13

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin 36 as output
pinMode(inputPin, INPUT_PULLUP); // sets the digital pin 13 as input
}

void loop()
{
int val = digitalRead(inputPin); // read the input pin
if (val == LOW)
digitalWrite(ledPin, HIGH); // enable led if input is LOW
else
digitalWrite(ledPin, LOW); // disable led if input is HIGH
}

digitalWrite()

Writes a HIGH or a LOW value to a digital pin.

digitalWrite(pin, value);
Functionvoid digitalWrite(uint8_t pin, uint8_t value)
Parameterspin - The pin which you want to write
value - HIGH or LOW
Returnsvoid
Click to view the code
uint8_t ledPin = 36;   // LED connected to digital pin 36
uint8_t inputPin = 13; // input connected to digital pin 13

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin 36 as output
pinMode(inputPin, INPUT_PULLUP); // sets the digital pin 13 as input
}

void loop()
{
int val = digitalRead(inputPin); // read the input pin
if (val == LOW)
digitalWrite(ledPin, HIGH); // enable led if input is LOW
else
digitalWrite(ledPin, LOW); // disable led if input is HIGH
}

digitalRead()

Reads the value from a specified digital pin, either HIGH or LOW.

digitalRead(pin);
Functionint digitalRead (uint8_t pin)
Parameterspin - The pin which you want to read
ReturnsHIGH or LOW(Type: int)
Click to view the code
uint8_t ledPin = 36;   // LED connected to digital pin 36
uint8_t inputPin = 13; // input connected to digital pin 13

void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin 36 as output
pinMode(inputPin, INPUT_PULLUP); // sets the digital pin 13 as input
}

void loop()
{
int val = digitalRead(inputPin); // read the input pin
if (val == LOW)
digitalWrite(ledPin, HIGH); // enable led if input is LOW
else
digitalWrite(ledPin, LOW); // disable led if input is HIGH
}

AnalogIO

analogRead()

Reads the value from the specified analog pin.

analogRead(pin);
Functionint analogRead(uint8_t pin)
Parameterspin - The name of the analog input pin to read from
ReturnsThe analog reading on the pin(Type: int)

analogReference()

Configures the reference voltage used for analog input.

analogReference(type);
Functionvoid analogReference(uint8_t type)
Parameters (Interval Vref RAK4630)type - Which type of reference to use:
RAK_ADC_MODE_DEFAULT (3.3 V)
RAK_ADC_MODE_3_0
RAK_ADC_MODE_2_4
RAK_ADC_MODE_1_8
RAK_ADC_MODE_1_2
Returnsvoid
warning

ADC voltage reference for RAK3172 and RAK3172-SiP is fixed to VDD voltage.

analogOversampling()

Sets the number of readings from the analog port.

void analogOversampling(uint32_t ulOversampling);
Functionvoid analogOversampling(uint32_t ulOversampling)
ParametersulOversampling - Number of readings from analog input
Returnsvoid

analogWrite()

Writes an analog value (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().

analogWrite(pin, value);
Functionvoid analogWrite(uint8_t pin, int value)
Parameterspin - The pin which you want to read
value - The duty cycle: between 0 (always off) and 255 (always on)
Returnsvoid
Click to view the code
int val = 0; // variable to write the LED pin
bool state = false;
bool ledSwitch = false;

void valChage()
{
state = !state;
if(val == 0)
ledSwitch = !ledSwitch;
}

void setup() {
// put your setup code here, to run once:
pinMode(GREEN_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
}

void loop() {
// put your main code here, to run repeatedly:
if(val == 0 || val == 255)
valChage();

// To determine to make the led lighter or darker
if(state)
val++;
else
val--;
// To switch the lighting led
if(ledSwitch)
analogWrite(GREEN_LED ,val); // Light the green led
else
analogWrite(BLUE_LED, val); //Light the blue led

} digitalWrite(ledPin, LOW); // disable led if input is HIGH

analogReadResolution()

analogReadResolution() 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.

analogReadResolution(bits);
Functionvoid analogReadResolution(uint8_t bits)
Parametersbits - Determines the resolution (in bits) of the value returned by the analogRead() function. You can set this between 1 and 32. You can also set the resolutions higher than the supported 12 or 16 bits, but values returned by analogRead() will suffer approximation.
Returnsvoid

analogWriteResolution()

analogWriteResolution() sets the resolution of the analogWrite() function. It defaults to 8 bits (values between 0-255) for backward compatibility with AVR based boards.

analogWriteResolution(bits);
Functionvoid analogWriteResolution(uint8_t bits)
Parametersbits - Determines the resolution (in bits) of the values used in the analogWrite() function. The value can range from 1 to 32. If you choose a resolution higher or lower than your board’s hardware capabilities, the value used in analogWrite() will be either truncated if it’s too high or padded with zeros if it’s too low.
Returnsvoid

Interrupts

interrupts()

Re-enables interrupts after they’ve been disabled by noInterrupts().

interrupts();
Functionvoid interrupts(void)
Returnsvoid
Click to view the code
void setup() {
}

void loop() {
noInterrupts();
// critical, time-sensitive code here
interrupts();
// other code here
}

noInterrupts()

Disables interrupts. You can re-enable them with interrupts().

noInterrupts();
Functionvoid noInterrupts(void)
Returnsvoid
Click to view the code
void setup() {
}

void loop() {
noInterrupts();
// critical, time-sensitive code here
interrupts();
// other code here
}

attachInterrupt()

Digital Pins With Interrupts. See also AttachInterrupt

attachInterrupt(pin, ISR, mode);
Functionvoid attachInterrupt(uint32_t pin, void(*)(void) userFunc, int mode)
Parameterspin - The number of the interrupt
ISR - The ISR to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine.
mode - Defines when the interrupt should be triggered
• LOW
• CHANGE
• RISING
• FALLING.
Returnsvoid
Click to view the code
uint8_t ledPin = 36;
uint8_t interruptPin = 13;
volatile byte state = LOW;
long startTime = 0;

void blink()
{
state = !state;
}

void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(interruptPin, blink, CHANGE);
startTime = millis();
}

void loop()
{
//After 20sec will disable ISR for pin13
if(millis() - startTime >= 20*1000)
detachInterrupt(13);

digitalWrite(ledPin, state);
}

detachInterrupt()

Turns off the given interrupt.

detachInterrupt(pin);
Functionvoid detachInterrupt(uint32_t pin)
Parameterspin - The number of the interrupt to disable
Returnsvoid
Click to view the code
uint8_t ledPin = 36;
uint8_t interruptPin = 13;
volatile byte state = LOW;
long startTime = 0;

void blink()
{
state = !state;
}

void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(interruptPin, blink, CHANGE);
startTime = millis();
}

void loop()
{
//After 20sec will disable ISR for pin13
if(millis() - startTime >= 20*1000)
detachInterrupt(13);

digitalWrite(ledPin, state);
}

RandomNumber

random

The random function generates pseudo-random numbers.

random(max);
random(min, max);
Functionlong random(long min, long max)
Parametersmin(optional) - Lower bound of the random value, inclusive(default = 0)
max - Upper bound of the random value, exclusive
ReturnsA random number between min and max-1(Type: long)
Click to view the code
uint8_t ledPin = 36;
uint8_t interruptPin = 13;
volatile byte state = LOW;
long startTime = 0;

void blink()
{
state = !state;
}

void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(interruptPin, blink, CHANGE);
startTime = millis();
}

void loop()
{
//After 20sec will disable ISR for pin13
if(millis() - startTime >= 20*1000)
detachInterrupt(13);

digitalWrite(ledPin, state);
}

randomSeed()

randomSeed() initializes the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same. If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

randomSeed(seed);
Functionvoid randomSeed (unsigned long seed)
Parametersseed number to initialize the pseudo-random sequence
Returnsvoid
Click to view the code
void setup() {
Serial.begin(115200);//UART0 baudrate 115200
randomSeed(analogRead(0));
}

void loop() {
Serial.print("Random number(0 ~ 999) : ");
uint32_t l = random(1000);
Serial.println(l);

//delay 1 second
delay(1000);
}