【问题标题】:Receive socket when in loop arduino (Interupt a while loop with a socket)在循环arduino中接收套接字(用套接字中断while循环)
【发布时间】:2019-12-03 19:06:08
【问题描述】:

我目前正在做一个 arduino 项目。 arduino 是否通过 Web 套接字与 NodeJS 服务器通信。

套接字连接工作正常,没有问题。但我目前遇到的问题是,我希望能够使用来自 NodeJS 服务器的套接字发出来中断无限循环。

我发现一个页面可以解决这个问题,但只有一个按钮连接到 arduino。

Link to page (Interrupt with button)

这是我希望能够用套接字中断的循环:

bool loopRunning = true;

void rainbow(int wait) {
while(loopRunning == true) {

      for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
        for(int i=0; i<strip.numPixels(); i++) { 
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show(); 
        delay(wait);  
      }
    }
}

我想在收到套接字发出时将 loopRunning 设置为 false。

任何人有任何想法我可以如何实现这一点?

Page to the socket functionality that I use

【问题讨论】:

    标签: socket.io interrupt nodemcu neopixel


    【解决方案1】:

    看来您需要使用两个主要功能:

    • SocketIoClient::on(event, callback) - 将事件绑定到函数
    • SocketIoClient::loop() - 处理 websocket 并获取任何传入事件

    我不能轻易测试这个,但根据文档,这样的东西应该可以工作:

    bool loopRunning = true;
    SocketIoClient webSocket;
    
    void handleEvent(const char* payload, size_t length) {
      loopRunning = false;
    }
    
    void setup() {
      // ...
      // general setup code
      // ...
    
      webSocket.on("event", handleEvent); // call handleEvent when an event named "event" occurs
      webSocket.begin(/* ... whatever ... */);
    }
    
    void rainbow(int wait) {
      while(loopRunning == true) {
        for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
          for(int i=0; i<strip.numPixels(); i++) { 
            int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
            strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
          }
          strip.show();
          webSocket.loop(); // process any incoming websocket events
          delay(wait);
        }
      }
    }
    

    【讨论】:

    • 我已经使用了你提到的两个主要功能。问题是当 while 循环被调用时,我无法再接收来自服务器的传入套接字。
    • @RobinFors,代码的主要补充是while循环中的webSocket.loop();
    • @RobinFors 如果你的代码已经包含了这些函数的使用(你分享的代码里面没有webSocket.loop())而且还是不行,请分享整个相关代码sn- p
    • 我尝试按照你说的做,但仍然没有运气,当调用循环获取时,我无法再接收套接字。
    • @MichelleTilley 我们仍然无法从服务器获取任何套接字。
    最近更新 更多