arduino将struct作为函数的参数传递

时间:2015-06-19 11:01:58

标签: function struct arduino

我正在使用Arduino库收音机。

Arduino radio

如果您执行crtl + f和“无ACK传输”,您将看到示例代码。

有一个名为sendPacketTimeout()的函数。此函数采用char类型的目标和有效内容数据包,例如像这样。

char message1 [] = "Hello";

void setup()
{

}
void loop(void)
{
e = sx1272.sendPacketTimeout(8, message1);
}  

我从下面的头文件中复制了sendPacketTimeout()函数声明。

问题

  1. 你能只将char传递给函数吗?
  2. 我可以创建一个包含信息的结构,并将其传递给函数,例如像这样。
  3. //

    struct messagePacket {
    char boardID[3];       
    char temperature[3];
    char humidity[3];
    };
    
    struct messagePacket myPacket;
    
    void setup() {
    struct messagePacket myPacket;
    Serial.begin(9600);
    strcpy(myPacket.boardID, "01");
    strcpy(myPacket.temperature, "75");
    strcpy(myPacket.humidity, "90"); 
    e = sx1272.sendPacketTimeout(8, myPacket;
    

    这是库中的函数声明

    uint8_t sendPacketTimeout(uint8_t dest, char *payload);
    
    //! It sends the packet wich payload is a parameter before ending MAX_TIMEOUT.
    /*!
    \param uint8_t dest : packet destination.
    \param uint8_t *payload: packet payload.
    \param uint16_t length : payload buffer length.
    \return '0' on success, '1' otherwise
    */
    uint8_t sendPacketTimeout(uint8_t dest, uint8_t *payload, uint16_t length);
    
    //! It sends the packet wich payload is a parameter before ending 'wait' time.
    /*!
    \param uint8_t dest : packet destination.
    \param char *payload : packet payload.
    \param uint16_t wait : time to wait.
    \return '0' on success, '1' otherwise
    */
    

2 个答案:

答案 0 :(得分:0)

这应该有效:

struct messagePacket myPacket;
...
e = sx1272.sendPacketTimeout(8, (uint8_t*)&myPacket, sizeof(struct messagePacket));

答案 1 :(得分:0)

您无法发送struct messagePacket作为参数,因为该函数需要char*

要解决这个问题,你可以创建你的函数并逐个发送结构字段,或者你可以连接它们并一次发送它们。

uint8_t sendPacketTimeout(uint8_t dest, struct messagePacket *myPacket);
{
    int e = 0;
    e = sx1272.sendPacketTimeout(8, myPacket->boardID);
    e += sx1272.sendPacketTimeout(8, myPacket->temperature);
    e += sx1272.sendPacketTimeout(8, myPacket->humidity);
    return e;
}

您现在可以将结构作为参数发送到此函数。

struct messagePacket myPacket;
Serial.begin(9600);
strcpy(myPacket.boardID, "01");
strcpy(myPacket.temperature, "75");
strcpy(myPacket.humidity, "90"); 
e = sx1272.sendPacketTimeout(8, &myPacket);