• Welcome to LusoRobótica - Robótica em Português.
 

Float to String

Started by DanBar, 06 de February de 2010, 23:14

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

DanBar

Já tinha experimentado tirar o pointer, dava erro na mesma
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas

DanBar

Vai te deitar amigo. Eu resolvo isso depois. Também já não dou uma para a caixa
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas

TigPT

É que não estou a visualizar as funções de manipulação de strings k o arduino tem incluidas... estou habituado a trabalhar em alto nível... Estava a esquecer-me que tem que ser um código de baixo nível.


Fica aqui só umas ideias para amanhã ver... o meu mal é sono!
void floatToStr(char * outstr, float value, int places, char separator){

  outstr = "" + (int)value + separator + (int)((value-(int)value)*(10*places));
}

void rIntToStr(int value, char *str){
if (value == 0) return;
rIntToStr(value/10, str++);
str = value % 10;
}

DanBar

#18
Este era o meu antigo código :


void Lcd_PrintFloat(float Number, byte decimals){
  int frac;
  int rnd;
  char NumStr[20];
  rnd = (unsigned int)(Number*1000)%10;
  frac=(unsigned int)(Number*100)%100;  //get three numbers to the right of the deciaml point.
  if (rnd>=5) frac=frac+1;
    itoa((int)Number,NumStr,10);           // I changed it to 2 decimal places
    strcat(NumStr,".");
    if (frac<10)  {itoa(0,&NumStr[strlen(NumStr)],10); }   // if fract < 10 should print .0 fract ie if fract=6 print .06
    itoa(frac,&NumStr[strlen(NumStr)],10); //put the frac after the deciaml
lcd.printIn(NumStr); 
}


Mas com este código aparece sempre 2 digitos.


Este é o que estou a utilizar agora (foto)

void floatToStr(char * outstr, float value, int places) {
  dtostrf(value,sizeof(value),places,outstr);
}
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas

Njay

QuoteThe minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width

Portanto, se queres 2 digitos inteiros positivos mais o ponto mais 1 digito decimal, o valor para width deve ser 4 (caracteres). Só por acaso, sizeof(float) é tipicamente 4.

Quoteand prec determines the number of digits after the decimal sign.

Como só queres 1 digito decimal, _prec deve ser 1.

Esqueçam essas funções "floatToStr", em C não há concatenação de strings suportado de base pela linguagem. "" + ... não existe; bom, na verdade até o podem fazer, se fizerem casts, mas "" representa o ponteiro, o ponteiro para a localização de memória que guarda a string constante "". Mas não é nada do que vocês querem.

msr

Em geral quando quero fazer conversões ou concatenar uma quantidade de valores numa string uso a função sprintf().
O uso é desta forma: sprintf(str,"%d %f",val1,val2);

Mas não sei se dará para fazer o mesmo no Arduino.
Dá uma vista de olhos neste link: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1200716061

DanBar

Já funciona:


char StrTemp[6];
floatToStr(StrTemp,MaxTempExt,1);

void floatToStr(char * outstr, float value, int places) {
int f_int;
int pows_of_ten[4] = {1, 10, 100, 1000};
int multiplier, whole, fract, d, n;
char DispString[32];
char fraction[32];

multiplier = pows_of_ten[places];
if (value < 0.0)
{
   value = -value;
   strcat(outstr,"-");
}
whole = (int) value;
fract = (int) (multiplier * (value - (float)whole));
itoa(whole,outstr,10);
strcat(outstr,".");
for (n=places-1; n>=0; n--) // print each digit with no leading zero suppression
{
   d = fract / pows_of_ten[n];
   itoa((int)d,&outstr[strlen(outstr)],10);
}
}


Obrigado pelo link msr  ;)
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas

DanBar

Resultado:

QuoteTemperatura Ambiente: 21.87 C
MaxTemp:21.87 lcd:21.8
MinTemp:21.87 lcd:21.8

Temperatura Ambiente: 21.94 C
MaxTemp:21.94 lcd:21.9
MinTemp:21.87 lcd:21.8

Temperatura Ambiente: 21.87 C
MaxTemp:21.94 lcd:21.9
MinTemp:21.87 lcd:21.8

MaxTemp:21.94 lcd:21.9
MinTemp:21.87 lcd:21.8

MaxTemp:21.94 lcd:21.9
MinTemp:21.87 lcd:21.8

Temperatura Ambiente: 24.62 C
MaxTemp:24.62 lcd:24.6
MinTemp:21.87 lcd:21.8

Temperatura Ambiente: 23.69 C
MaxTemp:24.62 lcd:24.6
MinTemp:21.87 lcd:21.8
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas

TigPT

Está a truncar em vez de arredondar... depois com mais calma vejo disso contigo! ;)

DanBar

#24
Talvez não me tenha explicado bem. Era mesmo isso que eu queria desde o inicio "truncar" e não "aredondar"  ;D

Mas posso sempre decidir depois:

void floatToStr(char * outstr, float value, int places, boolean rounds) {
if (rounds){ // arredondar
    dtostrf(value,sizeof(value),places,outstr);
} else { // truncar
   int f_int;
   int pows_of_ten[4] = {1, 10, 100, 1000};
   int multiplier, whole, fract, d, n;
   char DispString[32];
   char fraction[32];
   multiplier = pows_of_ten[places];
   if (value < 0.0) {
     value = -value;
     strcat(outstr,"-");
   }
   whole = (int) value;
   fract = (int) (multiplier * (value - (float)whole));
   itoa(whole,outstr,10);
   strcat(outstr,".");
   for (n=places-1; n>=0; n--){ // print each digit with no leading zero suppression
     d = fract / pows_of_ten[n];
     itoa((int)d,&outstr[strlen(outstr)],10);
   }
}
}
Antigo Nick do Forum: iCAR

Projectos iCAR
icar.lusorobotica.com

DB@G
http://www.facebook.com/daniel.barradas