﻿/*
 * OW.h
 *
 * Created: 02.10.2014 11:53:29
 *  Author: Дима
 */ 
#ifndef OW_H_
#define OW_H_


#define     OWI_PORT        PORTB   //!< 1-Wire PORT Data register.
#define     OWI_PIN         PINB    //!< 1-Wire Input pin register.
#define     OWI_DDR         DDRB    //!< 1-Wire Data direction register.

#define OWI_RELEASE_BUS(bitMask) \
            OWI_DDR &= ~bitMask; \
            OWI_PORT &= ~bitMask;

// Pin bitmasks.
#define     OWI_PIN_0       0x01
#define     OWI_PIN_1       0x02
#define     OWI_PIN_2       0x04
#define     OWI_PIN_3       0x08
#define     OWI_PIN_4       0x10
#define     OWI_PIN_5       0x20
#define     OWI_PIN_6       0x40
#define     OWI_PIN_7       0x80

#define		BUS				OWI_PIN_0

//volatile unsigned char receive = 0;
//volatile unsigned char global = 0;

// unsigned char byte_array[255];
// unsigned char byte_array_index;


typedef struct{
	unsigned char rx; 
	unsigned char tx;
	unsigned char byte;
	unsigned char buffer[255];
	unsigned char buffer_index;
	unsigned char cycle;
	unsigned char high;
	unsigned char low;
}OW;

volatile OW ow;

void OW_Init(unsigned char pins)
{
    OWI_RELEASE_BUS(pins);
	_delay_ms(1);
}

ISR(TIMER1_OVF_vect){
	if (ow.rx == 1){
		ow.cycle++;
		if (PINB & (1 << 0)){
			ow.byte = (ow.byte >> 1)|0x80;
			//ow.high ++;
		}else if (!(PINB & (1 << 0))){
			ow.byte = (ow.byte >> 1);
			//ow.low ++;
		}
		if(ow.cycle >= 8){
			ow.buffer[ow.buffer_index] = ow.byte;
			ow.buffer_index++;
			ow.cycle = 0;
			ow.byte = 0;
		}
	}
	TCNT1 = 0;
	TIMSK1 &= ~(1 << TOIE1);
}		

ISR(PCINT0_vect){
	if (!(PINB & (1 << 0))){
		if ((ow.rx == 1) && (ow.tx == 0)){//прием по 1-варе
			//global = 0;
			Flag.general=0;
			Flag.server=0;
			TIMSK0 |= (1 << TOIE0);
			TCNT0 = 0;
			TCNT1 = 65215;
			TIMSK1 |= (1 << TOIE1);
		}
	}
}	

void init_T1(void) {
	TCCR1B |= (1 << CS10);
}

void RS_RXBUF_RESET(void){
	cli();
	unsigned int y;
	for (y=0; y < sizeof(ow.buffer); y++ )
	{
		ow.buffer[y]=0;
	}
	ow.buffer_index = 0;
	ow.cycle = 0;
	sei();	
}


void MDM_putc(unsigned char temp_byte){

 	ow.rx = 0;
 	ow.tx = 1;
	ow.byte = temp_byte;
	PCICR &= ~(1 << 0);
  	PCMSK0 &= ~(1 << 0); 
	while(ow.cycle < 8){
		if ((ow.tx == 1) && (ow.rx == 0)){//передача по 1-варе
			DDRB |= (1 << 0);
			PORTB &= ~(1 << 0);
			_delay_us(15);
			if ((ow.byte & (1 << 0)) == 0){
				PORTB &= ~(1 << 0);
				_delay_us(40);
			}
			else{
				PORTB |= (1 << 0);
				_delay_us(40);
			}
			PORTB |= (1 << 0);
			_delay_us(60);
			ow.byte = ow.byte >> 1;
			ow.cycle++;
		}
	}
  	PCICR |= (1 << 0);
  	PCMSK0 |= (1 << 0);	
	DDRB &= ~ (1 << 0);
	PORTB |= (1 << 0);	
	ow.byte = 0;
	ow.cycle = 0;
}

#endif /* OW_H_ */