コード例 #1
0
ファイル: tempsensors.c プロジェクト: C3MA/Aiolos
void loopTempSensors(void) {
  error = 0;

  if ( nSensors == 0 ) {
    error++;
  }

  if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL ) 
      == DS18X20_OK) {

    for ( i = 0; i < nSensors; i++ ) {
      if ( DS18X20_read_maxres( &gSensorIDs[i][0], &temp_eminus4 )
          == DS18X20_OK ) {
        ;; // we're cool - read a value.
        //uart_put_temp_maxres( temp_eminus4 );
      }
      else {
        error++;
      }
    }
  } else {
    error++;
  }

  if ( error ) {
    nSensors = search_sensors();
    //uart_put_int( (int) nSensors );
    error = 0;
  }
}
コード例 #2
0
ファイル: ds18x20.c プロジェクト: atalax/avr-uip-2
void findSystemID(uint8_t *id)
{
	printf("Scanning for system id...\r\n");
	OW_selectPort(1);
	int nSensors = search_sensors(MAXSENSORS);  //Finder alle sensore (op til max)

	for (int i = 0; i < nSensors; i++) {
		if (sensorScan[i * OW_ROMCODE_SIZE + 0] == 0x01) {
			for (uint8_t o = 0; o < OW_ROMCODE_SIZE; o++)
				id[o] = sensorScan[i * OW_ROMCODE_SIZE + o];

			printf_P(PSTR("Found system id %02X%02X%02X%02X%02X%02X%02X%02X\r\n"),
			         id[0],
			         id[1],
			         id[2],
			         id[3],
			         id[4],
			         id[5],
			         id[6],
			         id[7]
			        );

			//Example system id : 01 51 99 36 14 00 00 F5
		}
	}
}
コード例 #3
0
ファイル: main.c プロジェクト: krystech/eclipseWorkspace
int main(void)
{
	DDRB |= (1<<PB0);
	PORTB |= (1<<PB0);

	DDRD &= ~(1<<PD6);
	PORTD &= ~(1<<PD6);

	czujniki_cnt = search_sensors();

	DS18X20_start_meas(DS18X20_POWER_EXTERN, NULL);
	_delay_ms(750);
	if(DS18X20_OK == DS18X20_read_meas_single(0x28, &subzero, &cel, &cel_frac_bits)) display_temp();
	else {
		lcd_puts_P("err");
	}

     lcd_clrscr();   /* clear display home cursor */

 for(;;){


 }


}
コード例 #4
0
ファイル: main.c プロジェクト: age/mss
void
configure (void)
{
  /* usb stuff. make the host re-enumerate our device */
  cli ();
  usbDeviceDisconnect ();
  /* configure timer 2 for calling usbPoll() */
  TIMSK2 = _BV (TOIE2);         /* overflow interrupt enabled */
  TCCR2B = _BV (CS02) | _BV (CS01) | _BV (CS00);        /* set prescaler to 1024, timer starts */
  /* end of usb stuff  */

  /* display configuration */
  d_status = &display[0];
  display[LCD_DISP_LENGTH] = '\0';
  d_content = &display[LCD_DISP_LENGTH + 1];
  display[LCD_DISP_LENGTH * 2 + 1] = '\0';
  lcd_init (LCD_DISP_ON);
  /* end display configuration */
  /* temperature sensors */
  t_sensors_count = search_sensors ();
  if (t_sensors_count)
    {
      have_ts = 1;
      d_status_update ("Found %d DS18B20", t_sensors_count);
      d_update ();
    }
  /* end if temperature sensors setup */
  /* twi/accelerometer configuration */
  i2c_init ();
  /* don't hurry! */
  _delay_ms (1000);
  if (!lis_initialize (0, 1, 0, 1))
    {
      have_ac = 1;
      d_content_update ("Found LIS302DL");
      d_update ();
    }
  /* end of accelerometer configuration */
  _delay_ms (1500);
  /* configure timer 0 for button state detection */
  TIMSK0 = _BV (TOIE0);         /* enable overflow interrupt */
  TCCR0B = _BV (CS02) | _BV (CS00);     /* set prescaler to 1024, timer starts */
  PORTD |= _BV (PD3) | _BV (PD4);       /* pullup for buttons */
  /* end if button detection setup */
  /* ADC configuration goes here */
  ADMUX = _BV (REFS0);
  ADCSRA = _BV (ADEN) | _BV (ADPS2) | _BV (ADPS1) | _BV (ADPS0);
  PORTC |= _BV (PC0) | _BV (PC1);
  /* end of ADC configuration */

  /* clear the display */
  d_content_update (" ");
  d_status_update (" ");
  d_update ();

  usbDeviceConnect ();
  usbInit ();
  sei ();
}
コード例 #5
0
int main(void){
  
  DDRD &= ~(1 << PD0); //button
  PORTD |= (1 << PD0); //pullup

  DDRC |= 0b00111111; //anodes + segments a, b and c
  DDRD |= 0b11111000; //segments d, e, f, g and led
    
  anodesOff;
  displayOn = 1; //display is on
      
  /* setup 16 bits timer1 for reading temperature
  with 1024 prescaler running at 1MHz with overflow interrupt
  1MHz / 1024 = 976.5625Hz
  976.56 / 0.1 Hz = 9765.6
  */
    
  OCR1A = 30000; //about once very 30 seconds w00t w00t 16 bits!
  TCCR1B |= (1<<WGM12); //CTC OCR1A
  TCCR1B |= (1<<CS12) | (1<<CS10); //1024 prescale 
  TIMSK = (1 << OCIE1A); //trigger interrupt on overflow

  /* setup timer2 for multiplexing 
  Timer 2 is an 8 bit timer, we'll set it with 1024 prescale with CTC mode 
  on OCR2 = 5;
  */

  OCR2 = 5;
  TCCR2 |= (1<<WGM21); //CTC mode
  TCCR2 |= (1<<CS20) | (1<<CS21) | (1<<CS22); //1024 
  TIMSK |= (1 << OCIE2); //trigger interrupt on overflow
  
  //uart_init((UART_BAUD_SELECT((BAUD),F_CPU)));
  sei(); //turn on interrupts
  
  /*
  for (uint8_t i=0; i<10; i++){
    display[0] = display[1] = display[2] = i;
    _delay_ms(300);
  }
  */
  search_sensors(); //populate gSensorIDs
  readTemp();
  
  while(1){
    set_sleep_mode(SLEEP_MODE_IDLE);
    sleep_enable();
    sleep_mode();
  }
  return 1; //never reached, but compiler longs for it.
}
コード例 #6
0
void init_temperature(void)
{
    nTempSensors = 0;

    uint8_t bus;
    for( bus = 0; bus < N_1W_BUS; bus++ )
    {
#ifndef OW_ONE_BUS
        ow_set_bus(&PINB,&PORTB,&DDRB,PB0+bus);
#endif
        //uint8_t sc =
        search_sensors(bus);
    }
}
コード例 #7
0
ファイル: main.c プロジェクト: atommann/temp2morse-led
int main(void)
{
    init();
    nSensors = search_sensors();
    sleep_init();
    
    while (1) {
        if (display_flag) {
            convert_show();
            display_flag = 0;
        }
	
        sleep_cpu();
        sleep_disable();
    }
}
コード例 #8
0
ファイル: main.c プロジェクト: peterzos/AVR_projects
void search_bus()
{
	uint8_t i;

	while(1)
	{
		sensor_fw.sensor_num = search_sensors();
		if (sensor_fw.sensor_num > 0)
			break;
		_delay_ms(1000);
	}
	/* get power status */
	for ( i = 0; i < sensor_fw.sensor_num; i++ )
	{
		if ( DS18X20_get_power_status(&sensor_fw.sensors[i].id[0] ) == DS18X20_POWER_PARASITE )
		{
			sensor_fw.sensors[i].power = POWER_PARASITE;
		}
		else
		{
			sensor_fw.sensors[i].power = POWER_EXTERNAL;
		}
	}
}
コード例 #9
0
ファイル: ds18x20.c プロジェクト: atalax/avr-uip-2
void updateOWSensors()
{
#ifdef OW_DEBUG
	printf_P(PSTR("Update onewire \r\n"));
#endif

	uint8_t subzero, cel, cel_frac_bits;
	uint16_t maalt;

	if (!DS18B20Conv) {
		DS18B20Conv = true;

		for (uint8_t active_OW_channel = 1; active_OW_channel <= 3;
		     active_OW_channel++) {
			OW_selectPort(active_OW_channel);
			DS18X20_start_meas(DS18X20_POWER_PARASITE, NULL);
		}

	} else {
		DS18B20Conv = false;

		for (uint8_t active_OW_channel = 1; active_OW_channel <= 3;
		     active_OW_channel++) {
			OW_selectPort(active_OW_channel);

#ifdef OW_DEBUG
			printf_P(PSTR("Scanner for onewire sensore paa %d\r\n"), active_OW_channel);
#endif

			int nSensors = search_sensors(MAXSENSORS);  //Finder alle sensore (op til max)

#ifdef OW_DEBUG
			printf("Found %d sensors \r\n", nSensors);
#endif

			for (int i = 0; i < nSensors; i++) {
				if (sensorScan[i * OW_ROMCODE_SIZE + 0] == 0x10
				    || sensorScan[i * OW_ROMCODE_SIZE + 0] == 0x28) {
					uint8_t sensorID[OW_ROMCODE_SIZE];
					for (uint8_t o = 0; o < OW_ROMCODE_SIZE; o++)
						sensorID[o] = sensorScan[i * OW_ROMCODE_SIZE + o];

					if (DS18X20_read_meas(sensorID, &subzero, &cel, &cel_frac_bits,
					                      &maalt) == DS18X20_OK) {
#ifdef OW_DEBUG
						int frac =
						    cel_frac_bits *
						    DS18X20_FRACCONV; //Ganger de sidste par bits, med det step DS18B20 bruger
#endif
						char sign = (subzero) ? '-' : '+';

						uint16_t pos = findSensor(
						                   sensorScan[i * OW_ROMCODE_SIZE + FAMILY],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID1],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID2],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID3],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID4],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID5],
						                   sensorScan[i * OW_ROMCODE_SIZE + ID6],
						                   sensorScan[i * OW_ROMCODE_SIZE + CRC]
						               );

						sensorValues[(pos * SENSORSIZE) + VALUE1]     = cel;
						sensorValues[(pos * SENSORSIZE) + VALUE2]     = cel_frac_bits;
						sensorValues[(pos * SENSORSIZE) + SIGN]       = sign;

#ifdef OW_DEBUG
						printf_P(PSTR("Sensor# %d (%02X%02X%02X%02X%02X%02X%02X%02X) =  : %c%d.%04d\r\n"),
						         i + 1,
						         sensorValues[(pos * SENSORSIZE) + FAMILY],
						         sensorValues[(pos * SENSORSIZE) + ID1],
						         sensorValues[(pos * SENSORSIZE) + ID2],
						         sensorValues[(pos * SENSORSIZE) + ID3],
						         sensorValues[(pos * SENSORSIZE) + ID4],
						         sensorValues[(pos * SENSORSIZE) + ID5],
						         sensorValues[(pos * SENSORSIZE) + ID6],
						         sensorValues[(pos * SENSORSIZE) + CRC],
						         sensorValues[(pos * SENSORSIZE) + SIGN],
						         sensorValues[(pos * SENSORSIZE) + VALUE1],
						         frac
						        );
#endif
					} else
						printf_P(PSTR("CRC Error (lost connection?)"));
				}
			}
		}
	}
}
コード例 #10
0
int main(void)
{
	
	wdt_disable();

	g_state = MEASURE_AND_TRANSMIT;
	INIT_RADIO_PORT();
	INIT_PERIPHERIAL_ON_PORT();
	ON_PERIPHERIA();
	_delay_ms(500);
	
	ow_reset();
	_delay_ms(500);
	ow_command( DS18X20_CONVERT_T, 0 );
	char numOfSensors = search_sensors();
	//g_cyclesToSleep = CYCLES_BEFORE_SLEEP;
	sei();
	
	_delay_ms(780);
	while(1){

		switch(g_state){
			case MEAS_AND_DISP://Таймер для отображения цифр, порт для вывода цифр и количество показов цифр устанавливаются в INT0
			case MEASURE_AND_TRANSMIT:{
				cli();
				DS18X20_read_temp(gSensorIDs[0],&g_temp);
				sei();
				g_selectSensor = 0;
				SendTempDataToBase();
		
				if (numOfSensors > 1)//Если есть еще датчики то читаем от него данные
				{
					if (g_cyclesToSleep == 0)
					{
						_delay_ms(3);
					}else
					_delay_ms(TIME_TO_DISP_SENSOR);
					cli();
					DS18X20_read_temp(gSensorIDs[1],&g_temp);
					sei();
					g_selectSensor = 1;
					SendTempDataToBase();
				}
			}break;
			case GO_TO_SLEEP:{//засыпаем по флагу сна				
				STOP_TIMER();
				OFF_PERIPHERIA();
				DEINIT_DIGIT_SELECT_PORT();
				DEINIT_SEGMENT_PORT();
				g_cyclesToSleep = 0;
				//Настраиваем вход прерывания 0 как вход и разрешаем прерывание
				ENABLE_INT0();
				START_ON_TIMER();
				//Спим не глубоко а просыпаемся на тикающий таймер для просыпания и отправки температуры по радиоканалу
				set_sleep_mode(SLEEP_MODE_IDLE);
				sleep_mode();
				//ON_PERIPHERIA();
			}break;
			case GO_TO_DEEP_SLEEP:{//уходим в глубокий сон по истечению таймера перед отправкой температуры при взведенной собаке
				set_sleep_mode(SLEEP_MODE_PWR_DOWN);
				sleep_mode();
			}break;
		}
		
		
		
		
		g_timerToSleep++;//Если оттикали количество секунд то уходим в сон
		if ((g_timerToSleep < g_cyclesToSleep))//если не оттикали нужное количество циклов то перезапускаем измерение и ждем
		{	cli();
			ow_reset();
			ow_command( DS18X20_CONVERT_T, 0 );
			sei();
			_delay_ms(TIME_TO_DISP_SENSOR);
			
		}else{
			g_timerToSleep = 0;
			g_state = GO_TO_SLEEP;
		}


	}

}
コード例 #11
0
/*-----------------------------------------------------------------------------
 * Main Program
 *---------------------------------------------------------------------------*/
int main(void) {
	uint8_t nSensors, i;
	uint8_t subzero, cel, cel_frac_bits;
	
	Mcu_Init();
	Timebase_Init();
	Serial_Init();
	
	sei();
	
	printf( "\nDS18X20 1-Wire-Reader\n" );
	printf( "-----------------------" );
	nSensors = search_sensors();
	printf( "%i DS18X20 Sensor(s) available:\n", (int) nSensors );
	
	for (i=0; i<nSensors; i++) {
		printf("Sensor# %i is a ", (int) i+1);
		if ( gSensorIDs[i][0] == DS18S20_ID)
			printf("DS18S20/DS1820");
		else printf("DS18B20");
		printf(" which is ");
		if ( DS18X20_get_power_status( &gSensorIDs[i][0] ) ==
			DS18X20_POWER_PARASITE ) 
			printf( "parasite" );
		else printf( "externally" ); 
		printf( " powered\n" );
	}
	
	printf("CanInit...\n");
	if (Can_Init() != CAN_OK) {
		printf("FAILED!\n");
	}
	else {
		printf("OK!\n");
	}
	
	uint32_t timeStamp = 0;
	
	Can_Message_t txMsg;
	Can_Message_t rxMsg;
	
	txMsg.DataLength = 2;
	txMsg.Id = 0;
	txMsg.RemoteFlag = 0;
	txMsg.ExtendedFlag = 1;
	
	/* main loop */
	while (1) {
		/* service the CAN routines */
		Can_Service();

		/* check if any messages have been received */
		while (Can_Receive(&rxMsg) == CAN_OK) {
			
		}

		/* check temperature and send on CAN once every other second */
		if (Timebase_PassedTimeMillis(timeStamp) >= 2000) {
			timeStamp = Timebase_CurrentTime();
			
			if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL ) == DS18X20_OK) {
				printf("Measuring temperature... ");
				delay_ms(DS18B20_TCONV_12BIT);
				for ( i=0; i<nSensors; i++ ) {
					if ( DS18X20_read_meas( &gSensorIDs[i][0], &subzero,
							&cel, &cel_frac_bits) == DS18X20_OK ) {
						
						//txMsg.Data.bytes[0] = subzero;
						if (subzero) {
							txMsg.Data.bytes[i*2] = -cel;
							txMsg.Data.bytes[i*2+1] = ~(cel_frac_bits<<4);
						} else {
							txMsg.Data.bytes[i*2] = cel;
							txMsg.Data.bytes[i*2+1] = (cel_frac_bits<<4);
						}
						
					}
					else printf("CRC Error (lost connection?)\n");
				}
				
				txMsg.DataLength = nSensors*2;
				printf("sending...\n");
				/* send txMsg */
				Can_Send(&txMsg);
			}
			else printf("Start meas. failed (short circuit?)\n");

		}
	}
	
	return 0;
}
コード例 #12
0
/*-----------------------------------------------------------------------------
 * Main Program
 *---------------------------------------------------------------------------*/
int main(void) {
#if defined(USE_DS18S20)
    uint8_t nSensors, i;
    uint8_t subzero, cel, cel_frac_bits;
    uint32_t timeStamp_DS = 0, timeStamp_DS_del = 0;
	/* This is to identify and give the sensors correct ID 
	 * TODO read ds18s20 serial id and that way give the "can id" */
	uint16_t sensor_ds_id[] = {TEMPSENSORID_1, TEMPSENSORID_2, TEMPSENSORID_3, TEMPSENSORID_4};
#endif
#if defined(USE_TC1047)
    uint32_t tcTemperature = 0, timeStamp_TC = 0;
    adcTemperatureInit();
#endif
#if defined(USE_LDR)
	uint32_t timeStamp_LDR = 0;
	uint8_t ldr;
	LDR_SensorInit();
#endif
    sei();

	Timebase_Init();

    Can_Message_t txMsg;
	txMsg.Id = (CAN_NMT_APP_START << CAN_SHIFT_NMT_TYPE) | (NODE_ID << CAN_SHIFT_NMT_SID);
	txMsg.DataLength = 4;
	txMsg.RemoteFlag = 0;
	txMsg.ExtendedFlag = 1;
	txMsg.Data.words[0] = APP_TYPE;
	txMsg.Data.words[1] = APP_VERSION;
	BIOS_CanSend(&txMsg);

#if defined(USE_DS18S20)
    /* Make sure there is no more then 4 DS-sensors. */
    nSensors = search_sensors();
#endif

    txMsg.DataLength = 2;

    /* main loop */
    while (1) {
#if defined(USE_DS18S20)
        /* check temperature and send on CAN */
		if( Timebase_PassedTimeMillis(timeStamp_DS) >= DS_SEND_PERIOD ){
			timeStamp_DS = Timebase_CurrentTime();

            if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL ) == DS18X20_OK) {
                delay_ms(DS18B20_TCONV_12BIT);
                for ( i=0; i<nSensors; i++ ) {
                    if ( DS18X20_read_meas( &gSensorIDs[i][0], &subzero, &cel, &cel_frac_bits) == DS18X20_OK ) {

                        if (subzero) {
                            txMsg.Data.bytes[0] = -cel-1;
                            txMsg.Data.bytes[1] = ~(cel_frac_bits<<4);
                        }else{
                            txMsg.Data.bytes[0] = cel;
                            txMsg.Data.bytes[1] = (cel_frac_bits<<4);
                        }
                    }
					/* Delay */
					timeStamp_DS_del = Timebase_CurrentTime();
					while(Timebase_PassedTimeMillis(timeStamp_DS_del) < DS_SEND_DELAY){}

					/* send txMsg */
					txMsg.Id = ((CAN_SNS << CAN_SHIFT_CLASS) | (SNS_TYPE_TEMPERATURE << CAN_SHIFT_SNS_TYPE) | (NODE_ID << CAN_SHIFT_SNS_SID));
					txMsg.Id |= ( sensor_ds_id[i] << CAN_SHIFT_SNS_ID); /* Set sensor id */
					BIOS_CanSend(&txMsg);
                }
            }
        }
#endif
#if defined(USE_TC1047)
#error tc1047 id is still not correct // FIXME
            /* check temperature and send on CAN */
		if( bios->timebase_get() - timeStamp_TC >= TC_SEND_PERIOD ){
			timeStamp_TC = bios->timebase_get();

            tcTemperature = getTC1047temperature();
            txMsg.Data.bytes[0] = tcTemperature & 0x00FF;
            txMsg.Data.bytes[1] = (tcTemperature & 0xFF00)>>8;
            txMsg.DataLength = 2;

			txMsg.Id = ((CAN_SNS << CAN_SHIFT_CLASS) | (SNS_TYPE_TEMPERATURE << CAN_SHIFT_SNS_TYPE) | (NODE_ID << CAN_SHIFT_SNS_SID));
			txMsg.Id |= (TEMPSENSORID_5 << CAN_SHIFT_SNS_ID); // sätt korrekt sensorid

            BIOS_CanSend(&txMsg);
        }
#endif
#if defined(USE_LDR)
            /* check light and send on CAN */
		if( Timebase_PassedTimeMillis(timeStamp_LDR) >= LDR_SEND_PERIOD ){
			timeStamp_LDR = Timebase_CurrentTime();

            ldr = (uint8_t)LDR_GetData(0);
            txMsg.Data.bytes[0] = ldr;
            txMsg.DataLength = 1;

			txMsg.Id = ((CAN_SNS << CAN_SHIFT_CLASS) | (SNS_TYPE_LIGHT << CAN_SHIFT_SNS_TYPE) | (LIGHTSENSORID_1 << CAN_SHIFT_SNS_ID) | (NODE_ID << CAN_SHIFT_SNS_SID));

			BIOS_CanSend(&txMsg);
        }
#endif
    }
コード例 #13
0
ファイル: main.c プロジェクト: ruslanec/mikrowerk
int main(void) {
  uint8_t i;
  
  //TODO: Enable watchdog.
  //TODO: Define compile-switch to disable serial output.
  
  // UART init
  uart_init((UART_BAUD_SELECT((BAUD),F_OSC)));
  // USB code init
  //	wdt_enable(WDTO_1S);
  //odDebugInit();
  DDRD = ~(1 << 2);   /* all outputs except PD2 = INT0 */
  PORTD = 0; /* no pullups on USB pins */
  /* We fake an USB disconnect by pulling D+ and D- to 0 during reset. This is
   * necessary if we had a watchdog reset or brownout reset to notify the host
   * that it should re-enumerate the device. Otherwise the host's and device's
   * concept of the device-ID would be out of sync.
   */
  //DDRB = ~USBMASK;    /* set all pins as outputs except USB */
  //computeOutputStatus();  /* set output status before we do the delay */
  usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
  i = 250;
  while(--i){         /* fake USB disconnect for > 500 ms */
	//wdt_reset();
	_delay_ms(2);
  }
  usbDeviceConnect();
  //TCCR0 = 5;          /* set prescaler to 1/1024 */
  usbInit();
  sei();

  // Init DS18X20 Connect LED.
  // Turn LED on: Pull to GND 
  DS18X20_STATUS_LED_DDR |= (1 << DS18X20_STATUS_LED_PIN);  // Output

  // search for the available sensors.
  nSensors = search_sensors();
  // TODO: Use LED to signal errors, i.e. CRC errors.
  if (nSensors == 0)
    DS18X20_STATUS_LED_PORT |= (1 << DS18X20_STATUS_LED_PIN); // Disable
  else
    DS18X20_STATUS_LED_PORT &= ~(1 << DS18X20_STATUS_LED_PIN); // Enable


  // Print debugging header
  logs_P( "\r\nUSBtemp - temperature at your fingertips\r\n" );
  logs_P( "----------------------------------------\r\n" );
  logi((int) nSensors);
  logs_P( " DS18X20 Sensor(s) available:\r\n" );
  for (i=0; i<nSensors; i++) {
    logs_P("# in Bus :");
    logi((int) i+1);
    logs_P(" : ");
#ifdef DEBUG
    DS18X20_show_id_uart( &gSensorIDs[i][0], OW_ROMCODE_SIZE );
#endif
    logs_P( "\r\n" );
  }
  sync_read_sensors();
  print_readings();
  // main loop
  uint32_t delay_counter=0;
  enum read_state_t state=IDLE;
  for(;;) {
    //wdt_reset();
    usbPoll();
    delay_ms(MAIN_DELAY_MS); 
    delay_counter+=MAIN_DELAY_MS;
    // statemachine
    if (state == IDLE && delay_counter > READOUT_INTERVAL_MS) {
      // start measurement.
      async_start_read_sensors();
      delay_counter=0;
      state=MEASURING;
    }
    if (state==MEASURING && delay_counter > READOUT_WAIT_MS) {
      // Read the values from the sensors.
      async_finish_read_sensors();
      delay_counter = 0;
      state=UPDATED;
    }
    if (state==UPDATED) {
      // print temperature on uart.
      print_readings();
      delay_counter = 0;
      state=IDLE;
    }
  }
}
コード例 #14
0
int main(void) {

  uint8_t numSensors = 0, i;
  // unsigned long nextflash = 0;

  // Configure all pins as inputs with pullups initially
  DDRA = 0x00;
  PORTA = 0xff;
  DDRB = 0x00;
  PORTB = 0xff;

  // Serial output line
  DDRB |= _BV(PINB0);
  PORTB |= _BV(PINB0);

  // LED
  // DDRA |= _BV(PINA0);

  // Radio power is PA1
  PORTA &= ~_BV(PINA1);
  DDRA |= _BV(PINA1);

  // Onewire power is PA2
  PORTA &= ~_BV(PINA2);
  DDRA |= _BV(PINA2);

  myPutStr("Hello world\r\n");

  // Various power-saving things

  // Disable BOD while sleeping. I hope.
  MCUCR |= (_BV(BODS) | _BV(BODSE));
  MCUCR &= ~_BV(BODSE);
  MCUCR |= (_BV(BODS));
 
  // Disable the ADC
  ADCSRA &= ~_BV(ADEN);

  // Disable the Analog Comparator
  ACSR |= _BV(ACD);

  // Disable clocking of timer1 and ADC
  PRR |= (_BV(PRTIM1)|_BV(PRADC));

  timerInit();
  wdtInit();
  initInterrupts();


  // Power up the Onewire bus
  PORTA |= _BV(PINA2);
  while(numSensors == 0) {
    myPutStr("Scanning for sensors\r\n");
    numSensors = search_sensors();
    myPutStr("Found ");
    myPutUint8(numSensors);
    myPutStr(" sensors\r\n");

    for (i=0;i<numSensors;i++) {
      uint8_t j;
      myPutStr("Sensor ");
      myPutUint8(i);
      myPutStr(" address ");
      for (j=0;j<OW_ROMCODE_SIZE;j++) {
	myPutUint8(gSensorIDs[i][j]);
      }
      if (gSensorIDs[i][0] == DS18S20_FAMILY_CODE ) {
	myPutStr(" DS18S20/DS1820");
      } else if ( gSensorIDs[i][0] == DS1822_FAMILY_CODE ) {
	myPutStr(" DS1822");
      } else {
	myPutStr(" DS18B20");
      }
      if ( DS18X20_get_power_status( &gSensorIDs[i][0] ) == DS18X20_POWER_PARASITE ) {
	myPutStr(" parasite\r\n");
      } else {
	myPutStr(" external\r\n");
      }

      // Enable 12 bit mode (won't do anything on DS18S20)
      DS18X20_write_scratchpad(&gSensorIDs[i][0], 0, 0, DS18B20_12_BIT);
      DS18X20_scratchpad_to_eeprom(DS18X20_get_power_status( &gSensorIDs[i][0] ),&gSensorIDs[i][0]);
	
    }
      

  }
  while(1) {
    unsigned long wakepoint;
    myRadioBuf_t radiobuf;
    //char debugbuf[10];

    // if ((signed long)now - (signed long)nextflash >= 0) {
    //   debugLedToggle(0);
    //   nextflash = now + 1000;
    // }

    // Power up the Onewire bus
    PORTA |= _BV(PINA2);
    // Let is stabilize for a few ms
    wakepoint = getMillis() + 15;
    numSensors = search_sensors();
    while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
      set_sleep_mode(SLEEP_MODE_IDLE);
      sleep_mode();
    }
    if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL ) == DS18X20_OK) {
      wakepoint = getMillis() + DS18B20_TCONV_12BIT;
      while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
	set_sleep_mode(SLEEP_MODE_IDLE);
	sleep_mode();
      }
      // Power the radio up
      PORTA |= _BV(PINA1);
      // Wakepoint set to now +100ms to allow radio to wake
      wakepoint = getMillis() + 100;

      for ( i = 0; i < numSensors; i++ ) {
        radiobuf.tenthousandths = -9999999L;
	if (DS18X20_read_maxres( &gSensorIDs[i][0], &(radiobuf.tenthousandths) ) != DS18X20_OK) {
	  radiobuf.tenthousandths = -9999999L;
	}

	//myPutStr("Sensor ");
	uint8_t j;
	for (j=0;j<OW_ROMCODE_SIZE;j++) {
            radiobuf.sensid[j] = gSensorIDs[i][j];
	    //myPutUint8(gSensorIDs[i][j]);
        }
	//myPutStr(" = ");
	//sprintf(debugbuf, "%d.%d\r\n", (int)(radiobuf.tenthousandths/10000), (int)(radiobuf.tenthousandths % 10000));
	//myPutStr(debugbuf);
        if (0 == i) {
	  // First time around, radio not initialized
	  while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
            set_sleep_mode(SLEEP_MODE_IDLE);
            sleep_mode();
          }
	  radioInit();
	  // No auto ack
	  radioSetAutoAck(0);
	  radioOpenWritingPipe(pipe);
        }
	radiobuf.tstamp = getMillis();
	//myPutStr("about to radioWrite, i=");
	//myPutUint8(i);
	//myPutStr("...");
	radioWrite(&radiobuf,sizeof(radiobuf));
	//myPutStr("Done\r\n");
      }
      // Power the radio down
      PORTA &= ~_BV(PINA1);
      // Plus the CE and CSN pins
      PORTA &= ~_BV(PINA7);
      PORTB &= ~_BV(PINB2);
      // And the onewire bus
      PORTA &= ~_BV(PINA2);
    } else {
      myPutStr("Error measuring sensors\n");
    }
    //tmp = getMillis();
    //radioWrite(&tmp , sizeof(unsigned long) );
    // Sleep hard until WDT fires
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();
  }
}
コード例 #15
0
ファイル: main.c プロジェクト: Andy1978/Brautomat
int main( void )
{
    uint8_t nSensors, i;
    int16_t decicelsius;
    uint8_t error;

    uart_init((UART_BAUD_SELECT((BAUD),F_CPU)));

#ifndef OW_ONE_BUS
    ow_set_bus(&PINA,&PORTA,&DDRA,PA6);
#endif

    sei();

    uart_puts_P( NEWLINESTR "DS18X20 1-Wire-Reader Demo by Martin Thomas" NEWLINESTR );
    uart_puts_P(            "-------------------------------------------" );

    nSensors = search_sensors();
    uart_put_int( (int)nSensors );
    uart_puts_P( " DS18X20 Sensor(s) available:" NEWLINESTR );

#if DS18X20_VERBOSE
    for (i = 0; i < nSensors; i++ ) {
        uart_puts_P("# in Bus :");
        uart_put_int( (int)i + 1);
        uart_puts_P(" : ");
        DS18X20_show_id_uart( &gSensorIDs[i][0], OW_ROMCODE_SIZE );
        uart_puts_P( NEWLINESTR );
    }
#endif

    for ( i = 0; i < nSensors; i++ ) {
        uart_puts_P( "Sensor# " );
        uart_put_int( (int)i+1 );
        uart_puts_P( " is a " );
        if ( gSensorIDs[i][0] == DS18S20_FAMILY_CODE ) {
            uart_puts_P( "DS18S20/DS1820" );
        } else if ( gSensorIDs[i][0] == DS1822_FAMILY_CODE ) {
            uart_puts_P( "DS1822" );
        }
        else {
            uart_puts_P( "DS18B20" );
        }
        uart_puts_P( " which is " );
        if ( DS18X20_get_power_status( &gSensorIDs[i][0] ) == DS18X20_POWER_PARASITE ) {
            uart_puts_P( "parasite" );
        } else {
            uart_puts_P( "externally" );
        }
        uart_puts_P( " powered" NEWLINESTR );
    }

#if DS18X20_EEPROMSUPPORT
    if ( nSensors > 0 ) {
        eeprom_test();
    }
#endif

    if ( nSensors == 1 ) {
        uart_puts_P( NEWLINESTR "There is only one sensor "
                     "-> Demo of \"DS18X20_read_decicelsius_single\":" NEWLINESTR );
        i = gSensorIDs[0][0]; // family-code for conversion-routine
        DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL );
        _delay_ms( DS18B20_TCONV_12BIT );
        DS18X20_read_decicelsius_single( i, &decicelsius );
        uart_put_temp( decicelsius );
        uart_puts_P( NEWLINESTR );
    }


    for(;;) {   // main loop

        error = 0;

        if ( nSensors == 0 ) {
            error++;
        }

        uart_puts_P( NEWLINESTR "Convert_T and Read Sensor by Sensor (reverse order)" NEWLINESTR );
        for ( i = nSensors; i > 0; i-- ) {
            if ( DS18X20_start_meas( DS18X20_POWER_PARASITE,
                                     &gSensorIDs[i-1][0] ) == DS18X20_OK ) {
                _delay_ms( DS18B20_TCONV_12BIT );
                uart_puts_P( "Sensor# " );
                uart_put_int( (int) i );
                uart_puts_P(" = ");
                if ( DS18X20_read_decicelsius( &gSensorIDs[i-1][0], &decicelsius)
                        == DS18X20_OK ) {
                    uart_put_temp( decicelsius );
                } else {
                    uart_puts_P( "CRC Error (lost connection?)" );
                    error++;
                }
                uart_puts_P( NEWLINESTR );
            }
            else {
                uart_puts_P( "Start meas. failed (short circuit?)" );
                error++;
            }
        }

        uart_puts_P( NEWLINESTR "Convert_T for all Sensors and Read Sensor by Sensor" NEWLINESTR );
        if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL )
                == DS18X20_OK) {
            _delay_ms( DS18B20_TCONV_12BIT );
            for ( i = 0; i < nSensors; i++ ) {
                uart_puts_P( "Sensor# " );
                uart_put_int( (int)i + 1 );
                uart_puts_P(" = ");
                if ( DS18X20_read_decicelsius( &gSensorIDs[i][0], &decicelsius )
                        == DS18X20_OK ) {
                    uart_put_temp( decicelsius );
                }
                else {
                    uart_puts_P( "CRC Error (lost connection?)" );
                    error++;
                }
                uart_puts_P( NEWLINESTR );
            }
#if DS18X20_MAX_RESOLUTION
            int32_t temp_eminus4;
            for ( i = 0; i < nSensors; i++ ) {
                uart_puts_P( "Sensor# " );
                uart_put_int( i+1 );
                uart_puts_P(" = ");
                if ( DS18X20_read_maxres( &gSensorIDs[i][0], &temp_eminus4 )
                        == DS18X20_OK ) {
                    uart_put_temp_maxres( temp_eminus4 );
                }
                else {
                    uart_puts_P( "CRC Error (lost connection?)" );


                    error++;
                }
                uart_puts_P( NEWLINESTR );
            }
#endif
        }
        else {
            uart_puts_P( "Start meas. failed (short circuit?)" );
            error++;
        }


#if DS18X20_VERBOSE
        // all devices:
        uart_puts_P( NEWLINESTR "Verbose output" NEWLINESTR );
        DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL );
        _delay_ms( DS18B20_TCONV_12BIT );
        DS18X20_read_meas_all_verbose();
#endif

        if ( error ) {
            uart_puts_P( "*** problems - rescanning bus ..." );
            nSensors = search_sensors();
            uart_put_int( (int) nSensors );
            uart_puts_P( " DS18X20 Sensor(s) available" NEWLINESTR );
            error = 0;
        }

        _delay_ms(3000);
    }
}
コード例 #16
0
ファイル: tempsensors.c プロジェクト: C3MA/Aiolos
uint8_t initTempSensors(void) {
  printf("Searching for OneWire temperature sensors.\n" );
  nSensors = search_sensors();
  return nSensors;
}	
コード例 #17
0
int main(void)
{	
	
#if _EXT_EEPROM_EMPTY==1
	DDRB=0xFF;
	PORTB=0x00;
	
	i2cSetBitrate(100); //Ustaw prêdkoœæ i2c na 100kHz
	EXT_EEPROM_var *struktura_eeprom;
	struktura_eeprom=malloc(sizeof(EXT_EEPROM_var));
	strcpy(struktura_eeprom->empty,  "                ");
	strcpy(struktura_eeprom->temperatura, "Temperatura:    ");
	strcpy(struktura_eeprom->m1,  "Ustawienia      ");
	strcpy(struktura_eeprom->m10, "Data:           ");
	strcpy(struktura_eeprom->m11, "Godzina:        ");
	strcpy(struktura_eeprom->m12, "LCD:            ");
	strcpy(struktura_eeprom->eePCF_Sunday, "Niedziela");
	strcpy(struktura_eeprom->eePCF_Monday, "Poniedzialek");
	strcpy(struktura_eeprom->eePCF_Tuesday, "Wtorek");
	strcpy(struktura_eeprom->eePCF_Wednesday, "Sroda");
	strcpy(struktura_eeprom->eePCF_Thursday, "Czwartek");
	strcpy(struktura_eeprom->eePCF_Friday, "Piatek");
	strcpy(struktura_eeprom->eePCF_Saturday, "Sobota");
	strcpy(struktura_eeprom->eePCF_January, "Styczen");
	strcpy(struktura_eeprom->eePCF_February, "Luty");
	strcpy(struktura_eeprom->eePCF_March, "Marzec");
	strcpy(struktura_eeprom->eePCF_April, "Kwiecien");
	strcpy(struktura_eeprom->eePCF_May, "Maj");
	strcpy(struktura_eeprom->eePCF_June, "Czerwiec");
	strcpy(struktura_eeprom->eePCF_July, "Lipiec");
	strcpy(struktura_eeprom->eePCF_August, "Sierpien");
	strcpy(struktura_eeprom->eePCF_September, "Wrzesien");
	strcpy(struktura_eeprom->eePCF_October, "Pazdziernik");
	strcpy(struktura_eeprom->eePCF_November, "Listopad");
	strcpy(struktura_eeprom->eePCF_December, "Grudzien");
	PORTB=0x0F;
	
	EI2C_write_buf(ADDR_EEMEM_24C64, 0, sizeof(EXT_EEPROM_var), (uint8_t*)struktura_eeprom);
	free(struktura_eeprom);
	PORTB=0xFF;
#endif // _EXT_EEPROM_EMPTY

#if _EXT_EEPROM_EMPTY==0

	char bufor_lcd[41];	//Bufor przechowuj¹cy znaki z pamiêci EEPROM
	
	//Zmienne wykorzystywane w opóŸnieniach:
	uint8_t state=0;
	uint32_t cnt=0, offset_cnt=0;
	uint8_t state_light=0;
	uint32_t cnt_light=0, offset_cnt_light=0;
	
	Ustawienia ustawienia;	//Struktura s³u¿¹ca do odczytania ustawieñ z EEPROM
	ustawienia.ustawienia_poczatkowe=0;
	
	//Ustaw PORTB jak wyjœcie dla LED:
	DDRB=0xFF;
	PORTB=0x00;
	Flagi.flaga_klawiatura=1;
	
	//// ustawienia TIMER0, przerwanie co 10us
	OCR0 = 19;
	TCCR0 |= (1<<WGM01);		//Tryb ctc
	TCCR0 |= (1<<CS01);			// Preskaler 8
	TIMSK |= (1<<OCIE0);

	// Przerwanie INT0
	MCUCR |= (1<<ISC01);	// wyzwalanie zboczem opadaj¹cym
	GICR |= (1<<INT0);		// odblokowanie przerwania
	PORTD |= (1<<PD2);		// podci¹gniêcie pinu INT0 do VCC
	
	i2cSetBitrate(100); //Ustaw prêdkoœæ i2c na 100kHz
	lcd_init();
	pobierz_czas(&czas);
	pobierz_date(&data);

	/* sprawdzamy ile czujników DS18xxx widocznych jest na magistrali */
	czujniki_cnt = search_sensors();

	/* wysy³amy rozkaz wykonania pomiaru temperatury
	 * do wszystkich czujników na magistrali 1Wire
	 * zak³adaj¹c, ¿e zasilane s¹ w trybie NORMAL,
	 * gdyby by³ to tryb Parasite, nale¿a³oby u¿yæ
	 * jako pierwszego prarametru DS18X20_POWER_PARASITE */
	DS18X20_start_meas( DS18X20_POWER_EXTERN, NULL );
	
	/* czekamy 750ms na dokonanie konwersji przez pod³¹czone czujniki */
	_delay_ms(750);

	/* dokonujemy odczytu temperatury z pierwszego czujnika o ile zosta³ wykryty */
	/* wyœwietlamy temperaturê gdy czujnik wykryty */
	if( DS18X20_OK == DS18X20_read_meas(gSensorIDs[0], &subzero, &cel, &cel_fract_bits) ) display_temp(0);
	else {
		lcd_locate(0,0);
		lcd_str("term. error ");	/* wyœwietlamy informacjê o b³êdzie jeœli np brak czujnika lub b³¹d odczytu */
	}
	
#endif	 // _EXT_EEPROM_EMPTY
    while (1) 
    {	
#if _EXT_EEPROM_EMPTY==0
		eeprom_read_block(&ustawienia, &deafult_flags, sizeof(deafult_flags));
		if (ustawienia.ustawienia_poczatkowe)
		{
			eeprom_read_block(&data, &deafult_data, sizeof(data));
			eeprom_read_block(&czas, &deafult_czas, sizeof(czas));
			ustaw_date(&data);
			ustaw_czas(&czas);

			ustawienia.ustawienia_poczatkowe=0;
			eeprom_update_block(&ustawienia, &deafult_flags, sizeof(deafult_flags));
		}

		switch(state_light)
		{
			case 0:
				if (Flagi.light_lcd)
				{

					state_light=1;
					cli();
					cnt_light=200000;
					offset_cnt_light=licznik;
					sei();
					
				}
			break;
			case 1:
			if(cnt_light<=licznik-offset_cnt_light)
			{
				Flagi.light_lcd=0;
				state_light=0;
			}
			break;
		}
		lcd_light(Flagi.light_lcd);
		
		//OpóŸnienie dzia³añ po wciœniêciu przycisku
		switch(state)
		{
			case 0:
					key_code=debouncer(KlawiaturaSkan());
					if(key_code)
					{
						state=1;
						Flagi.light_lcd=1;	//W³¹cz podœwietlanie LCD
						cli();
						cnt=50000;
						offset_cnt=licznik;
						sei();
					}

					break;
			case 1:
					key_code=0;
					if(cnt<=licznik-offset_cnt)
					{
						state=0;
					}
					break;
		}
		
		if (Flagi.flaga_menu_func==1)
		{
			EI2C_read_buf(ADDR_EEMEM_24C64, menu_ptr->addr_ext_eeprom, menu_ptr->size_ext_eeprom, (uint8_t *)bufor_lcd);
			if(Flagi.flaga_lcd)
			{
				lcd_locate(0, 0);
			}

			(*menu_ptr->funkcja)(bufor_lcd);		//WskaŸnik na funkcje dla danej pozycji menu
		}

		if(Flagi.flaga_klawiatura==1)
		{	
			if (key_code == PRZYCISK_PRAWO)
			{
				if(menu_ptr->next!=NULL)
				{
					Flagi.flaga_lcd=1;
					menu_ptr=menu_ptr->next;
				}
			}
			else if (key_code == PRZYCISK_LEWO)
			{
				if(menu_ptr->prev!=NULL)
				{
					Flagi.flaga_lcd=1;
					menu_ptr=menu_ptr->prev;
				}
			}
			else if (key_code == PRZYCISK_DOL)
			{
				if(menu_ptr->down!=NULL)
				{
					Flagi.flaga_lcd=1;
					menu_ptr=menu_ptr->down;
				}
			}
			else if (key_code == PRZYCISK_GORA)
			{
				if(menu_ptr->up!=NULL)
				{
					Flagi.flaga_lcd=1;
					menu_ptr=menu_ptr->up;
				}
			}
		}
		
		if(menu_ptr->funkcja!=NULL)
			Flagi.flaga_menu_func=1;
		else
			Flagi.flaga_menu_func=0;

#endif  // _EXT_EEPROM_EMPTY
    }
}
コード例 #18
0
ファイル: main.c プロジェクト: turboaffe/watercooling
void handle_input(char* input)
{

    if (state == START)
    {
        if (strcmp("set fan\r", input) == 0)
        {
            print_usb("enter fan speed, 0...40 \n\r");

            /* advance state machine */
            state = SET_FAN;

        }
        else if (strcmp("set pump\r", input) == 0)
        {
            print_usb("enter pump speed, 0...200  \n\r");

            /* advance state machine */
            state = SET_PUMP;
        }
        else if (strcmp("set led\r", input) == 0)
        {
            print_usb("enter led brightness, 0...255  \n\r");

            /* advance state machine */
            state = SET_LED;
        }
        else if (strcmp("read temp\r", input) == 0)
        {
            print_usb("reading temp...  \n\r");

            /* advance state machine */
            state = READ_TEMP;
        }
        else
        {
            /* didnt understand string */
            print_usb("did not understand command \n\r");

            /* dont change state */
            state = START;
        }
    }
    else if (state == SET_LED)
    {
        static uint16_t pwm;
        char *garbage = NULL;
        pwm = strtol(input, &garbage, 0);
        OCR4A = pwm;

        print_usb("led set. \n\r");

        /* go back to start */
        state = START;
    }
    else if (state == SET_FAN)
    {
        static uint16_t pwm;
        char *garbage = NULL;
        pwm = strtol(input, &garbage, 0);
        OCR3A = pwm;

        print_usb("fan set. \n\r");

        /* go back to start */
        state = START;
    }
    else if (state == SET_PUMP)
    {
        static uint16_t pwm;
        char *garbage = NULL;
        pwm = strtol(input, &garbage, 0);
        OCR4B = pwm;

        print_usb("pump set. \n\r");

        /* go back to start */
        state = START;
    }
    else if (state == READ_TEMP)
    {
        uint8_t nSensors;

        char maxres_buffer[10];

        ow_set_bus(&PIND, &PORTD, &DDRD, PD4);

        ow_reset();

        /* search for temperature sensors */
        nSensors = search_sensors();

        /* classify sensors */
        classify_sensors(nSensors);

        /* measure temperature */
        measure_temp(nSensors, temp_eminus4);

        DS18X20_format_from_maxres(temp_eminus4[0], maxres_buffer, 10);

        print_usb("\n\r ");
        print_usb("temp max res 1: ");
        print_usb(maxres_buffer);
        print_usb("\n\r ");

        DS18X20_format_from_maxres(temp_eminus4[1], maxres_buffer, 10);

        print_usb("temp max res 2: ");
        print_usb(maxres_buffer);
        print_usb("\n\r ");

        /* go back to start */
        state = START;

    }
    else
    {
        CDC_Device_SendString(&USB_Interface, "went into unknown state!? \n\r");

        state = START;

    }

}