4.0 Key Functionalities and Libraries
Arduino’s power comes from a set of built-in functions and libraries that simplify complex tasks.
4.1 Input/Output (I/O) Functions
- pinMode(pin, mode): Configures a specific pin to behave as an INPUT, OUTPUT, or INPUT_PULLUP. INPUT_PULLUP enables an internal pull-up resistor.
- digitalWrite(pin, value): Writes a HIGH (5V on UNO) or LOW (0V) value to a digital pin configured as an output.
- digitalRead(pin): Reads the value from a specified digital pin, either HIGH or LOW.
- analogRead(pin): Reads the value from a specified analog input pin. It returns an integer value from 0 to 1023, representing a voltage from 0V to 5V.
- analogWrite(pin, value): Writes a pseudo-analog value using Pulse Width Modulation (PWM) to a PWM-enabled pin. The value is between 0 (always off) and 255 (always on).
4.2 Advanced Topics
- Pulse Width Modulation (PWM): A technique used by analogWrite() to generate a square wave with a varying duty cycle (the ratio of on-time to the total period). This is used to control the brightness of LEDs and the speed of DC motors. On the UNO, the PWM frequency is approximately 490 Hz on most PWM pins and 980 Hz on pins 5 and 6.
- Interrupts: A mechanism that allows the microcontroller to respond to external hardware events (e.g., a pin changing state) immediately, halting the main program to execute a special function called an Interrupt Service Routine (ISR). This is more efficient than constantly checking a pin’s state in the main loop. The function attachInterrupt() is used to configure this.
- Time Functions:
- delay(ms): Pauses the program for a specified number of milliseconds.
- delayMicroseconds(us): Pauses for a specified number of microseconds.
- millis(): Returns the number of milliseconds since the board began running the current program. Useful for non-blocking timing.
- micros(): Returns the number of microseconds since the board began running. Overflows after approximately 70 minutes.
4.3 Standard Libraries
- Math Library (math.h): Provides standard mathematical functions for floating-point numbers, including trigonometric (sin, cos, tan), power (pow), and square root (sqrt) functions.
- Character Functions: A library (<cctype>) for testing characters, with functions like isdigit(), isalpha(), isspace(), etc.