2

我将开始告诉您,关于函数 serialEvent 的参考对于 Arduino 没有很好的记录。 https://www.arduino.cc/en/Reference/SerialEvent

由于缺乏信息,我误解了此功能的工作原理。因为我有 Arduino Mega 2560,它带有 4 个串行输入/输出,并且它们有自己的 serialEventX 函数(其中 X = {'',1,2,3})。

我已经成功地与一个 ESP8266 模块通信,一旦客户端连接到它,它就会发送和接收信息。

使用 serialEvent1(1,因为它连接到 RX1 和 TX1)我希望仅在数据传入时调用 serialEvent1,但实际上每当我使用 Serial1.write(msg) 时也会调用,所以这意味着发送消息时。

#define DEBUG_ESP8622 1
#include <esp8622.h>
#include <string.h>
#include "common.h"
#include <stdlib.h>
Wifi esp = Wifi(); //Here Serial1.begin(115200) happens
void setup() {
  Serial.begin(9600); //First of all SERIAL for debugging
  Serial.println("Starting");

  while(!esp.sReachable());   //Works
  Serial.println("ESP found");

  while(!esp.sSetMode(1));    //Works
  Serial.println("Mode set to Client");

  while(!esp.sConnect(WIFISSID,WIFIPASSWORD));  //Works
  Serial.println("Connected");
  Serial.print("IP:");
  Serial.println(esp.getIP());

  while(!esp.sStartServer(80));  //Works
  Serial.println("Server started");
}
void loop() {
    if(Serial.available()>0){
            int inByte=Serial.read();
            /*HERE whenever I call Serial1.write(inByte)
              serialEvent1 will be called at the end of the loop
              but actually I don't want it to
            */
            Serial1.write(inByte);
    }

}
void serialEvent(){
    return;
}
void serialEvent1(){
   Serial.println("Write or Read event?");
   while(Serial1.available()>0){
      int inByte=Serial1.read();
      //Serial.write(inByte);
   }
   //esp.onSerialEvent(); //Stores message and parses it, not relevant
   return;
}

所以现在,知道 Arduino 库是基于 AVR libc 库的,我想微控制器内部的 RX1 和 TX1 中断都通过 Arduino 库绑定到 serialEvent1。

是否可以使用该库仅从 serialEvent1 中取消绑定 TX1 并且仍然使用 Arduino 库(Serial1.write()/read())?

我使用最简单的方法使用 Makefile 将代码上传到 Mega。选择从命令行使用 arduino 是因为到目前为止它适合我的需求,我知道 avrdude 和 avr-gcc 是从命令行编译/上传的更完整或更好的方法,如果我错了,请纠正我。

CC=arduino
upload: terminal.ino
    $(CC) terminal.ino --upload

verify: terminal.ino
    $(CC) terminal.ino --verify

如果我开始使用,我应该开始学习如何使用 avrdude 和 avr-gcc 吗?(或者可能与使用 AVR 库的事实无关)

最后,我将上述 Makefile 与 USB 电缆一起使用,如果我使用 avrdude 和 avr-gcc 是通过 ICSP 还是仍然可以通过 USB 电缆使用?这会消除引导加载程序吗?

非常感谢

4

1 回答 1

0

是的,SerialEvent功能很愚蠢。它们与在loop. 如果您做一些耗时的事情并且没有loop足够快地恢复,您仍然可能会丢失数据。解决方案是附加到 RX 中断,但内置类不支持HardwareSerial.

我已经发布HardwareSerial了允许您附加到 RX 中断的修改版本。它被称为NeoHWSerial

因为它是替代品,所以您必须只使用NeoSerial[#]变量。你不能在同一个草图中使用Serial和。NeoSerial1只需使用NeoSerial而不是Serial,即使您不调用NeoSerial.attachInterrupt

void setup()
{
  NeoSerial.begin( 9600 );            // replaces `Serial.begin(9600)`
  NeoSerial.println( F("Started.") ); // ... and all your prints, too

  NeoSerial1.attachInterrupt( myRxFunction );
  NeoSerial1.begin( 9600 );

请记住,在中断期间myRxFunction调用。您必须快速处理每个字符,并且不要调用依赖于处于中断中的事物,例如. 坏朱朱!printmillis()

并确保将匹配的 IDE 版本子目录(例如 1.6.5r2)中的文件复制到您的libraries/NeoHWSerial子目录中。 不要将它们放入libraries/1.0.5libraries/1.6.5r2

于 2016-01-27T16:33:24.437 回答