Arduino 读取来自 Java 和 displaying/using 的信号
Arduino reading signals from Java and displaying/using them
我最近一直在研究java和arduino之间的通信,因为我有一个项目需要它,所以我已经阅读了很多关于它的内容并开始取得一些进展,比如发送来自 java 的字符串并在 arduino 中读取它并使用它然后再次将输出发送到 java ,无论如何之后我必须在 java 中设置一个滑块以便我可以发送 0 和之间的值1023 移动到 arduino 但问题开始出现在这里,我创建了滑块(使用 JSlider)并使用 stateChanged 方法将值发送到 arduino 然后 arduino 应该读取数据并报告回 java,我已将 MinorTickSpacing 设置为 100,因此无论何时单击滑块,它都会从 0 变为 100,因此,arduino 正确读取数据(读取 3 次,我不知道为什么)直到达到 300,这是我在 java 中看到的输出(使用 serialEvent 和 BufferReader 从 arduino 读取输出):
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 和 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 之间的数字被正确读取)
根据 Arduino Serial.Read()
文档:https://www.arduino.cc/en/Serial/Read 调用它 returns:
the first byte of incoming serial data available (or -1 if no data is available) - int
根据定义,一个字节的值可以介于 0 到 225 之间,这就是这些值可以正常工作的原因。
当您发送值 300 时,您会遇到一种叫做 "Arithmetic overflow" 的情况 - 假设您从 0 数到 300,但是在 255 时您又从 0 开始数,然后您数到 44。500 也是如此.
不知道为什么400得到65533,应该是144(400 modulo 256)。如果我发现,我会更新答案。
总结 - 您不应发送或期望超出 0-255 范围的值。如果您想发送更大的数字,请将其分成字节,然后 assemble 在通信通道的另一端返回。
我最近一直在研究java和arduino之间的通信,因为我有一个项目需要它,所以我已经阅读了很多关于它的内容并开始取得一些进展,比如发送来自 java 的字符串并在 arduino 中读取它并使用它然后再次将输出发送到 java ,无论如何之后我必须在 java 中设置一个滑块以便我可以发送 0 和之间的值1023 移动到 arduino 但问题开始出现在这里,我创建了滑块(使用 JSlider)并使用 stateChanged 方法将值发送到 arduino 然后 arduino 应该读取数据并报告回 java,我已将 MinorTickSpacing 设置为 100,因此无论何时单击滑块,它都会从 0 变为 100,因此,arduino 正确读取数据(读取 3 次,我不知道为什么)直到达到 300,这是我在 java 中看到的输出(使用 serialEvent 和 BufferReader 从 arduino 读取输出):
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 和 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 之间的数字被正确读取)
根据 Arduino Serial.Read()
文档:https://www.arduino.cc/en/Serial/Read 调用它 returns:
the first byte of incoming serial data available (or -1 if no data is available) - int
根据定义,一个字节的值可以介于 0 到 225 之间,这就是这些值可以正常工作的原因。
当您发送值 300 时,您会遇到一种叫做 "Arithmetic overflow" 的情况 - 假设您从 0 数到 300,但是在 255 时您又从 0 开始数,然后您数到 44。500 也是如此.
不知道为什么400得到65533,应该是144(400 modulo 256)。如果我发现,我会更新答案。
总结 - 您不应发送或期望超出 0-255 范围的值。如果您想发送更大的数字,请将其分成字节,然后 assemble 在通信通道的另一端返回。