//
// Created by 5ANK41 on 2024/11/28.

#include "onewire.h"

uchar OneWire_init(void) {
    uchar i;
    ONE_WIRE_P = 1;
    ONE_WIRE_P = 0;
    i = 247;
    while (--i);
    ONE_WIRE_P = 1;
    i = 32;
    while (--i);
    uchar ack = ONE_WIRE_P;
    i = 247;
    while (--i);
    return ack;
}

void OneWire_writeBit(uchar _bit) {
    uchar i;
    ONE_WIRE_P = 0;
    i = 4;
    while (--i);
    ONE_WIRE_P = _bit;
    i = 24;
    while (--i);
    ONE_WIRE_P = 1;
}

void OneWire_writeByte(uchar _byte) {
    for (uchar i = 0; i < 8; i++) {
        OneWire_writeBit(_byte & 0x01 << i);
    }
}

uchar OneWire_readBit(void) {
    uchar i, _bit;
    ONE_WIRE_P = 0;
    i = 2;
    while (--i);
    ONE_WIRE_P = 1;
    i = 2;
    while (--i);
    _bit = ONE_WIRE_P;
    i = 24;
    while (--i);
    return _bit;
}

uchar OneWire_readByte(void) {
    uchar _byte = 0x00;
    for (uchar i = 0; i < 8; i++) {
        if (OneWire_readBit()) { _byte |= 0x01 << i; }
    }
    return _byte;
}