sensor connected to arduino board . how to read analog input of this sensor in java ?
Via serial link.
I am trying below code
import org.sintef.jarduino.AnalogPin;
import org.sintef.jarduino.DigitalPin;
import org.sintef.jarduino.DigitalState;
import org.sintef.jarduino.JArduino;
import org.sintef.jarduino.PinMode;
public class TestClass extends JArduino
{
//Constructor taking a String describing the serial port where the Arduino Board is connected (eg, "COM7")
public TestClass(String port) {
super(port);
}
@Override
protected void setup() {
pinMode(DigitalPin.PIN_13,PinMode.OUTPUT);
}
@Override
protected void loop() {
int sensorValue;
sensorValue = analogRead(AnalogPin.A_0);
System.out.println("Sensor Vlaue ==="+sensorValue);
}
But its not working... how to read sensor value ?
You can use my open source library Ardulink.
www.ardulink.org
It needs some test for analog input (digital works fine) but if it doesn't work I can fix quickly.
You have just to obtain a Link class instance and add an analog listener. For example:
Link link = Link.getDefaultInstance();
link.connect(portNameArduinoUNO); // portNameArduinoUNO is a string (maybe "COM19" or something like this)
link.addAnalogReadChangeListener(new AnalogReadChangeListener() {
@Override
public void stateChanged(AnalogReadChangeEvent e) {
System.out.println(e.getValue());
}
@Override
public int getPinListening() {
return 3; // So it executes an analogRead(3)
}
});
let me know if you have some issues.
Of course you have to modify your sketch to manage messages from and to Ardulink. Please refer to Arduino sketches into Ardulink distribution.
pradnya:
I am trying below code
[snip]
That doesn't look like either Java code for the PC or Arduino code for the Arduino device - it looks a bit like a mix of the two.
What is it supposed to be, and what device is it supposed to run on?
You need to write an Arduino program (sketch) in C++ to read the analog to digital converter using analogRead() and then to send the resulting value to the PC via the USB cable using Serial.print() or Serial.write(). Then you need a Java program that can connect to the virtual serial port the Arduino is using and read the incoming data.
I wrote a demo of communicating with the Arduino using Python in this Thread. In one of the later posts I attached the code for a JRuby program that is equivalent to the Python program. JRuby uses the JVM so that may be of some interest. In any case, your Java program has to do much the same thing as the Python and JRuby programs.
....R