Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

eclipse - Control an Arduino with Java

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);
        }
}

How would I do this with a Java application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Here is a Java sample to blink an LED:

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 is available at: JArduino


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...