### Initialize and Start Logic Blocks (Without Erratum) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md Illustrates the initialization and starting sequence for logic blocks when the erratum is not a concern. This method allows for more flexibility, as logic blocks can be initialized and the CCL started at different points depending on the application's needs. ```c++ // first time setup, without erratum: Logic0.init(); Logic1.init(); Logic::start(); //Can be aanywhere depending on your needs. //Reconfigure Logic2: Logic2.init(); // Logic0 and Logic1 do run while applying changes to Logic2. ``` -------------------------------- ### Initialize and Start Logic Blocks (With Erratum) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md Demonstrates the correct procedure for initializing and starting logic blocks when a specific erratum is present. This involves stopping the CCL, initializing the target logic block, and then restarting the CCL. This ensures that configuration changes are applied correctly under the erratum's conditions. ```c++ // first time setup, with erratum: Logic0.init(); Logic1.init(); Logic::start(); //must be after all inits //Reconfigure Logic2: Logic::stop(); // Logic0 and Logic1 do not run while applying changes to Logic2. Logic2.init(); Logic::start(); ``` -------------------------------- ### DxCore Version Information and Usage Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Defines.md This snippet shows the preprocessor definitions for DxCore versioning and a C++ example demonstrating how to print this information to the serial monitor. It includes the full version string, major, minor, patch numbers, a released status flag, and a numerical version. The example highlights potential output variations based on IDE capabilities and build types. ```c++ #define DXCORE #define DXCORE_MAJOR #define DXCORE_MINOR #define DXCORE_PATCH #define DXCORE_RELEASED #define DXCORE_NUM // Example Usage: Serial.println(DXCORE); Serial.print(DXCORE_MAJOR); Serial.print(' '); // using ' ' instead of " " saves a tiny amount of flash! Serial.print(DXCORE_MINOR); Serial.print(' '); Serial.print(DXCORE_PATCH); Serial.print(' '); Serial.println(DXCORE_RELEASED); Serial.println(DXCORE_NUM, HEX); ``` -------------------------------- ### Start CCL Hardware Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md A static method to start the Connected-Configurable Logic (CCL) hardware. This should be called after all desired logic blocks have been initialized using the init() method. ```c++ Logic::start(); // Start CCL hardware ``` -------------------------------- ### Configure Pin with Bitwise OR and Comma Separated Arguments (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Demonstrates the usage of the pinConfigure() function to set various pin properties. The first example uses bitwise OR for combining constants, while the subsequent examples show the preferred comma-separated syntax for better readability. This function allows fine-grained control over pin direction, output state, pull-up resistors, inversion, and interrupt configurations. ```c++ pinConfigure(PIN_PA4,PIN_DIR_INPUT,PIN_PULLUP_ON,PIN_OUT_LOW); // Set PIN_PA4 to input, with pullup enabled and output value of LOW without changing whether the pin is inverted or triggers an interrupt. pinConfigure(PIN_PA4, PIN_DIR_INPUT, PIN_OUT_LOW, PIN_PULLUP_OFF, PIN_INVERT_OFF, PIN_ISC_ENABLE); // Set PA4 input, with output register set low, pullup turned off, invert turned off, and digital input enabled. Ie, the reset condition. // Equivalent: pinConfigure(PIN_PA4,(PIN_DIR_INPUT | PIN_OUT_LOW | PIN_PULLUP_OFF | PIN_INVERT_OFF | PIN_ISC_ENABLE)); ``` -------------------------------- ### Patching platform.txt for Arduino IDE Source: https://github.com/spencekonde/megatinycore/blob/master/Installation.md This code snippet demonstrates how to manually patch the platform.txt file to ensure compatibility with specific Arduino IDE versions when using megaTinyCore. This is a workaround for older IDE versions and manual installations. ```diff -version={versionnum.major}.{versionnum.minor}.{versionnum.patch}{versionnum.postfix} +version=2.6.0 ``` -------------------------------- ### Installing pyupdi using pip Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/PlatformIO.md This command installs the pyupdi tool, a Python-based programmer for tinyAVR and megaAVR devices, directly into the PlatformIO virtual environment. This allows it to be used as a custom uploader. ```bash pip install https://github.com/mraardvark/pyupdi/archive/master.zip ``` -------------------------------- ### Standard digitalWrite Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Illustrates the standard Arduino digitalWrite function, which is convenient but can be significantly slower than direct port manipulation due to function call overhead and table lookups. ```c++ digitalWrite(PIN_PA7, HIGH); ``` -------------------------------- ### Pin Configuration with Constraints Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Shows examples of the pinConfigure function with varying levels of argument constraints. The second argument controls direction and output value, pullup configuration, or can be unrestricted. ```c++ pinConfigure(pin, 0x00-0x0F); // Setting only direction and output value pinConfigure(pin, ...); // Configuring pullups pinConfigure(pin, ...); // Without restrictions ``` -------------------------------- ### SDA Hold and Setup Time Constants for C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Wire/README.md Defines for configuring SDA hold times (off, 50, 300, 500 ns) and setup times (4 or 8 cycles). These are used with the specialConfig() method. ```C++ #define WIRE_SDA_HOLD_OFF 0 #define WIRE_SDA_HOLD_50 1 #define WIRE_SDA_HOLD_300 2 #define WIRE_SDA_HOLD_500 3 #define WIRE_SDA_SETUP_4 0 #define WIRE_SDA_SETUP_8 1 #define WIRE_I2C_LEVELS 0 #define WIRE_SMBUS_LEVELS 1 ``` -------------------------------- ### Start Analog Comparator Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Comparator/README.md Starts the analog comparator. This function enables the comparator's operation after initialization. ```c++ Comparator.start(); // Start comparator ``` -------------------------------- ### Serial.begin() with Basic USART Options Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Serial.md Illustrates the usage of `Serial.begin()` to initialize serial communication with specified baud rate and basic USART options. This example shows how to combine data size, parity, and stop bit settings. ```cpp Serial1.begin(115200,(SERIAL_8N1 | SERIAL_OPENDRAIN | SERIAL_RS485 )) ``` -------------------------------- ### Initialize TinyNeoPixel with Empty Constructor and Dynamic Configuration Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md Demonstrates initializing the tinyNeoPixel library with an empty constructor, followed by dynamically setting the pin, LED count, and type at runtime. This approach is useful when these parameters are not known at compile time. The setup function configures the LEDs and displays the first LED in red. ```c++ #include volatile uint16_t numleds=100; // Declaring these volatile prevents the constants from being optimized. volatile neoPixelType led_type; // This is the easiest way to simulate not knowing what you're driving until runtime. volatile uint8_t neopin = PIN_PA6; // Maybe you read from EEPROM, maybe you have jumpers or switches, etc. tinyNeoPixel leds = tinyNeoPixel(); // empty constructor... void setup() { leds.updateLength(numleds); // Set the length leds.updateType(led_type); // Set the type leds.setPin(neopin); // set the pin leds.begin(); // now we've setup everything, and must call begin(). leds.setPixelColor(0, 255, 0, 0); // first LED full RED leds.show(); // LED turns on. } void loop() {/* empty loop */} ``` -------------------------------- ### DxCore Initialization and Callback Functions (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Functions.md A collection of functions intended for user overrides or core initialization within the DxCore framework. These include pre-main setup, variant initialization, timer setup, and main execution entry points. ```c++ void init_reset_flags() void onPreMain() void onBeforeInit() void init() // Part of ArduinoAPI void initVariant() //part of ArduinoAPI - reserved for core and rare libraries void init_TCA0() void init_TCA1() void init_TCBs() void init_TCD0() void init_millis() uint8_t onAfterInit() void onClockFailure() void onClockTimeout() int main(); // the Big One! ``` -------------------------------- ### Digital Read Fast Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Demonstrates using `digitalReadFast` to check the state of a digital pin. This function is significantly faster than the standard `digitalRead` and is suitable for use in conditional statements or simple polling loops. It provides near real-time pin state monitoring. ```c++ if (digitalReadFast(PIN_PA3)) { Serial.println("PA3 is high"); } while(digitalReadFast(PIN_PA3)) { ; //busywait for pin to go low } ``` -------------------------------- ### Conditional Compilation for Undefined Defines in C/C++ Source: https://github.com/spencekonde/megatinycore/blob/master/ChangeLog.md This example demonstrates how to safely handle potentially undefined preprocessor macros. It checks for the existence of specific defines and provides error messages if they are not set as expected, preventing unexpected behavior. ```c #if MEGATINYCORE // Core is defined #else #error "MEGATINYCORE define not found. This core is not in use." #endif #if X == A // Handle case A #elif X == B // Handle case B #elif X == C // Handle case C #else #error "X undefined or invalid, X must be #defined as A, B or C" #endif ``` -------------------------------- ### Basic Inline Assembly Structure in C Source: https://github.com/spencekonde/megatinycore/blob/master/ContributionGuidelines.md This C code snippet provides an example of inline assembly usage within a function. It includes comments explaining the purpose of the assembly and notes on when its use is justified. The example highlights the importance of checking assembly listings for efficiency before employing inline assembly for non-critical tasks. ```c uint8_t myfunc(uint8_t a, uint8_t b) { /* Returns b + a + (a-1)... or 255 if that would exceed 255 * Note that this is not a justified use on inline asm unless the code is time-critical, AND you compiled C code that does the same thing checked the assembly listing * and found the generated asm to be pathologically inefficient. */ ``` -------------------------------- ### Formatting Constant Tables in C Source: https://github.com/spencekonde/megatinycore/blob/master/ContributionGuidelines.md This example illustrates proper formatting for constant tables in C, using odd indentation to enhance clarity. It shows a `const uint8_t` array initialization with comments explaining the purpose of specific entries and how they relate to bitmasks and bit positions. This approach aids in understanding complex table structures. ```c const uint8_t constvalues[33] = { 255, 0, 1, 255, 2, 255, 255, 255, 3, // First 4 bitmasks can be converted to bitpositions with a 9 entry table 255, 255, 255, 255, 255, 255, 255, 4, // 17 entries gets us the 5th 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 5, // and 33 entries gets us the 6th. } ``` -------------------------------- ### Run Code After Initialization (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Callbacks.md The onAfterInit function is called just before the setup() function, following all other internal initializations. Returning a non-zero value from this function prevents interrupts from being enabled. This is particularly useful for debugging scenarios where an interrupt might be causing issues immediately upon enablement, such as an unidentified interrupt firing incorrectly or an infinite loop within an interrupt handler. ```cpp uint8_t onAfterInit() __attribute__((weak)) { return 0; } ``` -------------------------------- ### TCD0: Enabling Timer Ready State Check (C) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/PWMandTimers.md Shows how to check the ENABLERDY bit in the TCD0.STATUS register to ensure the timer is ready for configuration changes. This is crucial due to the synchronization process involved when stopping and starting the timer. ```c // Wait until the timer is ready for configuration changes while (!(TCD0.STATUS & TCD0_STATUS_ENABLERDY_bm)) { // Do nothing, wait for the flag } ``` -------------------------------- ### Detecting and Handling WDT Reset in Setup() (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Reset.md Shows how to detect if a Watchdog Timer (WDT) reset just occurred by checking the reset flags stored in GPIOR0. If a WDT reset is detected, it calls a function to notify the user. This allows for specific actions upon waking from a WDT-induced reset. ```c++ void NotifyUser() { Serial.println("The system reset via WDT after hang..."); } void setup() { wdt_enable(); //we're super paranoid, so we turn on WDT immediately. Serial.begin(MYBAUDRATE); // we use this down in NotifyUser(). uint8_t resetflags = GPIOR0; // Optiboot or the core stashes the reset flags here before clearing them to honor entry conditions // GPIOR0 = 0; // no need to clear because this is reset at startup to 0 either way, and then gets the reset flags stashed in it - unless you need it later.. if (resetflags == RSTCTRL_WDRF_bm) { //means it was a WDT reset. Notice the use of == - we only want to detect it when WDRF is the only reset flag; On Optiboot configurations, you will see WDRF along with another bit set if optiboot considered that to be an entry condition NotifyUser(); } } ``` -------------------------------- ### Start Event Generator Channel (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Event/README.md Initiates an event generator channel by configuring the EVSYS.CHANNELn register with the generator previously set using the set_generator() method. ```c++ Event0.start(); // Starts the Event0 generator channel ``` -------------------------------- ### Initialize and Configure Analog Comparator - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Comparator/README.md Initializes and configures an Analog Comparator (AC) peripheral. It demonstrates grabbing the AC struct, setting control registers for low power and standby modes, and enabling the comparator. This example is primarily for tinyAVR and megaAVR, with notes on Dx variants. ```c++ /* This only makes sense if you assume that this is executing in a context where * MyComparator was passed as a reference, so this code has no idea whether * it's Comparator0 or Comparator2 or Comparator6 on some future part with * way too many comparators */ MyComparator.init(); // initialize the comparator - let's assume it was configured a few lines before this example begins. AC_t& AC_struct = MyComparator.getPeripheral(); // Grab the ACn struct - AC0, AC1, AC2, etc. /* For tinyAVR and megaAVR the's LPMODE and or not-LPMODE*/ AC_struct.CTRLA |= AC_LPMODE_bm | AC_RUNSTBY_bm ; // Reduce power consumption at expense of response time and leave on in standby /* for Dx there are 3 power profiles, this has slowest response time and lowerst power: AC_struct.CTRLA |= AC_PROFILE2_gc | AC_RUNSTBY_bm; // Reduce power consumption at expense of response time and leave on in standby * and Ex adds a third: AC_struct.CTRLA |= AC_PROFILE3_gc | AC_RUNSTBY_bm; // Reduce power consumption at expense of response time and leave on in standby * DA's initial headers listed profile 3. One imagines they found it wasn't up to internal standards, and airbrushed it out of the datasheet * like they did with the 4x clock multiplier. That option works (and the PLL can be run ~2.5x overclock at room temp o_o) so I'm cautiously * optimistic that this would work on a Dx except under adverse conditions/* AC_struct.CTRLA |= 0x18 | AC_RUNSTBY_bm; // CTRLA is 0bSO_PPHHE where S = RUNSTBY, O = OUTEN, P = POWER, H = Hysteresis, and E = Enable. POWER = 3 is marked as reserved on the Dx, but was PROFILE3 in preliminary headers. */ MyComparator.start(); // Enable the comparator enterStandbySleep(); // enter standby sleep mode until the comparator interrupt fires, waking it up. ``` -------------------------------- ### Get Board Details - Arduino CLI Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Arduino-cli.md Retrieves detailed information about a specific board, including possible fuses and chip selection options. This is useful for identifying available programmers for your selected FQBN. ```bash arduino-cli board details -b ``` -------------------------------- ### TCA1 Errata Check and Handling (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Defines.md This C++ `setup()` function demonstrates how to check for a specific silicon errata related to TCA1's port multiplexing. If the errata is detected, it prints an error message and enters an infinite loop; otherwise, it proceeds with normal pin mapping operations. ```c++ void setup() { Serial.begin(115200); if (checkErrata(ERRATA_TCA1_PORTMUX)) { Serial.println("ERROR: This chip cannot direct output from TCA1 to PG0:5 or PE4:7 due to silicon errata"); while (1) { runInCirclesScreamAndShout(); } } else { doSomethingWithTCA1PinMapping(); partyDown(); // defined elsewhere. } } ``` -------------------------------- ### Direct Port Manipulation Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Demonstrates direct manipulation of a port's output register, often used for performance-critical operations instead of standard digitalWrite. This method bypasses the overhead of Arduino's digitalWrite function. ```c++ VPORTA.OUT |= 0x80; ``` -------------------------------- ### Optimized Pin Mode Setting for ATtiny Microcontrollers (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md This example illustrates more efficient methods for setting pin output modes on ATtiny microcontrollers, aiming to reduce code size and improve performance compared to the standard `pinMode()`. It includes direct port manipulation and the `pinModeFast()` function, which are beneficial when pin assignments are known at compile time. ```c++ /* More efficient, but annoying method. Does not depend on any API calls */ // VPORTA.DIR |= (1 << 6); /* Similarly efficient - but much more readable - mTC and DxC only at this point (though digitalWriteFast() is more common)*/ // pinModeFast(PIN_PA6, OUTPUT); ``` -------------------------------- ### NeoPixel LED Control with tinyNeoPixel Library Source: https://context7.com/spencekonde/megatinycore/llms.txt Provides control for WS2812/SK6812 RGB LEDs optimized for modern AVR microcontrollers using the tinyNeoPixel library. The example demonstrates initializing the LED strip and creating a rainbow effect by cycling through colors. ```cpp #include #define PIXEL_PIN PIN_PA1 #define PIXEL_COUNT 16 // Create NeoPixel object tinyNeoPixel strip = tinyNeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB); void setup() { pinMode(PIXEL_PIN, OUTPUT); strip.show(); // Initialize all pixels off } void loop() { // Rainbow effect for (uint16_t j = 0; j < 256; j++) { for (uint16_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, Wheel((i + j) & 255)); } strip.show(); delay(20); } } // Generate rainbow colors uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if (WheelPos < 85) { return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if (WheelPos < 170) { WheelPos -= 85; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } ``` -------------------------------- ### Get Any Object from EEPROM Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/EEPROM/README.md The EEPROM.get(address, object) function retrieves any object from the EEPROM starting at the specified address. It requires an integer address and a reference to the object to be populated. The function returns a reference to the object for convenience. ```c++ EEPROM.get(address, object); ``` -------------------------------- ### Initialization and Configuration Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md Methods for initializing the library, setting up pin configurations, and specifying LED strip properties. ```APIDOC ## Initialization and Configuration ### `begin()` **Description:** Initializes the NeoPixel library, sets the data pin to OUTPUT, and ensures it is LOW. This function must be called after all configuration is complete to enable data output. **Usage:** - **`tinyNeoPixel`:** Call after configuration. - **`tinyNeoPixel_static`:** This method does not exist. Initialization and pin configuration must be handled manually in the constructor and the user is responsible for setting the pin as OUTPUT and LOW. ### `setPin(uint8_t p)` **Description:** Sets the data pin for LED output. For `tinyNeoPixel_Static`, the user must ensure the pin is configured as an OUTPUT. ### `updateLength(uint16_t n)` **Description:** Sets the number of LEDs in the strip. **Note:** Not available on `tinyNeoPixel_Static`. ### `updateType(neoPixelType_t)` **Description:** Configures the color order and the number of color components per pixel (e.g., RGB, RGBW). **Note:** Not available on `tinyNeoPixel_Static`. ### `updateLatch(uint16_t time)` **Description:** Sets the minimum time in microseconds required between calls to `show()` for colors to latch correctly on certain LEDs. This feature relies on `micros()` and is not available if `millis()` is disabled. Available on both `tinyNeoPixel` and `tinyNeoPixel_static`. ``` -------------------------------- ### Flash Library Generic Data Storage (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Optiboot_flasher/README.md Provides methods for storing and retrieving arbitrary data types or objects to/from flash memory. `put(address, data)` writes the provided data starting at the specified flash address, and `get(address, variable)` reads data from the specified address and stores it into the provided variable. ```c++ float f = 123.456f; char text[13] = "Hello World!"; flash.put(0x00, f); // Store float value to flash, starting from address 0 flash.put(sizeof(float), text); // Store text after the float variable float f_read; char text_read[13]; flash.get(0x00, f_read); // Fetch float variable from flash address 0 and store it to variable f flash.get(sizeof(float), text_read); // Fetch text after the float variable ``` -------------------------------- ### Initialize tinyNeoPixel with Dynamic Memory Allocation (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md This snippet demonstrates the basic constructor for `tinyNeoPixel`, which uses dynamic memory allocation. It initializes a specified number of LEDs on a given pin with a color format. The `begin()` method must be called successfully for the LEDs to be enabled. Insufficient memory can cause `begin()` to fail without explicit error reporting. ```c++ #include #define NUMLEDS 100 tinyNeoPixel leds = tinyNeoPixel(NUMLEDS, PIN_PA6, NEO_GRB); void setup() { leds.begin(); leds.setPixelColor(0,255,0,0); // first LED full RED leds.show(); // LED turns on. } void loop() {/* empty loop */} ``` -------------------------------- ### Initialize tinyNeoPixel with Static Memory Allocation (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md This snippet shows the constructor for `tinyNeoPixel_static`, which uses a pre-allocated static buffer for LED data. This approach is more memory-efficient, especially on microcontrollers with limited RAM. It requires manual pin mode configuration and does not use a `begin()` method. The size of the pixel buffer must exactly match the number of LEDs and channels. ```c++ #include #define NUMLEDS 100 byte pixels[NUMLEDS * 3]; tinyNeoPixel leds = tinyNeoPixel(NUMLEDS, PIN_PA6, NEO_GRB, pixels); void setup() { /* less efficient, more obvious method */ pinMode(PIN_PA6, OUTPUT); //pinModeFast() now exists and would shave a few more bytes off if this and any other instances of pinMode were converted to pinModeFast. // see below for ways to make this even smaller. // No begin - any class member at any address, leds.setPixelColor(0, 255, 0, 0); // first LED full RED leds.show(); // LED turns on. } void loop() {/* empty loop */} ``` -------------------------------- ### Fast Digital Input with digitalWriteFast and VPORT Registers Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_DirectPortManipulation.md Illustrates how to perform high-speed digital input checks using both the `digitalReadFast` function and direct VPORT register polling. The code examples show how these approaches are often compiled into the same efficient machine code for checking a pin's state. This method is suitable for time-critical applications. ```c if (digitalReadFast(PIN_PA4) == HIGH) { /* rendered as sbis 2, 4; rjmp afterfunctionbody; typically. Overhead is just 2 clocks plus the function body itself if it runs, 3 otherwise, and 4 bytes of flash. */ //... } ``` ```c if (VPORTA.IN & (1 << 4)) { /* Same as above */ //... } ``` -------------------------------- ### C++ Loop Optimization Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/NotesOnPeripherals.md Demonstrates how a C++ compiler can optimize a `while(1)` loop. The original loop toggles a port pin, but aggressive optimization, including loop unrolling and constant condition elimination, can transform it into a simple, potentially unintended, behavior. This highlights the risks of relying solely on standard C++ for precise timing. ```c++ while(1){ if (!test2++) PORTA.OUTTGL=0x40; } ``` ```c++ if (!0) PORTA.OUTTGL=0x40; if (!1) PORTA.OUTTGL=0x40; if (!2) PORTA.OUTTGL=0x40; ... if (!65534) PORTA.OUTTGL=0x40; if (!65535) PORTA.OUTTGL=0x40; ``` ```c++ while(1){ PORTA.OUTTGL=0x40; } ``` -------------------------------- ### Get Register Pointers for Microcontroller Pins (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Provides functions to obtain pointers to specific control registers for microcontroller pins. These pointers allow direct manipulation of pin configurations, input/output states, and modes. The functions include getting pointers to PINnCTRL, PORT structs, and individual PORT registers (OUT, IN, DIR). ```c++ volatile uint8_t* getPINnCTRLregister(uint8_t port, uint8_t bit_pos); PORT_t* digitalPinToPortStruct(uint8_t pin); PORT_t* portToPortStruct(uint8_t port); volatile uint8_t* portOutputRegister(uint8_t port) volatile uint8_t* portInputRegister(uint8_t port) volatile uint8_t* portModeRegister(uint8_t port) ``` -------------------------------- ### Pixel Manipulation Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/tinyNeoPixel.md Functions for setting, getting, and manipulating the colors of individual pixels or ranges of pixels. ```APIDOC ## Pixel Manipulation ### `setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b)` **Description:** Sets the color of pixel `n` to the specified RGB values. ### `setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w)` **Description:** Sets the color of pixel `n` to the specified RGBW values. ### `setPixelColor(uint16_t n, uint32_t c)` **Description:** Sets the color of pixel `n` using a 32-bit packed color value (as returned by `getColor()`). ### `getPixelColor(uint16_t n)` **Description:** Returns the current color of pixel `n` as a 32-bit packed color value. ### `fill(uint32_t c, uint16_t first, uint16_t count)` **Description:** Sets a range of pixels to a specified color. `count` pixels, starting from `first`, are set to color `c`. If `first` is omitted, the first LED is assumed. If `count` is omitted or 0, all LEDs from `first` to the end are set. If `c` is omitted, it defaults to 0 (off), making `fill()` with no arguments equivalent to `clear()`. ### `clear()` **Description:** Clears the pixel buffer by setting all LED colors to 0 (off). ``` -------------------------------- ### Manual Temperature and Voltage Reading Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/megaTinyCore/README.md Demonstrates the manual process of reading the internal temperature and supply voltage of the microcontroller. While these manual implementations are shown, it is recommended to use the provided automatic functions for these tasks. ```c++ // Demonstrates how you would manually read the temperature and supply voltage. Remember that we provide automatic functions to do this; those should generally be used in preference to xeroxing the wheel and implementing them yourself, now that we have these functions. // These will be ported to DxCore in the next release ``` -------------------------------- ### Get Channel Number - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Event/README.md Retrieves the current channel number of an event object. This is useful when an event object is passed by reference to a function. ```c++ uint8_t what_channel(Event& event_chan) { event_chan.get_channel_number(); } ``` -------------------------------- ### Run Code Before Main Initialization (C) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Callbacks.md The onPreMain function serves as a callback executed before the main class constructors are invoked. It runs after init_reset_flags, meaning it will not execute if a 'dirty' reset occurs and reset flags are cleared as expected. This function is primarily used for setting up conditions or performing actions prior to the main program logic. ```c void onPreMain() __attribute__((weak)) { } ``` -------------------------------- ### Initialize I2C Master Mode using begin() Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Wire/README.md The `begin()` function initiates the I2C master mode. This function must be called before any I2C master communication can occur. Unlike the canonical Wire library, this version does not automatically enable pull-up resistors, requiring external pull-ups for reliable operation. ```c++ void begin(); ``` -------------------------------- ### Get EEPROM Size Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/EEPROM/README.md The EEPROM.length() function returns the total number of addressable cells in the EEPROM as an unsigned integer. ```c++ unsigned int size = EEPROM.length(); ``` -------------------------------- ### Conditional CCL Initialization Based on Hardware Errata (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md This example demonstrates a more advanced approach to initializing CCL logic blocks, taking into account potential hardware errata. It uses preprocessor directives to conditionally apply different initialization sequences, optimizing for parts with or without the erratum, or checking at runtime if the erratum is present. This aims to minimize disruption to other logic blocks like Logic0. ```c++ // Imagine there's some code above this that configured and enabled Logic0. /* So the past is approximately: * ConfigureLogic0(); * ConfigureLogic1(); * Logic0.init(); * Logic1.init(); * Logic::start(); * And now you want to enable Logic3 and change Logic1 settings, if possible without disturbing Logic0. */ void someFunction() { Logic1.truth=0x55; // new truth table Logic1.input2=logic::in::tca0; // and different input 2 Logic3.enabled=true; // enable another LUT Logic3.input0=logic::in::link; // Use link from LUT0 Logic3.input1=logic::in::ac; // and the analog comparator Logic3.input2=logic::in::pin; // and the LUT3 IN2 pin Logic3.truth=0x79; // truth table for LUT3 Logic3.attachInterrupt(RISING,interruptFunction); // Interrupt now attached - but - Logic3 not enabled, and logic1 is using old settings applyCCLChanges(); // you'll probably want to call this more than once - maybe with an argumnent that specifies which blocks to reinit, // depending on your application, other logic might be able to be aggregated there to save flash. void applyCCLChanges() { // Adjust to suit the logic blocks you need // As noted at the start we wanted to avoid disturbing the Logic0 channel if possible, so we want to avoid the stop-start. #if defined(ERRATA_CCL_PROTECTION) && ERRATA_CCL_PROTECTION == 1 /* Some parts have not received a die rev and hence all extant specimens exhibit this erratum, other parts came out after the bug was fixed and never had the issue. */ Logic::stop(); // have to turn off Logic0 too, even though I might not want to Logic1.init(); // apply changes to logic block 1 Logic3.init(); // apply settings to logic block 3 for the first time Logic::start(); // re-enable #elif defined(ERRATA_CCL_PROTECTION) && ERRATA_CCL_PROTECTION == 0 /* No version of the part has ever had this erratum, so there is no chance of encountering it */ Logic1.init(); // apply changes to logic block 1 Logic3.init(); // apply settings to logic block 3 for the first time #else /* Awesome! We got a die rev finally. Wait, crap, now I have to support both? */ if checkErrata(ERRATA_CCL_PROTECTION) { Logic::stop(); // have to turn off Logic0 too, even though I might not want to Logic1.init(); // apply changes to logic block 1 Logic3.init(); // apply settings to logic block 3 for the first time Logic::start(); // re-enable } else { Logic1.init(); // apply changes to logic block 1 Logic3.init(); } #endif } ``` -------------------------------- ### Get Event Channel Generator - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Event/README.md A method to retrieve the currently used generator for a specific event channel. The returned value can be compared against predefined generator constants. ```c++ uint8_t generator_used = Event0.get_generator(); if (generator_used == gen::ccl0_out) { Serial.println("We're using gen::ccl0_out as generator"); } ``` -------------------------------- ### TCD0 Timer Details Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Timers.md Provides information regarding the TCD0 timer. Specific code examples for TCD0 configuration are not provided in the source text, but it is mentioned as a timer that can be used for PWM. ```c // TCD0 timer functionality can be configured here. // Refer to specific microcontroller datasheets for TCD0 details. // Example: TCD0.CTRLA = 0x01; // Example control register setting ``` -------------------------------- ### Create Output Files (.eep, .hex, .bin) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/platform.txt This set of recipes outlines the commands to convert the compiled ELF executable into various output formats: EEPROM image, Intel HEX, and raw binary. It uses the compiler's objcopy or elf2hex utility with specific flags and input/output file paths. ```makefile recipe.objcopy.eep.pattern="{compiler.path}{compiler.objcopy.cmd}" {compiler.objcopy.eep.flags} {compiler.objcopy.eep.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.eep" recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex" recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.bin.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin" ``` -------------------------------- ### TCD0 Synchronization Status Check Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Timers.md Provides an example of how to check the ENABLERDY bit in the TCD0.STATUS register to confirm that synchronization operations have completed, which is necessary before making certain register modifications. ```c // Wait for timer to be ready for configuration changes while (!(TCD0.STATUS & TCD0_ENABLERDY_bm)); ``` -------------------------------- ### USERSIG.begin() and USERSIG.end() - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/USERSIG/README.md Shows how USERSIG.begin() and USERSIG.end() can be used to obtain USPtr objects for iterating over USERSIG cells, suitable for range-based for loops or custom iteration. ```C++ // Example usage with begin() and end() for iteration for (USPtr it = USERSIG.begin(); it != USERSIG.end(); ++it) { // Process the USERSIG cell pointed to by it } ``` -------------------------------- ### Get Current Analog Reference Voltage Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Analog.md This function retrieves the currently selected analog reference voltage. It returns a numerical value representing the reference, which can be compared against predefined constants. ```cpp int currentRef = getAnalogReference(); if (currentRef == INTERNAL2V500) { // Use 2.500V internal reference } ``` -------------------------------- ### Get Analog Comparator Peripheral Reference Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Comparator/README.md Returns a reference to the underlying analog comparator struct, allowing direct manipulation of peripheral registers. This is typically used for advanced configurations or library development. ```c++ // Example: Accessing peripheral registers directly // AC0.CTRLA = 0x01; // This is illustrative and depends on the specific peripheral struct definition. ``` -------------------------------- ### Configure Logic Block Inputs with Pull-up Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md This C++ code snippet demonstrates how to configure the input pins for a logic block. It shows how to connect outputs from other blocks or GPIOs to the logic block's inputs, including enabling a pull-up resistor on one input. The default state for unspecified inputs is 'unused'. ```cpp Logic0.input0 = logic::in::link; // Connect output from block 1 to input 0 of block 0 Logic0.input1 = logic::in::input; // Connect the input 1 from block 0 to its GPIO Logic0.input2 = logic::in::input_pullup; // Connect the input 2 from block 0 to its GPIO, with pullup on ``` -------------------------------- ### Initialize Logic Block Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md Initializes a specific logic block after its configuration. The initialization process applies the previously set configurations and configures the pins as requested. ```c++ Logic0.init(); // Initialize block 0 Logic1.init(); // Initialize block 1 ``` -------------------------------- ### TCD0 Protected Write Example Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Timers.md Demonstrates the protected write mechanism required for specific TCD0 registers, such as TCD0.FAULTCTRL, to prevent accidental changes during operation. This is crucial for safety-critical applications like motor control. ```c #define _PROTECTED_WRITE(reg, value) { volatile uint8_t temp = value; reg = temp; } // Example: Enabling PWM channels uint8_t pwm_enable_value = 0x01; // Example value to enable PWM _PROTECTED_WRITE(TCD0.FAULTCTRL, pwm_enable_value); ``` -------------------------------- ### Identify PWM Timer Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Digital.md Illustrates how to find the PWM timer associated with a pin using `digitalPinToTimer` and `digialPinToTimerNow`. The latter accounts for PORTMUX registers on DxCore, providing a more accurate timer identification for complex setups. ```c++ uint8_t timer = digitalPinToTimer(pin); // For PORTMUX-aware: uint8_t timer = digialPinToTimerNow(pin); ``` -------------------------------- ### Get User's Event Channel Number - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Event/README.md A static method to determine the event channel a user is connected to. Returns -1 if the user is not connected. It describes the one-to-one relationship between a user and a generator. ```c++ uint8_t connected_to = Event::get_user_channel_number(user::ccl0_event_a); // Returns the channel number ccl0_event_a is connected to ``` -------------------------------- ### Get Analog Reference Value (C) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Analog.md Retrieves the current analog reference setting as a uint8_t. This function is useful for checking or comparing against predefined reference constants like INTERNAL1V1. It is part of the mTC/DxC cores. ```c #include void setup() { Serial.begin(9600); uint8_t ref = getAnalogReference(); if (ref == INTERNAL1V1) { Serial.println("Analog reference is INTERNAL1V1"); } } ``` -------------------------------- ### Initialize Watchdog Timer (WDT) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Reset.md Enables the watchdog timer by writing to its control register with specified settings. The 'settings' parameter should be a WDT period or a combination of period and window settings. ```c++ _PROTECTED_WRITE(WDT.CTRLA, settings); //enable the WDT ``` -------------------------------- ### ClockDiagnose Sketch Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/megaTinyCore/README.md An example sketch designed to diagnose clock problems on the device. Upload the sketch and listen at the correct baud rate. The sketch attempts to identify and report the reasons for unexpected clock behavior. ```c++ // Basic usage is covered at the top of the sketch - the idea is upload it and listen at the correct baud rate. // If it can figure it out, it will try to tell you why you might not be happy with the clock behavior currently being demonstrated. ``` -------------------------------- ### Get Event Channel by Number - C++ Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Event/README.md A static method that returns the event object corresponding to a given channel number. It handles cases where the channel is invalid by returning 'Event_empty'. This is useful for runtime channel selection. ```c++ &Event MyEventChannel = Event::get_channel(MyUsedChannelCount); if (MyEventChannel.get_channel_number() == 255) { // damn, out of channels. return; } else { MyUsedChannelCount++; } ``` -------------------------------- ### Ersatz Reset Demonstration Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/megaTinyCore/README.md Demonstrates both methods of performing an Ersatz Reset from software on supported AVR microcontrollers. This sketch utilizes the included implementation of the Ersatz Reset functionality. ```c++ // Uses the included implementation of Ersatz Reset demonstrating both ways we can reset the chip from software. ``` -------------------------------- ### Get Pin Timer for PWM Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Functions.md Retrieves the timer associated with a pin for PWM output. Returns NOT_ON_TIMER (0), TIMERA0, TIMERD0 (1-series only), or DACOUT (1-series only) if the pin has PWM capabilities. ```c uint8_t digitalPinToTimer(pin); ``` -------------------------------- ### Run Code Before Initialization (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Callbacks.md The onBeforeInit function is designed to be the very first piece of code executed in the main function. It provides a hook for inserting custom logic between class constructors and the rest of the internal initialization process. This is generally a rarely used function, typically employed as a temporary fix for issues arising from poorly written libraries whose constructors might cause problems before the main initialization routines are called. ```cpp void onBeforeInit() __attribute__((weak));{ ;} ``` -------------------------------- ### Skewed Pulse Duration with Early digitalWriteFast() and Busy-Waiting Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Timers.md Shows how calling `digitalWriteFast()` before recording the `starttime` in a busy-wait loop can result in an inaccurate, longer measured pulse duration. This is because the start time is recorded after the pulse has already begun. ```c while (!digitalReadFast(pina)); // this is an extremely tight loop - sbrs rjmp .-4 - 3 clock cycles, so 0-2 clock cycles, + 0-2 clock cycles sync delay/ digitalWriteFast(pinb, HIGH); // this time, write the pin before recording starttime. starttime = micros(); // this is 6 us @ 20 MHz. starttime returns the time measured in the first few clocks after calling it. while (micros() - starttime < 100); // this loop only samples micros every ~6us, digitalWriteFast(pinb, LOW); // so now our pulse is too long ``` -------------------------------- ### Accurate Time Measurement with micros() Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/extras/Ref_Timers.md Demonstrates how to accurately measure the duration of a pulse using the `micros()` function by capturing start and end times. This method accounts for the overhead of `micros()` calls and provides a reliable duration calculation. ```c while (!digitalReadFast(pina)); // this is an extremely tight loop - sbrs rjmp .-4 - 3 clock cycles, so 0-2 clock cycles, + 0-2 clock cycles sync delay/ starttime = micros(); // this is 6 us @ 20 MHz. starttime returns the time measured in the first few clocks after calling it. //timetwo = micros(); // starttime - timetwo = ~6 while (digitalReadFast(pina)); endtime = micros(); // ``` -------------------------------- ### Initialize I2C Slave Mode using begin(address, receive_broadcast, second_address) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Wire/README.md This overload of `begin(address, receive_broadcast, second_address)` initializes the I2C slave functionality. It allows specifying the slave address, enabling general call reception, and optionally defining a second address or mask. Master functionality is not enabled by this call. ```c++ void begin(uint8_t address, bool receive_broadcast = 0, uint8_t second_address = 0); ``` -------------------------------- ### Define Constants with #define - C/C++ Source: https://github.com/spencekonde/megatinycore/blob/master/ContributionGuidelines.md Constants used as parameters or return values should be #defined and in all caps. This ensures clarity and consistency for magic numbers within the codebase. Example usage demonstrates signed and unsigned constant definitions. ```c #define FOO_BARRED (0) #define FOO_NOT_BARRED (1) #define FOO_CANNOT_BE_BARRED (-1) ``` -------------------------------- ### Configure and Initialize CCL Logic Blocks with Interrupts (C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/Logic/README.md This snippet shows how to configure multiple CCL logic blocks (Logic1, Logic3), set their truth tables and inputs, enable them, and attach an interrupt to Logic3. It includes a cautious approach to initialization that stops and restarts the CCL system to ensure changes are applied correctly, even if it causes a brief delay. ```c++ // Imagine there's some code above this that configured and enabled Logic0. Logic1.truth=0x55; // new truth table Logic1.input2=logic::in::tca0; // and different input 2 Logic3.enabled=true; // enable another LUT Logic3.input0=logic::in::link; // Use link from LUT0 Logic3.input1=logic::in::ac; // and the analog comparator Logic3.input2=logic::in::pin; // and the LUT3 IN2 pin Logic3.truth=0x79; // truth table for LUT3 Logic3.attachInterrupt(RISING,interruptFunction); // Interrupt now attached - but - Logic3 not enabled, and logic1 is using old settings // If we don't care that Logic0 will be briefly delayed, the cautious approach is fully portable. Logic::stop(); // have to turn off Logic0 too, even though I might not want to Logic1.init(); // apply changes to logic block 1 Logic3.init(); // apply settings to logic block 3 for the first time Logic::start(); // re-enable ``` -------------------------------- ### Get Length of USERSIG Space (Arduino C++) Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/USERSIG/README.md The `USERSIG.length()` function returns the total number of bytes available in the user signature space. This is useful for determining the capacity of the USERROW. ```c++ byte signatureSize = USERSIG.length(); ``` -------------------------------- ### Get Begin Iterator for EEPROM Source: https://github.com/spencekonde/megatinycore/blob/master/megaavr/libraries/EEPROM/README.md The EEPROM.begin() function returns an EEPtr pointing to the first cell in the EEPROM. This is useful for implementing custom iteration logic and C++11 style ranged for loops. ```c++ EEPtr begin_ptr = EEPROM.begin(); ```