// [ID, PIN, VALUE, TARGET, SENSOR?, TYPE]
int Device::toString(Print* conn){

	char v_str[6];
	/* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
	dtostrf(getValue(), 4, 2, v_str);

	conn->print('[');

	#if(ENABLE_PREFIX_NAME)
		if(type != Device::BOARD){
			conn->print(od::Config.moduleName);
			conn->print("::");
		}
	#endif

	conn->print(deviceName);
	conn->print(',');
	conn->print(id);
	conn->print(',');
	conn->print(pin);
	conn->print(',');
	conn->print(v_str);
	conn->print(',');
	conn->print(targetID);
	conn->print(',');
	conn->print((sensor ? 1 : 0));
	conn->print(',');
	conn->print((int)type);
	conn->print(']');

//	int size = sprintf (buffer, "[%s,%d,%d,%s,%d,%d,%d]",
//				(name != NULL ? name : ""),
//				id, pin, v_str, targetID, (sensor ? 1 : 0), itype);

//  Serial.print(">>>>>> Device :");
//  Serial.println(buffer);
	 return 0;
}
Example #2
0
/***********************************************************
 * 
 * fractionToString
 *
 *  
 * 
 ***********************************************************/
void BulbRamp::fractionToString(int optionConst, int fraction, char buffer[])
{
	  //output to result to buffer
	  char tempBuffer[5];
	  buffer[0] = 0;
	
	 if(option(optionConst) < 1000)		
	  {					
		strcat(buffer,"1/");
		utoa(fraction,tempBuffer,10);
		strcat(buffer,tempBuffer);
		strcat(buffer,"sec");	
		strcat(buffer,'\0');
	 }	
	 else if(option(optionConst) <= 60000) 
	 {
		float secf = (float) option(optionConst)/1000; //set from EndExposure or Start
		dtostrf(secf, 3, 1, tempBuffer); //avr lib float to str
		strcat(buffer,tempBuffer);
		strcat(buffer,"sec");	
		strcat(buffer,'\0');
	 }
}
void loop() {
  if (Serial.available()) {
    int value = Serial.parseInt();
    // Sometime we see a garbage number, so restrict to a lower number
    if(value > 100) {
        value = 5;
    }
    blink(value);
  } 

  strcpy(deviceEvent, "");
  
  char val[10];
  strcat(deviceEvent,"status temp:");
  dtostrf(getTemp(),1,2, val);
  strcat(deviceEvent,val);
  strcat(deviceEvent,",pir:");
  int buttonState = digitalRead(PIRPIN);
  itoa(buttonState, val, 10);
  strcat(deviceEvent,val);
  Serial.println(deviceEvent);
  delay(100);
}
Example #4
0
void DAQ::handleValue(float value){
  // Handle averaging if used...
  _averagingSum += value;
  _dataCount++;
  
  if(_dataCount == _averageCount){
    if(_valueHandler){
      float value = _averagingSum / _dataCount;

      // Don't send same val...! :O(
      // TODO - Use hysteresis.
      //if(value != _lastValue){
      if((value < (_lastValue - _hysteresis)) || (value > (_lastValue + _hysteresis))){
        char buf[20];
        dtostrf(value, 0, _precision, buf);
        _valueHandler(buf);
        _lastValue = atof(buf);
      }
    }
    _dataCount = 0; 
    _averagingSum = 0;
  }
}
void dump_fastlog( void )
{
	extern unsigned char top_ret;
	extern unsigned char bot_ret;
	newline();

	if(variables.current_cyl_idx < cfg.num_cyls && 
		variables.lastknock_tpfd[variables.current_cyl_idx] < 1500 && 
		variables.lastknock_tpfd[variables.current_cyl_idx] )
	{
		snprintf(output, OUTPUT_LEN, "%05lu", TICKS_PER_MIN/((unsigned long int) variables.lastknock_tpfd[variables.current_cyl_idx] *90));
		print_str(output);
		seperator();

		snprintf(output, OUTPUT_LEN, "%u", cfg.firing_order[variables.current_cyl_idx]);

	}
	else
	{
		snprintf(output, OUTPUT_LEN, "00000");
		print_str(output);
		seperator();

		snprintf(output, OUTPUT_LEN, "0");
	}

	print_str(output);
	seperator();

	dtostrf( (float) (variables.lastknock_volts[variables.current_cyl_idx] * TEN_BIT_LSB), 5, 3, output);
	print_str(output);

	seperator();
	snprintf(output, OUTPUT_LEN, "%u - %02X - %02X ", variables.rknock, top_ret, bot_ret);
	print_str(output);
return;
}
/**
 * Paint the BarGraph
 */
void BarGraph::paint(void) {
    char outStr[25];
    char outValueStr[6];

    //draw bargraph Background and outine
    stroke(fgColorR,
           fgColorG,
           fgColorB);

    fill(bgColorR,
         bgColorG,
         bgColorB);

    rect(xLocation,
         yLocation,
         graphWidth,
         graphHeight);

    //draw the bargraph label and value
    dtostrf(currValue, 5, 1, outValueStr);
    sprintf(outStr,"%s %s", graphLabel, outValueStr);
    text(outStr,
         xLocation,
         yLocation-10);

    //draw the bar
    noStroke();
    fill(fgColorR,
         fgColorG,
         fgColorB);
    rect(xLocation,
         yLocation,
         valueClamped * ((float)graphWidth / (maxValue - minValue)),
         graphHeight);


}
Example #7
0
void Gauchito::sendData() {

    dtostrf(irs[0]->readInCentimeters(), 0, 2, gData.dataset[0].value);
    dtostrf(irs[1]->readInCentimeters(), 0, 2, gData.dataset[1].value);
    dtostrf(irs[2]->readInCentimeters(), 0, 2, gData.dataset[2].value);
    dtostrf(irs[3]->readInCentimeters(), 0, 2, gData.dataset[3].value);
    dtostrf(irs[4]->readInCentimeters(), 0, 2, gData.dataset[4].value);
    dtostrf(ultrasonic->readInCentimeters(), 0, 2, gData.dataset[5].value);

/*
    Serial.print("IR_01 "); Serial.println(gData.dataset[0].value);
    Serial.print("IR_02 "); Serial.println(gData.dataset[1].value);
    Serial.print("IR_03 "); Serial.println(gData.dataset[2].value);
    Serial.print("IR_04 "); Serial.println(gData.dataset[3].value);
    Serial.print("IR_05 "); Serial.println(gData.dataset[4].value);
    Serial.print("ULTRASSOM "); Serial.println(gData.dataset[5].value);
*/

}
Example #8
0
//call to display detailed position information on the debug port.
void AsiMS2000::displayCurrentToDesired(char message[])
{
    char buffer[20];
    String reply = String(message);    
    AxisSettingsF a = AsiSettings.currentPos;
    AxisSettingsF d = AsiSettings.desiredPos;
    dtostrf(a.x,1,4,buffer);
    reply.concat(" " + String(buffer) + "->");
    dtostrf(d.x,1,4,buffer);
    reply.concat(String(buffer) + " ");
    
    dtostrf(a.y,1,4,buffer);
    reply.concat(String(buffer) + "->");
    dtostrf(d.y,1,4,buffer);
    reply.concat(String(buffer) + " ");

    dtostrf(a.z,1,4,buffer);
    reply.concat(String(buffer) + "->");
    dtostrf(d.z,1,4,buffer);
    reply.concat(String(buffer) + " ");
    
    debugPrintln(reply);
}
Example #9
0
String::String(float value, unsigned char decimalPlaces)
{
	init();
	char buf[33];
	*this = dtostrf(value, (33 - 1), decimalPlaces, buf);
}
void
CustomFrameBuilder::appendPositioningData()
{
  // time of fix
  strncpy(this->whereToAppend, this->gps->getTimeOfFix(), 6);
  this->whereToAppend += 6;

  // separator
  this->appendFieldSeparatorChar();

  // fix
  if (this->gps->getFix())
  {
    this->whereToAppend++[0] = 'A';
  }
  else
  {
    this->whereToAppend++[0] = 'V';
  }

  // separator
  this->appendFieldSeparatorChar();

  // longitude
  dtostrf(this->gps->getLongitude(), 2, 3, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // latitude
  dtostrf(this->gps->getLatitude(), 2, 3, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // altitude
  dtostrf(this->gps->getAltitude(), 2, 1, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // speed
  dtostrf(this->gps->getSpeedOverGround(), 2, 1, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // course
  dtostrf(this->gps->getCourseOverGround(), 2, 1, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // satellites in use
  itoa(this->gps->getSatellitesInUse(), this->whereToAppend, 10);
  this->whereToAppend += strlen(this->whereToAppend);

  // separator
  this->appendFieldSeparatorChar();

  // HDOP
  dtostrf(this->gps->getHDOP(), 2, 1, this->whereToAppend);
  this->whereToAppend += strlen(this->whereToAppend);
}
Example #11
0
/**
 *	\ingroup allgfunktionen
 *	Zeile nach Parameter durchsuchen und ersetzen
 *
 *	Mögliche Variable haben ein Prozentzeichen (\%) vorangestellt und sind:
 *	\li \b DATE	Tagesdatum
 *	\li \b USDATE	Tagesdatum im Internet kompatiblen Format
 *	\li	\b WDAY	Wochentag, abgekürzt auf 3 Buchstaben
 *	\li \b TIME	aktuelle Zeit
 *	\li \b VA\@nn	analoger Wert nn
 *	\li \b OW\@nn	nn = 00 bis MAXSENSORS-1 gibt 1-Wire Temperaturwerte in 1/10 °C aus
 *	\li \b OW\@mm	mm = 20 bis MAXSENSORS-1+20 gibt 1-Wire Temperaturwerte in °C mit einer Nachkommastelle aus<br>
 *	d.h. OW\@nn für Balkenbreite verwenden und OW\@mm für Celsius-Anzeige
 *	\li \b PORTnm	Status des Ausgangs Pin m (0, 1, ...) an Port n (A, B, C, ...)
 *	\li \b PINnm	Status des Eingangs Pin m (0, 1, ...) an Port n (A, B, C, ...)<br>
 *		 dargestellt durch eine jpg-Datei ledon.jpg / ledoff.jpg
 *
 *	\param[in] buffer String mit eingebetteten Parametern
 *	\param[in,out] ptr Speicherplatz des konvertierten Strings
 *	\param[out] nbytes Anzahl verarbeiteter Bytes
 *	\returns Anzahl der Bytes im konvertierten String
*/
uint16_t translate(char *buffer, char **ptr, uint16_t *nbytes )
{
	uint16_t len = 0;
	char *src = buffer;
	char *dest = *ptr;

	while (*src) {
		
		if (*src != '%') {
			*dest++ = *src++;
			++len;
		}
		else {
			++src;

			if (strncasecmp_P(src,PSTR("TIME"),4)==0) {
				uint16_t year;
				uint8_t month, day, hour, min, sec;
				FUNCS_DEBUG(" - Zeit");
				get_datetime(&year, &month, &day, &hour, &min, &sec);
				sprintf_P(dest,PSTR("%2.2d:%2.2d:%2.2d"),hour,min,sec);
				src += 4;
			}

			else if (strncasecmp_P(src,PSTR("DATE"),4)==0) {
				uint16_t year;
				uint8_t month, day, hour, min, sec;
				FUNCS_DEBUG(" - Datum");
				get_datetime(&year, &month, &day, &hour, &min, &sec);
				sprintf_P(dest,PSTR("%2.2d.%2.2d.%4d"),day,month,year);
				src += 4;
			}

			else if (strncasecmp_P(src,PSTR("USDATE"),6)==0) {
				FUNCS_DEBUG(" - USDatum");
				GetUSdate(dest);
				src += 6;
			}

			else if (strncasecmp_P(src,PSTR("WDAY"),4)==0) {
				FUNCS_DEBUG(" - Wochentag");
				memcpy_P(dest,&Tagesnamen[TM_DOW*3],3);
				dest += 3;
				*dest = '\0';
				src += 4;
			}

			#if USE_ADC
			else if (strncasecmp_P(src,PSTR("VA@"),3)==0) {	
				FUNCS_DEBUG(" - Analogwert");
				uint8_t i = (*(src+3)-48)*10 + (*(src+4)-48);
				itoa (var_array[i],dest,10);
				src += 5;
			}
			#endif

			#if 0
			//
			// KTY0D gibt Differenzmessung in dezimalen Grad aus
			// KTY0x gibt Wert in 1/10 Grad aus
			// entsprechend KTY1D/KTY1x für 2. Differenzmessung
			//
			else if (strncasecmp_P(src,PSTR("KTY"),3)==0) {	
				FUNCS_DEBUG(" - KTY-Wert");
				b = (*(src+3)=='0')? KTY_SENS1 : KTY_SENS2;	// Speicherplätze der Differenzmessungen

				int16_t T = (int16_t) (var_array[b] * -0.62 + 224.3);

				if (*(src+4)=='D') {
					int8_t j = (int8_t)(T / 10);
					itoa (j,dest,10);

					while (*dest++)			// neues Ende finden
						++len;
					--dest;

					*dest++ = ',';
					++len;

					j = T % 10;				// Nachkommastelle
					itoa (j,dest,10);
				} else if (T < 0) {
					T = -T;					// Vorzeichen abschneiden
					itoa (T,dest,10);

					while (*dest++)			// neues Ende finden
						++len;
					--dest;

					// "style rechtsbündig" anhängen
					strcpy_P(dest,PSTR("\" style=\"float: right"));
				}
				else {
					itoa (T,dest,10);
				}
				src += 5;
			}
			#endif
			
#if USE_OW
			/*
			*	1-Wire Temperatursensoren
			*	-------------------------
			*	OW@nn	nn = 00 bis MAXSENSORS-1 gibt Werte in 1/10 °C aus
			*	OW@mm	mm = 20 bis MAXSENSORS-1+20 gibt Werte in °C mit einer Nachkommastelle aus
			*	d.h. OW@nn für Balkenbreite verwenden und OW@mm für Celsius-Anzeige
			*/
			else if (strncasecmp_P(src,PSTR("OW@"),3)==0) {	
				FUNCS_DEBUG(" - 1-wire");
				uint8_t i = (*(src+3)-48)*10 + (*(src+4)-48);
				if (i >= 20) {	// Offset bei Sensor# abziehen und Wert als Dezimalzahl ausgeben
					i -= 20;
					dtostrf(ow_array[i] / 10.0,3,1,dest);
				} else {
					itoa (ow_array[i],dest,10);
				}
				src += 5;
			}
#endif

			//Einsetzen des Port Status %PORTxy durch "checked" wenn Portx.Piny = 1
			//x: A..G  y: 0..7 
			else if (strncasecmp_P(src,PSTR("PORT"),4)==0) {
				FUNCS_DEBUG(" - Portstatus");
				uint8_t pin  = (*(src+5)-48);	
				uint8_t b = 0;
				switch(*(src+4)) {
					case 'A':
						b = (PORTA & (1<<pin));
						break;
					case 'B':
						b = (PORTB & (1<<pin));
						break;
					case 'C':
						b = (PORTC & (1<<pin));
						break;
					case 'D':
						b = (PORTD & (1<<pin));
						break; 
				}
				
				if(b) {
					//strcpy_P(dest, PSTR("checked"));
					strcpy_P(dest, PSTR("ledon.gif"));
				}
				else {
					//strcpy_P(dest, PSTR("unchecked"));
					strcpy_P(dest, PSTR("ledoff.gif"));
				}

				src += 6;
			}
			
			//Einsetzen des Pin Status %PI@xy bis %PI@xy durch "ledon" oder "ledoff"
			//x = 0 : PINA / x = 1 : PINB / x = 2 : PINC / x = 3 : PIND
			else if (strncasecmp_P(src,PSTR("PIN"),3)==0) {
				FUNCS_DEBUG(" - Eingangswert");
				uint8_t pin  = (*(src+4)-48);	
				uint8_t b = 0;
				switch(*(src+3)) {
					case 'A':
						b = (PINA & (1<<pin));
						break;
					case 'B':
						b = (PINB & (1<<pin));
						break;
					case 'C':
						b = (PINC & (1<<pin));
						break;
					case 'D':
						b = (PIND & (1<<pin));
						break;    
				}
				
				if(b) {	// gesetztes bit bedeutet: nix dran, da Pullup Widerstand
					strcpy_P(dest, PSTR("ledoff.gif"));
				} else {
					strcpy_P(dest, PSTR("ledon.gif"));	// Schalter auf Masse geschlossen
				}

				src += 5;
			}
			else {	// nix gefunden -> '%' speichern
				*dest++ = '%';
				*dest = 0;
				++len;
			}

			while (*dest++)	// neues Ende finden
				++len;
			--dest;
		}

	}
	*ptr = dest;
	*nbytes = (uint16_t)(src - buffer);
	return len;
}
bool Adafruit_MQTT_Publish::publish(double f, uint8_t precision) {
  char payload[40];  // Need to technically hold float max, 39 digits and minus sign.
  dtostrf(f, 0, precision, payload);
  return mqtt->publish(topic, payload, qos);
}
Example #13
0
unsigned char String::concat(double num)
{
	char buf[20];
	char* string = dtostrf(num, 4, 2, buf);
	return concat(string, strlen(string));
}
int main(void) {
DDRB=0x08;
/* PB3 pin of PORTB is declared output (PWM1 pin of DC Motor Driver is connected) */

DDRD=0x80;
/* PD7 pin of PORTD is declared output (PWM2 pin of DC Motor Driver is connected) */

DDRA=0x0f;
/*PA0,PA1,PA2 and PA3 pins of PortC are declared output ( i/p1,i/p2,i/p3 and i/p4 pins of DC Motor Driver are connected)*/

set_timercounter0_mode(1);
/*Timer counter 0 is set to Phase Correct pwm mode*/

set_timercounter0_prescaler(4);
/*Timer counter 0 frequency is set to 3.90625KHz*/

set_timercounter0_output_mode(2);
/*Timer counter 0 output mode is set to non-inverting mode*/

set_timercounter2_mode(1);
/*Timer counter 2 is set to Phase Correct pwm mode*/

set_timercounter2_prescaler(4);
/*Timer counter 2 frequency is set to 3.90625KHz*/

set_timercounter2_output_mode(2);
/*Timer counter 2 output mode is set to non-inverting mode*/

	#if MPU6050_GETATTITUDE == 0
    int16_t ax = 0;
    int16_t ay = 0;
    int16_t az = 0;
    int16_t gx = 0;
    int16_t gy = 0;
    int16_t gz = 0;
    double axg = 0;
    double ayg = 0;
    double azg = 0;
    double gxds = 0;
    double gyds = 0;
    double gzds = 0;
	double accXangle = 0;
	double gyroXangle = 0;
	double Xangle = 0 ;
	double error = 0;
	double I_error = 0;
	double D_error = 0;
	double previous_error = 0 ;
	double outputspeed = 0;
	/*double initangle = 0;*/
	#endif
	
	
   
    //init uart
	uart_init(UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU));

	//init interrupt
	sei();

	//init mpu6050
	mpu6050_init();
	_delay_ms(50);
	
	#if MPU6050_GETATTITUDE == 0
	mpu6050_getRawData(&ax, &ay, &az, &gx, &gy, &gz);
	mpu6050_getConvData(&axg, &ayg, &azg, &gxds, &gyds, &gzds);
	accXangle = (atan2(ayg,azg)+PI)*RAD_TO_DEG;
	gyroXangle = accXangle;
	#endif
	
	for(;;) {
		#if MPU6050_GETATTITUDE == 0
		mpu6050_getRawData(&ax, &ay, &az, &gx, &gy, &gz);
		mpu6050_getConvData(&axg, &ayg, &azg, &gxds, &gyds, &gzds);
		#endif
		
        accXangle = (atan2(ayg,azg)+PI)*RAD_TO_DEG;
		gyroXangle = accXangle + gxds*dt;
		Xangle = 0.98*gyroXangle + 0.02*accXangle;
		
		error = 180 - Xangle;
		I_error += (error)*dt;
		D_error = (error - previous_error)/*/dt*/;
		
		outputspeed = (P_GAIN * error) + (I_GAIN * I_error) + (D_GAIN * D_error);
		previous_error = error;
	/*Bang Bang Controller 
	if((Xangle<=(180.01))&&(Xangle>=179.99))
	{
		
		PORTA = 0x00;
	}
	else if (Xangle>(180.01))
	{
		set_timercounter0_compare_value(255);
		

		set_timercounter2_compare_value(255);
		
		PORTA = 0x0a;
	}
	else if(Xangle<(179.99))
	{
		set_timercounter0_compare_value(255);
		

		set_timercounter2_compare_value(255);
		
		PORTA = 0x05;
	}
		Bang Bang Controller*/
		if((Xangle<=(180.1))&&(Xangle>=179.9))
		{
			
			PORTA = 0x00;
		}
		else if (Xangle>(180.1))
		{ 
				set_timercounter0_compare_value(abs(outputspeed));
				

				set_timercounter2_compare_value(abs(outputspeed));
				
		PORTA = 0x0a;
		}
		else if(Xangle<(179.9))
		{  
				set_timercounter0_compare_value(abs(outputspeed));
				

				set_timercounter2_compare_value(abs(outputspeed));
				
			PORTA = 0x05;
		}		
		#if MPU6050_GETATTITUDE == 0
		char itmp[10];
		/*dtostrf(ax, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		 dtostrf(ay, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		 dtostrf(az, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		 dtostrf(gx, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		 dtostrf(gy, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		 dtostrf(gz, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
	    dtostrf(axg, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(ayg, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(azg, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(gxds, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(gyds, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(gzds, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(accXangle, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(gyroXangle, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(initangle, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(Xangle, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(error, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(I_error, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		dtostrf(D_error, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');*/
		dtostrf(outputspeed, 3, 5, itmp); uart_puts(itmp); uart_putc(' ');
		uart_puts("\r\n");

		uart_puts("\r\n");
		#endif 

	}

}
Example #15
0
void loop() {
	
  File dataFile;
  //String dataString;
  //char dataToSD[40];
  //String timeString;
  char tempstring[10]; // create string arrays
  //float temp;
  static int WaitingForTemp = 0;
  //int readCount;
  DateTime now; // = rtc.now();
  static int nowriting = 0;
  
 delay(1000);
 
  switch(system_FSM) {
    case S_IDLE:
      //Read time from RTC
      now = rtc.now();
      
      if(now.minute() % 11 == 0)
        nowriting = 0;
      
      //Trigger state change
      if(WaitingForTemp == 1){
        if (millis() - lastTempRequest >= delayInMillis) // waited long enough??
		  system_FSM = S_READ_SENS;
	    }
      if(WaitingForTemp == 0) {
		system_FSM = S_TRIG_TEMP;
		if(now.minute() % 10 == 0 || nowriting == 0)
		  system_FSM = S_WRITE_SD;
		  nowriting = 1;
	    }
    break;
    case S_TRIG_TEMP:
      // Trig async reading of DS1820 temp sensor
      sensors.requestTemperatures(); 
      
      // remember time of trigger
      lastTempRequest = millis();
      WaitingForTemp = 1;
      system_FSM = S_IDLE; 
    break;
    case S_READ_SENS:
      //read value of sensors
      SensorData.sensor1 = sensors.getTempC(Sensor1);
      SensorData.sensor2 = sensors.getTempC(Sensor2);
      //SensorData.sensor1 = sensors.getTempC(Sensor1);
      //SensorData.sensor1 = sensors.getTempC(Sensor1);
      //SensorData.sensor1 = sensors.getTempC(Sensor1);
      WaitingForTemp = 0;

      system_FSM = S_IDLE;
/*
      if(readCount == 0)
        system_FSM = S_WRITE_SD;
        else
          system_FSM = S_IDLE;
      readCount++;
      */
    break;
    case S_WRITE_SD:
      // Read time and date from RTC
      TimeDate(rtc.now(),dateTimeString,1);

      // Open datafile
      dataFile = SD.open("templog.txt", FILE_WRITE);
      
      // Write values to SD card
      if (dataFile) {
        dataFile.print(dateTimeString);
        dataFile.print(";");
        dataFile.print(SensorData.sensor1);
        dataFile.print(";");
        dataFile.println(SensorData.sensor2);
        dataFile.close();
        }  
        
      // state change to IDLE
      system_FSM = S_IDLE;
    break;               
    default:
      system_FSM = S_IDLE;
  }
 
  switch(menu_FSM) {
    case M_PAGE1:
      if(menu_FSM !=menu_last_state) {
        DisplayClear();
        mySerial.write("Time"); // clear display + legends
        MenuShowTime = millis();
      }  
      now = rtc.now();
      DisplayGoto(1,0);
      mySerial.write("Time"); // clear display + legends

      DisplayGoto(1,8);
      TimeDate(now,dateTimeString,2);
      mySerial.print(dateTimeString);

      DisplayGoto(2,6);
      TimeDate(now,dateTimeString,3);
      mySerial.print(dateTimeString);

      //reserved for showing time and SD card status
      menu_last_state = M_PAGE1;

      if(millis() - MenuShowTime >= MenuDelayInMillis)
        menu_FSM = M_PAGE2;
      
      
      
    break;
    case M_PAGE2:
      if(menu_FSM !=menu_last_state) {
        DisplayClear();
        mySerial.write("Sens 1:        C"); 
        mySerial.write("Sens 2:        C"); 
        DisplayGoto(1,14);
        mySerial.write(223); 
        DisplayGoto(2,14);
        mySerial.write(223); 
        MenuShowTime = millis();
      }  

      DisplayGoto(1,10);
      mySerial.write(dtostrf(SensorData.sensor1,4,1,tempstring)); // write out the RPM value

      DisplayGoto(2,10);
      mySerial.write(dtostrf(SensorData.sensor2,4,1,tempstring)); // write out the TEMP value
      //mySerial.write(dtostrf(system_FSM,4,1,tempstring)); DEBUG
      
      menu_last_state = M_PAGE2;

      if(millis() - MenuShowTime >= MenuDelayInMillis)
        menu_FSM = M_PAGE3;
      
    break;
    case M_PAGE3:
      if(menu_FSM !=menu_last_state) {
		DisplayClear();
        mySerial.write("Sens 3:  N/A   C"); // clear display + legends
        mySerial.write("Sens 4:  N/A   C"); 
        DisplayGoto(1,14);
        mySerial.write(223); 
        DisplayGoto(2,14);
        mySerial.write(223);
        MenuShowTime = millis();
      }  

      DisplayGoto(1,7);
      
//    mySerial.write(dtostrf(SensorData.sensor1,4,1,tempstring)); // write out the RPM value

      DisplayGoto(2,7);

      //mySerial.write(dtostrf(MenuShowTime,4,1,tempstring)); // write out the TEMP value
      menu_last_state = M_PAGE3;

      if(millis() - MenuShowTime >= MenuDelayInMillis)
        menu_FSM = M_PAGE1;
      
    break;
    case M_PAGE4:
    break;
    default:
      menu_FSM = M_PAGE1;
  }
 }
Example #16
0
static void PacketReceived (PACKET_Instance_t *inst, PACKET_Packet_t *packet, PACKET_Error_t err)
{
	if (err == PACKET_ERROR_NONE)
	{
		// we really only care about packets for us...
		if (packet->m_id == 0x01)
		{
			switch (packet->m_cmd)
			{
				case PACKET_CMD_SET_ID:
				{
					//printf ("got SET_ID command\n");
					break;
				}
				
				case PACKET_CMD_START_ASYNC:
				{
					//printf ("got START_ASYNC command\n");
					turnOnAsyncCapture();
					break;
				}
				
				case PACKET_CMD_STOP_ASYNC:
				{
					//printf ("got STOP_ASYNC command\n");
					sendingSamples = 0;
					break;
				}
				
				case PACKET_CMD_TURN_OFF_BATTERY:
				{
					//printf ("got TURN_OFF_BATTERY command\n");
					Battery_EnableLow();
					break;
				}
				
				case PACKET_CMD_TURN_ON_BATTERY:
				{
					//printf ("got TURN_ON_BATTERY command\n");
					Battery_EnableHigh();
					break;
				}
				
				case PACKET_CMD_SEND_SAMPLE:
				{
					//printf ("got PACKET_CMD_SEND_SAMPLE command\n");
					//turnOnFlag();
					currentSample = 0;
					CreateSample(SAMPLE_NORMAL);
					SendSamples(1, PACKET_CMD_SAMPLE);
					break;
				}
				
				case PACKET_CMD_SET_CALIBRATION:
				{
					//printf ("got PACKET_CMD_SET_CALIBRATION command\n");
					calibrationFloor = *(float *)&packet->m_param[0];
					calibrationScale = *(float *)&packet->m_param[4];
					eeprom_write_float((float*)(CALIBRATION_EEPROM_BASE + CALIBRATION_FLOOR_LOCATION), calibrationFloor);
					eeprom_write_float((float*)(CALIBRATION_EEPROM_BASE + CALIBRATION_SCALE_LOCATION), calibrationScale);
					eeprom_write_byte((uint8_t*)(CALIBRATION_EEPROM_BASE + CALIBRATION_SIGNATURE_LOCATION), CALIBRATION_SIGNATURE);
					//printf("Calibration parameters saved to EEPROM\n");
					//char output[16];
					//dtostrf(calibrationFloor, 7, 4, output);
					//printf("FLOOR: %s\n", output);
					//dtostrf(calibrationScale, 7, 4, output);
					//printf("SCALE: %s\n", output);
					break;
				}
				
				case PACKET_CMD_GET_CALIBRATION:
				{
					if (debugMode) {
						printf ("got PACKET_CMD_GET_CALIBRATION command\n");
					}
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0x01); // ammeter id
					uint8_t checksum = 0x01;
					uint8_t floatSize = sizeof(calibrationFloor);
					uint8_t packetLength = (floatSize * 2) + 2;
					RingBuffer_Insert(&Send_USB_Buffer, packetLength); // packet length, including all framing
					checksum += packetLength;
					RingBuffer_Insert(&Send_USB_Buffer, PACKET_CMD_CALIBRATION); // command
					checksum += PACKET_CMD_CALIBRATION;
					for (int index=0; index < floatSize; index++) {
						uint8_t value = ((uint8_t *)&calibrationFloor)[index];
						RingBuffer_Insert(&Send_USB_Buffer, value);
						checksum += value;
					}
					for (int index=0; index < floatSize; index++) {
						uint8_t value = ((uint8_t *)&calibrationScale)[index];
						RingBuffer_Insert(&Send_USB_Buffer, value);
						checksum += value;
					}
					RingBuffer_Insert(&Send_USB_Buffer, ~checksum);
					break;
				}
				
				case PACKET_CMD_GET_COMPENSATION:
				{
					if (debugMode) {
						printf ("got PACKET_CMD_GET_COMPENSATION command\n");
					}
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0x01); // ammeter id
					uint8_t checksum = 0x01;
					uint8_t floatSize = sizeof(calibrationFloor);
					uint8_t packetLength = 1 + floatSize + 2;
					RingBuffer_Insert(&Send_USB_Buffer, packetLength); // packet length, including all framing
					checksum += packetLength;
					RingBuffer_Insert(&Send_USB_Buffer, PACKET_CMD_COMPENSATION); // command
					checksum += PACKET_CMD_COMPENSATION;
					RingBuffer_Insert(&Send_USB_Buffer, compensation);
					checksum += compensation;
					for (int index=0; index < floatSize; index++) {
						uint8_t value = ((uint8_t *)&baselineVoltage)[index];
						RingBuffer_Insert(&Send_USB_Buffer, value);
						checksum += value;
					}
					RingBuffer_Insert(&Send_USB_Buffer, ~checksum);
					break;
				}
				
				case PACKET_CMD_GET_RAW_SAMPLE:
				{
					//printf ("got PACKET_CMD_GET_RAW_SAMPLE command\n");
					currentSample = 0;
					CreateSample(SAMPLE_RAW);
					SendSamples(1, PACKET_CMD_GET_RAW_SAMPLE);
					break;
				}
				
				case PACKET_CMD_GET_VERSION:
				{
					//printf ("got PACKET_CMD_GET_VERSION command\n");
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0x01); // ammeter id
					uint8_t checksum = 0x01;
					uint8_t packetLength = 1 + 2;
					RingBuffer_Insert(&Send_USB_Buffer, packetLength); // packet length, including all framing
					checksum += packetLength;
					RingBuffer_Insert(&Send_USB_Buffer, PACKET_CMD_VERSION); // command
					checksum += PACKET_CMD_VERSION;
					RingBuffer_Insert(&Send_USB_Buffer, AMMETER_VERSION);
					checksum += AMMETER_VERSION;
					RingBuffer_Insert(&Send_USB_Buffer, ~checksum);
					break;
				}
				
				case PACKET_CMD_GET_SERIAL:
				{
					if (debugMode) {
						printf ("got PACKET_CMD_GET_SERIAL command\n");
					}
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
					RingBuffer_Insert(&Send_USB_Buffer, 0x01); // ammeter id
					uint8_t checksum = 0x01;
					uint8_t packetLength = 2 + 2;
					RingBuffer_Insert(&Send_USB_Buffer, packetLength); // packet length, including all framing
					checksum += packetLength;
					RingBuffer_Insert(&Send_USB_Buffer, PACKET_CMD_SERIAL); // command
					checksum += PACKET_CMD_SERIAL;
					RingBuffer_Insert(&Send_USB_Buffer, serialNumber & 0xFF);
					checksum += serialNumber & 0xFF;
					RingBuffer_Insert(&Send_USB_Buffer, serialNumber >> 8);
					checksum += serialNumber >> 8;
					RingBuffer_Insert(&Send_USB_Buffer, ~checksum);
					break;
				}

				case PACKET_CMD_SET_SERIAL:
				{
					//printf ("got PACKET_CMD_SET_SERIAL command\n");
					serialNumber = *(uint16_t *)&packet->m_param[0];
					eeprom_write_word((float*)(CALIBRATION_EEPROM_BASE + SERIAL_NUMBER_LOCATION), serialNumber);
					//printf("Serial number saved to EEPROM\n");
					//printf("Serial Number: %d\n", serialNumber);
					break;
				}

				case PACKET_CMD_DUMP_DEBUG_INFO:
				{
					dumpDebugInfo();
					break;
				}

				case PACKET_CMD_TURN_ON_COMPENSATION:
				{
					float value = *(float *)&packet->m_param[0];
					if ((value >= 3.7) && (value <= 4.2)) {
						compensation = 1;
						eeprom_write_byte((float*)(CALIBRATION_EEPROM_BASE + COMPENSATION_FLAG_LOCATION), compensation);
						baselineVoltage = value;
						eeprom_write_float((float*)(CALIBRATION_EEPROM_BASE + BASELINE_VOLTAGE_LOCATION), baselineVoltage);
					}
					break;
				}
				
				case PACKET_CMD_TURN_OFF_COMPENSATION:
				{
					compensation = 0;
					eeprom_write_byte((float*)(CALIBRATION_EEPROM_BASE + COMPENSATION_FLAG_LOCATION), compensation);
					break;
				}
				
				case PACKET_CMD_START_LOGGING:
				{
					loggingFlag = 1;
					if (debugMode) {
						debugMode = 0;
					} else {
						InitUART ();
						fdevopen (UART1_PutCharStdio, UART1_GetCharStdio);
					}
					eeprom_write_byte((float*)(CALIBRATION_EEPROM_BASE + LOGGING_FLAG_LOCATION), loggingFlag);
					turnOnAsyncCapture();
					break;
				}
				
				case PACKET_CMD_STOP_LOGGING:
				{
					sendingSamples = 0;
					loggingFlag = 0;
					eeprom_write_byte((float*)(CALIBRATION_EEPROM_BASE + LOGGING_FLAG_LOCATION), loggingFlag);
					break;
				}
				
				case PACKET_CMD_CHECK_AUX_BATTERY:
				{
					loggingFlag = 0;
					if (debugMode) {
						debugMode = 0;
					} else {
						InitUART ();
						fdevopen (UART1_PutCharStdio, UART1_GetCharStdio);
					}
					printf("I2C Test\n");
                    float voltage = readAuxBatteryVoltage();
                    char output[16];
                    dtostrf(voltage, 4, 2, output);
                    printf("Battery Voltage: %s volts\n", output);
					break;
				}

                case PACKET_CMD_TURN_OFF_AUX_USB:
                {
                    //printf ("got TURN_OFF_BATTERY command\n");
                    AuxUSB_Disable();
                    break;
                }

                case PACKET_CMD_TURN_ON_AUX_USB:
                {
                    //printf ("got TURN_ON_BATTERY command\n");
                    AuxUSB_Enable();
                    break;
                }

                case PACKET_CMD_GET_TEMPERATURE:
                {
                    if (debugMode) {
                        printf ("got PACKET_CMD_GET_TEMPERATURE command\n");
                    }
                    float temperature = ReadTemperatureProbe();
                    RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
                    RingBuffer_Insert(&Send_USB_Buffer, 0xFF);
                    RingBuffer_Insert(&Send_USB_Buffer, 0x01); // ammeter id
                    uint8_t checksum = 0x01;
                    uint8_t floatSize = sizeof(temperature);
                    uint8_t packetLength = floatSize + 2;
                    RingBuffer_Insert(&Send_USB_Buffer, packetLength); // packet length, including all framing
                    checksum += packetLength;
                    RingBuffer_Insert(&Send_USB_Buffer, PACKET_CMD_TEMPERATURE); // command
                    checksum += PACKET_CMD_TEMPERATURE;
                    for (int index=0; index < floatSize; index++) {
                        uint8_t value = ((uint8_t *)&temperature)[index];
                        RingBuffer_Insert(&Send_USB_Buffer, value);
                        checksum += value;
                    }
                    RingBuffer_Insert(&Send_USB_Buffer, ~checksum);
                    break;
                }
                
                case PACKET_CMD_SOFT_RESET:
                {
                    if (debugMode) {
                        printf ("got PACKET_CMD_SOFT_RESET command\n");
                    }
                    wdt_enable(WDTO_60MS);
                    while(1) {};
                    
                    break;
                }

                default:
				{
					// there are other commands that we don't care about....
					//printf ("ID:0x%02x Cmd: 0x%02x *** Unknown ***\n", packet->m_id, packet->m_cmd);
					break;
				}
			}
		}
		else {
			//printf ("Got packet for ID: %3d\n", packet->m_id);
		}
	}
Example #17
0
void CardReader::closeFile(bool store_location /*=false*/) {
  file.sync();
  file.close();
  saving = false;

  if (store_location) {
    char bufferFilerestart[50];
    char bufferX[11];
    char bufferY[11];
    char bufferZ[11];
    char bufferE[11];
    char bufferCoord[50];
    char bufferCoord1[50];
    char bufferCoord2[50];
    char bufferSdpos[11];
    char nameFile[15];
    snprintf(bufferSdpos, sizeof bufferSdpos, "%lu", (unsigned long)sdpos);

    strcpy(nameFile, "restart.gcode");
    if (!fileRestart.exists(nameFile)) {
      fileRestart.createContiguous(&workDir, nameFile, 1);
      fileRestart.close();
    }

    fileRestart.open(&workDir, nameFile, O_WRITE);
    fileRestart.truncate(0);

    dtostrf(current_position[X_AXIS], 1, 3, bufferX);
    dtostrf(current_position[Y_AXIS], 1, 3, bufferY);
    dtostrf(current_position[Z_AXIS], 1, 3, bufferZ);
    dtostrf(current_position[E_AXIS], 1, 3, bufferE);

    #if MECH(DELTA)
      strcpy(bufferCoord1, "G1 Z");
      strcat(bufferCoord1, bufferZ);
      strcat(bufferCoord1, " F8000");
    #else
      strcpy(bufferCoord1, "G92 Z");
      strcat(bufferCoord1, bufferZ);
    #endif

    strcpy(bufferCoord, "G1 X");
    strcat(bufferCoord, bufferX);
    strcat(bufferCoord, " Y");
    strcat(bufferCoord, bufferY);
    strcat(bufferCoord, " Z");
    strcat(bufferCoord, bufferZ);
    strcat(bufferCoord, " F3600");
    strcpy(bufferCoord2, "G92 E");
    strcat(bufferCoord2, bufferE);

    for (int8_t i = 0; i < (int8_t)strlen(fullName); i++)
      fullName[i] = tolower(fullName[i]);

    strcpy(bufferFilerestart, "M34 S");
    strcat(bufferFilerestart, bufferSdpos);
    strcat(bufferFilerestart, " @");
    strcat(bufferFilerestart, fullName);

    #if MECH(DELTA)
      fileRestart.write("G28\n");
    #else
      fileRestart.write(bufferCoord1);
      fileRestart.write("\n");
      fileRestart.write("G28 X Y\n");
    #endif

    if (degTargetBed() > 0) {
      char Bedtemp[15];
      sprintf(Bedtemp, "M190 S%i\n", (int)degTargetBed());
      fileRestart.write(Bedtemp);
    }

    char CurrHotend[10];
    sprintf(CurrHotend, "T%i\n", active_extruder);
    fileRestart.write(CurrHotend);

    for (uint8_t h = 0; h < HOTENDS; h++) {
      if (degTargetHotend(h) > 0) {
        char Hotendtemp[15];
        sprintf(Hotendtemp, "M109 T%i S%i\n", h, (int)degTargetHotend(h));
        fileRestart.write(Hotendtemp);
      }
    }

    #if MECH(DELTA)
      fileRestart.write(bufferCoord1);
      fileRestart.write("\n");
    #endif

    fileRestart.write(bufferCoord);
    fileRestart.write("\n");

   	if (fanSpeed > 0) {
      char fanSp[15];
      sprintf(fanSp, "M106 S%i\n", fanSpeed);
      fileRestart.write(fanSp);
    }

    fileRestart.write(bufferCoord2);
    fileRestart.write("\n");
    fileRestart.write(bufferFilerestart);
    fileRestart.write("\n");

    fileRestart.sync();
    fileRestart.close();

    HAL::delayMilliseconds(200);

    #if MECH(DELTA)
      enqueue_and_echo_commands_P(PSTR("G28"));
    #else
      enqueue_and_echo_commands_P(PSTR("G28 X0 Y0"));
    #endif

    disable_all_heaters();
    disable_all_coolers();
    fanSpeed = 0;
  }
}
void loop() {

  int tenMinArrayMin[2], tenMinArrayMax[2], tenMinArrayAvg[2]; //changing to 2 for testing purposes
  int oneMinArray[59];
  int oneSecArray[3];
  int qSecondCount = 0, maxVal = 0, secondTotal = 0, minVal = 25;
  int tenMinAvg, tenMinMax, tenMinMin;



  //getTemp
 
  char bufH[10], bufC[10], bufT[10], bufF[10], bufHI[10];  

  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
  


  dtostrf(h,4,2,bufH);
  dtostrf(t,4,2,bufC);
  dtostrf(f,4,2,bufF);
  dtostrf(hi,4,2,bufHI);
  
  Serial.println(bufH);
  Serial.println(bufC);
  Serial.println(bufF);
  Serial.println(bufHI);
        
 
  
  //getBaroPress
  
  char bufBT[10], bufBP[10];
  
   if(!BaroSensor.isOK()) 
  {
    Serial.print("Sensor not Found/OK. Error: "); 
    Serial.println(BaroSensor.getError());
    BaroSensor.begin(); // Try to reinitialise the sensor if we can
  }
  else 
  {
  float baroSensorTemp = BaroSensor.getTemperature();
  float baroSensorPress = BaroSensor.getPressure();
  
  dtostrf(baroSensorTemp,4,2,bufBT);
  dtostrf(baroSensorPress,4,2,bufBP);    
  }
  
  Serial.print("This is bufT:");  
  Serial.println(bufBT);
  Serial.print("This is bufBP:");  
  Serial.println(bufBP);


//char outBuf[64];
char urlStr[200];
//String urlStr = "POST /weather4/?DHTCelcius="+ bufF;// "&DHTFarenheight="+ bufF +"&DHTHeatIndex=" +bufHI+"&DHTHumidity="+bufH+"&BaroCelcius="+bufBT+"&BaroPressure="+bufBP+ "HTTP/1.1";

sprintf(urlStr,"POST /weather4/?DHTCelcius=%s&DHTFarenheight=%s&DHTHeatIndex=%s&DHTHumidity=%s&BaroCelcius=%s&BaroPressure=%s HTTP/1.1",bufC,bufF,bufHI,bufH,bufBT,bufBP);

//sprintf(outBuf,"POST %s HTTP/1.1",urlStr);

//send to api

  if (client.connect(server, 5000)) {
    Serial.println("connected");
    // Make a HTTP request:
    //client.println("POST /weather4/?t=abc&h=def&ws=hij&wd=klm23344 HTTP/1.1");
    client.println(urlStr);
    client.println("Host: 192.168.0.110");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println("Content-Length:0");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }

  if (client.connected())
    {
     client.stop();
    }

  //delay 20 mins
//  delay(1200000);
//10 mins
  delay(600000);
  //testing pace
  //delay(5000);

}
HomeNetPartialPacket* HomeNetDeviceLCD::process(const uint16_t& fromNode, const uint8_t& fromDevice, const uint8_t& command, const HomeNetPayload& payload) {
#ifdef DEBUG
    Serial.println("Process LCD");
#endif

    //receive outside packets
  //  if (fromNode != _homeNet->_nodeId) {
        for (uint8_t i = 0; i < _displayCount; i++) {
            if ((fromNode == _display[i].fromNode) && (fromDevice == _display[i].fromDevice)) {
#ifdef DEBUG
                    Serial.println("LCD Display Packet Matched");
#endif
                 _lcd->setCursor(0, _display[i].row);
                 char line[16];// = "                ";
                 char num[9];
                //display = &_display[i];
                switch (command) {

                    case CMD_REPLYBYTE:
                        //_lcd->print("Byte");
                        //_lcd->print(payload.getByte(),DEC);
                        sprintf(line,_display[i].message, itoa(payload.getByte(), num, 10));
                        break;

                    case CMD_REPLYINT:
                        //_lcd->print("Int");
                        //_lcd->print(payload.getInt(),DEC);
                        sprintf(line,_display[i].message, itoa(payload.getInt(), num, 10));
                        break;

                    case CMD_REPLYFLOAT:
                        //_lcd->print(_display[i].message);
                        //_lcd->print();
                        sprintf(line,_display[i].message, dtostrf(payload.getFloat(), 5, 2,num));
                        break;
                    
                }
                _lcd->print(line);
                return NULL;
            } 
        }
    //}

    switch (command) {

        case CMD_SETVALUE:
        case CMD_SETSTRING:
            uint8_t length;
            length = payload.getLength();
            _lcd->clear();
            _lcd->setCursor(0, 0);
            if (length <= 16) {
                for (uint8_t i = 0; i < length; i++) {
                    _lcd->print(payload.getByte(i));
                }
                break;
            }
            for (uint8_t i = 0; i < 16; i++) {
                _lcd->print(payload.getByte(i));
            }
            _lcd->setCursor(0, 1);
            for (uint8_t i = 16; i < length; i++) {
                _lcd->print(payload.getByte(i));
            }
            break;

        case CMD_ON:
            _lcd->backlight();
            break;

        case CMD_OFF:
            _lcd->noBacklight();
            break;
    }
    return NULL;
}
Example #20
0
void wsMessageReceived(WebSocket& socket, const String& message) {
	//Serial.printf("WebSocket message received:\r\n%s\r\n", message.c_str());
	char buf[22];
	dtostrf(pf, 10, 8, buf);
	socket.sendString(buf);
}
void mqtt_publish_float(const char *name, float val)
{
  char msg[20];
  dtostrf(val, 0, 4, msg);
  mqtt_publish_str(name, msg);
}
Example #22
0
void Telemachus::command(const char* command, float value) {
  dtostrf(value,4,3,floatBuffer);
  return Telemachus::command(command, floatBuffer);
}
Example #23
0
void TM1637Display::showNumber(float number,int decPlaces){
   char buffer[7];  
   dtostrf(number, 0, decPlaces, buffer);
   showText(buffer);
}
Example #24
0
ICACHE_FLASH_ATTR String::String(float value, unsigned char decimalPlaces) {
    init();
    char buf[33];
    *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
Example #25
0
void generateCANMsg(tExtendedCAN *M, uint8_t port) {
	// 0x00, priority, sender, receiver
	uint8_t id[4] = {0x00, PRIORITY_NORM, REKICK_ID, COMPASS_ID};
	char buff[5];
	double reCalc = 0.0;
	if (port == 11 || port == 12) { // relais (triggerd by sys) ACK 11,12 .. -> 1,2,...
		/*		M->id[1] = 0x90;
		M->id[2] = M_BOARD_ID2;*/
		M->id[0] = 0x00;
		M->id[1] = PRIORITY_NORM;
		M->id[2] = 0x50;
		M->id[3] = 0x00;
		M->header.rtr = 0;
		M->header.length = 5;
		M->data[0] = (uint8_t) 'o';
		M->data[1] = (uint8_t) 'k';
		M->data[2] = (uint8_t) ':';
		M->data[3] = (port -10);
		M->data[4] = (uint8_t) ' ';
	}
	if (port == NOMEASUREBOARD) {
		M->id[0] = 0x00;
		M->id[1] = PRIORITY_NORM;
		M->id[2] = 0x50;
		M->id[3] = 0x00;
		M->header.rtr = 0;
		M->header.length = 6;
		M->data[0] = (uint8_t) 'n';
		M->data[1] = (uint8_t) 'o';
		M->data[2] = (uint8_t) 'b';
		M->data[3] = (uint8_t) 'o';
		M->data[4] = (uint8_t) 'a';
		M->data[5] = (uint8_t) 'r';
	}
	if (port == LED_ALERT) {
		M->id[0] = 0x00;
		M->id[1] = PRIORITY_NORM;
		M->id[2] = 0x50;
		M->id[3] = 0x00;
		M->header.rtr = 0;
		M->header.length = 3;
		M->data[0] = (uint8_t) 'l';
		M->data[1] = (uint8_t) 'e';
		M->data[2] = (uint8_t) 'd';
	}
	if (port == ACK_CAN) { // ACK
		M->id[0] = 0x00;
		M->id[1] = PRIORITY_NORM;
		M->id[2] = 0x50;
		M->id[3] = 0x00;
		M->header.rtr = 0;
		M->header.length = 7;
		M->data[0] = (uint8_t) 'a';
		M->data[1] = (uint8_t) 'c';
		M->data[2] = (uint8_t) !(PINC & (1<< lastPin1)) ? 'R' : 'r';
		M->data[3] = (uint8_t) ' ';
		M->data[4] = (uint8_t) ':';
		M->data[5] = (uint8_t) !(PINC & (1<< lastPin2)) ? 'R' : 'r';
		M->data[6] = (uint8_t) ' ';
	} else {
		M->id[0] = 0x00;
		M->id[1] = PRIORITY_NORM;
		M->id[2] = 0x50; // sender
		M->id[3] = 0x00; // receiver
		M->header.rtr = 0;
		M->header.length = 8;
		switch (portModeMeasure[port]) {
		case Vol : reCalc = measurement; break;
		case Light : reCalc = getLightIntensity(); break;
		case Temp : reCalc = getTemp(); break;
		case Noise : reCalc = getNoise(); break;
		case Distance :	reCalc = getDistance(); break;
		}
		switch (portModeMeasure[port]) {
		case Vol :
			dtostrf(reCalc ,5,1, buff);
			M->data[6] = 'V';
			break;
		case Light :
			dtostrf(reCalc, 5,2, buff);
			M->data[4] = ' ';
			M->data[5] = ' ';
			M->data[6] = 'L';
			break;
		case Temp :
			dtostrf(reCalc ,5,2, buff);
			M->data[5] = ' ';
			M->data[6] = 'C';
			break;
		case Noise :
			dtostrf(reCalc ,5,1, buff);
			M->data[6] = 'S';
			break;
		case Distance :
			dtostrf(reCalc ,5,1, buff);
			M->data[4] = ' ';
			M->data[5] = ' ';
			M->data[6] = 'D';
			break;
		}
		memcpy((void *)M->data, (const void *)buff, 5);
		M->data[7] = port ;
	}
}
Example #26
0
unsigned char ICACHE_FLASH_ATTR String::concat(float num) {
    char buf[20];
    char* string = dtostrf(num, 4, 2, buf);
    return concat(string, strlen(string));
}
Example #27
0
String::String(double value, unsigned char decimalPlaces)
{
	init();
	char buf[33];
	*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
Example #28
0
String::String(float num, unsigned char digits)
{
	init();
	char buf[40];
	*this = dtostrf(num, digits + 2, digits, buf);
}
Example #29
0
char check_gps()
{
  newData=false;
  unsigned long chars;
  unsigned short sentences, failed;

  // For one second we parse GPS data and report some key values
  for (unsigned long start = millis(); millis() - start < 1000;)
  {
    while (Serial2.available())
    {
      char c = Serial2.read();
      // Serial.write(c); // uncomment this line if you want to see the GPS data flowing
      if (gps.encode(c)) // Did a new valid sentence come in?
        newData = true;
    }
  }

  if (newData)
  {
    float flat, flon;
    unsigned long age;
    int _year;
    byte _month, _day,_hour,_minute,_second,_hundredths;        
    gps.f_get_position(&flat, &flon, &age);
        gps.crack_datetime(&_year,&_month,&_day,&_hour,&_minute,&_second,&_hundredths,&age);
        flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6;
        flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6;
    dtostrf(flat, 11, 6, gps_lat); 
    dtostrf(flon, 10, 6, gps_lon); 
        
        strcpy(gps_sms,"lat:");
        strcat(gps_sms,gps_lat);
        strcat(gps_sms,"\n");
        strcat(gps_sms,"lon:");
        strcat(gps_sms,gps_lon);
        strcat(gps_sms,"\n");
        strcat(gps_sms,"time:");
        
    itoa(_year,gps_year,10);
    strcat(gps_sms,gps_year);
        
    itoa(_month,gps_mon,10);
    if(strlen(gps_mon)==1)
      strcat(gps_sms,"0");
    strcat(gps_sms,gps_mon);
        
    itoa(_day,gps_day,10);
        if(strlen(gps_day)==1)
      strcat(gps_sms,"0");
    strcat(gps_sms,gps_day);
        
    itoa(_hour,gps_hour,10);
        if(strlen(gps_hour)==1)
      strcat(gps_sms,"0");
    strcat(gps_sms,gps_hour);
        
    itoa(_minute,gps_min,10);
        if(strlen(gps_min)==1)
      strcat(gps_sms,"0");
    strcat(gps_sms,gps_min);
        
    itoa(_second,gps_sec,10);
        if(strlen(gps_sec)==1)
      strcat(gps_sms,"0");
    strcat(gps_sms,gps_sec);        
        
    Serial.println(gps_sms);


  }
  



}
Example #30
0
unsigned char String::concat(float num)
{
	char buf[20];
	char* string = dtostrf(num, (20 - 1), 2, buf);
	return concat(string, strlen(string));
}