Skip to content

File wiring_custom.c

File List > arduino > src > wiring > wiring_custom.c

Go to the documentation of this file.

/* Copyright (c) Kuba Szczodrzyński 2022-06-20. */

#include "wiring_private.h"

#if LT_HAS_FREERTOS
#include <FreeRTOS.h>
#endif

int _analogReadResolution  = 10;    // 0-1023
int _analogWriteResolution = 8;     // 0-255
int _analogWritePeriod     = 20000; // 50 Hz

static unsigned long periodicTasks[] = {0, 0};

void runPeriodicTasks() {
#if LT_LOG_HEAP
    if (millis() - periodicTasks[0] > 1000) {
        LT_HEAP_I();
        periodicTasks[0] = millis();
    }
#endif
#if LT_USE_TIME
    if (millis() - periodicTasks[1] > 10000) {
        gettimeofday(NULL, NULL);
        periodicTasks[1] = millis();
    }
#endif
}

void pinModeRemove(pin_size_t pinNumber, uint32_t mask) {
    PinInfo *pin = pinInfo(pinNumber);
    if (!pin)
        return;
    pinRemoveMode(pin, mask);
    if (pin->enabled == PIN_NONE && mask == PIN_MODE_ALL)
        pinRemoveData(pin);
}

PinInfo *pinInfo(pin_size_t pinNumber) {
    if (pinNumber < 0 || pinNumber > PINS_GPIO_MAX)
        return NULL;
    return lt_arduino_pin_gpio_map[pinNumber];
}

PinInfo *pinByIndex(uint32_t index) {
    if (index < 0 || index >= PINS_COUNT)
        return NULL;
    return &(lt_arduino_pin_info_list[index]);
}

PinInfo *pinByGpio(uint32_t gpio) {
    for (uint32_t i = 0; i < PINS_COUNT; i++) {
        if (lt_arduino_pin_info_list[i].gpio == gpio)
            return &(lt_arduino_pin_info_list[i]);
    }
    return NULL;
}

uint32_t pinIndex(PinInfo *pin) {
    return pin - lt_arduino_pin_info_list;
}

bool pinSupported(PinInfo *pin, uint32_t mask) {
    return (pin->supported & mask) == mask;
}

bool pinEnabled(PinInfo *pin, uint32_t mask) {
    return (pin->enabled & mask) == mask;
}

int analogRead(pin_size_t pinNumber) {
    float voltage    = analogReadVoltage(pinNumber);
    float maxVoltage = analogReadMaxVoltage(pinNumber);
    uint16_t ret     = round((1 << _analogReadResolution) * voltage / maxVoltage);
    if (ret >= (1 << _analogReadResolution))
        ret = (1 << _analogReadResolution) - 1;
    return ret;
}

void analogReadResolution(int res) {
    _analogReadResolution = res;
}

void analogWriteResolution(int res) {
    _analogWriteResolution = res;
}

void analogWriteFrequency(int hz) {
    _analogWritePeriod = 1E6 / hz;
}

void analogWritePeriod(int us) {
    _analogWritePeriod = us;
}

__attribute__((weak)) void analogReference(uint8_t mode) {}