用 Java 控制 Arduino [英] Control an Arduino with Java

查看:28
本文介绍了用 Java 控制 Arduino的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 Java 程序打开和关闭 LED.我在大约 5 分钟内用 C# 完成了这个项目,但在 Java 中似乎更具挑战性.我让 Arduino 等待 1 或 0 写入 COM 端口并将基于此更改 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 应用程序执行此操作?

How would I do this with a Java application?

推荐答案

您可以使用 JArduino (Java-Arduino) 库,它提供了一个 Java API 来使用串行端口(使用 USB 电缆或无线设备)控制您的 Arduino从软件的角度表现为串行端口)、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.

这是一个使 LED 闪烁的 Java 示例:

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

JArduino is available at: JArduino

这篇关于用 Java 控制 Arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆