问题描述
我希望通过Java程序打开和关闭。我在大概5分钟内在C#中完成了这个项目,但Java似乎更具挑战性。我有Arduino等待1或0写入并将基于此更改LED。我用于Arduino的代码如下。
I am looking to turn an LED on and off with a Java program. I did the project in C# in roughly 5 minutes, but it seems to be somewhat more challenging in Java. I had the Arduino wait for a 1 or 0 to be written to the COM port and would change the LED based on that. The code I am using for the Arduino is as follows.
int LedPin = 13;
char data;
void setup()
{
Serial.begin(9600);
pinMode( LedPin , OUTPUT );
}
void loop()
{
data = Serial.read();
if (Serial.available() > 0)
{
if(data == '1' )
{
digitalWrite(LedPin,HIGH);
}
else if(data == '0' )
{
digitalWrite(LedPin,LOW);
}
}
else
if (Serial.available()<0)
{
digitalWrite(LedPin,HIGH);
delay(500);
digitalWrite(LedPin,LOW);
delay(500);
}
}
我如何使用Java应用程序? / p>
How would I do this with a Java application?
推荐答案
您可以使用JArduino(Java-Arduino)库,它提供了一个Java API来使用串行端口来控制Arduino USB电缆或从软件角度看作串行端口的无线设备),UDP(通过以太网屏蔽)。所有与Java和Arduino之间的通信相关的代码都由库内部进行管理。
You can use the JArduino (Java-Arduino) library, which provides a Java API to control your Arduino using serial port (using a USB cable, or wireless devices behaving as serial ports from a software point of view), UDP (via an ethernet shield). All the code related to communication between Java and Arduino is managed internally by the library.
:
public class Blink extends JArduino {
public Blink(String port) {
super(port);
}
@Override
protected void setup() {
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(DigitalPin.PIN_12, PinMode.OUTPUT);
}
@Override
protected void loop() {
// set the LED on
digitalWrite(DigitalPin.PIN_12, DigitalState.HIGH);
delay(1000); // wait for a second
// set the LED off
digitalWrite(DigitalPin.PIN_12, DigitalState.LOW);
delay(1000); // wait for a second
}
public static void main(String[] args) {
String serialPort;
if (args.length == 1) {
serialPort = args[0];
} else {
serialPort = Serial4JArduino.selectSerialPort();
}
JArduino arduino = new Blink(serialPort);
arduino.runArduinoProcess();
}
}
JArduino可从以下网址获取:
JArduino is available at: JArduino
这篇关于用Java控制Arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!