Turn on the LED on Arduino with Java

2019-07-17 01:49发布

问题:

I installed the Java serial RXTX libraries and got my Arduino set up right. I even have the sample code up and running, but I can't seem to understand how to access the different Arduino pins in order to turn a LED for example. How can I access the pins with the OutputStream or any other way?

Do I need to send something special to the stream in order to tell it about a specific pin?

回答1:

Out of the box the Arduino doesn't provide any way to control the I/O ports from the serial link.

You will need to obtain or write a program which runs on the Arduino and which listens for commands from the serial port to control the I/O pins. Because the Arduino only has a small microcontroller on it, you probably cannot write this program in Java.

Here is an example program which runs on the Arduino and reads numbers spelt out in decimal ASCII characters over the serial line, then uses those to control an RGB LED. You should be able to use this example to understand how to approach the Arduino side of the problem, and your Java RXTX code can send the integers to control this once it's working.

http://arduino.cc/en/Tutorial/ReadASCIIString



回答2:

I am not sure how readable my code is, or how easily you can install it, but I wrote a small project to talk to the Arduino via RXTX. You can see my code here:

https://github.com/p90puma/SerialToIR

It should give you some ideas.

These three files should give you everything you need:

  • RXTX Code

  • Interface

  • Arduino Sketch



回答3:

No, the Arduino itself accesses its own pins. You use Java to send serial data to the Arduino, and it then decides which pin(s)/code to use.

So in your Arduino code you start with:

Serial.begin(9600);
...
...

And to make a serial connection from Java, you can use the SerialPortEventListener interface.



回答4:

All of the information in the prior answers is correct. The Arduino does not by itself, talk to a computer running Java and do anything. You need to put code onto the Arduino that will talk to your computer with some kind of protocol.

It turns out that a standard set of code for this exists. It is called Firmata. See http://firmata.org/wiki/Main_Page for the Firmata home page. See http://playground.arduino.cc/Interfacing/Processing for a discussion of Firmata and Processing.

Processing is a PC/Mac/Linux programming environment based on Java. The Processing and Arduino projects are closely related.

Try the various examples. Put Processing and the Arduino IDE on your computer. Upload Firmata onto your Arduino and the use the Processing / Firmata examples to try everything out.