CommonPIC32

Annotated lib/utils.c

154:c8a37eb47211
2021-12-14 Paul Boddie Fixed pin labels: RB10/PGEC3 should be RB10/PGED2.
paul@113 1
/*
paul@113 2
 * Some simple utility functions.
paul@113 3
 *
paul@113 4
 * Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk>
paul@113 5
 *
paul@113 6
 * This program is free software: you can redistribute it and/or modify
paul@113 7
 * it under the terms of the GNU General Public License as published by
paul@113 8
 * the Free Software Foundation, either version 3 of the License, or
paul@113 9
 * (at your option) any later version.
paul@113 10
 *
paul@113 11
 * This program is distributed in the hope that it will be useful,
paul@113 12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
paul@113 13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
paul@113 14
 * GNU General Public License for more details.
paul@113 15
 *
paul@113 16
 * You should have received a copy of the GNU General Public License
paul@113 17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
paul@113 18
 */
paul@113 19
paul@113 20
#include "utils.h"
paul@113 21
paul@113 22
paul@113 23
paul@113 24
/* A simple busy wait involving a register-based counter. */
paul@113 25
paul@113 26
void wait(uint32_t delay)
paul@113 27
{
paul@113 28
    uint32_t counter = delay;
paul@113 29
paul@113 30
    if (!delay) return;
paul@113 31
    while (counter--) __asm__("");      /* retain loop */
paul@113 32
}
paul@113 33
paul@113 34
/* Wrap a pointer within the given limits. */
paul@113 35
paul@113 36
uint8_t *wrap_pointer(uint8_t *ptr, uint8_t *lower, uint8_t *upper)
paul@113 37
{
paul@113 38
    uint32_t size = upper - lower;
paul@113 39
paul@113 40
    if (ptr < lower)
paul@113 41
        return upper - (lower - ptr) % size;
paul@113 42
    else if (ptr >= upper)
paul@113 43
        return lower + (ptr - upper) % size;
paul@113 44
    else
paul@113 45
        return ptr;
paul@113 46
}
paul@113 47
paul@113 48
/* Wrap a value within the bounds [0, limit). */
paul@113 49
paul@113 50
int wrap_value(int value, int limit)
paul@113 51
{
paul@113 52
    if (value < 0)
paul@113 53
        return limit - (-value % limit);
paul@113 54
    else if (value >= limit)
paul@113 55
        return (value - limit) % limit;
paul@113 56
    else
paul@113 57
        return value;
paul@113 58
}