简体   繁体   中英

sending integers from Java to Arduino uno on serial port

I have an issue in my serial communication between Java and arduino board, arduino can send Java bytes and Java is able to print them, Java is taking them as inputs. My problem is when I tend to use the serial port as an output for Java to send java with streams (Buffered, dataoutput...), and no byte is received by Arduino, and this is verified because i asked Arduino to send the bytes received and the it's always zero.can anyone give an advice? appreciate it.

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

I managed to send a char to arduino by using jserialcomm library. The method looks like this:

       // 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;

code in method

        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();

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM