jjzjj

java - Arduino 以太网客户端在发送 TCP 时出现问题

coder 2023-09-18 原文

我在尝试在 arduino 和 java 之间发送消息时遇到了几个问题。 arduino 有一个超声波传感器,我想将传感器检测到的距离发送到 java。

#include <NewPing.h>
#include <Ethernet.h>
#include <SPI.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#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);
int serverPort=8887;
EthernetClient client;

int msg;

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("connecting to Server ...");

// if you get a connection to the Server
if (client.connect(serverIP, serverPort)) {
  Serial.println("Conectado");//report it to the Serial
  String msg="Hola, servidor";//Message to be sent
  Serial.println("sending Message:"+msg);//log to serial
  client.println(msg);//send the message
}
else {
 // if you didn't get a connection to the server:
 Serial.println("connection failed");
}
}
void loop()
{
delay(50);                    
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
int msg=uS / US_ROUNDTRIP_CM;
Serial.print("Ping: ");
Serial.print(msg); 
Serial.println("cm");
client.print("Ping: ");
client.print(msg); 
client.println("cm");


if (client.available()) {
 char c = client.read();
 Serial.print(c);
}

// if the server's disconnected, stop the client:
if (!client.connected()) {
 Serial.println();//report it to the serial
 Serial.println("disconnected");
 client.stop();
}
}

这是java代码

public static void main(String[] args) {

    ServerSocket s; //Socket servidor
    Socket sc; //Socket cliente

    BufferedReader b; //Canal de Lectura

    String mensaje;

    try {
        //Creo el socket server
        s = new ServerSocket(8887);

        //Invoco el metodo accept del socket servidor, me devuelve una referencia al socket cliente
        sc = s.accept();

        //Obtengo una referencia a los canales de escritura y lectura del socket cliente
        b = new BufferedReader( new InputStreamReader ( sc.getInputStream() ) );


        while ( true ) {
            //Leo lo que escribio el socket cliente en el canal de lectura
            mensaje = b.readLine();
            System.out.println(mensaje);

            //Escribo en canal de escritura el mismo mensaje recibido

            if ( mensaje.equals("by")) { // this dont have sense now
                break;
            }
        }
        b.close();

        sc.close();
        s.close();
    } catch (IOException e) {
        System.out.println(e);
    }       

}

为什么我的 java 代码总是收到 0CM 的距离?

最佳答案

问题解决了。

在这里我找到了它不起作用的原因:Arduino Ethernet UDPSendReceive example disables all pin outputs?

我只改了超声波连接的引脚:

#define TRIGGER_PIN  8  
#define ECHO_PIN     7

关于java - Arduino 以太网客户端在发送 TCP 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858814/

有关java - Arduino 以太网客户端在发送 TCP 时出现问题的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

  10. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

随机推荐