Hola buena, actualmente tengo el proyecto de carrera con arduino pero me estoy metiendo una burrada de cabezazos con la comunicacion entre java y arduino.
Estoy usando un arduino uno con un shield ethernet. En estos momentos no tengo ningun sensor ni actuador conectado ya que quiero antes que el arduino sea capaz de recibier una cadena de caracteres.
Los codigos que pongo a continuacion son codigos sencillos donde solo tienen lo minimo para la comunicacion y mostrar el mensaje recibido a traves del monitor serie
Codigo JAVA
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// TODO Auto-generated method stub
String hostName = "192.168.1.6";
int portNumber = 8886;
int b=78; String txt ="Texto";
System.out.print(txt);
System.out.println("Test");
Socket clientSocket = new Socket(hostName, portNumber);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("enviando msj: "+txt+"\n");
outToServer.writeChars(txt);
System.out.println("enviado");
clientSocket.close();
}
}
Codigo Arduino
#include <NewPing.h>
#include <SPI.h>
#include <Ethernet.h>
//Si tenemos la libreria SPI, debemos de conectar los sensores en pins q no esten entre 12 y 10
#define TRIGGER_PIN 8
#define ECHO_PIN 7
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress gateway(192,168,1, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress serverIP(192,168,1,3);
EthernetClient client;
EthernetServer server(8886);
const int MAX_LEN = 20;
void setup()
{
Serial.begin(115200);
if (Ethernet.begin(mac) == 0)
{
Serial.println("Error con conexion DHCP");
Serial.println("Pasamos a direccion estatica");
IPAddress IP(192,168,1,177);
Ethernet.begin(mac,IP,gateway,subnet);
}
delay(1000);
Serial.println("Esperando servidor");
Serial.println(Ethernet.localIP());
server.begin();
char chArray[]= "some characters";
String aux= String(chArray);
Serial.println(aux);
}
void loop()
{
char inByte;
client = server.available();
char command[MAX_LEN];
static int c = 0;
String test;
if(client)
{
Serial.println(String(command));
inByte = client.read();
switch (inByte)
{
case 13:
c = 0;
Serial.println(command);
test=String(command);
Serial.println("mensaje enviado");
command[c] = 0;
break;
case 10:
break;
default:
if (c < (MAX_LEN - 1))
{
command[c] = inByte;
c++;
}
}
}
}
Para lo que necesito, paquetes UDP estan descartados ya que necesito que sean mensajes que seguro se recibe. El codigo que esta de arduino, es en su mayoria de cosas que he sacado por internet pero no consigo el resultado deseado.
Por favor, ayudadme. LLevo varios dias pegandome contra un muro