简体   繁体   English

如何将串行 object 作为数字传递(使用 arduino 串行的新库)

[英]How to pass Serial object as a number (New library using arduino Serial)

I want to create a new library which controls arduino's Serial library.我想创建一个控制 arduino 的串行库的新库。

Here is what I want...这就是我想要的...

main Sketch主要草图

#include <newLibrary.h>

newLibrary connection(2,9600); // 2 is Serial2, 9600 is baudRate

void main()
{
   connection.start();
}

newLibrary.cpp新图书馆.cpp

newLibrary::newLibrary (uint8_t port, long baudRate)
{
   __port = port;
   __baudRate = baudRate;
}

void newLibrary::start()
{
   (Serial+port).begin(); // I need to add port to Serial to make Serial2
}

What I want to do is,我想做的是,

The user will choose which Serial port(eg. Serial/Serial1/Serial2 etc...) is going to be used with;用户将选择要使用的串行端口(例如 Serial/Serial1/Serial2 等...);

newLibrary connection(2,9600);  // 2 is Serial2, 9600 is baudRate

and after that the start function in newLibrary.h will start that Serial port with an algorithm like;之后,newLibrary.h 中的启动 function 将使用类似的算法启动该串行端口;


void newLibrary::start()
{
   (Serial+port).begin(); //  Which is equal to Serial.begin() or Serial1.begin() etc
}

I know it can be done by if statement or switch case...我知道它可以通过 if 语句或 switch case 来完成......

But is there another way?但是还有其他方法吗?

Such as macros....比如宏......

I know that the macros can be used like;我知道宏可以像这样使用;

#define serialPort (Serial##1) // so the serialPort refers to Serial1

But this way doesnt work for me....但是这种方式对我不起作用......

C++ doesn't supportreflection . C++ 不支持反射 You can't build variable names at runtime.您不能在运行时构建变量名称。

You could store pointers to the objects in a container.您可以将指向对象的指针存储在容器中。

#include <array>

class S {
public:
    void begin() {}
} Serial, Serial1, Serial2;

int main() {
    std::array serials = {&Serial, &Serial1, &Serial2};
    std::uint8_t port = 1;
    serials[port]->begin();
}

Instead of taking a uint8_t why don't you take a Stream object and then you can pass Serial2 directly like: newLibrary connection(Serial2,9600);而不是采用 uint8_t 为什么不采用 Stream object 然后您可以直接通过 Serial2 像:newLibrary connection(Serial2,9600);

newLibrary::newLibrary (Stream port, long baudRate)
{
   __port = port;
   __baudRate = baudRate;
}


newLibrary connection(Serial2,9600);



void newLibrary::start()
{
   _port.begin(_baudRate); //  Which is equal to Serial.begin() or Serial1.begin() etc
}

Of course you also need to change the line in the class definition that defines _port, but since you didn't post that bit I'll assume you know how to do that.当然,您还需要更改定义 _port 的 class 定义中的行,但是由于您没有发布该位,因此我假设您知道该怎么做。

Moral of the story is, those serial ports are objects of type Stream, so you can pass them around just like variables as long as you use the type Stream instead of int or byte or char.故事的寓意是,这些串行端口是 Stream 类型的对象,因此只要使用 Stream 类型而不是 int 或 byte 或 char,就可以像变量一样传递它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM