This file is part of OneWire routines

by Isaac Marino Bavaresco

This is file "OneWireHAL-PIC24.c.h"

/*============================================================================*/
/*
 Copyright (c) 2016-2019, Isaac Marino Bavaresco
 All rights reserved.
 isaacbavaresco@yahoo.com.br

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
     * Neither the name of the author nor the
       names of its contributors may be used to endorse or promote products
       derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*============================================================================*/
#include <string.h>
#include <xc.h>
#include "OneWire.h"
/*============================================================================*/
#define CONVERT_us_TO_TCY(t)    ((unsigned)(14.745600*(t)+0.5))
/*============================================================================*/
static inline __attribute__((always_inline)) void SetTimer( unsigned int t )
    {
    T4CONbits.TON   = 0;
    TMR4            = 0;
    PR4             = CONVERT_us_TO_TCY(t);
    IFS1bits.T4IF   = 0;
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void StartTimer( void )
    {
    T4CONbits.TON   = 1;
    }
/*============================================================================*/
static inline __attribute__((always_inline)) int TimerExpired( void )
    {
    return IFS1bits.T4IF;
    }
/*============================================================================*/
void __attribute__((noinline)) delay_us( int t )
    {
    for( ; t; t-- )
        asm volatile( "nop" );
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void EnterCritical( void )
    {
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void ExitCritical( void )
    {
    }
/*============================================================================*/
/*============================================================================*/
/*============================================================================*/
/*============================================================================*/
int __attribute__((noinline)) OneWireReset( void )
    {
    int Result;

    if( OneWireQueryBus() )
        return ONE_WIRE_STATUS_BUS_CONTENTION;

    OneWirePullDownOn();            /* A */
    delay_us( 480 );
    EnterCritical();
    OneWirePullDownOff();           /* B */
    while( OneWireQueryBus() == 0 )
        {}
    OneWirePullUpOn();              /* E */
    delay_us( 8 );
    OneWirePullUpOff();             /* F */
    delay_us( 64 );
    Result  = OneWireQueryBus();    /* H */
    ExitCritical();
    delay_us( 240 );
    OneWirePullUpOn();              /* J/K */
    delay_us( 60 );
    OneWirePullUpOff();             /* L */
    delay_us( 10 );                 /* M */

    return Result == 0 ? ONE_WIRE_STATUS_OK : ONE_WIRE_STATUS_NO_RESPONSE;
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void OneWireWriteZero( void )
    {
    EnterCritical();
    OneWirePullDownOn();            /* A */
    delay_us( 60 );
    OneWirePullDownOff();           /* B0 */
    delay_us(  2 );
    OneWirePullUpOn();              /* C0 */
    delay_us( 16 );
    OneWirePullUpOff();             /* D0 */
    ExitCritical();
    delay_us(  2 );                 /* E0 */
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void OneWireWriteOne( void )
    {
    EnterCritical();
    OneWirePullDownOn();            /* A */
    delay_us(  9 );
    OneWirePullDownOff();           /* BR */
    delay_us(  9 );
    OneWirePullUpOn();              /* D1 */
    ExitCritical();
    delay_us( 60 );
    OneWirePullUpOff();             /* E1 */
    delay_us(  2 );                 /* F1 */
    }
/*============================================================================*/
static void __attribute__((noinline)) OneWireWriteBit( int Value )
    {
    if( Value )
        OneWireWriteOne();
    else
        OneWireWriteZero();
    }
/*============================================================================*/
static int __attribute__((noinline)) OneWireReadBit( void )
    {
    int Result;

    SetTimer( 60 );

    EnterCritical();

    OneWirePullDownOn();            /* A */
    delay_us(  9 );
    OneWirePullDownOff();           /* BR */
    delay_us(  9 );
    Result  = OneWireQueryBus();    /* CR */
    StartTimer();
    while( OneWireQueryBus() == 0 )
        {}
    OneWirePullUpOn();              /* F0 */
    ExitCritical();
    while( !TimerExpired() )
        {}
    OneWirePullUpOff();             /* G0 */
    delay_us(  4 );                 /* H0 */

    return Result;
    }
/*============================================================================*/
void __attribute__((noinline)) OneWireWriteByte( unsigned char Value )
    {
    int i;

    for( i = 0; i < 8; i++, Value >>= 1 )
        OneWireWriteBit( Value & 0x01 );
    }
/*============================================================================*/
unsigned char __attribute__((noinline)) OneWireReadByte( void )
    {
    unsigned char   Value;
    int             i;

    for( i = 0, Value = 0; i < 8; i++ )
        Value = ( Value >> 1 ) | ( OneWireReadBit() ? 0x80 : 0x00 );

    return Value;
    }
/*============================================================================*/
unsigned char CalcCRC8( unsigned char Seed, unsigned char Value )
    {
    static const unsigned char  CRC8Table[256] =
        {
          0,  94, 188, 226,  97,  63, 221, 131, 194, 156, 126,  32, 163, 253,  31,  65,
        157, 195,  33, 127, 252, 162,  64,  30,  95,   1, 227, 189,  62,  96, 130, 220,
         35, 125, 159, 193,  66,  28, 254, 160, 225, 191,  93,   3, 128, 222,  60,  98,
        190, 224,   2,  92, 223, 129,  99,  61, 124,  34, 192, 158,  29,  67, 161, 255,
         70,  24, 250, 164,  39, 121, 155, 197, 132, 218,  56, 102, 229, 187,  89,   7,
        219, 133, 103,  57, 186, 228,   6,  88,  25,  71, 165, 251, 120,  38, 196, 154,
        101,  59, 217, 135,   4,  90, 184, 230, 167, 249,  27,  69, 198, 152, 122,  36,
        248, 166,  68,  26, 153, 199,  37, 123,  58, 100, 134, 216,  91,   5, 231, 185,
        140, 210,  48, 110, 237, 179,  81,  15,  78,  16, 242, 172,  47, 113, 147, 205,
         17,  79, 173, 243, 112,  46, 204, 146, 211, 141, 111,  49, 178, 236,  14,  80,
        175, 241,  19,  77, 206, 144, 114,  44, 109,  51, 209, 143,  12,  82, 176, 238,
         50, 108, 142, 208,  83,  13, 239, 177, 240, 174,  76,  18, 145, 207,  45, 115,
        202, 148, 118,  40, 171, 245,  23,  73,   8,  86, 180, 234, 105,  55, 213, 139,
         87,   9, 235, 181,  54, 104, 138, 212, 149, 203,  41, 119, 244, 170,  72,  22,
        233, 183,  85,  11, 136, 214,  52, 106,  43, 117, 151, 201,  74,  20, 246, 168,
        116,  42, 200, 150,  21,  75, 169, 247, 182, 232,  10,  84, 215, 137, 107,  53
        };

    return CRC8Table[Seed ^ Value];
    }
/*============================================================================*/
int OneWireReadSerialNumber( unsigned char *Buffer )
    {
    unsigned char   CRC;
    int             i, Status;

    if(( Status = OneWireReset() ) < 0 )
        return Status;

    OneWireWriteByte( ONE_WIRE_COMMAND_READ_ROM );

    for( CRC = 0, i = 0; i < ONE_WIRE_ADDRESS_SIZE; i++ )
        CRC = CalcCRC8( CRC, Buffer[i] = OneWireReadByte() );
    if( CRC != 0 )
        return ONE_WIRE_STATUS_CRC_ERROR;
    else
        return ONE_WIRE_STATUS_OK;
    }
/*============================================================================*/
/*============================================================================*/
static inline __attribute__((always_inline)) int BitVectorExtract( unsigned char *V, unsigned int Bit )
    {
    return ( V[ Bit / 8 ] >> Bit % 8 ) & 0x01;
    }
/*============================================================================*/
static inline __attribute__((always_inline)) void BitVectorInsert( unsigned char *V, unsigned int Bit, int Value )
    {
    V[ Bit / 8 ]    = ( V[ Bit / 8 ] & ~( 1 << Bit % 8 )) | (( Value & 0x01 ) << Bit % 8 );
    }
/*============================================================================*/
void OneWireSearchInit( onewiresearch_t *SearchStruct, int FamilyCode )
    {
    memset( SearchStruct->Address, 0x00, sizeof SearchStruct->Address );
    memset( SearchStruct->Branches, 0x00, sizeof SearchStruct->Branches );
    if( FamilyCode >= 0 && FamilyCode <= 255 )
        {
        SearchStruct->Address[0]    = (unsigned char)FamilyCode;
        SearchStruct->FixedBits     = 8;
        }
    else
        SearchStruct->FixedBits     = 0;

    SearchStruct->FirstSearch   = 1;
    SearchStruct->Finished      = 0;
    }
/*============================================================================*/
int OneWireSearch( onewiresearch_t *SearchStruct, unsigned char *Address )
    {
    int BitTrue, BitNegated, CurrentBit;
    int Status;
    int i;

    if( SearchStruct->Finished != 0 )
        return ONE_WIRE_SEARCH_STATUS_NOT_FOUND;

    if(( Status = OneWireReset() ) < 0 )
        return Status;

    /*
    If this is not the first search iteration we must unwind the tree before
    starting the next iteration.
    */
    if( SearchStruct->FirstSearch == 0 )
        {
        /*
        We start at a leaf of the tree and walk up until we reach the closest
        branch where we took a left turn and then switch it to a right turn (set address bit),
        while we zero the bits for all other occurrences.
        */
        for( i = 8 * ONE_WIRE_ADDRESS_SIZE - 1; i >= SearchStruct->FixedBits; i-- )
            {
            if( BitVectorExtract( SearchStruct->Branches, i ) == 1 && BitVectorExtract( SearchStruct->Address, i ) == 0 )
                {
                BitVectorInsert( SearchStruct->Address, i, 1 );
                break;
                }
            BitVectorInsert( SearchStruct->Address, i, 0 );
            BitVectorInsert( SearchStruct->Branches, i, 0 );
            }
        if( i < SearchStruct->FixedBits )
            {
            SearchStruct->Finished  = 1;
            return ONE_WIRE_SEARCH_STATUS_NOT_FOUND;
            }
        }

    SearchStruct->FirstSearch   = 0;

    OneWireWriteByte( ONE_WIRE_COMMAND_SEARCH_ROM );

    /*
    Walk down the tree marking the branches and taking the left path
    unless on a previous excursion we switched the direction of the branch.
    */
    for( i = 0; i < 8 * ONE_WIRE_ADDRESS_SIZE; i++ )
        {
        BitTrue     = OneWireReadBit();
        BitNegated  = OneWireReadBit();

        if( BitTrue == 1 && BitNegated == 1 )
            {
            SearchStruct->Finished  = 1;
            return ONE_WIRE_STATUS_NO_RESPONSE;
            }
        if( i < SearchStruct->FixedBits )
            CurrentBit  = BitVectorExtract( SearchStruct->Address, i );
        else if( BitTrue == 0 && BitNegated == 0 )
            {
            BitVectorInsert( SearchStruct->Branches, i, 1 );
            CurrentBit  = BitVectorExtract( SearchStruct->Address, i );
            }
        else
            {
            BitVectorInsert( SearchStruct->Address, i, BitTrue );
            CurrentBit  = BitTrue;
            }
        OneWireWriteBit( CurrentBit );
        }
    memcpy( Address, SearchStruct->Address, sizeof SearchStruct->Address );

    return ONE_WIRE_SEARCH_STATUS_FOUND;
    }
/*============================================================================*/
int OneWireInit( void )
    {
    //ANSB              = 1 << 14;

//@@@@  ANSBbits.ANSB12     = 0;
    LATBbits.LATB12     = 0;
    TRISBbits.TRISB12   = 0;

//@@@@  ANSBbits.ANSB13     = 0;
    LATBbits.LATB13     = 1;
    TRISBbits.TRISB13   = 0;

//@@@@  ANSBbits.ANSB14     = 1;
    TRISBbits.TRISB14   = 1;

    CVRCONbits.CVRSS    = 0;
    CVRCONbits.CVR      = (unsigned)(( 32 * ( 1.4 / 5.0 )) + 0.5 );
    CVRCONbits.CVREN    = 1;

//@@@@  CM3CONbits.CREF     = 1;
//@@@@  CM3CONbits.CCH      = 0;
//@@@@  CM3CONbits.CON      = 1;

    T4CONbits.TON       = 0;
    T4CONbits.TSIDL     = 0;
    T4CONbits.TGATE     = 0;
    T4CONbits.TCKPS     = 0;
    T4CONbits.T32       = 0;
    T4CONbits.TCS       = 0;

    return ONE_WIRE_STATUS_OK;
    }
/*============================================================================*/