Domanda

Sto cercando di comunicare tra il mio PC (Windows 7 usando Netbeans e RXTX) con un Arduino Pro, utilizzando la porta seriale. Arduino è effettivamente collegato al PC tramite un cavo FTDI.

Il codice è basato su Java SimpleRead.Java trovato qui.

Al momento l'Arduino stampa semplicemente una stringa quando viene avviato. Il mio programma Java deve stampare il numero di byte che sono stati letti e poi stampare il contenuto. Le opere programma Java, sorta di ...

Se la stringa è lunga (> 10 byte o così) all'uscita avranno suddivise.

Quindi, se sulla stampa Arduino I

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

L'uscita del mio programma Java può essere simile a:

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

o

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

Sto pensando che sia un problema di temporizzazione, perché quando vado manualmente tramite il codice utilizzando il debugger, la stringa risultato è sempre quello che dovrebbe essere:. Una stringa di 20 byte

Sono stato pasticciano con le varie cose, ma non sono stato in grado di risolvere il problema.

Ecco la parte del codice che mi sta dando problemi:

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");
    }
}
È stato utile?

Soluzione

dati seriale è solo un flusso di dati. A seconda di quando lo si legge e il buffer che sta accadendo, solo una parte dei dati può essere disponibile quando lo si legge.

Dal momento che si stanno utilizzando i dati di linea orientata, ciò che si vuole fare è buffer di dati fino a vedere il terminatore di linea e solo allora elaborare i dati.

Altri suggerimenti

Non ho usato Java RXTX, ma ho giocato con Arduino e di elaborazione ed è abbastanza facile da leggere i valori / scrittura da Arduino. Ecco un esempio di lettura che viene fornito con Processing (File> Esempi> Biblioteche> Seriale> 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
}

*/

Per quanto mi ricordo, il baud thingy si imposta in Arduino quando si crea un'istanza di serie è abbastanza importante. Se si utilizza 9600 di inviare, ad esempio, è necessario utilizzare lo stesso numero per ascoltare.

Inoltre è abbastanza importante per inviare le vostre informazioni come BYTE , altrimenti dovrete roba come \ r \ n nel modo.

versione più breve, provare:

Serial.println(123456789123456789,BYTE);

Il più semplice e meglio è.

Credo che è necessario utilizzare modelli di progettazione event-driven per risolvere questo problema. Mi raccomando di visitare: http: //www.whatisarduino. org / bin / Tutorials / Java + Serial + API + e + Arduino

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top