Pregunta

Estoy tratando de comunicarse entre mi PC (Windows 7 utilizando Netbeans y RXTX) con un Arduino Pro, utilizando el puerto serie. El Arduino está realmente conectado al PC mediante un cable FTDI.

El código se basa en Java SimpleRead.Java encontró aquí.

Actualmente el Arduino simplemente imprime una cadena cuando se inicia. Mi programa Java debe imprimir el número de bytes que se han leído y luego imprimir el contenido. Funciona el programa Java, una especie de ...

Si la cadena es larga (> 10 bytes o menos) La salida se consiguen rotas.

Así que si en la impresión Arduino I

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

La salida de mi programa Java puede ser algo como:

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

o

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

Estoy pensando que es un problema de tiempo, porque cuando voy manualmente a través del código utilizando el depurador, la cadena de resultado siempre es lo que debe ser:. Una cadena de 20 bytes

He estado jugando con varias cosas, pero no he sido capaz de solucionar el problema.

Aquí es la parte del código que me está 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");
    }
}
¿Fue útil?

Solución

Los datos serie es sólo un flujo de datos. Dependiendo de cuando lo lee y el almacenamiento temporal que está pasando, sólo una parte de los datos puede estar disponible cuando lo lea.

dado que está utilizando datos orientada a la línea, lo que tendrá que hacer es amortiguar los datos hasta que vea el final de línea y sólo entonces procesar los datos.

Otros consejos

No he utilizado Java RXTX, pero he jugado con Arduino y Processing y es bastante fácil de leer valores de lectura / escritura de Arduino. Este es un ejemplo de lectura que viene con Processing (Archivo> Ejemplos> Bibliotecas> Serie> 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
}

*/

Por lo que yo recuerdo, la transmisión THINGY que preparó en Arduino cuando usted instancia de serie es bastante importante. Si utiliza 9600 para enviar, por ejemplo, se debe utilizar el mismo número para escuchar.

También es bastante importante enviar su información como BYTE , de lo contrario tendrá cosas como \ n \ r o en el camino.

versión más corta, trate de:

Serial.println(123456789123456789,BYTE);

El más simple, mejor.

Creo que es necesario utilizar por eventos patrones de diseño para resolver este problema. Le recomiendo que visite: http: //www.whatisarduino. org / bin / tutoriales / Java + Serial + API + y + Arduino

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top