void UartGetStatus(char param)
{
	int8_t tbutton[12];
	int8_t buff[COMM_BUFFER_LEN];
	float xg,yg,zg,ltemp;

	xg = LIS3DSH_Get_X_Out(LIS3DSH_Sense_2g);
	yg = LIS3DSH_Get_Y_Out(LIS3DSH_Sense_2g);
	zg = LIS3DSH_Get_Z_Out(LIS3DSH_Sense_2g);

	if(button == FALSE)
	{
		sprintf(tbutton,"NotPressed");
	}
	else
	{
		sprintf(tbutton,"Pressed");
	}
	ltemp = GetTemp();

	sprintf(buff,"s,x:%.3f,y:%.3f,z:%.3f,b:%s,t:%.3f\n",xg,yg,zg,tbutton,ltemp);

	VCP_send_str(buff);

}
Пример #2
0
void sendStats( boolean isStart ) {
	uint8_t tt			= GetTemp();
	uint16_t starts		= eeprom_read_word(&eeprom_starts);
	uint8_t rid_low		= eeprom_read_byte((unsigned char *)(EEPROM_ROBOT_ID_LOW*2));
	uint8_t rid_high	= eeprom_read_byte((unsigned char *)(EEPROM_ROBOT_ID_HIGH*2));
	// RRS,VERSION,TEMP,STARTS,ROBOT_ID
	// RRS,4,60,3222,40,0,3		= version 4, TEMP = 60 somethings (not celsius or fahrenheits), starts 3222, robot_id_low = 40,  robot_id_high = 0, pcb_type = 3
	Serial.print("RRS,");
	Serial.print(B2_VERSION, DEC );
	Serial.print(",");
	Serial.print(tt, DEC);
	Serial.print(",");
	Serial.print(starts, DEC);
	Serial.print(",");
	Serial.print(rid_low, DEC);
	Serial.print(",");
	Serial.print(rid_high, DEC);
	Serial.print(",");
	Serial.print(pcb_type, DEC);			// pcb type
	Serial.println();
	if(isStart){
		starts++;
		eeprom_write_word(&eeprom_starts, starts);
	}
}
Пример #3
0
static void MakeBook() {
  int i;
  TempStruct tmpLast, tmp;
  BookStruct bk;

  tmpLast.dwZobristLock0 = tmpLast.dwZobristLock1 = 0;
  tmpLast.mv = tmpLast.vl = 0;
  for (i = 0; i < MakeBook2.nTempLen; i ++) {
    tmp = GetTemp(i);
    if (tmpLast < tmp) {
      if (tmpLast.vl >= MakeBook2.nRatio) {
        bk.dwZobristLock = tmpLast.dwZobristLock1;
        bk.wmv = tmpLast.mv;
        bk.wvl = tmpLast.vl / MakeBook2.nRatio;
        fwrite(&bk, sizeof(BookStruct), 1, MakeBook2.fpBookFile);
      }
      tmpLast = tmp;
    } else {
      tmpLast.vl += tmp.vl;
    }
  }
  if (tmpLast.vl >= MakeBook2.nRatio) {
    bk.dwZobristLock = tmpLast.dwZobristLock1;
    bk.wmv = tmpLast.mv;
    bk.wvl = tmpLast.vl / MakeBook2.nRatio;
    fwrite(&bk, sizeof(BookStruct), 1, MakeBook2.fpBookFile);
  }
}
Пример #4
0
main()
{ unsigned char i; 
  system_Ini();
    while(1)
   {	
	  GetTemp();

   	  /********以下将读18b20的数据送到LED数码管显示*************/
       LedNumVal=Temperature;      //把实际温度送到LedNumVal变量中
	  LedOut[0]=Disp_Tab[LedNumVal%10000/1000];
      LedOut[1]=Disp_Tab[LedNumVal%1000/100];
      LedOut[2]=Disp_Tab[LedNumVal%100/10];	 //十位
      LedOut[3]=Disp_Tab[LedNumVal%10];    //个位
  	  
    for(i=0; i<4; i++) 
	  {		
		 P0 = LedOut[i] ;
	  			 	 	  	
		switch(i)					  
         {	    	  //138译码
			case 0:LS138A=0; LS138B=0; LS138C=0; break;         
            case 1:LS138A=1; LS138B=0; LS138C=0; break;             	
            case 2:LS138A=0; LS138B=1; LS138C=0; break; 
            case 3:LS138A=1; LS138B=1; LS138C=0; break; 
         }
		 
		delay(100);
	  }

	  P0 = 0;  
  
    }
}
Пример #5
0
void ConvertDataValue(WIDATAITEM *UpdateData, TCHAR *Data)
{
	TCHAR str[MAX_DATA_LEN];

	// convert the unit
	if (mir_tstrcmp(Data, TranslateT("<Error>")) && mir_tstrcmp(Data, NODATA) && mir_tstrcmp(Data, TranslateTS(NODATA))) {
		// temperature
		if (!mir_tstrcmp(UpdateData->Name, _T("Temperature")) || !mir_tstrcmp(UpdateData->Name, _T("High")) ||
			!mir_tstrcmp(UpdateData->Name, _T("Low")) || !mir_tstrcmp(UpdateData->Name, _T("Feel")) ||
			!mir_tstrcmp(UpdateData->Name, _T("Dewpoint")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("C")) || !mir_tstrcmpi(UpdateData->Unit, _T("F")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("K"))) {
			GetTemp(Data, UpdateData->Unit, str);
			mir_tstrcpy(Data, str);
		}
		// pressure
		else if (!mir_tstrcmp(UpdateData->Name, _T("Pressure")) || !mir_tstrcmpi(UpdateData->Unit, _T("HPA")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("KPA")) || !mir_tstrcmpi(UpdateData->Unit, _T("MB")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("TORR")) || !mir_tstrcmpi(UpdateData->Unit, _T("IN")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("MM"))) {
			GetPressure(Data, UpdateData->Unit, str);
			mir_tstrcpy(Data, str);
		}
		// speed
		else if (!mir_tstrcmp(UpdateData->Name, _T("Wind Speed")) || !mir_tstrcmpi(UpdateData->Unit, _T("KM/H")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("M/S")) || !mir_tstrcmpi(UpdateData->Unit, _T("MPH")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("KNOTS"))) {
			GetSpeed(Data, UpdateData->Unit, str);
			mir_tstrcpy(Data, str);
		}
		// visibility
		else if (!mir_tstrcmp(UpdateData->Name, _T("Visibility")) || !mir_tstrcmpi(UpdateData->Unit, _T("KM")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("MILES"))) {
			GetDist(Data, UpdateData->Unit, str);
			mir_tstrcpy(Data, str);
		}
		// elevation
		else if (!mir_tstrcmp(UpdateData->Name, _T("Elevation")) || !mir_tstrcmpi(UpdateData->Unit, _T("FT")) ||
			!mir_tstrcmpi(UpdateData->Unit, _T("M"))) {
			GetElev(Data, UpdateData->Unit, str);
			mir_tstrcpy(Data, str);
		}
		// converting case for condition to the upper+lower format
		else if (!mir_tstrcmpi(UpdateData->Unit, _T("COND")))
			CaseConv(Data);
		// degree sign
		else if (!mir_tstrcmpi(UpdateData->Unit, _T("DEG"))) {
			if (!opt.DoNotAppendUnit) mir_tstrcat(Data, opt.DegreeSign);
		}
		// percent sign
		else if (!mir_tstrcmpi(UpdateData->Unit, _T("%"))) {
			if (!opt.DoNotAppendUnit) mir_tstrcat(Data, _T("%"));
		}
		// truncating strings for day/month to 2 or 3 characters
		else if (!mir_tstrcmpi(UpdateData->Unit, _T("DAY")) || !mir_tstrcmpi(UpdateData->Unit, _T("MONTH")))
			if (opt.dUnit > 1 && mir_tstrlen(Data) > opt.dUnit)
				Data[opt.dUnit] = '\0';
	}
}
Пример #6
0
void ConvertDataValue(WIDATAITEM *UpdateData, char *Data) 
{
	char str[MAX_DATA_LEN];

	// convert the unit
	if (strcmp(Data, Translate("<Error>")) && strcmp(Data, NODATA) && strcmp(Data, Translate(NODATA))) 
	{
		// temperature
		if (!strcmp(UpdateData->Name, "Temperature") || !strcmp(UpdateData->Name, "High") || 
			!strcmp(UpdateData->Name, "Low") || !strcmp(UpdateData->Name, "Feel") || 
			!strcmp(UpdateData->Name, "Dewpoint") ||
			!_stricmp(UpdateData->Unit, "C") || !_stricmp(UpdateData->Unit, "F") || 
			!_stricmp(UpdateData->Unit, "K"))
		{
			GetTemp(Data, UpdateData->Unit, str);
			strcpy(Data, str);
		}
		// pressure
		else if (!strcmp(UpdateData->Name, "Pressure") || !_stricmp(UpdateData->Unit, "HPA") || 
			!_stricmp(UpdateData->Unit, "KPA") || !_stricmp(UpdateData->Unit, "MB") ||
			!_stricmp(UpdateData->Unit, "TORR") || !_stricmp(UpdateData->Unit, "IN") || 
			!_stricmp(UpdateData->Unit, "MM"))
		{
			GetPressure(Data, UpdateData->Unit, str);
			strcpy(Data, str);
		}
		// speed
		else if (!strcmp(UpdateData->Name, "Wind Speed") || !_stricmp(UpdateData->Unit, "KM/H") || 
			!_stricmp(UpdateData->Unit, "M/S") || !_stricmp(UpdateData->Unit, "MPH") || 
			!_stricmp(UpdateData->Unit, "KNOTS"))
		{
			GetSpeed(Data, UpdateData->Unit, str);
			strcpy(Data, str);
		}
		// visibility
		else if (!strcmp(UpdateData->Name, "Visibility") || !_stricmp(UpdateData->Unit, "KM") || 
			!_stricmp(UpdateData->Unit, "MILES"))
		{
			GetDist(Data, UpdateData->Unit, str);
			strcpy(Data, str);
		}
		// converting case for condition to the upper+lower format
		else if (!_stricmp(UpdateData->Unit, "COND"))
			CaseConv(Data);
		// degree sign
		else if (!_stricmp(UpdateData->Unit, "DEG"))
		{
			if (!opt.DoNotAppendUnit) strcat(Data, opt.DegreeSign);
		}
		// percent sign
		else if (!_stricmp(UpdateData->Unit, "%"))
		{
			if (!opt.DoNotAppendUnit) strcat(Data, "%");
		}
		// truncating strings for day/month to 2 or 3 characters
		else if (!_stricmp(UpdateData->Unit, "DAY") || !_stricmp(UpdateData->Unit, "MONTH"))
			if (opt.dUnit > 1 && strlen(Data) > opt.dUnit)		Data[opt.dUnit] = '\0';
	}
}
Пример #7
0
int H101CryoControl::OnGetTemp(MM::PropertyBase* pProp, MM::ActionType eAct)
{
 if(eAct==MM::BeforeGet)
  {
   double temperature=0;
   if(GetTemp(temperature)==DEVICE_OK) pProp->Set(temperature);
  }
 return DEVICE_OK;     
}
Пример #8
0
bool ThermalManager::TripPoint::willTrip() {
    int32_t currentTemp = GetTemp(fThermalZoneRoot);
    bool wouldTrip = !fDisabled && currentTemp + fThreshold >= fPoint;

    if (wouldTrip) {
        SkDebugf("%s/%s would trip {%d,%d,%d,%d}\n", fThermalZoneRoot.c_str(),
                 fPointName.c_str(), fBase, currentTemp, fPoint, fThreshold);
    }
    return wouldTrip;
}
Пример #9
0
static void SortTemp(int low, int high) {
  TempStruct tmpMid, tmpSwap;
  int lowMid, highMid, nLen;

  nLen = high - low + 1;
  if (nLen > TEMP_BUFFER_SIZE) {
    lowMid = low;
    highMid = high;
    tmpMid = GetTemp((low + high) / 2);
    while (lowMid <= highMid) {
      while (lowMid < high && GetTemp(lowMid) < tmpMid) {
        lowMid ++;
      }
      while (low < highMid && tmpMid < GetTemp(highMid)) {
        highMid --;
      }
      if (lowMid <= highMid) {
        tmpSwap = GetTemp(lowMid);
        SetTemp(lowMid, GetTemp(highMid));
        SetTemp(highMid, tmpSwap);
        lowMid ++;
        highMid --;
      }
    }

    if (low < highMid) {
      SortTemp(low, highMid);
    }
    if (lowMid < high) {
      SortTemp(lowMid, high);
    }

  } else {
    ReadTemp(low, MakeBook2.TempBuffer, nLen);
    if (nLen > 1) {
      SortMem(0, nLen - 1);
    }
    WriteTemp(low, MakeBook2.TempBuffer, nLen);
  }
}
Пример #10
0
ThermalManager::TripPoint::TripPoint(SkString thermalZoneRoot, SkString pointName,
                                     int32_t threshold)
    : fThermalZoneRoot(thermalZoneRoot)
    , fPointName(pointName) {
    SkString fullPath(thermalZoneRoot);
    fullPath.appendf("/%s", pointName.c_str());
    fPoint = OpenFileAndReadInt32(fullPath.c_str());
    fBase = GetTemp(fThermalZoneRoot);
    fThreshold = threshold;
    fDisabled = fBase + fThreshold >= fPoint;  // We disable any trip point which start off
                                               // triggered
    if (!fDisabled) {
        SkDebugf("Trip point %s base - %d trip point-%d\n", fullPath.c_str(),
                 fBase, fPoint);
    }
}
Пример #11
0
int main(void)
{
        Setup_I2C();
	//SYSTEMConfigPerformance(SYSCLK);
	// Peripheral function that configures for best performance given the system's
	// clock frequency--this is for general practice.

	// This part is analogous to the void setup(){}; in Arduino.
	//TRISDCLR = 0x0100; 	// Set pin RD8 as an output, could be written as TRISD = 0xFEFF;
				// but takes more clock cycles to perform.
	//TRISESET = 0x0080;	// Set pin RE7 (PROG button) as an input, could be written as TRISE = 0x0080;
				// but takes more clock cycles to perform.

	// This part is analogous to the void loop(){}; in Arduino.
        //SDA = SCL = 0;
        //SCL_IN = SDA_IN = 0;
	Setup_MPU6050();
	Calibrate_Gyros();
        MPU6050_Test_I2C();
	while(1) 		// Loop forever...
	{

		// Reads the state of pin RE7, and latches RD8 accordingly.
		// Note that RE7 is normally set HIGH (3.3V) through an internal pull-up
		//	resistor and will actually be set LOW when the PROG button is pressed.
		// LATDbits.LATD8 = PORTEbits.RE7;
		//Get_Accel_Angles();

            //i2c_start();
           // i2c_tx(0x68);
            //i2c_start();    //ok
            //i2c_stop();
            //DelayMs(1000);
            //MPU6050_Test_I2C();
            Get_Accel_Values();
            Get_Accel_Angles();

            GetTemp();
	}

	return 0; // Included because main returns an int which is being expected.
} // Make sure the program ends in a new line
Пример #12
0
void Thermocycler::ControlPeltier() {
  Thermocycler::ThermalDirection newDirection = Thermocycler::ThermalDirection::OFF;
  if (iProgramState == ERunning || (iProgramState == EComplete && ipCurrentStep != NULL)) {
    // Check whether we are nearing target and should switch to PID control
    // float plateTemp = GetPlateTemp();
    /* Test: Use estimated sample temp instead or measured well temp */
    float plateTemp = GetTemp();
    if (iPlateControlMode == EBangBang && absf(iTargetPlateTemp - plateTemp) < PLATE_BANGBANG_THRESHOLD) {
      iPlateControlMode = EPIDPlate;
      iPlatePid.SetMode(AUTOMATIC);
      iPlatePid.ResetI();
    }

    // Apply control mode
    if (iPlateControlMode == EBangBang) {
      // Full drive
      iPeltierPwm = (iTargetPlateTemp > plateTemp) ? MAX_PELTIER_PWM : MIN_PELTIER_PWM;
    }
    iPlatePid.Compute();

    if (iDecreasing && iTargetPlateTemp > PLATE_PID_DEC_LOW_THRESHOLD) {
      if (iTargetPlateTemp < plateTemp) {
        iPlatePid.ResetI();
      }
      else {
        iDecreasing = false;
      }
    }

    if (iPeltierPwm > 0)
      newDirection = HEAT;
    else if (iPeltierPwm < 0)
      newDirection = COOL;
    else
      newDirection = OFF;
  }
  else {
    iPeltierPwm = 0;
  }
  iThermalDirection = newDirection;
  SetPeltier(newDirection, iPeltierPwm);
}
Пример #13
0
void *UpdateThread(void *idThread) {
  int   nSample;
  XClientMessageEvent  evt;

  while(1) {

    nSample = (nLastSample + 1)  % kMAXSAMPLES;

    if(GetTemp(fTemps + nSample))
      continue;

    if(fTemps[nSample] < fMinTemp)
      fMinTemp = fTemps[nSample];

    if(fTemps[nSample] > fMaxTemp)
      fMaxTemp = fTemps[nSample];

    nLastSample = nSample;
    if(nSamples < kMAXSAMPLES)
      nSamples++;

    memset(&evt, 0, sizeof(XClientMessageEvent));
    evt.type = ClientMessage;
    evt.window = win;
    evt.format = 32;
    evt.data.l[0] = 42;
    XSendEvent(dpy, win, 0, 0, (XEvent*)&evt);
    XFlush(dpy);

    if(nSleepSecs < 1)
      nSleepSecs = 1;

    sleep(nSleepSecs);
  }

  pthread_exit(NULL);
}
Пример #14
0
void CCape::Update( CCommand& commandIn )
{

    if( time.HasElapsed( 100 ) )
    {
        // subtract the last reading:
        total = total - readings[index];
        // read from the sensor:
        readings[index] = iout.Read();
        delay( 1 );
        // add the reading to the total:
        total = total + readings[index];
        // advance to the next position in the array:
        index = index + 1;

        // if we're at the end of the array...
        if( index >= numReadings )
            // ...wrap around to the beginning:
        {
            index = 0;
        }

        // calculate the average:
        average = total / numReadings;
    }

    // send voltage and current
    if( statustime.HasElapsed( 100 ) )
    {
        NDataManager::m_capeData.VOUT = mapf( vout.Read(), 0, 1023, 0, 50 );
        NDataManager::m_capeData.IOUT = mapf( average, 0, 1023, 0, 5 ) + .4;
        NDataManager::m_capeData.FMEM = FreeMemory();
        NDataManager::m_capeData.ATMP = GetTemp();
        NDataManager::m_capeData.UTIM = millis();
    }
}
Пример #15
0
// internal
boolean Thermocycler::Loop() {

  ipCommunicator->Process();
  unsigned long loopElapsedTimeMs = millis() - iPrevLoopStartTimeMs;
  iPrevLoopStartTimeMs = millis();

  switch (iProgramState) {
  case EStartup:
    iTempUpdated = false;
    if (millis() > STARTUP_DELAY) {
      iProgramState = EStopped;
      	iRestarted = false;
      if (!iRestarted && !ipCommunicator->CommandReceived()) {
        //check for stored program
        SCommand command;
        /*
        if (ProgramStore::RetrieveProgram(command, (char*)ipCommunicator->GetBuffer())) {
          ProcessCommand(command);
        }
        */
      }
    }
    break;

  case ELidWait:
    if (GetLidTemp() >= iTargetLidTemp - LID_START_TOLERANCE) {
      //lid has warmed, begin program
      iThermalDirection = OFF;
      iPeltierPwm = 0;
      PreprocessProgram();
      iProgramState = ERunning;

      ipProgram->BeginIteration();
      AdvanceToNextStep();

      iProgramStartTimeMs = millis();
    }
    break;

  case ERunning:
    //update program
    if (!iPaused) {
      if (iRamping) {
        // Increment ramping time
        iRampElapsedTimeMs += loopElapsedTimeMs;
      } else {
        // Increment holding time
        iCycleElapsedTimeMs += loopElapsedTimeMs;
      }
      if (iProgramState == ERunning) {
        if (!ipCurrentStep->IsFinal() && (iNextStepPending || iNextCyclePending)) {
          if (iNextStepPending) {
            iNextStepPending = false;
            AdvanceToNextStep();
          }
          if (iNextCyclePending) {
            iNextCyclePending = false;
            AdvanceToNextCycle();
          }
          //check for program completion
          if (ipCurrentStep == NULL || ipCurrentStep->IsFinal()) {
            iProgramState = EComplete;
          }
        } else if (iRamping && abs(ipCurrentStep->GetTemp() - GetTemp()) <= CYCLE_START_TOLERANCE && GetRampElapsedTimeMs() > ipCurrentStep->GetRampDurationS() * 1000) {
          //begin step hold
          //eta updates
          if (ipCurrentStep->GetRampDurationS() == 0) {
            //fast ramp
            iElapsedFastRampDegrees += absf(GetTemp() - iRampStartTemp);
            iTotalElapsedFastRampDurationMs += iRampElapsedTimeMs;
          }

          if (iRampStartTemp > GetTemp()) {
            iHasCooled = true;
          }
          iRamping = false;
          iCycleElapsedTimeMs = 0;
        }
        else if (!iRamping && !ipCurrentStep->IsFinal() && iCycleElapsedTimeMs > (unsigned long)ipCurrentStep->GetStepDurationS() * 1000) {
          //begin next step
          AdvanceToNextStep();
          //check for program completion
          if (ipCurrentStep == NULL || ipCurrentStep->IsFinal()) {
            iProgramState = EComplete;
          }
        }
      }
      break;

    case EComplete:
      PCR_DEBUG_LINE(ipCurrentStep->GetTemp());
      if (iRamping && ipCurrentStep != NULL && abs(ipCurrentStep->GetTemp() - GetTemp()) <= CYCLE_START_TOLERANCE) {
        iRamping = false;
      }
      break;
    }
  }

  statusBuff[statusIndex].timestamp = millis();
  //Read lid and well temp
  statusBuff[statusIndex].hardwareStatus = HARD_NO_ERROR;
  HardwareStatus result = iPlateThermistor.ReadTemp();
  if (result!=HARD_NO_ERROR) {
      statusBuff[statusIndex].hardwareStatus = result;
  }
  result = iLidThermistor.ReadTemp();
  if (result!=HARD_NO_ERROR) {
      statusBuff[statusIndex].hardwareStatus = result;
  }

  statusBuff[statusIndex].lidTemp = GetLidTemp();
  statusBuff[statusIndex].wellTemp = GetPlateTemp();

  float lidTemp = 0;
  float wellTemp = 0;

  CheckHardware(&lidTemp, &wellTemp);
  PCR_DEBUG("L=");
  PCR_DEBUG(lidTemp);
  PCR_DEBUG(" W=wellTemp");
  PCR_DEBUG_LINE(wellTemp);

  iLidThermistor.setTemp(lidTemp);
  iPlateThermistor.setTemp(wellTemp);

  double estimatedAirTemp = wellTemp * 0.4 + lidTemp * 0.6;
  // Estimated delta to next 1 sec
  double diff = ((wellTemp - iEstimatedSampleTemp)/THETA_WELL + (estimatedAirTemp-iEstimatedSampleTemp)/THETA_LID ) / CAPACITY_TUBE;

  if (!iTempUpdated) {
    iTempUpdated = true;
    iEstimatedSampleTemp = estimatedAirTemp;
  } else if ( 5>diff && diff > -5) {
    iEstimatedSampleTemp += diff;
  }

  CalcPlateTarget();

  // Check error
  //if (iHardwareStatus==HARD_NO_ERROR || true) { //TODO WELL_TEST (dummy line)
  if (iHardwareStatus==HARD_NO_ERROR) { //TODO WELL_TEST
      ControlLid();
      ControlPeltier();
      if (iHardwareStatus!=HARD_NO_ERROR) {
        PCR_DEBUG("ERR=");
        PCR_DEBUG_LINE(iHardwareStatus);
      }
  } else {
      PCR_DEBUG_LINE("ALL OFF");
      iProgramState = EError;
      SetPeltier(OFF, 0);
      SetLidOutput(0);
  }

  //program
  UpdateEta();
 #ifdef USE_LCD
  ipDisplay->Update();
 #endif
  statusIndex = (statusIndex+1) % CyclerStatusBuffSize;
  statusCount++;
  return true;
}
Пример #16
0
double MacroXS(long rea0, double E, long id)
{
  long i, ptr, rea, erg, ne, mat, nuc, ncol, mt;
  double xs0, xs1, xs, adens, f, mult, Emin, Emax, Er, T;
  
  /* Check Pointer */

  CheckPointer(FUNCTION_NAME, "(rea0)", DATA_ARRAY, rea0);

  /* Get mt */
  
  mt = (long)RDB[rea0 + REACTION_MT];
  CheckValue(FUNCTION_NAME, "mt", "", mt, -30, -1);

  /* Get pointer to material */
      
  mat = (long)RDB[rea0 + REACTION_PTR_MAT];
  CheckPointer(FUNCTION_NAME, "(mat)", DATA_ARRAY, mat);

  /* Get pointer to data */

  if ((ptr = (long)RDB[rea0 + REACTION_PTR_XS]) > VALID_PTR)
    {
      /***********************************************************************/

      /***** Interpolate pre-calculated data *********************************/

#ifdef DEBUG

      /* Sanity check for TMS */

      if (((long)RDB[mat + MATERIAL_TMS_MODE] == TMS_MODE_MG) ||
	  (((long)RDB[mat + MATERIAL_TMS_MODE] == TMS_MODE_CE) &&
	   (mt != MT_MACRO_TMP_MAJORANTXS)))
	Die(FUNCTION_NAME, "Pre-calculated data in %s %ld", 
	    GetText(mat + MATERIAL_PTR_NAME), mt);

#endif

      /* Test existing data (ei voi käyttää TMS:n kanssa) */

      if ((xs = TestValuePair(rea0 + REACTION_PTR_PREV_XS, E, id)) > -INFTY)
	return xs;
      
      /* Get pointer to energy grid */

      erg = (long)RDB[rea0 + REACTION_PTR_EGRID];
      CheckPointer(FUNCTION_NAME, "(erg)", DATA_ARRAY, erg);

      /* Get interpolation factor */

      if ((f = GridFactor(erg, E, id)) < 0)
	xs = 0.0;
      else
	{
	  /* Check interpolation factor */

	  CheckValue(FUNCTION_NAME, "f", "", f, 0.0, MAX_EGRID_NE);

	  /* Separate integer and decimal parts of interpolation factor */
      
	  i = (long)f;
	  f = f - (double)i;
      
	  /* Get number of points */
      
	  ne = (long)RDB[rea0 + REACTION_XS_NE];
	  CheckValue(FUNCTION_NAME, "ne", "", ne, 2, MAX_EGRID_NE);
      
	  /* Check boundaries */
	  
	  if ((i < 0) || (i > ne - 1))
	    xs = 0.0;
	  else
	    {      
	      /* Get tabulated cross sections */
	  
	      xs0 = RDB[ptr + i];
	      xs1 = RDB[ptr + i + 1];

	      if (mt != MT_MACRO_TMP_MAJORANTXS) 
		{	      		
		  /* Interpolate in normal case */
		  
		  if (i == ne - 1)
		    xs = (1.0 - f)*xs0;
		  else
		    xs = f*(xs1 - xs0) + xs0;
		}
	      else 
		{     		
		  /* TMS-tapauksessa majoranttia ei interpoloida */
		  /* (histogrammimajorantti) */
		  
		  xs = xs0;
		}
      	    }
	}

      /* Add poison cross section */
      
      if (((long)RDB[DATA_XENON_EQUILIBRIUM_MODE] == YES) ||
	  ((long)RDB[DATA_SAMARIUM_EQUILIBRIUM_MODE] == YES))
	if ((mt == MT_MACRO_TOTXS) || (mt == MT_MACRO_ABSXS))
	  xs = xs + PoisonXS(mat, E, mt, id);
      
      /* Perform ures correction */

      xs = MacroUresCorr(rea0, xs, E, id);

      /* Store value */

      StoreValuePair(rea0 + REACTION_PTR_PREV_XS, E, xs, id);

      /* Return value */
      
      return xs;

      /***********************************************************************/
    }
  else if (((long)RDB[mat + MATERIAL_TMS_MODE] != TMS_MODE_NONE) &&
	   (mt != MT_MACRO_TMP_MAJORANTXS))
    {
      /***********************************************************************/
      
      /***** TMS-moodi ******************************************************/

#ifdef DEBUG

      /* Sanity check for TMS */

      if ((RDB[mat + MATERIAL_TMS_TMIN] == 0.0) || 
	  (RDB[mat + MATERIAL_TMS_TMIN] > RDB[mat + MATERIAL_TMS_TMAX]))
	Die(FUNCTION_NAME, "Error in temperature in %s", 
	    GetText(mat + MATERIAL_PTR_NAME));

#endif

      /* Get collision number */

      ptr = (long)RDB[DATA_PTR_COLLISION_COUNT];
      ncol = (long)GetPrivateData(ptr, id);

      /* Test existing data (HUOM! ncol, koska lämpötila voi olla eri) */
      
      if ((xs = TestValuePair(rea0 + REACTION_PTR_PREV_XS, ncol, id)) > -INFTY)
	return xs;
      
      /* Reset cross section */

      xs = 0.0;
   
      /* Get material temperature for on-the-fly temperature treatment */

      if ((T = GetTemp(mat, id)) > 0.0)
	{
	  /* Get pointer to partial list */

	  ptr = (long)RDB[rea0 + REACTION_PTR_PARTIAL_LIST];
	  CheckPointer(FUNCTION_NAME, "(ptr)", DATA_ARRAY, ptr);

	  /* Reset reaction pointer (rewind list) */
	  
	  rea = -1;

	  /* Loop over reactions */
	  
	  while (NextReaction(ptr, &rea, &adens, &Emin, &Emax, id) > VALID_PTR)
	    {
	      /* Check reaction pointer */
	      
	      CheckPointer(FUNCTION_NAME, "(rea)", DATA_ARRAY, rea);
	      
	      /* get multiplier */
	      
	      mult = ReaMulti(rea, mt, E, id);

	      /* Pointer to nuclide */

	      nuc = (long)RDB[rea + REACTION_PTR_NUCLIDE];
	      CheckPointer(FUNCTION_NAME, "(nuc)", DATA_ARRAY, nuc);
		
	      /* Add to cross section */
	  
	      xs = xs + mult*adens*DopMicroXS(mat, rea, E, &Er, T, id);
	  
	      /* Check energy cut-off */
	      
	      if (E < Emin)
		break;
	    }
	  
	  /* Store cross section */

	  StoreValuePair(rea0 + REACTION_PTR_PREV_XS, ncol, xs, id);

	  /* Return interpolated value */
	  
	  return xs;
	}

      /***********************************************************************/
    }

  /***************************************************************************/
  
  /***** Calculate sum of partials *******************************************/

  /* Test existing data */

  if ((xs = TestValuePair(rea0 + REACTION_PTR_PREV_XS, E, id)) > -INFTY)
    return xs;

  /* Reset cross section */
  
  xs = 0.0;
  
  /* Get pointer to partial list */
  
  ptr = (long)RDB[rea0 + REACTION_PTR_PARTIAL_LIST];
  CheckPointer(FUNCTION_NAME, "(ptr)", DATA_ARRAY, ptr);

  /* Reset reaction pointer (rewind list) */
  
  rea = -1;
  
  /* Loop over reactions */

  while (NextReaction(ptr, &rea, &adens, &Emin, &Emax, id) > VALID_PTR)
    {
      /* Check reaction pointer */

      CheckPointer(FUNCTION_NAME, "(rea)", DATA_ARRAY, rea);

      /* Get multiplier */

      mult = ReaMulti(rea, mt, E, id);

      /* Add to cross section */

      if (mt != MT_MACRO_TMP_MAJORANTXS)
	xs = xs + mult*adens*MicroXS(rea, E, id);

      /* In case of majorantxs, use MicroMajorantXS */

      else
	xs = xs + mult*adens*MicroMajorantXS(rea, E, id);
            
      /* Check energy cut-off */
      
      if (E < Emin)
	break;
    }

  /* Store cross section */

  StoreValuePair(rea0 + REACTION_PTR_PREV_XS, E, xs, id);

  /* Return value */

  return xs;
  
  /****************************************************************************/
}
Пример #17
0
void loop() {
	// try to get client
	EthernetClient client = server.available();
	String getStr;
	
	if (client) {
		digitalWrite(greLed,HIGH);
		boolean currentLineIsBlank = true;
		boolean indice = false;
		while (client.connected()) {
			if (client.available()) {	// client data available to read
				char c = client.read();	// read 1 byte (character) from client
				// filter GET request
				// GET /index.html HTTP/1.1
				if (c == 'G') {
					c = client.read();
					if (c == 'E') {
						c = client.read();
						if (c == 'T') {
							Serial.print("GET=");
							c = client.read(); // space
							while (true) {
								c = client.read();
								if (c == ' ') {
									break;
								}
								//Serial.println(c);
								getRequest[getIndi] = c;
								getIndi++;
							}
							Serial.print(getRequest);
							Serial.println("@");
						}
					}
				}
				if (c == '\n' && currentLineIsBlank) {
					// convert to string and clear char array
					String getStr(getRequest);
					Clear();

					// if check
					// first page
					if (getStr == "/" || getStr == "/index.html") {
						indice = true;
					}

					// ajax GET info
					else if (getStr.startsWith("/Set?")) {
						indice = true;
						int getRequestStart = getStr.indexOf('?' );
						int getRequestFirst = getStr.indexOf('=' );
						int getRequestFinal = getStr.indexOf('/',2);
						int getRequestDuall = getStr.indexOf('&' );	// 2 GET
						if (getRequestDuall>0) {	// /index.html?X=20&Y=30
							int getRequestSecon = getStr.indexOf('=', getRequestFirst+1);
							String inputFirst_1 = getStr.substring(getRequestStart+1, getRequestFirst);	// X
							String valueFirst_1 = getStr.substring(getRequestFirst+1, getRequestDuall);	// 20
							String inputFirst_2 = getStr.substring(getRequestDuall+1, getRequestSecon);	// Y
							String valueFirst_2 = getStr.substring(getRequestSecon+1, getRequestFinal);	// 30
							if (inputFirst_1 == "X") {
								Update('X',valueFirst_1.toInt());
								Update('Y',valueFirst_2.toInt());
							}
							// reverse
							else if (inputFirst_1 == "Y") {
								Update('Y',valueFirst_1.toInt());
								Update('X',valueFirst_2.toInt());
							}
						}
						else {						// /index.html?Y=50 or X=50
							String inputFirst = getStr.substring(getRequestStart+1, getRequestFirst);	// Y
							String valueFirst = getStr.substring(getRequestFirst+1, getRequestFinal);	// 50
							if (inputFirst == "X") {
								Update('X',valueFirst.toInt());
							}
							else if (inputFirst == "Y") {
								Update('Y',valueFirst.toInt());
							}
						}
					}

					//ajax SAVE info
					else if (getStr.startsWith("/Save/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("SAVE");
						Serial.println("");
						SD.remove(LOG);
						dataFile = SD.open(LOG, FILE_WRITE);
						if(dataFile) {				// X=123-Y=45-
							dataFile.print("X=");
							dataFile.print(X);
							dataFile.print("-Y=");
							dataFile.print(Y);
							dataFile.print("-");
							dataFile.close();
						}
						digitalWrite(redLed,LOW);
					}

					//ajax RESET info
					else if (getStr.startsWith("/Reset/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("RESET");
						Serial.println("");
						delay(1);
						servoX.detach();
						servoY.detach();
						digitalWrite(redLed,LOW);
						digitalWrite(resetPin, LOW);
					}
					// ajax SET info
					else if (getStr.startsWith("/Coordinate/")) {
						digitalWrite(redLed,HIGH);
						GetValue();
						double temp = analogRead(thermRes);
						int phot = analogRead(photoRes);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						client.println();
						// JSON
						client.print("{\"coordinate\":{\"X\":");
						client.print(X);
						client.print(",\"Y\":");
						client.print(Y);
						client.print("},\"temp\":");
						client.print(GetTemp(temp),1);
						client.print(",\"light\":");
						client.print(phot);
						client.print(",\"network\":\"");
						client.print(Ethernet.localIP());
						client.print("\",\"file\":[");
						for (int i=0; i<HTTP_FILE; i++) {
							File dFile = SD.open(GET[i]);
							if (dFile) {
								if(i>0) {
									client.print(",");
								}
								client.print("{");
								client.print("\"name\":\"");
								client.print(GET[i]);
								client.print("\",\"size\":");
								client.print(dFile.size());
								client.print("}");
							}
						}
						client.println("]}");
						digitalWrite(redLed,LOW);
					}

					// print other file
					else {
						for(int i=1; i<HTTP_FILE; i++) {
							if (getStr == TYP[0][i]) {
								webFile = SD.open(GET[i]);
								if (webFile) {
									client.println("HTTP/1.1 200 OK");
									client.println(TYP[1][i]);
									if(TYP[2][i] == "1") {
										client.println("Content-Encoding: gzip");
									}
									client.print("Content-Length: ");
									client.println(webFile.size());
									client.println("Cache-Control: max-age=302400, public");
									client.println("Connection: close");
									client.println();
								}
								break;
							}
						}
					}
					// endif check

					// print index.html
					if (indice) {
						webFile = SD.open(GET[0]);
						if (webFile) {
							client.println("HTTP/1.1 200 OK");
							client.println(TYP[1][0]);
							client.print("Content-Length: ");
							client.println(webFile.size());
							client.println("Connection: close");
							client.println();
						}
					}
					// read file and write into web client
					if (webFile) {
						while(webFile.available()) {
							client.write(webFile.read());
						}
						webFile.close();
					}
					
					break;
				}

				if (c == '\n') {
					// last character on line of received text. Starting new line with next character read
					currentLineIsBlank = true;
				} 
				else if (c != '\r') {
					// you've gotten a character on the current line
					currentLineIsBlank = false;
				}
			}
		}
		//delay(1);		// give the web browser time to receive the data
		client.stop();	// close the connection
		digitalWrite(greLed,LOW);
	}
}
Пример #18
0
void DS1820Sensor::PrintTemp(void)
{
  long temp = GetTemp() / 1000000;
  Serial.print(temp);
}
Пример #19
0
void loop() {
 delay(100);
 temp = GetTemp();
}
Пример #20
0
int main (void)
{ 
    uint8_t setpoint = 0;	/* setpoint in degrees centigrade */
    uint8_t tempc = 0; 		/* temp reading in centigrade */
    
    DDRA = 0;
    DDRB = _BV(4);                 // Set line B4 to be an output, the rest are inputs.
    DDRD = 0;
    
    // Pull-ups on inputs:
    PORTA = InputMaskA;
    PORTB = InputMaskB;
    PORTD = InputMaskD; 
    

    /* We're not really usingthe timer but we'll keep it running... */
    CLKPR = (1 << CLKPCE);        // enable clock prescaler update
    CLKPR = 0;                    // set clock to maximum
    WDTCSR = 0x00;                // disable watchdog timer
    // Set up the timer interrupt:
    TCCR0A = 2;
    OCR0A = 128;
    TIFR = (1 << TOV0);           // clear interrupt flag
    TIMSK = (1 << OCIE0A);         // enable compare interrupt
    TCCR0B = (1 << CS01);         // start timer, prescale by 8

    /* set up the uart for serial debugging; baud rate and sys clock
     are set in UART.c. TX and RX are on X10 and X60 (PD0 PD1)
     switches, keep them OFF. UART rate set in */
    UART_Init();



    /* set up the bit-banged I2C channel to get temp readings, SDA and SCL
     pin assignments are in I2Cbang.c*/
    I2C_Init();

    // Pull-ups on inputs:
    PORTA = 0x03;
    DDRA &= ~(0x03);
    
    /* Sneaky here, in order to reduce wiring, power TC74 from VDD on
     PB3 and GND on PB1. SCLK is PB2 and SDAT is PB0, but those are
     set in i2cbang.c  Also drive PB7, PB6, PB5*/


    DDRB |=  0b11101010;
    PORTB |= 0b00001000;
    PORTB &= 0b11111101;
    //PORTB = InputMaskB;
    PORTD = InputMaskD; 

    sei();		// ENABLE global interrupts


    putstr("Therm 1.0\r\n");

    TurnCoilOff();

    /* like making waffles, throw the first batch away */
    GetTemp();
    _delay_ms(10);		

    GetTemp();
    _delay_ms(10);		


    /* preload the average buffer with the current temp */
    InitBuffer(GetTemp());
         
    for (;;) {  // main loop
        
      setpoint = GetSetPointFromDIP();

      tempc = GetTemp();

      putstr("\r\nsp: ");
      putU8(setpoint);


      putstr(" tc: ");
      putU8(tempc);
      /* add temp to running average, and get the average back */
      tempc = BufferTemp(tempc);
      putstr(" bt: ");
      putU8(tempc);

      putstr(" trig: ");
      putU8((uint8_t)IS_TRIGGERED);


      /* TRIGGER IN is thermostat override switch on PD6*/
      if ((tempc > setpoint) || IS_TRIGGERED) {
	TurnCoilOn();
      }
      else if (tempc <= setpoint - HYSTERESIS) {
	TurnCoilOff();
      }

      /* wait this many milliseconds */
      _delay_ms(500);		



    }
    return 0;
}
Пример #21
0
//センサからデータを取得
void* SensorDataThread(void *param)
{
	sigset_t	ss;
	siginfo_t	sig;
	struct timespec timeOut;
	int sigNo;
	int oldOutputMode = MODE_CLOCK;
	unsigned int i;
	const unsigned int dpSleepTime = 100000;

	//log用
	time_t 		t;
	struct tm 	*ts;
	char		dateBuf[20];

	//シグナルのタイムアウト
	timeOut.tv_sec = g_dataInterval;
	timeOut.tv_nsec = 0;
	if( SetSignalBlock(&ss) == -1 )
		pthread_exit(NULL);

	//スレッドを高優先に
	SetPriority(HIGH_PRIO);

	do{
		if( sigNo == THREAD_MSG_EXIT )
		{
			MySysLog(LOG_DEBUG, "Data Thread exit signal\n");
			break;
		}
		//センサー間隔が1分以上はセンサー実行時アニメーションモードにする
		if( g_dataInterval >= 60 )
		{
			oldOutputMode	= g_outputMode;
			g_outputMode	= MODE_ANI_0;
		}

		//DPの桁

		//sensorが何かで止まるので個別にログを取ってどこで止まるか確認
		//log用の時間
		t  = time(NULL);
		ts = localtime(&t);
		//strftime(dateBuf, sizeof(dateBuf), "%F %T", ts);
		strftime(dateBuf, sizeof(dateBuf), "%T", ts);
		SensorLogPrintf(SENSOR_LOG_LEVEL_0, 	"%s\t",		dateBuf);		//時刻

		i = 0;
		//Lps331をone shotモードでたたき起こす
			//SetDP(i++, DP_ON);
			usleep(dpSleepTime);
			WakeUpLps331();

		//外気温
			//SetDP(i++, DP_ON);
			usleep(dpSleepTime);
			g_temp	= GetTemp();
			SensorLogPrintf(SENSOR_LOG_LEVEL_0, 	"%.1f\t", 	g_temp);		//外気温

		//気圧
			//SetDP(i++, DP_ON);
			usleep(dpSleepTime);
			g_press	= GetPress();

			SensorLogPrintf(SENSOR_LOG_LEVEL_0, 	"%.1f\t",	g_press);		//大気圧

		//照度
			//SetDP(i++, DP_ON);
			usleep(dpSleepTime);
			//g_lux   = GetLuxOhm(100e+3); //100kohm
			g_lux	= GetLux();
			Set7segLightControl(g_lux);
			if( g_lux < 1 )
				SensorLogPrintf(SENSOR_LOG_LEVEL_0, "%.4f\t", 	g_lux);			//照度
			else
				SensorLogPrintf(SENSOR_LOG_LEVEL_0, "%.1f\t", 	g_lux);			//照度

		//湿度
			g_hum	= GetHumidity();
			SensorLogPrintf(SENSOR_LOG_LEVEL_0, 	"%.1f\t",	g_hum);			//湿度


		//CPU温度
			g_coreTemp = GetCoreTemp();
			SensorLogPrintf(SENSOR_LOG_LEVEL_0, 	"%.1f\n",	g_coreTemp);	//CPU温度


		usleep(dpSleepTime);
		//for( i=0; i<SEG_COUNT; i++)
		//	SetDP(i, DP_OFF);
			//g_dispData[i] &= ~(SEG_DP);


		////正常にデータ取得後データの保存
		//SensorLog();


		//モードを元に戻す
		if( g_dataInterval >= 60 )
			g_outputMode = oldOutputMode;

		//残り時間用に現在の時間の取得
		clock_gettime(CLOCK_MONOTONIC, &g_waitLog);

		sigNo = sigtimedwait( &ss, &sig, &timeOut);
		//何らかの形でシグナルが来なかった時の保険
		if( g_threadStatus == 0 )
			break;
	}while( 1 );

	SetPriority(NOMAL_PRIO);

	g_threadStatus = 0;

	pthread_exit(NULL);
}
Пример #22
0
int main(int argc, char **argv) {
  pthread_t   tidUpdate;
  int         nFlag, nQuit=0, c;
  KeySym      key;
  char        str[kSTRMAX];

  opterr = 0;
     
  while ((c = getopt (argc, argv, "hl:w:r:")) != -1) {
    switch (c) {

    case 'h':
      Usage();
      return 0;

    case 'l':
      fTempLimit = atof(optarg);
      break;
	
    case 'w':
      fTempWarn = atof(optarg);
      break;

    case 'r':
      nSleepSecs = atoi(optarg);
      break;

    case '?':
      if (optopt == 'l' || optopt == 'w' || optopt == 'r')
	fprintf (stderr, "Option -%c requires an argument.\n", optopt);
      else if (isprint (optopt))
	fprintf (stderr, "Unknown option `-%c'.\n", optopt);
      else
	fprintf (stderr,
		 "Unknown option character `\\x%x'.\n",
		 optopt);
      return 1;

    default:
      abort ();
    }
  }
  
  XInitThreads();

  if(InitX()) {
    return 1;
  } if(GetConstants()) {
    return 2;
  } if(pthread_create(&tidUpdate, NULL, &UpdateThread, NULL)) {
    fprintf(stderr, "ERROR: Can't create update thread.\n");
    return 3;
  }

  float fTemp;
  GetTemp(&fTemp);
  printf("Current Temp = %.1f\n", fTemp);

  while(1) {
    XEvent e;
    XNextEvent(dpy, &e);

    nFlag = 0;
    switch(e.type) {

    case Expose:
      nFlag = 1;
      break;

    case ClientMessage:
      
      if(e.xclient.data.l[0] == 42) {
	nFlag = 1;
      } else if(e.xclient.data.l[0] == wmDeleteMessage) {
	XDestroyWindow(dpy, e.xclient.window);
	nQuit = 1;
      }
      break;

    case KeyPress:
      if(XLookupString(&e.xkey, str, kSTRMAX-1, &key, 0)==1) {
	if(str[0] == 'q' || str[0] == 'Q') {
	  XDestroyWindow(dpy, win);
	  nQuit = 1;
	}
      }
      break;

    case ConfigureNotify:
      break;
    
    }

    if(nQuit)
      break;

    if(nFlag) {

      int rc = Redraw();
      if(rc) {
	fprintf(stderr, "ERROR: Redraw() returned %d\n", rc);
	break;
      }
    }
  }

  XCloseDisplay(dpy);
  pthread_kill(tidUpdate, 1);
  pthread_exit(NULL);
}