Pages: [1]   Go Down
Author Topic: Serial Communication between java and Arduino  (Read 810 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

my goal is to send an input from the user using java and send it to the arduino via serial. But arduino isn't behaving like I want it to. I send the data and simply nothing happens! The arduino Rx led blinks when I input something indicating that it's reading, but I don't know why isn't it lighting up LED 13.

Java code:

Code:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
import java.util.Scanner;


public class SerialTest implements SerialPortEventListener {
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
"COM7", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private DataInputStream input;
/** The output stream to the port */
private DataOutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private 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);

input = new DataInputStream (serialPort.getInputStream());
output = new DataOutputStream (serialPort.getOutputStream());

serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}catch (Exception e) {
System.err.println(e.toString());
}

while(true)
{
// open the streams
System.out.print("Input something: ");
Scanner sc = new Scanner(System.in);
short x = sc.nextShort();
System.out.println("short is " + x);

//output = new OutputStreamWriter(serialPort.getOutputStream());*/
byte upper = (byte) (x >> 8); //Get the upper 8 bits
byte lower = (byte) (x & 0xFF); //Get the lower 8bits
try{
output.write(upper);
output.write(lower);
}
catch(Exception ex)
{}

// add event listeners
}
}

/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}

/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int inputLine=input.read();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}

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


}
}

Arduino Code:

Code:
void setup(){
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop(){
  if (Serial.available() > 0){
  byte upper = Serial.read();
  byte lower = Serial.read();
  int x = (upper<<8) | lower;
  if(x==1200){
    digitalWrite(13,HIGH);
  }
  else{
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    delay(1000);
  }
  }
}
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 644
Posts: 50500
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
  if (Serial.available() > 0){
  byte upper = Serial.read();
  byte lower = Serial.read();
If there is at least one byte, read both of them. Ummm, no.

Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

i read somewhere on these forums to use this method, but before that I was simply using a switch case:

Code:
switch (inByte) {
    case '1':   
      digitalWrite(13, HIGH);
      break;
    case '2':   
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        delay(1000);
      break;

in both ways i got the same result.
Logged

Offline Offline
Full Member
***
Karma: 1
Posts: 158
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I was able to send/receive data using rxtx serial lib and even upload sketch using stk500 protocol. Thouht i have problems with uploading from android as is has specific USB API
Logged

Pages: [1]   Go Up
Jump to: