首页 > 解决方案 > 如何将传感器数据从作为服务器的arduino发送到tomcat上的jsp?

问题描述

我有带以太网屏蔽的 Arduino。我想从超声波传感器发送读数以显示在我本地机器上的 tomcat 上的 JSP 上。我怎样才能做到这一点?

标签: javajsparduinoiot

解决方案


使用 Arduino 的串行通信,您需要为您的 java 代码使用 Serial-Comm 库,下面是 Maven 依赖项:

<dependency>
   <groupId>com.fazecast</groupId>
   <artifactId>jSerialComm</artifactId>
   <version>[2.0.0,3.0.0)</version>
</dependency>

之后将接收到的数据打包到一个对象中,并使用以下命令将其发送到您的 JSP:

request.setAttribute("key",object); 

然后遍历您的对象以显示以下这 2 个链接中的数据可能会帮助您做到这一点:

假设您知道如何从 Arduino 代码发送数据,此代码将帮助您在 java 代码中接收数据:

    SerialPort[] ports = SerialPort.getCommPorts();
    System.out.println("Select a port:");
    int i = 1;
    for(SerialPort port : ports)
        System.out.println(i++ +  ": " + port.getSystemPortName());
    Scanner s = new Scanner(System.in);
    int chosenPort = s.nextInt();

    SerialPort serialPort = ports[chosenPort - 1];
    if(serialPort.openPort())
        System.out.println("Port opened successfully.");
    else {
        System.out.println("Unable to open the port.");
        return;
    }

    serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);

    Scanner data = new Scanner(serialPort.getInputStream());
    int value = 0;
    while(data.hasNextLine()){
        try{

        value = Integer.parseInt(data.nextLine());
        System.out.println(value);
    }

    catch(Exception e){}
}
System.out.println("Done.");

推荐阅读