Enviar iuma string pela porta serial

7 respostas
Willdoidao

Pessoal,
Estou com a seguinte duvida preciso mandar um string para a porta serial o metodo usado para enviar é esse:

public void EnviarUmaString(byte[] cmd) {

        if (Escrita == true) {
            try {
                saida = porta.getOutputStream();

                System.out.println("FLUXO OK!");

            } catch (Exception e) {
                System.out.println("Erro.STATUS: " + e);
            }
            try {
                int numBytes = 0;

                entrada = new ByteArrayInputStream(cmd);

                System.out.println("Enviando um byte para " + Porta);
                System.out.println("Enviando : ");
                while (entrada.available() > 0) {
                    numBytes = entrada.read(cmd);
                    String result = new String(cmd);
                    System.out.println("teste>>>" + result);
                }

                saida.write(cmd);

                Thread.sleep(100);
                saida.flush();
            } catch (Exception e) {
                System.out.println("Houve um erro durante o envio. ");
                System.out.println("STATUS: " + e);
                System.exit(1);
            }
        } else {
            System.exit(1);
        }
    }

    public void run() {

        try {

            Thread.sleep(5);

        } catch (Exception e) {

            System.out.println("Erro de Thred: " + e);

        }

    }

No main está assim:

public class Exemplo_Hex {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String teste, str, tela = null;

        teste = JOptionPane.showInputDialog("Digite o Comando");
        char[] chars = teste.toCharArray();
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            strBuffer.append(Integer.toHexString((int) chars[i]));
        }
        tela = strBuffer.toString();

        //Iniciando leitura serial  

        SerialcomLeitura leitura = new SerialcomLeitura("COM1", 4800, 0);

        leitura.HabilitarEscrita();
        leitura.EnviarUmaString(chars);
        leitura.HabilitarLeitura();
        leitura.ObterIdDaPorta();
        leitura.AbrirPorta();
        leitura.LerDados();

        //Controle de tempo da leitura aberta na serial  

        try {

            Thread.sleep(1000);

        } catch (InterruptedException ex) {

            System.out.println("Erro na Thread: " + ex);

        }

        leitura.FecharCom();
   }
}

Sei que é o tipo de string que estou tentando enviar está errado (pelo menos eu acho que é isso), se estiver certo como arrumar isso?
Caso esteja errado minha suposição o que seria o erro?

7 Respostas

j.silvestre
public void EnviarUmaString(String message){
          String msg ;
        msg =message;
          try{
        saida.write(msg.getBytes());
       // Thread.sleep(100);
        saida.flush();
        }catch(IOException e){
        System.out.println("ERRRROOOOOOO");
        }

para testar:

EnviarUmaString("isso é um teste");

sds

j.silvestre

matheuslmota

Tu tem que enviar vetores de bytes para a porta serial.
Tu converte a String em um vetor de chars e envia cada char como um byte.
Como o char assume valores que vão de -127 à 128 e você provavelmente irá trabalhar com dispositivos que um byte varia de 0 à 255, você pode usar a seguinte técnica:

...
saida = porta.getOutputStream();
char array[] = "O rato roeu a roupa do Rei de Roma".toCharArray();
for(int i = 0; i < array.length(); i++)
{
    byte b = (byte)array[i];
    int bb = (int)b & 0xFF;
    saida.write(bb);
}
saida.flush();
...

Com essa pequena gambiarra você pode enviar byters que vão de 0 à 255, que é o que a maioria dos dispositivos seriais aceitam.
Abs.

Willdoidao

matheuslmota,

Desculpa minha ignorância mas aonde faço essa transformação? no main ou dentro da função q envia?
Pq a ideia é pegar um comando do cliente, transformo em Hexadecimal e envio para a placa, aonde coloco esse comando e como passo a string para ser enviado, mas o que vc falou faz todo sentido falta agora saber como fazer, mas muito obrigado pela ajuda!

Willdoidao

Não sei se ajuda mas vou postar a classe inteira aqui, pq pelo que entendi já faz um tratamento para trabalhar em Hex:

public class SerialcomLeitura implements Runnable, SerialPortEventListener {

    public static String stringToHex(String str) {
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch < 0x10) {
                buff.append('0');
            }
            buff.append(Integer.toHexString(ch & 0xFF));
        }
        return buff.toString();
    }

    public static String stringToHex2(String base) {
        StringBuffer buffer = new StringBuffer();
        int intValue;
        for (int x = 0; x < base.length(); x++) {
            int cursor = 0;
            intValue = base.charAt(x);
            String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
            for (int i = 0; i < binaryChar.length(); i++) {
                if (binaryChar.charAt(i) == '1') {
                    cursor += 1;
                }
            }
            if ((cursor % 2) > 0) {
                intValue += 128;
            }
            buffer.append(Integer.toHexString(intValue) + " ");
        }
        return buffer.toString();
    }
    public String Dadoslidos;
    public int nodeBytes;
    private int baudrate;
    private int timeout;
    private CommPortIdentifier cp;
    private SerialPort porta;
    private OutputStream saida;
    //private DataOutputStream saida;  
    private InputStream entrada;
    private Thread threadLeitura;
    private boolean IDPortaOK;
    private boolean PortaOK;
    private boolean Leitura;
    private boolean Escrita;
    private String Porta;
    protected String peso;

    public void setPeso(String peso) {

        this.peso = peso;

    }

    public String getPeso() {

        return peso;

    }

    public SerialcomLeitura(String p, int b, int t) {

        this.Porta = p;

        this.baudrate = b;

        this.timeout = t;

    }

    public void HabilitarEscrita() {

        Escrita = true;

        Leitura = false;

    }

    public void HabilitarLeitura() {

        Escrita = false;

        Leitura = true;

    }

    public void ObterIdDaPorta() {

        try {

            cp = CommPortIdentifier.getPortIdentifier(Porta);

            if (cp == null) {

                System.out.println(" Erro na porta ");

                IDPortaOK = false;

                System.exit(1);

            }

            IDPortaOK = true;

        } catch (Exception e) {

            System.out.println("Erro obtendo ID da porta: " + e);

            IDPortaOK = false;

            System.exit(1);

        }

    }

    public void AbrirPorta() {

        try {

            porta = (SerialPort) cp.open("SerialComLeitura", timeout);

            PortaOK = true;

            //configurar parâmetros  

            porta.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            porta.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

        } catch (Exception e) {

            PortaOK = false;

            System.out.println("Erro abrindo comunicação: " + e);

            System.exit(1);

        }

    }

    public void LerDados() {

        if (Escrita == false) {

            try {

                entrada = porta.getInputStream();

            } catch (Exception e) {

                System.out.println("Erro de stream: " + e);

                System.exit(1);

            }

            try {

                porta.addEventListener(this);

            } catch (Exception e) {

                System.out.println("Erro de listener: " + e);

                System.exit(1);

            }

            porta.notifyOnDataAvailable(true);

            try {

                threadLeitura = new Thread(this);

                threadLeitura.start();

                run();

            } catch (Exception e) {

                System.out.println("Erro de Thred: " + e);

            }

        }

    }

    public void EnviarUmaString(byte[] cmd) {

        if (Escrita == true) {
            try {
                saida = porta.getOutputStream();

                System.out.println("FLUXO OK!");

            } catch (Exception e) {
                System.out.println("Erro.STATUS: " + e);
            }
            try {
                int numBytes = 0;

                entrada = new ByteArrayInputStream(cmd);

                System.out.println("Enviando um byte para " + Porta);
                System.out.println("Enviando : ");
                while (entrada.available() > 0) {
                    numBytes = entrada.read(cmd);
                    String result = new String(cmd);
                    System.out.println("teste>>>" + result);
                }

                saida.write(cmd);

                Thread.sleep(100);
                saida.flush();
            } catch (Exception e) {
                System.out.println("Houve um erro durante o envio. ");
                System.out.println("STATUS: " + e);
                System.exit(1);
            }
        } else {
            System.exit(1);
        }
    }

    public void run() {

        try {

            Thread.sleep(5);

        } catch (Exception e) {

            System.out.println("Erro de Thred: " + e);

        }

    }

    public void serialEvent(SerialPortEvent ev) {

        StringBuffer bufferLeitura = new StringBuffer();

        int novoDado = 0;




        switch (ev.getEventType()) {

            case SerialPortEvent.BI:

            case SerialPortEvent.OE:

            case SerialPortEvent.FE:

            case SerialPortEvent.PE:

            case SerialPortEvent.CD:

            case SerialPortEvent.CTS:

            case SerialPortEvent.DSR:

            case SerialPortEvent.RI:

            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

                break;

            case SerialPortEvent.DATA_AVAILABLE:



                //Novo algoritmo de leitura.  

                while (novoDado != -1) {

                    try {

                        novoDado = entrada.read();

                        if (novoDado == -1) {

                            break;

                        }

                        bufferLeitura.append((char) novoDado);



                    } catch (IOException ioe) {

                        System.out.println("Erro de leitura serial: " + ioe);

                    }

                }


                //setPeso(new String(bufferLeitura)); 







                String str = new String(bufferLeitura);

                System.out.println(str);


                System.out.println(stringToHex(str));



                break;

        }

    }

    public void FecharCom() {

        try {

            porta.close();

        } catch (Exception e) {

            System.out.println("Erro fechando porta: " + e);

            System.exit(0);

        }

    }

    public String obterPorta() {

        return Porta;

    }

    public int obterBaudrate() {

        return baudrate;

    }
}
matheuslmota
Willdoidao:
matheuslmota,

Desculpa minha ignorância mas aonde faço essa transformação? no main ou dentro da função q envia?
Pq a ideia é pegar um comando do cliente, transformo em Hexadecimal e envio para a placa, aonde coloco esse comando e como passo a string para ser enviado, mas o que vc falou faz todo sentido falta agora saber como fazer, mas muito obrigado pela ajuda!

Essa transformação deve ser aplicada na hora de enviar a String para a porta Serial:
public void EnviarUmaString(byte[] cmd) {

        if (Escrita == true) {
            try {
                saida = porta.getOutputStream();

                System.out.println("FLUXO OK!");

            } catch (Exception e) {
                System.out.println("Erro.STATUS: " + e);
            }
            try {
                int numBytes = 0;

                entrada = new ByteArrayInputStream(cmd);

                System.out.println("Enviando um byte para " + Porta);
                System.out.println("Enviando : ");
                while (entrada.available() > 0) {
                    char array[] = cmd.toCharArray();
                    //tratamento dos bytes - inicio
                    for(int i = 0; i < array.length();i++)
                    {
                        byte b = (byte)array[i];
                        int bb = (int)b & 0xFF;
                        saida.write(bb);
                    }
                    //tratamento dos bytes - fim
                    System.out.println("teste>>>" + result);
                }

                saida.write(cmd);

                Thread.sleep(100);
                saida.flush();
            } catch (Exception e) {
                System.out.println("Houve um erro durante o envio. ");
                System.out.println("STATUS: " + e);
                System.exit(1);
            }
        } else {
            System.exit(1);
        }
}
Willdoidao

matheuslmota,

Cara pode ser burrice da minha parte mas ainda não consegui porque estava lendo o que vc mandou e comparei com o que fiz até agora no main fiz algo parecido olha:

teste = JOptionPane.showInputDialog("Digite o Comando"); char[] chars = teste.toCharArray(); StringBuffer strBuffer = new StringBuffer(); for (int i = 0; i < chars.length; i++) { strBuffer.append(Integer.toHexString((int) chars[i])); } tela = strBuffer.toString();

  • ou - parecido com o tratamento que você passou:

char array[] = cmd.toCharArray(); //tratamento dos bytes - inicio for(int i = 0; i < array.length();i++) { byte b = (byte)array[i]; int bb = (int)b & 0xFF; saida.write(bb); } //tratamento dos bytes - fim

Faço esse tratamento antes para transformar em Hex e enviar para serial pq o sensor só lê Hex, neste caso pergunto o que faço tiro esse tratamento dai e coloco lá dentro da função de envio?
E se puder realizar aqui como fazer? e como passar para a função?
Pq se fosse uma string seria:

leitura.EnviarUmaString(tela);

Já em array[], não faço ideia de como enviar para lá, já que a classe começa com :

public void EnviarUmaString(byte[] cmd) {
matheuslmota

Hum, entendi. Nesse caso, eu acho que seria mais interessante você capturar a String que representa o comando e enviá-la para o método enviarString.
O método enviarString deve receber uma String como parâmetro e não um vetor de bytes. Fazendo dessa maneira funciona. Qualquer dúvida pergunta ae.
Abs.

Criado 19 de julho de 2011
Ultima resposta 19 de jul. de 2011
Respostas 7
Participantes 3