Arduino从Java读取信号并显示/使用它们

时间:2015-08-06 18:06:12

标签: java arduino rxtx

我最近一直致力于java和arduino之间的沟通,因为我有一个需要它的项目,所以我已经阅读了很多关于它的内容,并开始在其中取得一些进展,例如从java并在arduino中读取并使用它然后再次向java发送输出,反正之后我必须在java中设置一个滑块所以我可以在移动它时将0到1023之间的值发送到arduino但问题开始出现在这里,我创建了滑块(使用JSlider)并使用stateChanged方法将值发送到arduino,然后arduino应该读取数据并向java报告,我将MinorTickSpacing设置为100,因此每当您单击滑块时它从0到100,因此,arduino正确读取数据(它读取3次,我不知道为什么),直到它达到300这是我在java中看到的输出(使用serialEvent读取arduino的输出和BufferReader):

COM port found:COM3
Port open succesful: COM3
100
100
200
200
200
44
44
44
65533
65533
65533
244
244

我在滑块上点击了5次,所以它应该是100,200,300,400和100。 500,但我看到那些奇怪的数字,我不知道为什么。 这是我的Java程序(二手RXTX库和Eclipse IDE)和Arduino的。

Java程序:

import java.io.BufferedReader;                    //BufferedReader makes reading operation efficient
import java.io.IOException;
import java.io.InputStreamReader;         //InputStreamReader decodes a stream of bytes into a character set
import java.io.OutputStream;          //writes stream of bytes into serial port
import gnu.io.CommPortIdentifier;           
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;            //deals with possible events in serial port (eg: data received)
import gnu.io.SerialPortEventListener; //listens to the a possible event on serial port and notifies when it does
import java.util.Enumeration;
import gnu.io.PortInUseException;           //all the exceptions.Never mind them for now
import gnu.io.UnsupportedCommOperationException;
import java.util.Scanner;                                   //to get user input of name
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;

public class TestingGUI implements SerialPortEventListener,ActionListener, ChangeListener {        

    private SerialPort serialPort ;         //defining serial port object
    private CommPortIdentifier portId  = null;       //my COM port
    private static final int TIME_OUT = 2000;    //time in milliseconds
    private static final int BAUD_RATE = 9600; //baud rate to 9600bps
    private BufferedReader input;               //declaring my input buffer
    private OutputStream output;                //declaring output stream
    private String name;        //user input name string
    public static String status;
    JFrame frame;
    JPanel panel;
    JLabel label,label1;
    JSlider slide;
    JProgressBar progress;
    JButton onButton,offButton,blinkButton;
    Scanner inputName;          //user input name
    public TestingGUI()
    {
        frame = new JFrame();
        frame.setSize(700, 150);
        frame.setTitle("Arduino Test");
        panel = new JPanel();
        frame.add(panel);
        slide = new JSlider();
        slide.setMinimum(0);
        slide.setMajorTickSpacing(5);
        slide.setMaximum(1023);
        slide.setMinorTickSpacing(100);
        slide.setPaintLabels(true);
        slide.setPaintTicks(true);
        slide.setSnapToTicks(true);
        slide.setToolTipText("Move the slider to desired location.");
        slide.setValue(0);
        slide.setValueIsAdjusting(true);
        slide.addChangeListener(this);
        panel.setLayout(null);
        slide.setBounds(10,10, 650, 50);
        panel.add(slide);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    //method initialize
    private void initialize()
    {
        CommPortIdentifier ports = null;      //to browse through each port identified
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); //store all available ports
        while(portEnum.hasMoreElements()) //browse through available ports
        {  
                ports = (CommPortIdentifier)portEnum.nextElement();
             //following line checks whether there is the port i am looking for and whether it is serial
               if(ports.getPortType() == CommPortIdentifier.PORT_SERIAL&&ports.getName().equals("COM3"))
               { 
                    System.out.println("COM port found:COM3");
                    portId = ports;                  //initialize my port
                    break;                                                                                     
               }
         }
       //if serial port am looking for is not found
        if(portId==null)
        {
            System.out.println("COM port not found");
            System.exit(1);
        }
                            }

    //end of initialize method

    //connect method

    private void portConnect()
    {
        //connect to port
        try
        {
            serialPort = (SerialPort)portId.open(this.getClass().getName(),TIME_OUT);   //down cast the comm port to serial port
                                                                                     //time to wait
            System.out.println("Port open succesful: COM3"); 

            //set serial port parameters
            serialPort.setSerialPortParams(BAUD_RATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
        }
        catch(PortInUseException e){
            System.out.println("Port already in use");
            System.exit(1);
        }
        catch(NullPointerException e2){
            System.out.println("COM port maybe disconnected");
        }
        catch(UnsupportedCommOperationException e3){
            System.out.println(e3.toString());
        }

        //input and output channels
        try
        {
                input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                output =  serialPort.getOutputStream();
                //adding listeners to input and output streams
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
                serialPort.notifyOnOutputEmpty(true);
      //defining reader and output stream
        }
        catch(Exception e){
            System.out.println(e.toString());
                            }

    }
    //end of portConncet method
    @Override
    public void stateChanged(ChangeEvent e)
    {
        if(e.getSource() == slide)
        {
            try {
                int out = slide.getValue();
                output.write(out);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    @Override
    public void actionPerformed(ActionEvent event) {
    }
    //readWrite method
    @Override
    public void serialEvent(SerialPortEvent evt) 
    { 

        if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) //if data available on serial port
        { 
            try {
            if(input.ready())
            {
                int testInt = input.read();
                System.out.println(testInt);
             }
                } catch (Exception e) 
            {
                System.err.println(e.toString());
            }
        }

    }
    //end of serialEvent method
    //main method
    public static void main(String[] args) 
    {
        TestingGUI myTest = new TestingGUI();  //creates an object of the class
        myTest.initialize();
        myTest.portConnect();
    }//end of main method
}// end of  SerialTest 

和Arduino计划:

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

}

void loop() {
  while(Serial.available() == 0)
  {

  }
  int test2 = Serial.read();
  Serial.write(test2);
}

我应该怎么做才能获得正确的数字并超过arduino所显示的限制? (显然只能正确读取0到255之间的数字)

1 个答案:

答案 0 :(得分:0)

根据Arduino In this downloaded only one image.文档:https://www.arduino.cc/en/Serial/Read调用它返回:

  

可用的传入串行数据的第一个字节(如果没有可用的数据,则为-1) - int

根据定义,一个字节的值可以在0到225之间,这就是这些值正常工作的原因。

当你发送300的值时,你会遇到一些名为"算术溢出" - 想象你从0到300计数,但在255你再从0开始,然后你达到44.同样适用于500.

我不确定为什么你得到65533为400,它应该是144(400 modulo 256)。如果我发现,我会更新答案。

总结 - 你不应该发送或期望0-255范围之外的值。如果要发送更大的数字,请将其分成字节并在通信通道的另一侧汇回。