Esempio n. 1
0
void dumpPacket(int offset, int len) {
  int i, j, k;
  int c;
  char ascii[33];
  memset(ascii, 0, 33);
  Serial.print("Paquet  (");
  Serial.print(numPk++);
  Serial.print("), len=");
  Serial.print(len);
  Serial.println(" bytes.");
  j = 0;
  for (i = 0; i < len; i++) {
    if (j < 32) {
      c = ENC28J60::buffer[offset + i];
      Serial.print(" ");
      printHexByte(c);
      if (isprint(c)) {
        ascii[j] = c;
      } else {
        ascii[j] = '.';
      }
      j += 1;
    } else {
      j = 0;
      Serial.print(" ");
      Serial.println(ascii);
      memset(ascii, 0, 33);
    }
  }
  for (; j < 32; j++) {
    Serial.print("   ");
  }
  Serial.print(" ");
  Serial.println(ascii);
}
Esempio n. 2
0
void search_i2c() {
	//write_nineAxis(55, 0x02); //set i2c bypass enable bit to true
	//write_nineAxis(106, 0x01); //reset i2c master

    unsigned char ret;
    for (uint8_t addy=0; addy < 128; addy++) {
    	printBinaryByte(addy<<1);
    	printString(" (0x");
    	printHexByte(addy<<1);
    	printString(")");
        ret = i2c_start((addy<<1)+I2C_WRITE);       // set device address and write mode
        if ( ret == 0 ) {
        	printString(": Device found on I2C port !!!");
        	i2c_stop();
        }
    	printString("\r\n");
    }
    printString("Finished searching I2C bus\r\n");
    return;
}
int main(void)
{
	char buf[7]; // antes apenas 7 era o suficiente
	uint8_t contador;

	uint8_t	ciclosWDTSono, min5s300;

	iniciaPORTAS();
	
	PORTD |= (1<<PD7);					// liga MOSFET
	_delay_ms(20);						// espera 20ms para energizar os circuitos
	
	// MCUSR – MCU Status Register
	// The MCU Status Register provides information on which reset source caused an MCU reset.
	
	printString("MCU Status Register:");
	printHexByte(  ((MCUSR | WDRF)  &0b1000 >> 3) );
	printString(",");
	printHexByte(  ((MCUSR | BORF)  &0b0100 >> 2) );
	printString(",");
	printHexByte(  ((MCUSR | EXTRF) &0b0010 >> 1) );
	printString(",");
	printHexByte(  ((MCUSR | PORF)  &0b0001     ) );
	printString("\r\nProj 07B v1.1b PSW (sem RTC)");	

	//WDTCSR – Watchdog Timer Control Register
	
	/*
	When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses, Table 28-6 on page 293,
	the BOD is actively monitoring the power supply voltage during a sleep period. To save power, it
	is possible to disable the BOD by software for some of the sleep modes, see Table 10-1 on page
	40. The sleep mode power consumption will then be at the same level as when BOD is globally
	disabled by fuses. If BOD is disabled in software, the BOD function is turned off immediately
	after entering the sleep mode. Upon wake-up from sleep, BOD is automatically enabled again.
	This ensures safe operation in case the VCC level has dropped during the sleep period.
	
	When the BOD has been disabled,the wake-up time from sleep mode will be approximately 60
	µs to ensure that the BOD is working correctly before the MCU continues executing code.
	BOD disable is controlled by bit 6, BODS (BOD Sleep) in the control register MCUCR, see
	”MCUCR – MCU Control Register” on page 45. Writing this bit to one turns off the BOD in relevant 
	sleep modes, while a zero in this bit keeps BOD active. Default setting keeps BOD active,
	i.e. BODS set to zero.
	*/
		
	//sleep_bod_disable();
	/* faz o mesmo que abaixo */
	//MCUCR |= (1<<BODS) | (1<<BODSE);		// desabilita o BOD para o sleep mode
	//MCUCR |= (1<<BODS);						// desabilita o BOD
	//MCUCR &= ~(1<<BODSE);					//
	
	//SMCR |= (1<<SE);						// Sleep Enable
	//SMCR |= (1<<SM2) | (1<<SM1) | (1<<SM0);	// IDLE
	
	//power_tx_modulator_enable();
	
	// disable ADC
	//ADCSRA = 0;		//	With that there the power consumption drops a large amount, down from 335 µA to 0.355 µA! (that is, 355 nA)
	
	
			/*
		20.7.3 Receive Compete Flag and Interrupt
		The USART Receiver has one flag that indicates the Receiver state.
		The Receive Complete (RXCn) Flag indicates if there are unread data present in the receive 
		buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive
		buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXENn = 0),
		the receive buffer will be flushed and consequently the RXCn bit will become zero.
		
		When the Receive Complete Interrupt Enable (RXCIEn) in UCSRnB is set, the USART Receive
		Complete interrupt will be executed as long as the RXCn Flag is set (provided thatglobal interrupts 
		are enabled). When interrupt-driven data reception is used, the receive complete routine
		must read the received data from UDRn in order to clear the RXCn Flag, otherwise a new interrupt 
		will occur once the interrupt routine terminates.
		*/
		UCSR0B |= (1<<RXCIE0);				// Habilita a Interrupcao de RX no controle da USART
		sei();
		_delay_ms(10000);
		
		
	printString("\r\nLoop Sleep Indefinido - RXINT.\r\n");
    while(1)
    {
		cli();
		for (contador=0;contador<3;contador++)
		{
			getEnv();
			_delay_ms(3333);
		}
			
		
		
		if(MODO=='0')		// o MODO 0 caracteriza-se por dormir indefinidamente
							// ate que uma interrupcao na USART acorde o MCU
		{
			set_sleep_mode(SLEEP_MODE_IDLE);	// configura o MODO de sleep
			sei();								// habilita todos interrupts
			
			liga_mcp23008();
			seqLed_mcp23008();
		
			//printString("Habilitando Sleep.\r\n");
			sleep_enable();						// habilita a dormirda
		
			power_adc_disable();
			power_spi_disable();
			power_timer0_disable();
			power_timer1_disable();
			power_timer2_disable();
			power_twi_disable();
		
			sleep_bod_disable();				// desliga o comparador de voltagem do BOD
		
			PORTD &= ~(1<<PD7);					// desliga MOSFET
		
			printString("dormindo...");
			sleep_mode();						// realmente coloca para dormir
			/*--------------------------------------------------------------*/
			printString("...Acordou!\r\n");
			sleep_disable();
			
			PORTD |= (1<<PD7);					// liga MOSFET
			_delay_ms(20);						// espera 20ms para energizar os circuitos
			
			power_all_enable();
			
		}
		else
		{
			printString("\r\nLoop Sono de 1h/5m (64s/64s).\r\n_");
			
			// Marca ZERO ciclos de Sleep com WDT
			ciclosWDTSono=0;	
			min5s300=0;			// contador multiplo de 5 minutos (ou 300 seg)
			
			while ( (MODO=='1') | (MODO=='2') )	// o Modo 1 eh o Sleep com WDT de no maximo 1h
											// o Modo 2 eh o Sleep com WDT sem hora para realmente acordar
			{
				//UCSR0B &= ~(1<<RXCIE0);	// Deabilita a Interrupcao de RX no controle da USART
				sei();					// Habilita interrupcoes, por causa do WDT
				
				PORTD &= ~(1<<PD7);					// desliga MOSFET
				
				habilitarWDT();		// coloca a CPU para dormir em SLEEP_MODE_PWR_DOWN
									// sendo acordada 8 segundos depois pelo WDT
									
				ciclosWDTSono++;	// computa mais um ciclo de WDT de 8 segundos
				
				if (ciclosWDTSono >= 37)	// ciclos de sleep+WDT forem maiores que 37 (8s*37 = 300s = 5min )
				{
					ciclosWDTSono=0;	// zera o contador de ciclos a cada "minuto" (ou mais segundos) de sono
					min5s300++;			// incrementa o contador de 5 minutos
					PORTD |= (1<<PD7);					// liga MOSFET
					_delay_ms(20);						// espera 20ms para energizar os circuitos
					
					liga_mcp23008();
					seqLed_mcp23008();
					
					////////////////////////////////////////////////////				

						printString( itoa(( min5s300 * 5) ,buf,10) );
						printString("min _ \r\n");
						getEnv();
						_delay_ms(2000);

					////////////////////////////////////////////////////				
					if ( (min5s300 == 12) & (MODO=='1'))	
						// testa se ja faz 1 hora que dormi
						{
							MODO='0';	// forcar para sair do MODO 1 (WDT) e voltar para o MODO 0 (USART RX INT)
							printString("Saindo do Modo Sono de 1 hora.\r\n_");
						}
					////////////////////////////////////////////////////
					_delay_ms(2000);	
				}
			}
		}
		
    }
}
int main(void)
{
	uint16_t valorADC;		// coleta do ADC de 0 a 1023

	//float vcc;				// valor calculado para voltagem da bateria
	float luz;				// valor calculado para luminosidade

	uint16_t tempChip;		// temperatura interna do chip
	uint8_t contador;		// contador para pisca-led
	char serialCharacter;	// caractere recebido na console serial
	char buf[7];			// buffer de string com ate 6 caracteres
	
	DDRB |= (1<<PB0) | (1<<PB5);		// leds vermelho e amarelo (conjunto)
	DDRD |= (1<<PD6);					// led grande branco do PWM
	DDRD |= (1<<PD1);					// saida da UART TX
	DDRD |= ~(1<<PD0);					// entrada da UART RX
	
	// As seguintes configuracoes abaixo sao DESNECESSARIAS, pois o AVR ja tem
	// as portas inicialmente com DDR = 0 (input)
	//PORTC &= ~(1<<PC2);	// zerando a porta antes de configurar a direcao DDR
	//PORTC &= ~(1<<PC3);	// zerando a porta antes de configurar a direcao DDR
	//DDRC &= ~(1<<PC2);		// entradas analogicas do ADC (Volts)
	//DDRC &= ~(1<<PC3);		// entradas analogicas do ADC (LDR)

	
	PORTB &= ~(1<<LED01) | ~(1<<LED02);		// inicia com leds apagados
	PORTD &= ~(1<<LED03);					// inicia led PWM apagado
	
	initUSART();						// por default essa biblioteca usa 9600 bps
	//hello();							// imprime mensagem inicial na console
	printString("\r\n? para help\r\n");
	
    while(1)
    {
		serialCharacter = receiveByte();
		
		if (serialCharacter == '*')
		{	
			printString("\rADC Luz:");
			
			valorADC = coletarADC( (1<<MUX1)|(1<<MUX0) );	// coleta o pino C3
			luz = ( (valorADC * 1.00	) / 1023 ) * 100;	// Resistor 4.7k down, e 10k antes do LDR com positivo
			// OBS: eh necessario usar o numero 1 como 1.00 para que o FLOAT seja estipulado.
			// caso contrario o numero calculado se comportara como inteiro.
						
			PORTB |= (1<<LED01);		// iniciando com led aceso
			PORTB &= ~(1<<LED02);		// iniciando com led apagado
			
			flipLed();
			
			valorRecebido(valorADC);
				
			dtostrf(luz,3,0,buf);
			printString(buf);
			
			flipLed();
			
			
			
			/* ==============VOLTAGEM===========*/
			/* =================================*/
			
			valorADC = coletarADC ( (1<<MUX1) );	// coleta o pino C2
			//vcc = (valorADC * 4.56) / 1023;	// 4.56 volts foi o valor maximo medido no multimetro
											// quando o ADC estava em 1023, com sol pleno na placa solar

			flipLed();
			printString("% , tensao:");
			valorRecebido(valorADC);
				
			dtostrf(((valorADC * 4.56) / 1023),4,2,buf);
			printString(buf);
			printString("v , temp_AVR:");
			
			
			/* ======Temperatura=do=CHIP========*/
			/* =================================*/
			valorADC = coletarADC( _BV(MUX3) );	// coleta o ADC8 (virtual)
			
			valorRecebido(valorADC);
			
				//tempChip = (valorADC * 1024) /1024;			// por Roney
				tempChip = (valorADC - 125) * 1.075 / 10;		// exemplo de Peter Knight
				
			sprintf(buf, "%d", tempChip );
			printString(buf);
			printString(" graus.\r\n");
			
			PORTB &= ~(1<<LED01) & ~(1<<LED02);	// no final da rotina, apaga os leds
			/* =================================*/
			
		}
		else
		if (serialCharacter == '!')
		{
			PORTB |= (1<<LED01);		// iniciando com led aceso
			PORTB &= ~(1<<LED02);		// iniciando com led apagado
			
			printString("\r\nContador: ");
			for(contador=0;contador<60;contador++)
			{
				
				_delay_ms(500);
				printString(itoa(contador,buf,10));
				printString(",");
				_delay_ms(500);		// pisca-leds por 60 segundos	
				
				flipLed();
				
			}	
			printString(" fim.\r\n");
			PORTB &= ~(1<<LED01) & ~(1<<LED02);	// no final da rotina, apaga os leds
		}
		else
		if (serialCharacter == '0')
		{
			printString("\rLEDs [Verm, Amar], Brco: ");
			printHexByte((PINB | LED01) & 0b1); printString(","); // B0
			printHexByte((PINB | LED02) >>5 ); printString(","); // B5
			printHexByte((PIND | LED03) >>6 & 0b1 ); printString("\r\n"); // D6
		}
		else
		if (serialCharacter == '1')