从Java发送int到Arduino

时间:2017-06-01 11:54:45

标签: java arduino serial-port

我正在尝试从我的Java程序向我的Arduino板发送一个int 我从http://playground.arduino.cc/Interfacing/Java

获得了Java代码

Java代码:

package com.thetrialbot.arduinosteppercontrol;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;


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/ttyACM0", // Raspberry Pi
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
    };
    /**
    * A BufferedReader which will be fed by a InputStreamReader 
    * converting the bytes into characters 
    * making the displayed results codepage independent
    */
    private BufferedReader input;
    /** The output stream to the port */
    private OutputStream 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() {
                // the next line is for Raspberry Pi and 
                // gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
                //System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

        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 = serialPort.getOutputStream();

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

    /**
     * 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 {
                String inputLine=input.readLine();
                System.out.println(inputLine);
                output.write(1);
            } 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();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

Arduino代码:

#define led 13  // built-in LED
char inputBuffer[10];   
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Hello world");
  delay(1000);
  if (Serial.available() > 0) {
    Serial.readBytes(inputBuffer, Serial.available());
    delay(5000);
    Serial.print(inputBuffer);
  }
}

这是控制台的图像,因为角色无法正确粘贴。

1 个答案:

答案 0 :(得分:0)

我已经在Arduino端更改了程序,以便它可以同步运行。 Arduino方面足够缓慢,没有延迟。 delay( 5 );是为了争取时间并在端口上收集挂起的输入。使用inputBuffer时,输入的数字会被切掉,而丢失的部分会从下一部分覆盖。要通过char获得输入char足够快,仅提交数字。 "Hello world!"应该只发送一次?!

boolean show = false;
int c = 0;
int num = 0;

void setup() {
  Serial.begin( 9600 );
  Serial.setTimeout( 450 );
  while( ! Serial ) {}
  Serial.println( "Hello world!" );
}

void loop() {
  while( Serial.available() > 0 ) {
    c = Serial.read();
    if( c != '\n' )   // only needed for terminal-programs
      num = num * 10 + (c - '0');
    if( Serial.available() == 0 )
      delay( 5 );  /* 2 */
    show = true;
  }
  if( show ) {
    Serial.println( num );
    Serial.flush();
    num = 0;
    show = false;
  }
}

从Java(这里有第7个脚本引擎)中,数字1…100作为字符串发送,并在Arduino端更改为其数字值–再次发送回Java并打印出来。要进行安装,请访问7th JSerial这边,并将3个jar文件放入同一目录。启动 Seventh.jar 文件。将程序剪切并粘贴到编辑器中,然后按 Eval 1500 sleep使Arduino有时间打开端口。

: numbers
  101 0 do
    i str$ portwrite
    portread type
  loop
;
"COM10" 9600 8 0 1 0  6 PORT a!
portopen
1500 sleep  (* 1 *)
numbers
portclose