Arduino:在 Stream 对象上调用 serial.begin() [英] Arduino: Calling serial.begin() on a Stream object

查看:44
本文介绍了Arduino:在 Stream 对象上调用 serial.begin()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改此类,以便我可以同时使用两者SoftwareSerialHardwareSerial 对象.因此,我添加了一个接受 Stream 对象的构造函数,它是 Software 和 HardwareSerial 的超类:

I am trying to modify this class so that I can use both SoftwareSerial and HardwareSerial objects. I therefore added a constructor that takes in a Stream object, the superclass of both Software and HardwareSerial:

/**
 * Instantiates an SBUS object
 * @param Stream* A HardwareSerial or SoftwareSerial object pointer
 */
SBUS::SBUS(const Stream *serialPort){
    port = serialPort;
}

不幸的是,在 SBUS::begin() 方法中,我必须调用 port->begin(BAUDRATE),尽管 begin()code> 作为方法存在于两个子类中,因为它不在 Stream 超类中,我无法调用它.

Unfortunately, in the SBUS::begin() method I must call port->begin(BAUDRATE), and although begin() exists as a method in both subclasses, because it is not in the Stream superclass, I cannot call it.

如何调用port->begin()?我试图在 SBUS 构造和 SBUS::begin() 方法之间在外部的 Hardware 或 SoftwareSerial 对象上调用 begin(),但这似乎没有初始化SBUS 对象正确.有没有办法从 SBUS 类内部调用 begin() ?

How can I call port->begin()? I have tried to call begin() on the Hardware or SoftwareSerial object externally in between SBUS construction and the SBUS::begin() method, but this does not seem to initialize the SBUS object properly. Is there a way to call begin() from inside the SBUS class?

我非常感谢任何帮助.(为了便于编程,FUTABA_SBUS 改为 SBUS)

I greatly appreciate any help. (FUTABA_SBUS was changed to SBUS for ease of programming)

推荐答案

有一些可能性:

  • 在通过指针传递之前初始化串行

  • Initialize the Serial before passing it by a pointer

你可以在Stream类中添加相应的方法并使其成为虚拟的

You can add coresponding method to the Stream class and make it virtual

虚拟开始(long x){}

virtual begin(long x) {}

以便编译器停止抱怨并为对象使用正确的方法.

so that the compiler stops complaining and uses the correct method for the object.

  • 将指针传递给构造函数的正确 begin(..) 方法,保存它并在您需要时调用它喜欢
  • 您可以创建多个构造函数(可能是最好的解决方案):

  • Pass a pointer to the correct begin(..) method to your constructor, save it and call it whenever you like
  • You can create multiple constructors(likely the best solution):

<代码>bool hwSerial;流 * 端口;SBUS::SBUS(SoftwareSerial * serial) {hwserial = false;端口 = 串行;}SBUS::SBUS(HWSerial * serial) {swserial = true;端口 = 串行;}

然后你可以做这样的事情:<代码>SBUS::portBegin(长波特率){如果(hwserial){static_cast(端口)->begin(波特率);} 别的 {static_cast(port)->begin(baudrate);}- 编辑 -更正的动态 -> 静态转换

Then you can do something like this: SBUS::portBegin(long baudrate) { if(hwserial) { static_cast<HWSerial*>(port)->begin(baudrate); } else { static_cast<SoftwareSerial*>(port)->begin(baudrate); } --EDIT-- Corrected, dynamic -> static cast

这篇关于Arduino:在 Stream 对象上调用 serial.begin()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆