### Initialize and Terminate Pigpio Library for Signal Handling (JavaScript) Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Demonstrates the correct way to initialize and terminate the pigpio C library when dealing with Node.js signal events. This is crucial to avoid conflicts with signal handlers registered by the application. The example shows how to properly handle SIGINT to turn off an LED before the program exits. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; let led; let iv; pigpio.initialize(); // pigpio C library initialized here process.on('SIGINT', () => { led.digitalWrite(0); pigpio.terminate(); // pigpio C library terminated here clearInterval(iv); console.log('Terminating...'); }); led = new Gpio(17, {mode: Gpio.OUTPUT}); iv = setInterval(() => { led.digitalWrite(led.digitalRead() ^ 1); }, 1000); ``` -------------------------------- ### Measure Pulse Width using GPIO Alerts Source: https://github.com/fivdi/pigpio/blob/master/README.md This example uses the trigger method to generate a short pulse on a GPIO pin and utilizes alerts to capture the exact duration of that pulse. It demonstrates high-precision timing for monitoring signal states. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, { mode: Gpio.OUTPUT, alert: true }); const watchLed = () => { let startTick; led.on('alert', (level, tick) => { if (level == 1) { startTick = tick; } else { const endTick = tick; const diff = (endTick >> 0) - (startTick >> 0); console.log(diff); } }); }; watchLed(); setInterval(() => { led.trigger(15, 1); }, 1000); ``` -------------------------------- ### Get Raspberry Pi Hardware Revision (JavaScript) Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Retrieves the hardware revision of the Raspberry Pi using the pigpio library. It returns an unsigned integer, or 0 if the revision cannot be determined. The example shows how to print this revision in hexadecimal format. ```javascript const pigpio = require('pigpio'); console.log('Hardware Revision: ' + pigpio.hardwareRevision().toString(16)); ``` -------------------------------- ### Mode Management Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Methods for setting and getting the mode of a GPIO pin (INPUT, OUTPUT, ALT0-ALT5). ```APIDOC ## Mode Management ### Description Methods for setting and getting the mode of a GPIO pin. ### Methods - **mode(mode)**: Sets the mode of the GPIO pin. - **getMode()**: Returns the current mode of the GPIO pin. ### Parameters #### mode(mode) - **mode** (Constant) - Required - The desired mode (e.g., Gpio.INPUT, Gpio.OUTPUT, Gpio.ALT0). #### getMode() No parameters. ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const pin = new Gpio(17, {mode: Gpio.INPUT}); console.log('Current mode:', pin.getMode()); pin.mode(Gpio.OUTPUT); console.log('New mode:', pin.getMode()); ``` ### Response #### Success Response (200) - **mode()**: void - **getMode()**: (Constant) - The current mode of the GPIO pin. ``` -------------------------------- ### Send Wavechain with pigpio Source: https://github.com/fivdi/pigpio/blob/master/README.md Chains multiple waveforms together using the waveChain method. This example creates two distinct waveforms, assigns them wave IDs, and then constructs a chain array that includes modifiers for repeating the second waveform. The chain is then transmitted, and the waveforms are deleted. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, {mode: Gpio.OUTPUT}); output.digitalWrite(0); pigpio.waveClear(); let firstWaveForm = []; let secondWaveForm = []; for (let x = 0; x < 10; x++) { if (x % 2 === 0) { firstWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 10 }); } else { firstWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 10 }); } } pigpio.waveAddGeneric(firstWaveForm); let firstWaveId = pigpio.waveCreate(); for (let x = 0; x < 10; x++) { if (x % 2 === 0) { secondWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 20 }); } else { secondWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 20 }); } } pigpio.waveAddGeneric(secondWaveForm); let secondWaveId = pigpio.waveCreate(); if (firstWaveId >= 0 && secondWaveId >= 0) { let chain = [firstWaveId, 255, 0, secondWaveId, 255, 1, 3, 0]; pigpio.waveChain(chain); } while (pigpio.waveTxBusy()) {} pigpio.waveDelete(firstWaveId); pigpio.waveDelete(secondWaveId); ``` -------------------------------- ### GET /waveStatus Source: https://github.com/fivdi/pigpio/blob/master/doc/global.md Endpoints for monitoring the status and progress of waveform transmission. ```APIDOC ## GET /waveTxBusy ### Description Checks if a waveform is currently being transmitted. ### Response - **result** (integer) - 1 if busy, 0 otherwise. ## GET /waveTxAt ### Description Returns the ID of the waveform currently being transmitted. ### Response - **wave_id** (integer) - The ID of the current wave. ## POST /waveTxStop ### Description Aborts the current waveform transmission immediately. ``` -------------------------------- ### Get Current Tick and Calculate Time Difference (JavaScript) Source: https://github.com/fivdi/pigpio/blob/master/doc/global.md Retrieves the current system tick in microseconds since boot using getTick(). The tickDiff() function calculates the difference between two tick values, correctly handling potential 32-bit overflows. These functions are essential for accurate time measurements in pigpio applications. ```javascript const pigpio = require('pigpio'); let startUsec = pigpio.getTick(); // Do some time-consuming things. let currentUsec = pigpio.getTick(); let deltaUsec = pigpio.tickDiff(startUsec, currentUsec); ``` -------------------------------- ### Initialize Gpio Instances Source: https://context7.com/fivdi/pigpio/llms.txt Demonstrates how to instantiate Gpio objects for input and output, including configuring pull resistors, interrupts, and alerts. It also shows how to iterate through available GPIO pins to read their state. ```javascript const Gpio = require('pigpio').Gpio; // Basic output GPIO const led = new Gpio(17, {mode: Gpio.OUTPUT}); // Input with pull-down resistor and interrupt on both edges const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.EITHER_EDGE }); // Input with alert enabled for microsecond-accurate timing const sensor = new Gpio(24, { mode: Gpio.INPUT, alert: true }); // Read GPIO info without changing mode for (let gpioNo = Gpio.MIN_GPIO; gpioNo <= Gpio.MAX_GPIO; gpioNo += 1) { const gpio = new Gpio(gpioNo); console.log('GPIO ' + gpioNo + ':' + ' mode=' + gpio.getMode() + ' level=' + gpio.digitalRead() ); } ``` -------------------------------- ### Gpio Constructor and Initialization Source: https://context7.com/fivdi/pigpio/llms.txt Demonstrates how to create Gpio instances for various configurations including output, input with pull resistors, and interrupt/alert enabled inputs. ```APIDOC ## Gpio Constructor ### Description The `Gpio` class is the primary interface for GPIO operations. Create a Gpio instance by specifying the GPIO number and optional configuration for mode, pull resistors, interrupts, and alerts. The Gpio object is an EventEmitter that can emit 'interrupt' and 'alert' events. ### Method `new Gpio(gpioNo, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **gpioNo** (number) - Required - The GPIO pin number. - **options** (object) - Optional - Configuration options. - **mode** (number) - Gpio.OUTPUT, Gpio.INPUT - **pullUpDown** (number) - Gpio.PUD_OFF, Gpio.PUD_DOWN, Gpio.PUD_UP - **edge** (number) - Gpio.RISING_EDGE, Gpio.FALLING_EDGE, Gpio.EITHER_EDGE - **alert** (boolean) - Enable alert for microsecond-accurate timing. ### Request Example ```javascript const Gpio = require('pigpio').Gpio; // Basic output GPIO const led = new Gpio(17, {mode: Gpio.OUTPUT}); // Input with pull-down resistor and interrupt on both edges const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.EITHER_EDGE }); // Input with alert enabled for microsecond-accurate timing const sensor = new Gpio(24, { mode: Gpio.INPUT, alert: true }); // Read GPIO info without changing mode for (let gpioNo = Gpio.MIN_GPIO; gpioNo <= Gpio.MAX_GPIO; gpioNo += 1) { const gpio = new Gpio(gpioNo); console.log('GPIO ' + gpioNo + ':' + ' mode=' + gpio.getMode() + ' level=' + gpio.digitalRead() ); } ``` ### Response #### Success Response (200) Returns a Gpio instance. #### Response Example ```json { "gpioInstance": "Gpio object" } ``` ``` -------------------------------- ### Initialize and Read GPIO State Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md This snippet demonstrates how to instantiate a Gpio object for each available GPIO pin and retrieve its current mode and digital logic level. ```javascript const Gpio = require('pigpio').Gpio; for (let gpioNo = Gpio.MIN_GPIO; gpioNo <= Gpio.MAX_GPIO; gpioNo += 1) { const gpio = new Gpio(gpioNo); console.log('GPIO ' + gpioNo + ':' + ' mode=' + gpio.getMode() + ' level=' + gpio.digitalRead() ); } ``` -------------------------------- ### GET /waveMetadata Source: https://github.com/fivdi/pigpio/blob/master/doc/global.md Endpoints to retrieve metrics regarding waveform length, pulses, and DMA control blocks. ```APIDOC ## GET /waveMetadata ### Description Retrieves various statistics about the current and maximum waveform capabilities. ### Endpoints - `waveGetMicros()`: Returns length of current waveform in microseconds. - `waveGetPulses()`: Returns length of current waveform in pulses. - `waveGetCbs()`: Returns length of current waveform in DMA control blocks. - `waveGetMaxMicros()`: Returns maximum possible waveform size in microseconds. ### Response - **value** (integer) - The requested metric value. ``` -------------------------------- ### GpioBank Constructor Source: https://github.com/fivdi/pigpio/blob/master/doc/gpiobank.md Initializes a new GpioBank instance for a specific bank. ```APIDOC ## Constructor: GpioBank(bank) ### Description Creates a new GpioBank object to manage up to 32 GPIOs as a single operation. ### Parameters - **bank** (Integer) - Optional - The bank identifier (BANK1 or BANK2). Defaults to BANK1. ### Request Example const bank = new GpioBank(BANK1); ``` -------------------------------- ### Signal Handling with Initialize/Terminate Source: https://context7.com/fivdi/pigpio/llms.txt Use explicit `initialize()` and `terminate()` functions when your application needs custom signal handlers to ensure proper cleanup during application exit. ```APIDOC ## Signal Handling with Initialize/Terminate ### Description Use explicit `initialize()` and `terminate()` functions when your application needs custom signal handlers. This ensures proper cleanup when the application exits. ### Method N/A (Signal handling and library lifecycle) ### Endpoint N/A (Library lifecycle management) ### Parameters None ### Request Example ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Initialize BEFORE registering signal handlers pigpio.initialize(); let led; let interval; process.on('SIGINT', () => { console.log('Received SIGINT, cleaning up...'); led.digitalWrite(0); // Turn off LED clearInterval(interval); pigpio.terminate(); // Clean up pigpio process.exit(0); }); led = new Gpio(17, {mode: Gpio.OUTPUT}); // Blink LED every second interval = setInterval(() => { led.digitalWrite(led.digitalRead() ^ 1); }, 1000); console.log('Press Ctrl+C to exit'); ``` ### Response #### Success Response (200) N/A (This demonstrates signal handling and library cleanup) #### Response Example ```json { "message": "Application running, press Ctrl+C to exit." } ``` ``` -------------------------------- ### Configuration Functions Source: https://context7.com/fivdi/pigpio/llms.txt Configure the pigpio library's behavior before creating Gpio objects. This includes setting the sample rate, controlling network interfaces, and managing library initialization and termination. ```APIDOC ## Configuration Functions ### Description Configure the pigpio library behavior before creating Gpio objects. Set sample rate with `configureClock()`, control interfaces with `configureInterfaces()`, and manage initialization with `initialize()` and `terminate()`. ### Method N/A (Configuration calls) ### Endpoint N/A (Library configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Must be called BEFORE creating Gpio objects // Set sample rate to 1µs (highest resolution, 25% CPU) pigpio.configureClock(1, pigpio.CLOCK_PCM); // Disable socket and pipe interfaces for security pigpio.configureInterfaces( pigpio.DISABLE_FIFO_IF | pigpio.DISABLE_SOCK_IF ); // Custom socket port (default is 8888) pigpio.configureSocketPort(8889); // Get hardware revision console.log('Hardware revision:', pigpio.hardwareRevision().toString(16)); // Now create GPIO objects const led = new Gpio(17, {mode: Gpio.OUTPUT}); ``` ### Response #### Success Response (200) N/A (Configuration functions do not return specific status codes in this context) #### Response Example ```json { "message": "Configuration applied successfully" } ``` ``` -------------------------------- ### Configure PWM and Hardware PWM Source: https://context7.com/fivdi/pigpio/llms.txt Illustrates how to control PWM output for fading LEDs or driving motors. It covers setting custom ranges, frequencies, and using hardware-based PWM for precise timing. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); // Pulse LED using PWM (fade in/out) let dutyCycle = 0; let direction = 1; setInterval(() => { led.pwmWrite(dutyCycle); dutyCycle += direction * 5; if (dutyCycle >= 255) { dutyCycle = 255; direction = -1; } else if (dutyCycle <= 0) { dutyCycle = 0; direction = 1; } }, 20); // Custom PWM range and frequency const motor = new Gpio(18, {mode: Gpio.OUTPUT}); motor.pwmRange(1000); // Set range to 1000 motor.pwmFrequency(8000); // Set frequency to 8kHz motor.pwmWrite(500); // 50% duty cycle // Hardware PWM (GPIO18 supported on all Pi models) const hwPwm = new Gpio(18, {mode: Gpio.OUTPUT}); hwPwm.hardwarePwmWrite(10000, 500000); // 10kHz, 50% duty cycle (range 0-1000000) ``` -------------------------------- ### Configure Internal Pull-Up/Down Resistors Source: https://context7.com/fivdi/pigpio/llms.txt Shows how to configure internal pull-up or pull-down resistors for GPIO pins to ensure stable input states. ```javascript const Gpio = require('pigpio').Gpio; // Button with internal pull-up (active low when pressed) const button1 = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_UP }); // Button with internal pull-down (active high when pressed) const button2 = new Gpio(17, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN }); // Change pull resistor at runtime const gpio = new Gpio(23, {mode: Gpio.INPUT}); gpio.pullUpDown(Gpio.PUD_UP); // Enable pull-up gpio.pullUpDown(Gpio.PUD_OFF); // Disable pull resistor ``` -------------------------------- ### Generate and Transmit Generic Waveform (JavaScript) Source: https://github.com/fivdi/pigpio/blob/master/doc/global.md This snippet demonstrates how to create a custom waveform by adding generic pulses and then transmitting it using pigpio. It includes clearing existing waveforms, adding a series of pulses with specified GPIO states and durations, creating the waveform, sending it in one-shot mode, and cleaning up afterwards. This is useful for generating complex signal patterns. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, { mode: Gpio.OUTPUT }); let waveform = []; for (let x = 0; x < 20; x++) { if (x % 2 == 1) { waveform.push({ gpioOn: outPin, gpioOff: 0, usDelay: x + 1 }); } else { waveform.push({ gpioOn: 0, gpioOff: outPin, usDelay: x + 1 }); } } pigpio.waveClear(); pigpio.waveAddGeneric(waveform); let waveId = pigpio.waveCreate(); if (waveId >= 0) { pigpio.waveTxSend(waveId, pigpio.WAVE_MODE_ONE_SHOT); } while (pigpio.waveTxBusy()) {} pigpio.waveDelete(waveId); ``` -------------------------------- ### Handle GPIO Interrupts with pigpio Source: https://context7.com/fivdi/pigpio/llms.txt Demonstrates how to enable interrupts on GPIO pins to detect state changes. It covers both standard edge detection and the use of timeouts for sensor monitoring. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.EITHER_EDGE }); // Control LED with button via interrupt button.on('interrupt', (level) => { led.digitalWrite(level); console.log('Button pressed, level:', level); }); // Interrupt with timeout (level will be TIMEOUT=2 if expired) const sensor = new Gpio(23, { mode: Gpio.INPUT, edge: Gpio.RISING_EDGE, timeout: 5000 // 5 second timeout }); sensor.on('interrupt', (level, tick) => { if (level === Gpio.TIMEOUT) { console.log('Timeout - no signal detected'); } else { console.log('Signal detected at tick:', tick); } }); ``` -------------------------------- ### Gpio Constructor Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Initializes a new Gpio object for a specified GPIO pin. Options can be provided to configure mode, pull-type, interrupts, and alerts. ```APIDOC ## Gpio Constructor ### Description Initializes a new Gpio object for a specified GPIO pin. Options can be provided to configure mode, pull-type, interrupts, and alerts. ### Method Constructor ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const ledPin = new Gpio(17, {mode: Gpio.OUTPUT}); ``` ### Response #### Success Response (200) Returns a new Gpio object. #### Response Example ```javascript // Gpio object instance ``` ``` -------------------------------- ### Wave Chains API Source: https://context7.com/fivdi/pigpio/llms.txt Learn how to chain multiple waveforms together using loops, delays, and repeat commands with the `waveChain()` function. This enables the creation of complex timing patterns and protocols by sequencing predefined waves. ```APIDOC ## Wave Chains Chain multiple waveforms together with loops, delays, and repeat commands using `waveChain()`. This enables complex timing patterns and protocols. ### Method This describes a programmatic approach using a JavaScript library, not a direct HTTP API endpoint. ### Endpoint N/A (Library functions) ### Parameters N/A ### Request Example ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, {mode: Gpio.OUTPUT}); output.digitalWrite(0); pigpio.waveClear(); // Create first wave (10µs pulses) let firstWaveForm = []; for (let x = 0; x < 10; x++) { if (x % 2 === 0) { firstWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 10 }); } else { firstWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 10 }); } } pigpio.waveAddGeneric(firstWaveForm); let firstWaveId = pigpio.waveCreate(); // Create second wave (20µs pulses) let secondWaveForm = []; for (let x = 0; x < 10; x++) { if (x % 2 === 0) { secondWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 20 }); } else { secondWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 20 }); } } pigpio.waveAddGeneric(secondWaveForm); let secondWaveId = pigpio.waveCreate(); // Chain: first wave, then second wave repeated 3 times // Command codes: 255,0=loop start, 255,1,x,y=repeat x+y*256 times let chain = [ firstWaveId, 255, 0, // Loop start secondWaveId, 255, 1, 3, 0 // Repeat 3 times (3 + 0*256) ]; pigpio.waveChain(chain); while (pigpio.waveTxBusy()) {} pigpio.waveDelete(firstWaveId); pigpio.waveDelete(secondWaveId); ``` ### Response N/A (Library operations) ### Response Example N/A ``` -------------------------------- ### configureInterfaces Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Configures the availability of fifo and socket interfaces. ```APIDOC ## configureInterfaces(ifFlags) ### Description Configures support for fifo and socket interfaces. Must be called before creating Gpio objects. ### Parameters - **ifFlags** (integer) - Required - Bitwise flags (e.g., DISABLE_FIFO_IF, DISABLE_SOCK_IF, LOCALHOST_SOCK_IF). ### Request Example ```javascript pigpio.configureInterfaces(pigpio.DISABLE_FIFO_IF | pigpio.DISABLE_SOCK_IF); ``` ``` -------------------------------- ### Configure pigpio Clock for PWM Hardware Source: https://github.com/fivdi/pigpio/blob/master/doc/troubleshooting.md This snippet demonstrates how to configure the pigpio clock to use PWM hardware before initializing any GPIO objects. This is necessary to prevent conflicts with sound cards that rely on the same hardware resources. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Call configureClock before creating Gpio objects pigpio.configureClock(1, pigpio.CLOCK_PWM); const led = new Gpio(25, { mode: Gpio.OUTPUT }); ``` -------------------------------- ### Perform Digital Read and Write Operations Source: https://context7.com/fivdi/pigpio/llms.txt Shows how to read the state of an input pin and write to an output pin using digitalRead and digitalWrite methods. These operations are fundamental for controlling external components like LEDs based on button states. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); const button = new Gpio(4, {mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN}); // Read button state and control LED setInterval(() => { const buttonState = button.digitalRead(); led.digitalWrite(buttonState); console.log('Button:', buttonState, 'LED:', led.digitalRead()); }, 100); // Toggle LED state setInterval(() => { led.digitalWrite(led.digitalRead() ^ 1); }, 1000); ``` -------------------------------- ### Control Servo Motors Source: https://context7.com/fivdi/pigpio/llms.txt Demonstrates how to control a servo motor using the servoWrite method. It shows how to cycle through pulse widths and retrieve the current pulse width setting. ```javascript const Gpio = require('pigpio').Gpio; const servo = new Gpio(10, {mode: Gpio.OUTPUT}); // Move servo through full range let pulseWidth = 1000; let increment = 100; setInterval(() => { servo.servoWrite(pulseWidth); console.log('Pulse width:', pulseWidth, 'µs'); pulseWidth += increment; if (pulseWidth >= 2000) { increment = -100; } else if (pulseWidth <= 1000) { increment = 100; } }, 1000); // Get current servo pulse width console.log('Current pulse width:', servo.getServoPulseWidth()); ``` -------------------------------- ### GPIO Configuration Constants Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Reference for constants used to configure GPIO modes, pull resistors, and edge detection. ```APIDOC ## GPIO Configuration Constants ### Modes - **INPUT**: Set GPIO as input. - **OUTPUT**: Set GPIO as output. - **ALT0 - ALT5**: Set GPIO to alternative modes 0 through 5. ### Pull Resistors - **PUD_OFF**: Disable pull-up/down resistors. - **PUD_DOWN**: Enable pull-down resistor. - **PUD_UP**: Enable pull-up resistor. ### Edge Detection - **RISING_EDGE**: Interrupt on rising edge. - **FALLING_EDGE**: Interrupt on falling edge. - **EITHER_EDGE**: Interrupt on both edges. ### Limits - **MIN_GPIO**: Smallest GPIO number. - **MAX_GPIO**: Largest GPIO number. - **MAX_USER_GPIO**: Largest user-accessible GPIO number. ``` -------------------------------- ### Configure pigpio Library Behavior Source: https://context7.com/fivdi/pigpio/llms.txt Configure the pigpio library behavior before creating Gpio objects. This includes setting the sample rate, controlling interface availability (socket and pipe), and optionally setting a custom socket port. These configurations affect how the pigpio library interacts with the system and its communication channels. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Must be called BEFORE creating Gpio objects // Set sample rate to 1µs (highest resolution, 25% CPU) pigpio.configureClock(1, pigpio.CLOCK_PCM); // Disable socket and pipe interfaces for security pigpio.configureInterfaces( pigpio.DISABLE_FIFO_IF | pigpio.DISABLE_SOCK_IF ); // Custom socket port (default is 8888) pigpio.configureSocketPort(8889); // Get hardware revision console.log('Hardware revision:', pigpio.hardwareRevision().toString(16)); // Now create GPIO objects const led = new Gpio(17, {mode: Gpio.OUTPUT}); ``` -------------------------------- ### configureClock Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Configures the global sample rate and timing peripheral for PWM and PCM operations. ```APIDOC ## configureClock(microseconds, peripheral) ### Description Sets the global sample rate and the hardware peripheral used for timing. This must be called before creating any Gpio objects. ### Parameters - **microseconds** (unsigned integer) - Required - The sample rate in microseconds (1, 2, 4, 5, 8, or 10). - **peripheral** (unsigned integer) - Required - The peripheral for timing (use CLOCK_PWM or CLOCK_PCM). ### Request Example ```javascript pigpio.configureClock(1, pigpio.CLOCK_PCM); ``` ``` -------------------------------- ### Chain Multiple Waveforms Source: https://context7.com/fivdi/pigpio/llms.txt Shows how to link multiple pre-defined waveforms into a sequence. Uses control codes to implement loops and repetitions for complex timing patterns. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, {mode: Gpio.OUTPUT}); output.digitalWrite(0); pigpio.waveClear(); let firstWaveForm = []; for (let x = 0; x < 10; x++) { if (x % 2 === 0) { firstWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 10 }); } else { firstWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 10 }); } } pigpio.waveAddGeneric(firstWaveForm); let firstWaveId = pigpio.waveCreate(); let secondWaveForm = []; for (let x = 0; x < 10; x++) { if (x % 2 === 0) { secondWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 20 }); } else { secondWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 20 }); } } pigpio.waveAddGeneric(secondWaveForm); let secondWaveId = pigpio.waveCreate(); let chain = [ firstWaveId, 255, 0, secondWaveId, 255, 1, 3, 0 ]; pigpio.waveChain(chain); while (pigpio.waveTxBusy()) {} pigpio.waveDelete(firstWaveId); pigpio.waveDelete(secondWaveId); ``` -------------------------------- ### Generate and Transmit Waveforms Source: https://context7.com/fivdi/pigpio/llms.txt Demonstrates creating a sequence of pulses using the waveform API. It clears existing waves, adds a generic pulse pattern, and transmits the waveform using DMA for microsecond accuracy. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, {mode: Gpio.OUTPUT}); output.digitalWrite(0); pigpio.waveClear(); let waveform = []; for (let x = 0; x < 20; x++) { if (x % 2 === 1) { waveform.push({ gpioOn: outPin, gpioOff: 0, usDelay: x + 1 }); } else { waveform.push({ gpioOn: 0, gpioOff: outPin, usDelay: x + 1 }); } } pigpio.waveAddGeneric(waveform); let waveId = pigpio.waveCreate(); if (waveId >= 0) { console.log('Wave length:', pigpio.waveGetMicros(), 'µs'); console.log('Wave pulses:', pigpio.waveGetPulses()); pigpio.waveTxSend(waveId, pigpio.WAVE_MODE_ONE_SHOT); } while (pigpio.waveTxBusy()) {} pigpio.waveDelete(waveId); ``` -------------------------------- ### Initialize and Terminate pigpio for Signal Handling Source: https://context7.com/fivdi/pigpio/llms.txt Use explicit initialize() and terminate() functions when your application requires custom signal handlers. This ensures proper cleanup of pigpio resources when the application exits, preventing potential issues with GPIO state or library resources. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Initialize BEFORE registering signal handlers pigpio.initialize(); let led; let interval; process.on('SIGINT', () => { console.log('Received SIGINT, cleaning up...'); led.digitalWrite(0); // Turn off LED clearInterval(interval); pigpio.terminate(); // Clean up pigpio process.exit(0); }); led = new Gpio(17, {mode: Gpio.OUTPUT}); // Blink LED every second interval = setInterval(() => { led.digitalWrite(led.digitalRead() ^ 1); }, 1000); console.log('Press Ctrl+C to exit'); ``` -------------------------------- ### Pulse an LED with PWM Source: https://github.com/fivdi/pigpio/blob/master/README.md Demonstrates how to control the brightness of an LED connected to a GPIO pin using Pulse Width Modulation (PWM). It cycles the duty cycle from 0 to 255 to create a pulsing effect. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); let dutyCycle = 0; setInterval(() => { led.pwmWrite(dutyCycle); dutyCycle += 5; if (dutyCycle > 255) { dutyCycle = 0; } }, 20); ``` -------------------------------- ### Configure Pigpio Clock Rate and Peripheral Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Sets the sample rate for pigpio's PWM/PCM timing and the peripheral used for timing. This function must be called before creating Gpio objects. The sample rate affects CPU usage and the number of samples per second. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Call configureClock before creating Gpio objects piggio.configureClock(1, pigpio.CLOCK_PCM); const led = new Gpio(17, {mode: Gpio.OUTPUT}); ``` -------------------------------- ### Alert Handling Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Methods for enabling and disabling alerts for GPIO state changes, and handling alert events. ```APIDOC ## Alert Handling ### Description Methods for enabling and disabling alerts for GPIO state changes, and handling alert events. ### Methods - **enableAlert()**: Enables alerts for GPIO state changes. - **disableAlert()**: Disables alerts for GPIO state changes. ### Parameters #### enableAlert() No parameters. #### disableAlert() No parameters. ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const alertPin = new Gpio(17, {alert: true}); alertPin.on('alert', (level, tick) => { console.log(`GPIO changed to ${level} at tick ${tick}`); }); // To disable alerts later: // alertPin.disableAlert(); ``` ### Response #### Success Response (200) - **enableAlert()**: void - **disableAlert()**: void #### Events - **'alert'**: Emitted when the GPIO state changes. The listener receives the new level and the timestamp (tick) of the change. ``` -------------------------------- ### Configure Pigpio Interfaces (FIFO and Socket) Source: https://github.com/fivdi/pigpio/blob/master/doc/configuration.md Configures pigpio's support for FIFO and socket interfaces. This function must be called before creating Gpio objects. Options include disabling one or both interfaces, or restricting socket access to localhost. ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; // Call configureInterfaces before creating Gpio objects piggio.configureInterfaces(pigpio.DISABLE_FIFO_IF | pigpio.DISABLE_SOCK_IF); const led = new Gpio(17, {mode: Gpio.OUTPUT}); ``` -------------------------------- ### Handle 32-bit Tick Wrap-around Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Demonstrates how to correctly calculate the difference between two 32-bit ticks in JavaScript by using the sign-propagating right shift operator to avoid issues with integer overflow. ```javascript const startTick = 0xffffffff; // 2^32-1 or 4294967295, the max unsigned 32 bit integer const endTick = 1; console.log((endTick >> 0) - (startTick >> 0)); // prints 2 which is what we want ``` -------------------------------- ### Buttons and Interrupt Handling Source: https://github.com/fivdi/pigpio/blob/master/README.md Configures a button with an internal pull-down resistor and listens for state changes via interrupts. The LED state is updated to match the button level whenever an interrupt occurs. ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.EITHER_EDGE }); button.on('interrupt', (level) => { led.digitalWrite(level); }); ``` -------------------------------- ### Servo Control Source: https://context7.com/fivdi/pigpio/llms.txt Explains how to control servo motors using the `servoWrite` method, which sends pulses at 50Hz with adjustable pulse widths. ```APIDOC ## Servo Control ### Description The `servoWrite(pulseWidth)` method controls servos by sending pulses at 50Hz. Pulse width ranges from 500 (most anti-clockwise) to 2500 (most clockwise) microseconds, with 0 turning off servo pulses. ### Method - `servoWrite(pulseWidth)` - `getServoPulseWidth()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pulseWidth** (number) - Required - The pulse width in microseconds (0 to turn off, 500-2500 for servo movement). ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const servo = new Gpio(10, {mode: Gpio.OUTPUT}); // Move servo through full range let pulseWidth = 1000; let increment = 100; setInterval(() => { servo.servoWrite(pulseWidth); console.log('Pulse width:', pulseWidth, 'µs'); pulseWidth += increment; if (pulseWidth >= 2000) { increment = -100; } else if (pulseWidth <= 1000) { increment = 100; } }, 1000); // Get current servo pulse width console.log('Current pulse width:', servo.getServoPulseWidth()); ``` ### Response #### Success Response (200) - `servoWrite`: Returns undefined upon successful operation. - `getServoPulseWidth()`: Returns the current servo pulse width in microseconds. #### Response Example ```json { "servoPulseWidth": 1500 } ``` ``` -------------------------------- ### POST /waveChain Source: https://github.com/fivdi/pigpio/blob/master/doc/global.md Transmits a chain of waveforms, supporting loops and delays. Note that hardware PWM will be cancelled upon execution. ```APIDOC ## POST /waveChain ### Description Transmits a sequence of waveform IDs with optional control codes for looping and delays. ### Method POST ### Endpoint /waveChain ### Parameters #### Request Body - **chain** (Array) - Required - An ordered list of wave_ids and command codes (255 followed by command data). ### Request Example { "chain": [1, 255, 2, 136, 19, 255, 3] } ### Response #### Success Response (200) - **status** (string) - Confirmation of transmission initiation. ``` -------------------------------- ### PWM Control Source: https://context7.com/fivdi/pigpio/llms.txt Details how to control Pulse Width Modulation (PWM) output on GPIO pins, including setting duty cycle, range, frequency, and using hardware PWM. ```APIDOC ## PWM Control ### Description The `pwmWrite(dutyCycle)` method starts PWM output on a GPIO with duty cycle from 0 (off) to 255 (fully on) by default. Use `pwmRange(range)` to change the range, and `pwmFrequency(frequency)` to set the PWM frequency. Hardware PWM is available via `hardwarePwmWrite(frequency, dutyCycle)`. ### Method - `pwmWrite(dutyCycle)` - `pwmRange(range)` - `pwmFrequency(frequency)` - `hardwarePwmWrite(frequency, dutyCycle)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dutyCycle** (number) - Required - The PWM duty cycle value (0-255 by default). - **range** (number) - Required - The maximum value for the duty cycle. - **frequency** (number) - Required - The PWM frequency in Hz. ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const led = new Gpio(17, {mode: Gpio.OUTPUT}); // Pulse LED using PWM (fade in/out) let dutyCycle = 0; let direction = 1; setInterval(() => { led.pwmWrite(dutyCycle); dutyCycle += direction * 5; if (dutyCycle >= 255) { dutyCycle = 255; direction = -1; } else if (dutyCycle <= 0) { dutyCycle = 0; direction = 1; } }, 20); // Custom PWM range and frequency const motor = new Gpio(18, {mode: Gpio.OUTPUT}); motor.pwmRange(1000); // Set range to 1000 motor.pwmFrequency(8000); // Set frequency to 8kHz motor.pwmWrite(500); // 50% duty cycle // Hardware PWM (GPIO18 supported on all Pi models) const hwPwm = new Gpio(18, {mode: Gpio.OUTPUT}); hwPwm.hardwarePwmWrite(10000, 500000); // 10kHz, 50% duty cycle (range 0-1000000) ``` ### Response #### Success Response (200) - `pwmWrite`, `pwmRange`, `pwmFrequency`, `hardwarePwmWrite`: Returns undefined upon successful operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Pull-Type Configuration Source: https://github.com/fivdi/pigpio/blob/master/doc/gpio.md Method for configuring the pull-up/pull-down resistor for a GPIO pin. ```APIDOC ## Pull-Type Configuration ### Description Configures the pull-up/pull-down resistor for a GPIO pin. ### Method - **pullUpDown(pud)**: Sets the pull-up/pull-down state. ### Parameters #### pullUpDown(pud) - **pud** (Constant) - Required - The pull-type (Gpio.PUD_OFF, Gpio.PUD_DOWN, Gpio.PUD_UP). ### Request Example ```javascript const Gpio = require('pigpio').Gpio; const pin = new Gpio(17, {pullUpDown: Gpio.PUD_OFF}); pin.pullUpDown(Gpio.PUD_UP); ``` ### Response #### Success Response (200) - **pullUpDown()**: void ``` -------------------------------- ### Perform Bulk GPIO Operations with GpioBank Source: https://context7.com/fivdi/pigpio/llms.txt Utilizes the GpioBank class to read or write up to 32 GPIO pins simultaneously. This is useful for atomic operations using bit masks. ```javascript const GpioBank = require('pigpio').GpioBank; const bank = new GpioBank(GpioBank.BANK1); const levels = bank.read(); console.log('GPIO levels:', levels.toString(2).padStart(32, '0')); const gpio17State = (levels >> 17) & 1; console.log('GPIO17 state:', gpio17State); bank.set((1 << 17) | (1 << 18)); bank.clear((1 << 17) | (1 << 18)); console.log('Bank:', bank.bank() === GpioBank.BANK1 ? 'BANK1' : 'BANK2'); ``` -------------------------------- ### Waveform Generation API Source: https://context7.com/fivdi/pigpio/llms.txt This section details how to create and transmit precise, time-accurate waveforms using the pigpio waveform API. It covers building pulse sequences, creating waves, and transmitting them with microsecond timing accuracy using DMA. ```APIDOC ## Waveform Generation Create precise, time-accurate waveforms using the waveform API. Build a sequence of pulses, create a wave, and transmit it. Waveforms provide microsecond timing accuracy using DMA. ### Method This describes a programmatic approach using a JavaScript library, not a direct HTTP API endpoint. ### Endpoint N/A (Library functions) ### Parameters N/A ### Request Example ```javascript const pigpio = require('pigpio'); const Gpio = pigpio.Gpio; const outPin = 17; const output = new Gpio(outPin, {mode: Gpio.OUTPUT}); output.digitalWrite(0); pigpio.waveClear(); // Create alternating pulse waveform let waveform = []; for (let x = 0; x < 20; x++) { if (x % 2 === 1) { waveform.push({ gpioOn: outPin, gpioOff: 0, usDelay: x + 1 }); } else { waveform.push({ gpioOn: 0, gpioOff: outPin, usDelay: x + 1 }); } } pigpio.waveAddGeneric(waveform); let waveId = pigpio.waveCreate(); if (waveId >= 0) { console.log('Wave length:', pigpio.waveGetMicros(), 'µs'); console.log('Wave pulses:', pigpio.waveGetPulses()); // Send waveform once pigpio.waveTxSend(waveId, pigpio.WAVE_MODE_ONE_SHOT); // Or repeat continuously // pigpio.waveTxSend(waveId, pigpio.WAVE_MODE_REPEAT); } // Wait for transmission to complete while (pigpio.waveTxBusy()) {} pigpio.waveDelete(waveId); ``` ### Response N/A (Library operations) ### Response Example N/A ```