Ciao!
Ho provato a fare qualche piccola modifica a questo programma: Oracle Java Technologies | Oracle per fargli inviare un intero direttamente in questo modo:
import java.io.;
import java.util.;
import gnu.io.*;
public class Serial {
static Enumeration portList;
static CommPortIdentifier portId;
static int numeroDaInviare = 0;
static SerialPort serialPort;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort = "COM3";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port " + defaultPort);
portFound = true;
try {
serialPort =
(SerialPort) portId.open("SimpleWrite", 2000);
} catch (PortInUseException e) {
System.out.println("Port in use.");
continue;
}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try {
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
System.out.println(
"Writing "" + numeroDaInviare + "" to " + serialPort.getName());
for(int i=0; i<20; i++){
System.out.println("Scrittura del numero su seriale");
try {
outputStream.write(numeroDaInviare);
} catch (IOException e) {}
try {
Thread.sleep(1000); // Be sure data is xferred before closing
} catch (Exception e) {}
}
serialPort.close();
System.exit(1);
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
}
Mentre in arduino ho scritto questo:
void setup(){
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop(){
int x;
while (Serial.available() > 0) {
int x;
x = Serial.parseInt();
if(x == 2){
digitalWrite(13, HIGH);
delay(150);
digitalWrite(13, LOW);
delay(150);
digitalWrite(13, HIGH);
delay(150);
}
}
Cioè se legge dalla seriale un intero (2), deve far lampeggiare il led sul pin 13.
Ho tentato in tutti i modi di illuminare quel dannato led ma non c'è verso.
E' un problema di sincronizzazione? Metodi sbagliati? Inesperienza?