在Java上将整数从串口发送到Arduino uno

时间:2015-03-20 09:24:51

标签: java io arduino

我在Java和arduino板之间的串行通信中遇到问题,arduino可以发送Java字节,Java可以打印它们,Java将它们作为输入。我的问题是当我倾向于使用串口作为Java的输出来发送带有流的java(Buffered,dataoutput ...),并且Arduino没有收到任何字节,这是经过验证的,因为我要求Arduino发送字节收到了,它总是零。任何人都可以提出建议吗?欣赏它。

My java code is the following: 

package Arduino;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.util.Enumeration;
public class SerialClass implements SerialPortEventListener {

 public static int ch = 2;  
 public SerialPort serialPort;
 /** The port we're normally going to use. */
 private static final String PORT_NAMES[] = {
 "/dev/tty.usbserial-A9007UX1", // Mac OS X
 "/dev/ttyUSB0", // Linux
 "COM19", // Windows
 };

public static BufferedReader input;
public static BufferedWriter output;
//public static BufferedOutputStream out= new BufferedOutputStream(output);
//public static DataOutputStream data= new DataOutputStream(out);
 /** Milliseconds to block while waiting for port open */
 public static final int TIME_OUT = 2000;
 /** Default bits per second for COM port. */
 public static final int DATA_RATE = 9600;

public void initialize() {
 CommPortIdentifier portId = null;
 Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

//First, Find an instance of serial port as set in PORT_NAMES.
 while (portEnum.hasMoreElements()) {
 CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
 for (String portName : PORT_NAMES) {
 if (currPortId.getName().equals(portName)) {
 portId = currPortId;
 break;
                  }
          }
 }
 if (portId == null) {
 System.out.println("Could not find COM port.");
 return;
 }

try {
 // open serial port, and use class name for the appName.
 serialPort = (SerialPort) portId.open(this.getClass().getName(),
 TIME_OUT);;

// set port parameters
 serialPort.setSerialPortParams(DATA_RATE,
 SerialPort.DATABITS_8,
 SerialPort.STOPBITS_1,
 SerialPort.PARITY_NONE);


// open the streams
 input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
 output= new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream()));

 // add event listeners
 serialPort.addEventListener(this);
 serialPort.notifyOnDataAvailable(true);
 serialPort.notifyOnOutputEmpty(true);

 } catch (Exception e) {
 System.err.println(e.toString());
 }
 }

public synchronized void close() {
 if (serialPort != null) {
 serialPort.removeEventListener();
 serialPort.close();
 System.out.println("port closed");
        }
 }

public static synchronized void writeData() {
System.out.println("I'm in...");
try {
output.write(ch);
output.close();
System.out.println("Sent: " + ch);
} catch (Exception e) {
System.out.println("could not write to port");
}

} 

public synchronized void serialEvent(SerialPortEvent oEvent) {  
 if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
 try {
 String inputLine=input.readLine();
// input.close();
 System.out.println(inputLine);
 } catch (Exception e) {
 System.err.println(e.toString());
     }
 }

 } 

public static void main(String[] args) throws Exception {
 SerialClass main = new SerialClass();

main.initialize();
SerialClass.writeData();

}
}


My arduino code is:

byte valeur;
int val;
int led = 13;
char buffer[10];

void setup()
{
 Serial.begin(9600);
 pinMode(led, OUTPUT);
}

void loop(){
  delay(10000);
  //val= Serial.parseInt();
  //Serial.println( val );
  if ( Serial.available ()) {
    Serial.println("In if");
    Serial.readBytes( buffer , 10 );
    //val = valeur - '0';
    //Serial.println( val ) ;
    Serial.println( buffer[0] , DEC ) ;

    if( buffer[0] == 2 ) {  //Switch on the LED, if the received value is 1.
      Serial.println("Val  = 2");
      digitalWrite(led, HIGH);
    }

    else if( buffer[0] == 1) { //Switch off the LED, if the received value is 1.
      Serial.println("Val  = 1");
      digitalWrite(led, LOW);
    }
 }

 else{
   Serial.readBytes( buffer , 10 );
   Serial.println( buffer[0] , DEC ) ;
   Serial.println( "No data Available" );
 }

 // Serial.println("Succesfully received.");
}


and the result in java is (after uploading the arduino code to arduino uno):

I'm in...
Sent: 2
0
No data Available

1 个答案:

答案 0 :(得分:0)

我设法通过使用jserialcomm库向arduino发送一个char。该方法如下所示:

       // imports I make in my class
  import javax.swing.*;
  import java.awt.FlowLayout;
  import java.awt.event.*;
  import com.fazecast.jSerialComm.*;
  import java.io.PrintWriter;

方法中的代码

        System.out.println("connect");
        port = SerialPort.getCommPort("COM5"); // change if different
        port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER,0,0);            
        port.openPort();
        //port.setBaudRate(9600);

        System.out.println(port.getBaudRate());

        try {Thread.sleep(600); } catch(Exception e) {} // I think this sleep is a must until it opens
        System.out.println(port.isOpen());
        if(port.isOpen()) {
            System.out.println("port open!");
            try {Thread.sleep(500); } catch(Exception e) {}

            PrintWriter output = new PrintWriter(port.getOutputStream());           
                output.write(2);
                try {Thread.sleep(800); } catch(Exception e) {}
                output.flush();
                System.out.println("char sent");

            try {Thread.sleep(600); } catch(Exception e) {}
            port.closePort();
        }
    } 
    else {
        // disconnect from the serial port
        //port.closePort();

    }

}