4 years, 10 months ago.

string convert to int

I have this code :

#include "mbed.h"

#include "stdio.h"
 
SPI DDS(p5, p6, p7); // mosi, miso, sclk

DigitalOut SPI_EN(p8); //Pino de enable da DDS.

DigitalOut IO_UPD(p9); //Pino de update da DDS.

Serial pc(USBTX, USBRX); // tx, rx

DigitalOut led(LED1);


char DDS_REGIS[21] = {0x00,0x01,0x02,0x03,0x04,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16};

void DDS_WRITE(char regis_0, int dado_0) 
{

    SPI_EN = 0;        

    wait(0.0001);  
       
    DDS.write(regis_0); 

    wait(0.0001);

    DDS.write(dado_0); 

    wait(0.0001);

    SPI_EN = 1;         
}

void DDS_ATUALIZA(void) 
{
    wait(0.0001);

    IO_UPD = 1;

    wait(0.00005);

    IO_UPD = 0;

}



///////////////////////////////////////////////////// [Programa Principal] //////////////////////////////////////////////////////////////////////////

int main (){
    
DDS.format(8,0); 

DDS.frequency(10000);
                   
SPI_EN = 1;

IO_UPD = 0; 
  
  int DADOS_SPI;

  char DADOS_PC[33];

      
  pc.gets(DADOS_PC,33);

  pc.printf(" Digitou '%s' \n ",DADOS_PC);
  
  DADOS_SPI = atoi(DADOS_PC);

  pc.printf(" %d \n",DADOS_SPI);
    
 wait(0.1);

 DDS_WRITE(DDS_REGIS[0],DADOS_SPI);

 wait(0.0001);

DDS_ATUALIZA();


}

When i send my comand to mbed , i got this answer : 2147483647.

I don't uderstand whats its means.

Can anyone helps me ?

/media/uploads/Hetan97/sem_t-tulo.jpg /media/uploads/Hetan97/sem_t-tulo.jpg

2 Answers

4 years, 10 months ago.

Hello Rogério,
To make you code nicer when diplayed on this page (i.e. formatted as computer source code), could you please enclose it with the lines as indicated below?

<<code>>

your source code

<</code>>

Your additinal notes, comments and pictures.

Thank you.

4 years, 10 months ago.

atoi assumes that the string you are giving it is in base 10 and returns an int data type. You are passing it what looks like a 32 bit binary number. Since an int is defined as being at least 16 bits it's not large enough to store your result even if the conversion was correct.

In other words it's not going to work.

If you want to convert a string of binary digits into to an integer use strtol()

e.g.

long int DADOS_SPI  = strtol(DADOS_PC,NULL,2); // strtol returns a long (at least 32 bits)
pc.printf(" %ld \n",DADOS_SPI); // %ld since it is a long int

http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

Thank you Andy, I was looking for an example of the use "strtol" in mbed,

Best regards.

posted by Felícito Manzano 09 Jun 2016

strtol is part of the standard library, it is the same everywhere. There is no need for an mbed specific example because that code would look the same as an example for anything else.

The link in the original answer gives examples, if you want more use google.

posted by Andy A 09 Jun 2016

Assigned to Rogério Barros 4 years, 10 months ago.

This means that the question has been accepted and is being worked on.