Pergunta

Eu estou tentando se comunicar entre meu PC (Windows 7 usando o NetBeans e RXTX) com um Arduino Pro, usando a porta serial. O Arduino é realmente ligado ao PC usando um cabo FTDI.

O código é baseado no Java SimpleRead.Java encontrada aqui.

Atualmente, o Arduino simplesmente imprime uma corda quando ele inicia. Meu programa Java deve imprimir o número de bytes que foram lidas e, em seguida, imprimir o conteúdo. As obras do programa Java, uma espécie de ...

Se o texto é longo (> 10 bytes ou mais) a saída vai ser quebrado.

Então, se no Arduino I print

Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'

A saída do meu programa Java pode ser algo como:

Number of Bytes: 15   
1234567891234  
Number of Bytes: 5  
56789

ou

Number of Bytes: 12   
1234567891  
Number of Bytes: 8  
23456789

Eu estou pensando que é um problema de tempo, porque quando eu ir manualmente através do código usando o depurador, a seqüência de resultado é sempre o que deveria ser:. Uma cadeia de 20 bytes

Eu fui brincar com várias coisas, mas eu não tenho sido capaz de corrigir o problema.

Aqui está a parte do código que está me dando problemas:

static int baudrate = 9600,
           dataBits = SerialPort.DATABITS_8,
           stopBits = SerialPort.STOPBITS_1,
           parity   = SerialPort.PARITY_NONE;    

byte[] readBuffer = new byte[128];

...
...

public void serialEvent(SerialPortEvent event)
{
   if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {

    try {
        if (input.available() > 0) { 
            //Read the InputStream and return the number of bytes read
            numBytes = input.read(readBuffer);

            String result  = new String(readBuffer,0,numBytes);
            System.out.println("Number of Bytes: " + numBytes);
            System.out.println(result);
        }
    } catch (IOException e) {
        System.out.println("Data Available Exception");
    }
}
Foi útil?

Solução

dados de série é apenas um fluxo de dados. Dependendo de quando você lê-lo eo buffer que está acontecendo, apenas parte dos dados podem estar disponíveis quando você lê-lo.

Uma vez que você estiver usando dados da linha orientada, o que você vai querer fazer é amortecer a dados até ver o terminador de linha e só então processar os dados.

Outras dicas

Eu não usei Java RXTX, mas eu joguei com Arduino e Processamento e é muito fácil de ler / os valores de escrita do Arduino. Aqui está uma amostra de leitura que vem com Processing (File> Exemplos> Bibliotecas> Serial> SimpleRead)

/**
 * Simple Read
 * 
 * Read data from the serial port and change the color of a rectangle
 * when a switch connected to a Wiring or Arduino board is pressed and released.
 * This example works with the Wiring / Arduino program that follows below.
 */


import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }
  background(255);             // Set background to white
  if (val == 0) {              // If the serial value is 0,
    fill(0);                   // set fill to black
  } 
  else {                       // If the serial value is not 0,
    fill(204);                 // set fill to light gray
  }
  rect(50, 50, 100, 100);
}



/*

// Wiring / Arduino Code
// Code for sensing a switch status and writing the value to the serial port.

int switchPin = 4;                       // Switch connected to pin 4

void setup() {
  pinMode(switchPin, INPUT);             // Set pin 0 as an input
  Serial.begin(9600);                    // Start serial communication at 9600 bps
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {  // If switch is ON,
    Serial.print(1, BYTE);               // send 1 to Processing
  } else {                               // If the switch is not ON,
    Serial.print(0, BYTE);               // send 0 to Processing
  }
  delay(100);                            // Wait 100 milliseconds
}

*/

Tanto quanto me lembro, a transmissão coisinha que você configurar em Arduino quando você instancia de série é bastante importante. Se você usar 9600 para enviar, por exemplo, você deve usar o mesmo número para ouvir.

Também é muito importante para enviar suas informações como BYTE , caso contrário, você vai ter coisas como \ r ou \ n no caminho.

versão mais curta, tente:

Serial.println(123456789123456789,BYTE);

Quanto mais simples, melhor.

Eu acho que você precisa usar padrões de design orientados a eventos para resolver este problema. Eu recomendo que você visite: http: //www.whatisarduino. org / bin / Tutoriais / Java + Serial + API + e + Arduino

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top