Converts String to int Arduino in C

Asked

Viewed 716 times

0

Good people, I will try to explain my problem. I am developing a little software in Netbeans that communicates with Arduino via Serial Port.

My problem is that in Netbeans IDE I am sending String, and I need to convert this String to a whole and I’m not getting it. The Serial port is declared as integer. But it still does not receive the Netbeans String.

I’m not sure I was clear on the question, but please help me.

Arduino code:

 void loop(){

     // Loop Função main  
     if(Serial.available()>0){  // Vericando se Existe conexão 

         //declarando variável que irá recebe comandos do NetBeans

          int  byteEntrada = 0; // A variável byteEntrada irá  recebe Bits do NetBeans , Esses Bits sera transforma em  comandos para o Acendimento de LEDS.
          int  Porta1 =0;    
          int  Porta2 =0;          // A variável Por1, por2,port3, Será ultizada para indicar as portas que vão  se usada no Arduino.
          int  Porta3 =0; 


             byteEntrada =  Serial.read();      // Fazendo Leitura da porta Serial  para o Comando byteEntrada
                  Porta1 =  Serial.read();     // Fazendo Leitura da porta Serial  para o Comando porta1
                  Porta2 =  Serial.read();    // Fazendo Leitura da porta Serial  para o Comando porta2
                  Porta3 =  Serial.read();  // Fazendo Leitura da porta Serial  para o Comando porta3



          if(byteEntrada == '1')
           {  // Se o Bit que veio do NetBeans for igual a 1
             Desligado(Porta1,Porta2,Porta3,'h','h','l'); // Sera passado por parametro  as portas, e a situação para cada led   se ( H )  ligado se (L) desligado.
           } 

    }
}

Here is the Netbeans code you are sending:

public void enviarDados(String dados, String p1,String p2,String p3){
    try{
    output.write(dados.getBytes());
    output.write(p1.getBytes());
    }catch(IOException e){
        Exibir_ERRO("Erro");
        System.exit(ERROR);
    }
}

The function Desligado:

void  Desligado (int x,int y,int z,char st1,char st2,char st3){

    if ( st1 == 'l' ) {
        digitalWrite (x,LOW); 
     } else {
        digitalWrite (x,HIGH);
     }
    if ( st2 == 'l' ) {
       digitalWrite (y,HIGH); 
     } else {
       digitalWrite (y,HIGH);
     }
    if ( st3 == 'l' ) {
       digitalWrite (z,HIGH); 
     } else {
      digitalWrite (z,HIGH);
     }
}

The part of Netbeans that is configuring communication with the Arduino:

public void iniciarConexao(){
    CommPortIdentifier portaId = null;
    Enumeration portaEnum = CommPortIdentifier.getPortIdentifiers();

    while(portaEnum.hasMoreElements()){
        CommPortIdentifier atualPortaId =(CommPortIdentifier) portaEnum.nextElement();
        if(porta.equals(atualPortaId.getName())){
            portaId=atualPortaId;
            break;
        }
    }
    if(portaId == null){
        Exibir_ERRO("Não se pode conectar a porta");
        System.exit(ERROR);
    }

    try{
        serialPort = (SerialPort) portaId.open(this.getClass().getName(), timeOut);
        //parametros da porta serial

        serialPort.setSerialPortParams(dataRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        output = serialPort.getOutputStream();
    }catch(Exception e){
        Exibir_ERRO(e.getMessage());
        System.exit(ERROR);
    }
}

public void enviarDados(String dados,String p1,String p2,String p3){
    try{
    output.write(dados.getBytes());
    output.write(p1.getBytes());
    output.write(p2.getBytes());
    output.write(p3.getBytes());

    }catch(IOException e){
        Exibir_ERRO("Erro");
        System.exit(ERROR);
    }
}
  • 1

    Hello Jefferson. Just by the code and description of your question is not very clear what you are trying to do and what problem you are facing. What is output? That’s the OutputStream of the door? As the SerialPort is configured on the java side? Where are you reading the C-side string? Maybe this example of Soen clarify a few things.

  • What is the content of these strings you are trying to upload? Why does the upload method use the parameters dados and p1, but does not use the p2 and the p3?

  • sorry if I was unclear in my question , this output would be to send to Arduino, @Anthony Accioly *? public void startConexao(){ Commportidentifier portaId = null; Enumeration portaEnum = Commportidentifier.getPortIdentifiers(); while(portaEnum.hasMoreElements()){
 CommPortIdentifier atualPortaId =(CommPortIdentifier) portaEnum.nextElement();
 if(porta.equals(atualPortaId.getName())){
 portaId=atualPortaId;
 break;
 }
 }
 **

  • @Victorstafusa I am trying to send the following command , The data is referring to the command if you turn on or delete the LED, already P1, P2,P3, is configuring which pin will be connected.

  • @Jeffersonsantos Edit the question to make it clearer. I don’t understand the strings, what are the possible contents of each string? It seems to me that these strings should be booleans.

  • Enter the function code Desligado from the West as well.

  • @Victorstafusa I changed the question I know if now ta but clear

  • @Jeffersonsantos I already have an answer in half, but there’s still one thing left for me to finish it: Who is calling the method enviarDados?

Show 3 more comments

2 answers

3


The first thing I see wrong is in your job Desligado:

void  Desligado (int x,int y,int z,char st1,char st2,char st3){

    if ( st1 == 'l' ) {
        digitalWrite (x,LOW); 
     } else {
        digitalWrite (x,HIGH);
     }
    if ( st2 == 'l' ) {
       digitalWrite (y,HIGH); 
     } else {
       digitalWrite (y,HIGH);
     }
    if ( st3 == 'l' ) {
       digitalWrite (z,HIGH); 
     } else {
      digitalWrite (z,HIGH);
     }
}

Note the second if-else: If the st2 is equal to l then he puts HIGH in the y. Otherwise, he also puts HIGH equally the same way! I guess it had to be LOW and HIGH instead of HIGH and HIGH. The same goes for the third if-else.

So your code would look like this:

void Desligado(int x, int y, int z, char st1, char st2, char st3) {
    if (st1 == 'l') {
        digitalWrite(x, LOW); 
    } else {
        digitalWrite(x, HIGH);
    }
    if (st2 == 'l') {
        digitalWrite(y, LOW); 
    } else {
        digitalWrite(y, HIGH);
    }
    if (st3 == 'l') {
        digitalWrite(z, LOW);
    } else {
        digitalWrite(z, HIGH);
    }
}

In the meantime, thanks to the ternary operator, there is still room for further simplification:

void Desligado(int x, int y, int z, char st1, char st2, char st3) {
    digitalWrite(x, st1 == 'l' ? LOW : HIGH);
    digitalWrite(y, st2 == 'l' ? LOW : HIGH);
    digitalWrite(z, st3 == 'l' ? LOW : HIGH);
}

On the other hand, we don’t really need the ternary operator. It’s being used to translate from char to constants LOW or HIGH. If we pass as a parameter the counts themselves, we eliminate the need to have the ternary operator:

void Desligado(int x, int y, int z, int st1, int st2, int st3) {
    digitalWrite(x, st1);
    digitalWrite(y, st2);
    digitalWrite(z, st3);
}

And on the outside instead:

Desligado(Porta1,Porta2,Porta3,'h','h','l');

We get that:

Desligado(Porta1, Porta2, Porta3, HIGH, HIGH, LOW);

However, this function is only associating three gates to three logical levels directly and independently. That is, it is not encapsulating any complex logic and is not contributing much to the simplicity of the code. So we can eliminate it and then the function loop is like this (I took the comments):

void loop() {
    if (Serial.available() > 0) {
        int byteEntrada = 0;
        int Porta1 = 0;
        int Porta2 = 0;
        int Porta3 = 0;
        byteEntrada = Serial.read();
        Porta1 = Serial.read();
        Porta2 = Serial.read();
        Porta3 = Serial.read();

        if (byteEntrada == '1') {
            digitalWrite(Porta1, HIGH);
            digitalWrite(Porta2, HIGH);
            digitalWrite(Porta3, LOW);
        }
    }
}

You can simplify the loop function by seeing that the zeros used at startup are never used, and therefore can be deleted:

void loop() {
    if (Serial.available() > 0) {
        int byteEntrada = Serial.read();
        int Porta1 = Serial.read();
        int Porta2 = Serial.read();
        int Porta3 = Serial.read();

        if (byteEntrada == '1') {
            digitalWrite(Porta1, HIGH);
            digitalWrite(Porta2, HIGH);
            digitalWrite(Porta3, LOW);
        }
    }
}

You can simplify it a little more by realizing that if the flow doesn’t enter the if, then the function will come to the end without doing anything else (and with that we can take a shortcut):

void loop() {
    if (Serial.available() <= 0) return;
    int byteEntrada = Serial.read();
    int Porta1 = Serial.read();
    int Porta2 = Serial.read();
    int Porta3 = Serial.read();

    if (byteEntrada != '1') return;
    digitalWrite(Porta1, HIGH);
    digitalWrite(Porta2, HIGH);
    digitalWrite(Porta3, LOW);
}

Well, as for the "Netbeans side", that doesn’t exist. The right thing to say is "Java side". Java runs this, not Netbeans. Netbeans is just an anabolic text editor, it’s not him who runs your real programs. What happens is that Netbeans gives you little buttons to run the program, but all it actually does is ask the operating system to run the JVM and ask the JVM to run its program. That’s more or less the same as asking your nephew to turn on the living room fan, who will give you the wind is the fan and not your nephew, the nephew just turned on him.

Well, let’s see on the Java side:

public void enviarDados(String dados,String p1,String p2,String p3){
    try{
    output.write(dados.getBytes());
    output.write(p1.getBytes());
    output.write(p2.getBytes());
    output.write(p3.getBytes());

    }catch(IOException e){
        Exibir_ERRO("Erro");
        System.exit(ERROR);
    }
}

This won’t do what you want. What you want is to send bytes 1, 2, 3, not strings "1", "2", "3". That’s quite different because character "1" is encoded with byte 49, character "2" is encoded with byte 50 and "3" with byte 51. Therefore, we need to do the conversion in Java.

I don’t know where you use the function enviarDados, but let’s assume you want to use it like this:

enviarDados(1, 3, 4, 5);

So you’d have to use the type int instead of String:

public void enviarDados(int dados, int p1, int p2, int p3) {
    try {
        output.write((byte) dados);
        output.write((byte) p1);
        output.write((byte) p2);
        output.write((byte) p3);
    } catch (IOException e) {
        Exibir_Erro("Erro");
        System.exit(ERROR);
    }
}

But if you want to wear it like that:

enviarDados("1", "3", "4", "5");

So you’d have to do it like this:

public void enviarDados(String dados, String p1, String p2, String p3) {
    try {
        output.write(Byte.parseByte(dados));
        output.write(Byte.parseByte(p1));
        output.write(Byte.parseByte(p2));
        output.write(Byte.parseByte(p3));
    } catch (IOException e) {
        Exibir_Erro("Erro");
        System.exit(ERROR);
    }
}

Or if you already have it in bytes:

byte a = ..., b = ..., c = ..., d = ...;
enviarDados(a, b, c, d);

Then you wouldn’t need any conversion:

public void enviarDados(byte dados, byte p1, byte p2, byte p3) {
    try {
        output.write(dados);
        output.write(p1);
        output.write(p2);
        output.write(p3);
    } catch (IOException e) {
        Exibir_Erro("Erro");
        System.exit(ERROR);
    }
}

You can separate the serial port location from the aperture into two separate methods. The only annoying thing is that the API javax.comm is so still in time that even today it will not offer the Generics of Java 5 (who is already very old with his 12 years):

private CommPortIdentifier localizarPortaSerial() {
    CommPortIdentifier portaId = null;
    List<CommPortIdentifier> portas = Collections.list((Enumeration<CommPortIdentifier>) CommPortIdentifier.getPortIdentifiers());

    for (CommPortIdentifier portaId : portas) {
        if (porta.equals(portaId.getName())) return portaId;
    }
    Exibir_ERRO("Não se pode conectar a porta");
    System.exit(ERROR);
    throw new AssertionError(); // Nunca será executado por causa do System.exit.
}

public void iniciarConexao() {
    CommPortIdentifier portaId = localizarPortaSerial();

    try {
        serialPort = (SerialPort) portaId.open(this.getClass().getName(), timeOut);
        serialPort.setSerialPortParams(dataRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        output = serialPort.getOutputStream();
    } catch (Exception e) {
        Exibir_ERRO(e.getMessage());
        System.exit(ERROR);
    }
}

There should be a lot more possible improvements, but for that I would need to know more details of the class that has the methods iniciarConexao() and enviarDados() and the countryside porta. In particular, use System.exit is a bad programming practice - never use it - but without seeing the rest of the class, I can’t tell you how you could eliminate it.

  • 1

    First of all I want to thank you for answering you so clearly my doubt, I help me not only in my problem but in many things I had doubts, from heart thank you very much indeed, I’m a beginner in the programming world but when I get to know I promise to help the next one like you did to me. Obg himself.

0

No matter what type of variable you put on the Netbeans side because it is "converted" to serial communication.

From what I understand, you want to read integers from a string sent by Netbeans. I will use a case of my own as an example. I would send 3 integer values through the serial port and read as follows:

int t1=0, t2=90, t3=0;
String a;
a=Serial.readString();
sscanf(a,"%d %d %d",&t1,&t2,&t3);

Helped?

  • Mt obg for help but did not work very well no , I return this ERROR, Exit status 1 cannot Convert 'String' to 'const char*' for argument '1' to 'int sscanf(const char*, const char*, ...)', giving error in line sscanf(a,"%d %d",&t1,&t2,&T3); , I want to pass through these read ports of the serial port , porta1 porta2 porta3 , only that it fails to convert in , For example Off(Porta1,Porta2,Porta3,'h','h','l'); ,Would be Off(1,2,3,'h','h','l'); so sure I put number, but wanted to last Off(Porta1,Porta2,Porta3,'h','','l'); , GAVE TO UNDERSTAND?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.