java - 如何通过串口将多个参数传递给 Arduino mega [英] java - how to pass multiple parameters over serial port to Arduino mega
问题描述
通过我的java程序.我想将一个字节值传递给 Arduino mega 来使 LED 闪烁同时我想将一个字符串值传递给 Arduino 以显示在液晶显示器中.
Through my java program. i want to pass a byte value to the Arduino mega to blink an Led and also at the same time i want to pass a string value to the Arduino to be displayed in the lcd.
如何分别从 java 程序中获取以上 2 个输入到 Arduino 并在 Arduino 内部的不同进程中使用它们..
How can I separately get above 2 inputs from the java program to Arduino and use them in different processes inside Arduino..
LiquidCrystal lcd (12, 11, 10, 9, 8, 7);
int operation;
void setup() {
lcd.begin(16, 2);
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
pinMode(3, OUTPUT);
pinMode(2, OUTPUT);
}
int count = 0;
void loop() {
//LCD start
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(50);
// clear the screen
lcd.clear();
delay(10);
// read all the available characters
while (Serial.available() > 0) {
// display each character to the LCD
lcd.write(Serial.read());
}
}
//LCD end
//LED Blink start
if (Serial.available() > 0)
delay(10);
{
operation = Serial.read();
}
if(operation == '2')
{
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
delay(50);
digitalWrite(3, LOW);
delay(50);
}
if(operation == '1')
{
digitalWrite(3, LOW);
digitalWrite(2, HIGH);
delay(50);
digitalWrite(2, LOW);
delay(50);
}
//LED Blink end
// Recieve rfid tag numbers
if(Serial1.available()) {
int x = Serial1.read();
Serial1.print(x);
}
if(Serial2.available()) {
int x = Serial2.read();
Serial1.print(x);
}
}
下面是发送数据的Java代码
将数字 1 发送到 Arduino 的代码
Below is the Java code to send data
Code to send number 1 to Arduino
String buf = "1";
char buf2[] = buf.toCharArray();
output.write((byte)buf2[0]);
发送字符串以显示在lcd中的代码
Code to send string to display in lcd
output.write("Hellow world. this is a String from java".getBytes());
当我单独运行这些代码时,它运行良好而不会受到任何干扰..但是当我同时执行它们时......有时液晶显示器中会显示值 1 或 2 ......并且 LED 无法正常闪烁.如何从java到arduino获取两个输入并在Arduino内部分别处理它们?
推荐答案
您可以连接数据.因此,如果您将Hello"和200"作为 2 个项目传递,那么在发送到 Arduino 之前将它们组合起来并发送Hello%200"并在 Arduino 内部的 % 上拆分.
You could concatenate the data. So, if you are passing "Hello" and "200" as 2 items then combine them before the send to Arduino and send "Hello%200" and split on the % inside the Arduino.
这篇关于java - 如何通过串口将多个参数传递给 Arduino mega的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!