Arduino not able to send serial data back
So I found out how to connect the Arduino to my java program. But using the serial connections doesn't give any useful data back, its either in the wrong format, or just sends it as a box. I've looked at the related questions posted ea开发者_运维知识库rly in here, but none of the tips seems to help. So does anyone know how to send the data between an Arduino and a computer using the serial port?
This is the code I'm using, provided by this person: http://silveiraneto.net/2009/03/01/arduino-and-java/
package serialtalk;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;
public class Main {
static InputStream input;
static OutputStream output;
public static void main(String[] args) throws Exception{
Preferences.init();
System.out.println("Using port: " + Preferences.get("serial.port"));
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(
Preferences.get("serial.port"));
SerialPort port = (SerialPort)portId.open("serial talk", 4000);
input = port.getInputStream();
output = port.getOutputStream();
port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
while(true){
while(input.available()>0) {
System.out.print((char)(input.read()));
}
}
}
}
The Arduino is this: http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
The code simply receives a number, and determines which analog reading it should be sending back, from my Arduino.
When dealing with serial connections make sure of the following key points:
- BAUD Rates match
- DATABITS should match
- STOPBITS should match
- PARITY should match
- Make sure you are using the correct cable (Null modem if needed)
- Make sure the cable run isn't too long
All of the above can cause odd stuff to come out of the com port on the Java side. Once you get the hang of this it gets much easier.
My personal favorite library here.
精彩评论