示例#1
0
文件: main.cpp 项目: rootming/AutoCar
int main()
{
    UltraSonic us;
    Motor motor(0, 255);
    LED led(100, 255);
    Brightness bg;
    Temperature temp;
    led.setPin(4);
    led.on();
    sleep(1);
    led.off();
    us.setPin(0, 1);
    us.autoScan();
    motor.setPin(2, 3, 22, 23, 24, 25);
    motor.setLeftSpeed(-100);
    motor.setRightSpeed(100);
    sleep(2);
    motor.setLeftSpeed(100);
    motor.setRightSpeed(-100);
    sleep(2);

    for(int i = 0; i < 5; i++){
        cout << us.getDistance() << endl;
        cout << bg.getValue() << endl;
        cout << temp.getValue() << endl;
        sleep(1);
    }
    cin.get();
    return 0;
}
示例#2
0
int main(){
    
	char unit;
	double temp;
	char ans;
	Temperature T;

	do{
	cout << "Please enter the temperature unit (Celsius = C, Kelvin = K, Fahrenheit = F): " << endl;
	cin >> unit;
	cout << "Please enter the temperature given the unit you entered previously: " << endl;
	cin>>temp;
	if (unit == 'C' || unit == 'c')
	{T.setTempCelsius(temp);}
	if (unit == 'F' || unit == 'F')
	{T.setTempFahrenheit(temp);}
	if (unit == 'K' || unit == 'K')
	{T.setTempKelvin(temp);}
	
	T.ShowResult();
	cout << "Re-calculate?" <<endl;
	cin>>ans;
	}while(ans=='Y'|| ans =='y');
	

}
示例#3
0
TemperatureStatus DomainTemperature_002::getTemperatureStatus(UIntN participantIndex, UIntN domainIndex)
{
    try
    {
        Temperature temperature = getParticipantServices()->primitiveExecuteGetAsTemperatureTenthK(
            esif_primitive_type::GET_TEMPERATURE, domainIndex);

        if (!temperature.isValid())
        {
            getParticipantServices()->writeMessageWarning(
                ParticipantMessage(FLF, "Last set temperature for virtual sensor is invalid."));
            return TemperatureStatus(Temperature::minValidTemperature);
        }

        return TemperatureStatus(temperature);
    }
    catch (primitive_destination_unavailable)
    {
        return TemperatureStatus(Temperature::minValidTemperature);
    }
    catch (dptf_exception& ex)
    {
        getParticipantServices()->writeMessageWarning(ParticipantMessage(FLF, ex.what()));
        return TemperatureStatus(Temperature::minValidTemperature);
    }
}
void ParticipantGetSpecificInfo_001::RequestPrimitiveTemperatureAndAddToMap(esif_primitive_type primitive,
    ParticipantSpecificInfoKey::Type key, std::map<ParticipantSpecificInfoKey::Type, UIntN>& resultMap,
    UIntN instance)
{
    try
    {
        Temperature temp = m_participantServicesInterface->primitiveExecuteGetAsTemperatureC(primitive,
            Constants::Esif::NoDomain, static_cast<UInt8>(instance));
        resultMap.insert(std::pair<ParticipantSpecificInfoKey::Type, UIntN>(key, temp.getTemperature()));
    }
    catch (...)
    {
        // if the primitive isn't available we receive an exception and we don't add this item to the map
    }
}
int main()
{
    Temperature       temp;
    Pressure          press;
    EnvironmentWindow win;
    PanicSirene       panic;

    temp.attach(win);
    temp.attach(panic);
    press.attach(win);

    temp.temperatureChanged();
    press.pressureChanged();

    return (0);
}
示例#6
0
void ParticipantProxy::setTemperatureThresholds(const Temperature& lowerBound, const Temperature& upperBound)
{
    refreshDomainSetIfUninitialized();
    if (m_domains.size() > 0)
    {
        if (m_domains[0].getTemperatureProperty().implementsTemperatureInterface())
        {
            m_policyServices.messageLogging->writeMessageDebug(PolicyMessage(FLF,
                "Setting thresholds to " + lowerBound.toString() + ":" + upperBound.toString() + "."));
            m_domains[0].getTemperatureProperty().setTemperatureNotificationThresholds(lowerBound, upperBound);
        }
    }

    m_previousLowerBound = lowerBound;
    m_previousUpperBound = upperBound;
}
示例#7
0
void Temperature::throwIfInvalid(const Temperature& temperature) const
{
    if (temperature.isValid() == false)
    {
        throw temperature_out_of_range("Temperature is not valid.");
    }
}
示例#8
0
Bool Temperature::operator==(const Temperature& rhs) const
{
    // Do not throw an exception if temperature is not valid.

    if (this->isValid() == true && rhs.isValid() == true)
    {
        return (this->m_temperature == rhs.m_temperature);
    }
    else if (this->isValid() == false && rhs.isValid() == false)
    {
        return true;
    }
    else
    {
        return false;
    }
}
示例#9
0
MARG::MARG(const MARGConfiguration& configuration,
	     const Readout::MARG& readout,
		 const Temperature& temperature_difference,
		 const Calibration& calibration)
{
#ifdef USE_TEMPERATURE_COMPENSATION
	const int16_t temperature_offset[2] = {
		(int16_t)((temperature_difference.degreesCelsius() * LSM9DS0_OFFSET_PER_CELSIUS_G) / configuration.gScaleMdps()),
		(int16_t)((temperature_difference.degreesCelsius() * LSM9DS0_OFFSET_PER_CELSIUS_A) / configuration.aScaleMg())
	};
	const float temperature_scale[2] = {
		(float)temperature_difference.degreesCelsius() * sensitivity_per_celsius_g,
		(float)temperature_difference.degreesCelsius() * sensitivity_per_celsius_a
	};
#else
	const int16_t temperature_offset[2] = { 0, 0 };
	const float temperature_scale[2] = { 1, 1 };
#endif

	const Vector<int16_t> raw_offset_adjusted[2] = {
		readout.g - calibration.g_offset - temperature_offset[0],
		readout.a - calibration.a_offset - temperature_offset[1]
	};
	const Vector<float> scale_adjusted[2] = {
		calibration.g_scale * (1 + temperature_scale[0]),
		calibration.a_scale * (1 + temperature_scale[1])
	};

	g_ = toVector(raw_offset_adjusted[0] * scale_adjusted[0], configuration.gScaleMdps() / 1000 * M_PI / 180);
	a_ = toVector(raw_offset_adjusted[1] * scale_adjusted[1], configuration.aScaleMg() / 1000);
	m_ = toVector(readout.m * calibration.m_rotation - calibration.m_offset, configuration.mScaleMgauss() / 1000);
	
	if (calibration.hasInvertedPlacement()) {
		a_.setX(-a_.x());
		a_.setY(-a_.y());
	}
	if (!calibration.hasInvertedPlacement()) {
		g_.setX(-g_.x());
		g_.setY(-g_.y());
	}

	g_.setX(-g_.x());
	g_.setY(-g_.y());
	g_.setZ(-g_.z());
}
示例#10
0
Temperature Temperature::snapWithinAllowableTripPointRange(Temperature aux)
{
    if ((UInt32)aux != Constants::MaxUInt32)
    {
        Temperature minAux = fromCelsius(ESIF_SDK_MIN_AUX_TRIP);
        if (aux.isValid() && aux < minAux)
        {
            aux = minAux;
        }

        Temperature maxAux = fromCelsius(ESIF_SDK_MAX_AUX_TRIP);
        if (aux.isValid() && aux > maxAux)
        {
            aux = maxAux;
        }
    }

    return aux;
}
示例#11
0
void DptfMessage::addMessage(const std::string& messageKey, Temperature messageValue)
{
    try
    {
        m_messageKeyValuePair.push_back(MessageKeyValuePair(messageKey, messageValue.toString()));
    }
    catch (...)
    {
    }
}
示例#12
0
void EsifServices::primitiveExecuteSetAsTemperatureC(esif_primitive_type primitive, Temperature temperature,
    UIntN participantIndex, UIntN domainIndex, UInt8 instance)
{
    throwIfParticipantDomainCombinationInvalid(FLF, participantIndex, domainIndex);

#ifdef ONLY_LOG_TEMPERATURE_THRESHOLDS
    // Added to help debug issue with missing temperature threshold events
    if (primitive == esif_primitive_type::SET_TEMPERATURE_THRESHOLDS)
    {
        ManagerMessage message = ManagerMessage(m_dptfManager, FLF,
            "Setting new temperature threshold for participant.");
        message.addMessage("Temperature", temperature.toString());
        message.setEsifPrimitive(primitive, instance);
        message.setParticipantAndDomainIndex(participantIndex, domainIndex);
        writeMessageDebug(message, MessageCategory::TemperatureThresholds);
    }
#endif

    eEsifError rc = m_esifInterface.fPrimitiveFuncPtr(m_esifHandle, m_dptfManager,
        (void*)m_dptfManager->getIndexContainer()->getIndexPtr(participantIndex),
        (void*)m_dptfManager->getIndexContainer()->getIndexPtr(domainIndex),
        EsifDataTemperature(temperature), EsifDataVoid(), primitive, instance);

#ifdef ONLY_LOG_TEMPERATURE_THRESHOLDS
    // Added to help debug issue with missing temperature threshold events
    if (primitive == esif_primitive_type::SET_TEMPERATURE_THRESHOLDS &&
        rc != ESIF_OK)
    {
        ManagerMessage message = ManagerMessage(m_dptfManager, FLF,
            "Failed to set new temperature threshold.");
        message.addMessage("Temperature", temperature.toString());
        message.setEsifPrimitive(primitive, instance);
        message.setParticipantAndDomainIndex(participantIndex, domainIndex);
        message.setEsifErrorCode(rc);
        writeMessageError(message, MessageCategory::TemperatureThresholds);
    }
#endif

    throwIfNotSuccessful(FLF, rc, primitive, participantIndex, domainIndex, instance);
}
示例#13
0
UIntN ActivePolicy::findTripPointCrossed(SpecificInfo& tripPoints, const Temperature& temperature)
{
    auto trips = tripPoints.getSortedByKey();
    for (UIntN index = 0; index < trips.size(); index++)
    {
        if (temperature.getTemperature() >= trips[index].second)
        {
            UIntN acIndex = trips[index].first - ParticipantSpecificInfoKey::AC0;
            return acIndex;
        }
    }
    return Constants::Invalid;
}
示例#14
0
UIntN ActivePolicy::determineUpperTemperatureThreshold(const Temperature& currentTemperature, SpecificInfo& tripPoints) const
{
    auto trips = tripPoints.getSortedByKey();
    UIntN upperTemperatureThreshold = Constants::Invalid;
    for (UIntN ac = 0; ac < trips.size(); ++ac)
    {
        if ((currentTemperature.getTemperature() < trips[ac].second) &&
            (trips[ac].second != Constants::Invalid))
        {
            upperTemperatureThreshold = trips[ac].second;
        }
    }
    return upperTemperatureThreshold;
}
示例#15
0
UIntN ActivePolicy::determineLowerTemperatureThreshold(const Temperature& currentTemperature, SpecificInfo& tripPoints) const
{
    auto trips = tripPoints.getSortedByKey();
    UIntN lowerTemperatureThreshold = Constants::Invalid;
    for (UIntN ac = 0; ac < trips.size(); ++ac)
    {
        if (currentTemperature.getTemperature() >= trips[ac].second)
        {
            lowerTemperatureThreshold = trips[ac].second;
            break;
        }
    }
    return lowerTemperatureThreshold;
}
示例#16
0
int main()
{
    Temperature outside = Temperature();
    outside.set_fahrenheit(0.0);
    Temperature inside = Temperature(273.15);
    cout << "Outside F: " << outside.getFahrenheit() << endl;
    cout << "Outside K: " << outside.getKelvin() << endl;
    cout << "Inside F: " << inside.getFahrenheit() << endl;
    cout << "Inside K: " << inside.getKelvin() << endl;
//    cout << (outside + 5).getFahrenheit() << endl;
//    Temperature both =  outside + inside;
//    cout << both.getFahrenheit() << endl;
//    cout << both.getKelvin() << endl;
    cout << (outside + inside).getFahrenheit() << endl;
    cout << (outside + inside).getKelvin() << endl;
    return 0;
}
示例#17
0
// Program to demonstrate Temperature class
//-----------------------------------------
int main()
{
   Temperature freezing;
   Temperature boiling;
   Temperature coldcold;
   Temperature hothot;
   freezing.setCelsius(0);
   boiling.setCelsius(100);
   coldcold.setCelsius(-500);
   hothot.setCelsius(20000000);
   cout << "freezing: " << freezing.getFahrenheit() << "F\n";
   cout << "boiling: " << boiling.getFahrenheit() << "F\n";
   cout << "coldcold: " << coldcold.getCelsius() << "C\n";
   cout << "hothot: " << hothot.getCelsius() << "C\n";
   return 0;
}
示例#18
0
bool test4() {
    Temperature temperature;
    temperature.setTempKelvin(300);
    return roundl(temperature.getTempFahrenheit()) == 80;
};
示例#19
0
bool test2() {
    Temperature temperature;
    temperature.setTempCelsius(50);
    return roundl(temperature.getTempKelvin()) == 323;
};
示例#20
0
bool test1() {
    Temperature temperature;
    temperature.setTempFahrenheit(50);
    return roundl(temperature.getTempKelvin()) == 283;
};
示例#21
0
bool test0() {
    Temperature temperature;
    temperature.setTempKelvin(50);
    return temperature.getTempKelvin() == 50;
};
示例#22
0
//-------------------------------------------------------------------------------------------------------------------------------------------------------
void PhModule::ApplyCalculation(Temperature* temp)
{
  // Эта функция вызывается при любом обновлении значения с датчика pH, откуда бы это значение
  // ни пришло. Здесь мы можем применить к значению поправочные факторы калибровки, в том числе
  // по температуре, плюс применяем к показаниям поправочное число.
  
  if(!temp)
    return;

  if(!temp->HasData())
    return;

  // теперь проверяем, можем ли мы применить калибровочные поправки?
  // для этого все вольтажи, наличие показаний с датчика температуры
  // и выставленная настройки температуры калибровочных растворов
  // должны быть актуальными.

  if(ph4Voltage < 1 || ph7Voltage < 1 || ph10Voltage < 1 || phTemperatureSensorIndex < 0 
  || !phSamplesTemperature.HasData() || phSamplesTemperature.Value > 100 || phSamplesTemperature.Value < 0)
    return;

  AbstractModule* tempModule = MainController->GetModuleByID("STATE");
  if(!tempModule)
    return;

  OneState* os = tempModule->State.GetState(StateTemperature,phTemperatureSensorIndex);
  if(!os)
    return;

  TemperaturePair tempPair = *os;
  Temperature tempPH = tempPair.Current;

  if(!tempPH.HasData() || tempPH.Value > 100 || tempPH.Value < 0)
    return;

  Temperature tDiff = tempPH - phSamplesTemperature;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("T diff: "), tDiff);
  #endif

  long ulDiff = tDiff.Value;
  ulDiff *= 100;
  ulDiff += tDiff.Fract;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("ulDiff: "), ulDiff);
  #endif
  
  float fTempDiff = ulDiff/100.0;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("fTempDiff: "), fTempDiff);
    PH_DEBUG_OUT(F("source PH: "), *temp);
  #endif 

  // теперь можем применять факторы калибровки.
  // сначала переводим текущие показания в вольтаж, приходится так делать, поскольку
  // они приходят уже нормализованными.
  long curPHVoltage = temp->Value;

  curPHVoltage *= 100;
  curPHVoltage += temp->Fract + calibration; // прибавляем сотые доли показаний, плюс сотые доли поправочного числа
  curPHVoltage *= 100;
  curPHVoltage /= 35; // например, 7,00 pH  сконвертируется в 2000 милливольт

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("curPHVoltage: "), curPHVoltage);
    PH_DEBUG_OUT(F("ph4Voltage: "), ph4Voltage);
    PH_DEBUG_OUT(F("ph7Voltage: "), ph7Voltage);
    PH_DEBUG_OUT(F("ph10Voltage: "), ph10Voltage);
  #endif

  long phDiff = ph4Voltage;
  phDiff -= ph10Voltage;

  float sensitivity = phDiff/6.0;
  sensitivity = sensitivity + fTempDiff*0.0001984;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("sensitivity: "), sensitivity);
  #endif

  phDiff = ph7Voltage;
  phDiff -= curPHVoltage;
  
  float calibratedPH = 7.0 + phDiff/sensitivity;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("calibratedPH: "), calibratedPH);
  #endif

  // теперь переводим всё это обратно в понятный всем вид
  uint16_t phVal = calibratedPH*100;

  // и сохраняем это дело в показания датчика
  temp->Value = phVal/100;
  temp->Fract = phVal%100;

  #ifdef PH_DEBUG
    PH_DEBUG_OUT(F("pH result: "), *temp);
  #endif
  
}
示例#23
0
Temperature TemperatureSensor::GetCurrentReading() {
    //TODO define proper translation to degrees
    Temperature t =  Temperature(_arduino.readSignal() * 50 - 10);
    std::cout << "Temp-S:: el nivel de temperatura sensado es: " << LevelHandler::Serialize(t.levelOf()) << std::endl;
    return t;
}
示例#24
0
int main()
{
	setConsole();	
	Temperature t;
	Helper h;
	bool loop1 = true;
	bool loop2 = true;
	string user_temperature;
	string user_temp_scale;
	double temperature;
	double celcius_temp;
	double fahrenheit_temp;

	//creating a loop so the application can be used multiple times without restarting it
	while (loop1)
	{
		//get temperature(number) from user
		cout << "Please enter the temperature(number)\nyou want to convert, ('q' to quit): ";
		cin >> user_temperature;

		//see if user wants to quit the application
		if (user_temperature == "q" || user_temperature == "Q")
		{
			loop1 = false;
		}
		else
		{
			//check to see if input is numeric or not
			if (h.IsNumeric(user_temperature))
			{
				temperature = h.ConvertToDouble(user_temperature);

				//reset loop 2 to true
				loop2 = true;				

				//creating a loop to make user pick a valid option
				while (loop2)
				{					
					//get temperature scale from the user
					cout << "\nPlease enter the temperature scale your number" << endl
						<< "is currently in ('f' for fahrenheit, 'c' for celcius): ";
					cin >> user_temp_scale;
										
					//determine which temperature scale the user is using
					if (user_temp_scale == "f" || user_temp_scale == "F")
					{
						//end the loop
						loop2 = false;

						//set the celcius and fahrenheit values
						t.set_celcius(temperature);
						t.set_fahrenheit(t.celcius());

						//display output
						cout << endl << endl << setprecision(2) << fixed << t.fahrenheit() << " degrees Fahrenheit is equal to " 
							<< t.celcius() << " degrees Celcius\n\n\n";
					}
					else if (user_temp_scale == "c" || user_temp_scale == "C")
					{
						//end the loop
						loop2 = false;

						//set the fahrenheit and celcius values
						t.set_fahrenheit(temperature);
						t.set_celcius(t.fahrenheit());

						//display output
						cout << endl << endl << setprecision(2) << fixed << t.celcius() << " degrees Celcius is equal to " 
							<< t.fahrenheit() << " degrees Fahrenheit\n\n\n";
					}
					else
					{
						//if the user entered an invalid option
						cout << "\n\t\tINVALID INPUT!\n";
					}					
				}				
			}
			else
			{
				//if input is not numeric
				cout << "\n\t\tINVALID INPUT!\n\n";
			}
		}
示例#25
0
std::string temperature(Temperature temperature) {
	return to_string_dec_int(temperature.celsius(), 3);
}
示例#26
0
int main(void)
{
	sei();
	Clock::start();

	TWI::init();
	TWI::write(0x40, 255);

	max6675::SPI::start();

	SerialPort<9600> com;

	Led::SetDirWrite();

	com << "Starting on 9600" << endl;

	RadiatorCascade radiatorCascade;
	BoilerCascade boilerCascade;
	const uint8_t MaxAddrs = 16;
	OneWire::Addr addrs[MaxAddrs];
	uint16_t fails = 0;
	for(;;)
	{

		Clock::clock_t startTime = Clock::millis();

		com << "Search ";
		uint8_t count = 0;
		OneWire::Search<Wire> search;
		{
			LedOn<Led> l;
			do {
				addrs[count++] = search();
			} while (!search.isDone() && count < MaxAddrs);
		}
		if (search.isFail())
		{
			com << "failed on " << int(count) << ": " << search.error();
			search.errorDetail(com) <<  endl;
			fails++;
		} else {
			com << int(count) << endl;
			fails = 0;
		}

		if (!Wire::reset())
		{
			com << "Reset failed" << endl;
			fails++;
			continue;
		}

		{
			LedOn<Led> l;
			Wire::skip();
			DS1820::convert();
			com << "Radiator " << radiatorCascade << endl;
			com << "Boiler   " << boilerCascade << endl;
			DS1820::wait();
		}

		for (int i = 0; i < count; ++i)
		{
			Led::Set();
			Temperature t = DS1820::read(addrs[i]);
			Led::Clear();

			if (t.isValid()) {
				radiatorCascade.processSensor(addrs[i], t.get());
				boilerCascade.processSensor(addrs[i], t.get());

				com << "Temp: " << addrs[i] << '=' << t << endl;
			} else {
				com << "Fail  " << addrs[i] << endl;
				fails++;
			}
		}

		{
			Temperature t = max6675::temperature();
			if (t.isValid()) {
				boilerCascade.processTC(t.get());
				com << "Temp: TC=" << t << endl;
			} else {
				com << "Fail  TC" << endl;
				fails++;
			}
		}
		com << "Temp: fails=" << fails << endl;

		if (!radiatorCascade.step())
			com << "Radiator Cascade fail" << endl;
		if (!boilerCascade.step())
			com << "Boiler Cascade fail" << endl;

		//Clock::clock_t regStart = Clock::millis();
		int16_t rDelay = radiatorCascade.getAbsOutput();
		int16_t bDelay = boilerCascade.getAbsOutput();

		TWI::write(0x40, ~Data::data);
		if (rDelay > 0 || bDelay > 0) {
			if (rDelay < bDelay) {
				delay_ms(rDelay);
				RadiatorCascade::action_t::stop();
				TWI::write(0x40, ~Data::data);
				delay_ms(bDelay - rDelay);
				BoilerCascade::action_t::stop();
				TWI::write(0x40, ~Data::data);
			} else {
				delay_ms(bDelay);
				BoilerCascade::action_t::stop();
				TWI::write(0x40, ~Data::data);
				delay_ms(rDelay - bDelay);
				RadiatorCascade::action_t::stop();
				TWI::write(0x40, ~Data::data);
			}
		}
		Clock::clock_t regStop = Clock::millis();
		com << "cycle time " << regStop - startTime << endl;
		if (cycleTime > (regStop - startTime))
			delay_ms(cycleTime - (regStop - startTime));
	}
}
示例#27
0
const Temperature operator+(const Temperature &temp1, const Temperature &temp2)
{ return Temperature(temp1.getKelvin() + temp2.getKelvin()); }
/*
 * Name        : lab_10_unit_test.cpp
 * Author      : Luke Sathrum
 * Description : Unit test to test Lab #10 Functionality
 */
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "lab_10.h"
// Double Include to Check for Header Guards
#include "lab_10.h"

TEST_CASE("Temperature Using Default Constuctor") {
  Temperature temp;

  SECTION("GetTempAsKelvin()") {
    CHECK(temp.GetTempAsKelvin() == 0);
  }

  temp.SetTempFromKelvin(50);
  SECTION("SetTempFromKelvin(50) / GetTempAsCelsius()") {
    CHECK(temp.GetTempAsKelvin() == 50);
  }

  temp.SetTempFromCelsius(5);
  SECTION("SetTempFromCelsius(5) / GetTempAsFarenheit()") {
    CHECK(temp.GetTempAsFahrenheit() >= 40.99);
    CHECK(temp.GetTempAsFahrenheit() <= 41.01);
  }

  temp.SetTempFromFahrenheit(5);