CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-avrgirl-arduino

A NodeJS library for flashing compiled sketch files to Arduino microcontroller boards.

Overview
Eval results
Files

flashing.mddocs/

Arduino Flashing

Core functionality for uploading compiled sketch files (.hex files) to Arduino boards with automatic board detection, protocol selection, and error handling.

Capabilities

AvrgirlArduino Constructor

Creates a new Arduino flashing instance with the specified configuration.

/**
 * Creates a new Arduino flashing instance
 * @param {object} options - Configuration options
 */
function AvrgirlArduino(options);

interface AvrgirlArduinoOptions {
  board: string | BoardConfig;      // Board type name or custom board configuration
  port?: string;                    // Serial port path (auto-detected if omitted)
  debug?: boolean | function;       // Debug logging: true, false, or custom function
  megaDebug?: boolean;             // Enhanced protocol-level debugging for detailed analysis
  manualReset?: boolean;           // Manual reset configuration for AVR109 boards
  disableVerify?: boolean;         // Skip verification after flash for AVR109 boards
}

Usage Examples:

const Avrgirl = require('avrgirl-arduino');

// Basic usage with board type
const avrgirl = new Avrgirl({
  board: 'uno'
});

// With custom port and debugging
const avrgirlCustom = new Avrgirl({
  board: 'leonardo',
  port: '/dev/ttyACM0',
  debug: true
});

// With custom debug function
const avrgirlWithLogger = new Avrgirl({
  board: 'mega',
  debug: function(message) {
    console.log('[AVRGIRL]', new Date().toISOString(), message);
  }
});

// With enhanced protocol debugging
const avrgirlMegaDebug = new Avrgirl({
  board: 'leonardo',
  megaDebug: true  // Enhanced protocol-level debugging
});

// Using custom board configuration
const customBoard = {
  name: 'my-custom-board',
  baud: 115200,
  signature: Buffer.from([0x1e, 0x95, 0x0f]),
  pageSize: 128,
  numPages: 256,
  timeout: 400,
  productId: ['0x0043'],
  protocol: 'stk500v1'
};

const avrgirlCustomBoard = new Avrgirl({
  board: customBoard
});

Flash Method

Uploads a hex file to the connected Arduino board with automatic protocol handling.

/**
 * Flash a hex file to the Arduino board
 * @param {string|Buffer} file - Path to hex file or Buffer containing hex data
 * @param {function} callback - Completion callback function(error)
 */
flash(file: string | Buffer, callback: (error?: Error) => void): void;

Usage Examples:

const Avrgirl = require('avrgirl-arduino');
const fs = require('fs');

const avrgirl = new Avrgirl({ board: 'uno' });

// Flash from file path
avrgirl.flash('/path/to/sketch.hex', function(error) {
  if (error) {
    console.error('Flash failed:', error.message);
  } else {
    console.log('Flash completed successfully!');
  }
});

// Flash from Buffer (useful for in-memory hex data)
const hexData = fs.readFileSync('/path/to/sketch.hex');
avrgirl.flash(hexData, function(error) {
  if (error) {
    console.error('Flash failed:', error.message);
  } else {
    console.log('Flash completed successfully!');
  }
});

// Flash from Buffer with hex string data
const hexBuffer = Buffer.from(':100000000C9434000C9446000C9446000C944600A2\n:00000001FF', 'ascii');
avrgirl.flash(hexBuffer, function(error) {
  if (error) {
    console.error('Flash from hex buffer failed:', error.message);
  } else {
    console.log('Hex buffer flashed successfully!');
  }
});

// Flash with error handling
avrgirl.flash('sketch.hex', function(error) {
  if (error) {
    if (error.message.includes('not a supported board type')) {
      console.error('Unsupported board type specified');
    } else if (error.message.includes('no Arduino')) {
      console.error('Arduino board not found. Check connection.');
    } else if (error.message.includes('port')) {
      console.error('Port communication error:', error.message);
    } else {
      console.error('Unknown error:', error.message);
    }
    return;
  }
  console.log('Successfully flashed Arduino!');
});

Board Validation

Internal method that validates board configuration before attempting to flash.

/**
 * Validates the board properties and configuration
 * @param {function} callback - Validation callback function(error)
 */
_validateBoard(callback: (error?: Error) => void): void;

This method checks:

  • Board type is recognized and supported
  • Protocol is available for the board type
  • Required port is specified for boards that need it (e.g., pro-mini)
  • Board configuration is valid

Hex Parsing Tools

The AvrgirlArduino instance provides access to hex file parsing utilities through the tools property.

/**
 * Hex file parsing and utility functions
 */
interface Tools {
  _parseHex(file: string | Buffer): Buffer | Error;  // Parse Intel HEX format to binary
  _hexStringToByte(str: string): Buffer;             // Convert hex string to Buffer
}

Usage Examples:

const avrgirl = new Avrgirl({ board: 'uno' });

// Parse hex file to binary data
const hexPath = 'sketch.hex';
const binaryData = avrgirl.tools._parseHex(hexPath);
if (binaryData instanceof Error) {
  console.error('Hex parsing failed:', binaryData.message);
} else {
  console.log('Parsed hex file, binary size:', binaryData.length);
}

// Convert hex string to Buffer
const hexString = '1E950F'; // Example device signature
const buffer = avrgirl.tools._hexStringToByte(hexString);
console.log('Hex to buffer:', buffer); // <Buffer 1e 95 0f>

Event Handling

The AvrgirlArduino class extends EventEmitter, allowing you to listen for events during the flashing process.

interface AvrgirlArduino extends EventEmitter {
  // EventEmitter methods available
  on(event: string, listener: Function): this;
  emit(event: string, ...args: any[]): boolean;
  removeListener(event: string, listener: Function): this;
  removeAllListeners(event?: string): this;
}

Usage Examples:

const avrgirl = new Avrgirl({ board: 'uno', debug: true });

// Listen for internal events (implementation-dependent)
avrgirl.on('error', (error) => {
  console.error('Internal error:', error);
});

// Flash with event handling
avrgirl.flash('sketch.hex', (error) => {
  // Main callback
});

Flash Process Flow

The flashing process follows these steps:

  1. Board Validation: Verify board configuration and protocol availability
  2. Port Detection: Auto-detect Arduino port if not specified, or validate specified port
  3. Connection Setup: Initialize serial port communication with board-specific settings
  4. Hex File Processing: Parse and validate the hex file format
  5. Protocol Selection: Choose appropriate protocol (STK500v1, STK500v2, or AVR109)
  6. Board Reset: Reset the Arduino board to enter bootloader mode
  7. Firmware Upload: Upload hex data using the selected protocol
  8. Verification: Verify successful upload (unless disabled)
  9. Cleanup: Close serial connection and complete the process

Error Types

Common errors that may occur during flashing:

// Board configuration errors
"\"unknown-board\" is not a supported board type."
"not a supported programming protocol: unknown-protocol"
"using a pro-mini, please specify the port in your options."

// Connection errors
"no Arduino 'uno' found."
"an unexpected error happened when connecting to board: [details]"

// File errors
"ENOENT: no such file or directory, open 'missing-file.hex'"
"Invalid hex file format"

// Protocol errors
"Communication timeout"
"Upload failed"
"Verification failed"

Hex File Support

The library supports Intel HEX format files with the following characteristics:

  • File Extensions: .hex files (standard Intel HEX format)
  • Input Types: String file paths or Buffer objects containing hex data
  • Parsing: Automatic hex file parsing and validation
  • Memory Layout: Supports standard Arduino memory layout and addressing
  • Size Limits: Respects board-specific flash memory constraints

Protocol Support

STK500v1 Protocol

  • Boards: Arduino Uno, Mega, Nano, Duemilanove, Pro Mini, etc.
  • Features: Page-based programming, signature verification, auto-reset via DTR
  • Baud Rates: Typically 115200 or 57600 bps

STK500v2 Protocol

  • Boards: Specialized boards like Pinoccio Scout
  • Features: Enhanced protocol with improved error handling
  • Baud Rates: Board-specific configuration

AVR109 Protocol

  • Boards: Arduino Leonardo, Micro, Yun, Esplora, etc.
  • Features: Native USB communication, different reset mechanism
  • Baud Rates: Typically 57600 bps

Install with Tessl CLI

npx tessl i tessl/npm-avrgirl-arduino

docs

cli.md

flashing.md

index.md

port-management.md

tile.json