Я пытаюсь связаться между своим ПК (использование Windows 7 Netbeans и RXTX) с Ардуино Pro, с помощью последовательного порта. Ардуино на самом деле подключен к ПК с помощью кабеля FTDI.
Код основан на Java SimpleRead. Java найден здесь.
В настоящее время Ардуино просто распечатывает строку, когда он запускает. Моя программа Java должна распечатать число байтов, которые были считаны и затем распечатывают содержание. Работы программы Java, вид...
Если строка будет длинна (> приблизительно 10 байтов), то вывод будет разбит.
Таким образом, если на Ардуино я печатаю
Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'
Вывод моей программы Java может посмотреть что-то как:
Number of Bytes: 15
1234567891234
Number of Bytes: 5
56789
или
Number of Bytes: 12
1234567891
Number of Bytes: 8
23456789
Я думаю, что это - проблема синхронизации, потому что, когда я вручную прохожу код с помощью отладчика, строка результата всегда, каково это должно быть: одни 20 строк байтов.
Я смешивал с различными вещами, но я не смог решить проблему.
Вот часть кода, который дает мне проблемы:
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");
}
}
Последовательные данные - это просто поток данных. В зависимости от того, когда вы его читаете, и от выполняемой буферизации, только часть данных может быть доступна при чтении.
Поскольку вы используете строчно-ориентированные данные, вам нужно буферизовать данные до тех пор, пока вы не увидите признак конца строки, и только потом обрабатывать данные.
] Я не использовал Java RXTX, но я играл с Arduino и Processing, и это довольно легко читать/записывать значения с Arduino. Вот пример для чтения, который поставляется с Processing(File > Examples > Libraries > 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
}
*/
]
[]Насколько я помню, хитрость, которую вы настраиваете в Arduino, когда вы создаете мгновенный сериал, очень важна. Если вы используете 9600 для отправки, например, вы должны использовать тот же номер для прослушивания.[
] []Также очень важно отправлять информацию как []BYTE[], в противном случае у вас будут такие вещи, как \r или \n.[
] []Короткая версия, попробуйте:[
] [Serial.println(123456789123456789,BYTE);
]
[]Чем проще, тем лучше. [
]