Subversion Repositories group.electronics

Rev

Rev 130 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * twires.c
 *
 *  Created on: 16/07/2014
 *      Author: pfowler
 *
 *       USAGE is modeled after the TinyWireS . . . which is modeled on standard Wire library . . .
 *
 * Put in setup():
 *      TinyWireS.begin(I2C_SLAVE_ADDR);                 // initialize I2C lib & setup slave's address (7 bit - same as Wire)
 *
 * To Receive:
 *   someByte = TinyWireS.available(){                // returns the number of bytes in the received buffer
 *   someByte = TinyWireS.receive(){                  // returns the next byte in the received buffer
 *
 * To Send:
 *      TinyWireS.send(uint8_t data){                    // sends a requested byte to master
 *
 * TODO:        (by others!)
 *      - onReceive and onRequest handlers are not implemented.
 *      - merge this class with TinyWireM for master & slave support in one library
 */

#include <inttypes.h>
#include "usiTwiSlave.h"
#include <avr/interrupt.h>
#include "avrutil.h"
#include "twires.h"


void twires_begin(uint8_t slaveAddr) {
        usiTwiSlaveInit(slaveAddr);
}

void twires_send(uint8_t data) {
        usiTwiTransmitByte(data);
}

uint8_t twires_available() {
        return usiTwiAmountDataInReceiveBuffer();
}

uint8_t twires_receive() {
        return usiTwiReceiveByte();
}

void twires_onReceive( void (*function)(uint8_t) ) {
        usi_onReceiverPtr = function;
}

void twires_onRequest( void (*function)(void) ) {
        usi_onRequestPtr = function;
}

void twires_stop_check() {
        if (!usi_onReceiverPtr) {
                // No onreceive callback
                return;
        }
        if (!(USISR & ( 1 << USIPF ))) {
                //Stop not detected
                return;
        }
        uint8_t amount = usiTwiAmountDataInReceiveBuffer();
        if (amount==0) {
                return;
        }
        usi_onReceiverPtr(amount);
}

void twires_delay(unsigned long ms) {

    uint16_t start = (uint16_t)millis();
    while (ms > 0)
    {
        twires_stop_check();
        if (((uint16_t)millis() - start) >= 1)
        {
            ms--;
            start += 1;
        }
    }

}