Arduino: struct pointer as function parameter

后端 未结 4 1247
我在风中等你
我在风中等你 2020-12-21 16:45

The code below gives the error:

sketch_jul05a:2: error: variable or field \'func\' declared void

So my question is: how can I pass a point

相关标签:
4条回答
  • 2020-12-21 17:13

    The problem is, that the Arduino-IDE auto-translates this into C like this:

    #line 1 "sketch_jul05a.ino"
    #include "Arduino.h"
    void func(Struc *p);
    void setup();
    void loop();
    #line 1
    typedef struct
    { int a,b;
    } Struc;
    
    
    void func(Struc *p) {  }
    
    void setup() {
      Struc s;
      func(&s);
    }
    
    void loop()
    {
    }
    

    Which means Struc is used in the declaration of func before Struc is known to the C compiler.

    Solution: Move the definition of Struc into another header file and include this.

    Main sketch:

    #include "datastructures.h"
    
    void func(Struc *p) {  }
    
    void setup() {
      Struc s;
      func(&s);
    }
    
    void loop()
    {
    }
    

    and datastructures.h:

    struct Struc
    { int a,b;
    };
    
    0 讨论(0)
  • 2020-12-21 17:13

    The answer above works. In the meantime I had found the following also to work, without the need for a .h file:

    typedef struct MyStruc
    { int a,b;
    } Struc;
    
    void func(struct MyStruc *p) {  }
    
    void setup() {
      Struc s;
      func(&s);
    }
    
    void loop()
    {
    }
    

    Be warned: Arduino coding is a little flaky. Many of the libraries are also a bit flaky!

    0 讨论(0)
  • 2020-12-21 17:26

    Prolly old news, but typedef struct allows member functions (at least in IDE 1.6.4). Depending on what you want to do, of course, but I can't think of any func(struct *p) that couldn't be handled also with object.func(param pdata). Just that something like p->a = 120; becomes something like object.setA(120);

    typedef struct {
       byte var1;
       byte var2;
    
       void setVar1(byte val){
          this->var1=val; 
       }
    
       byte getVar1(void) {
           return this->var1; 
       }
    } wtf;
    
    wtf testW = {127,15};
    
    void initwtf(byte setVal) {
        testW.setVar1(setVal); 
        Serial.print("Here is an objective returned value: ");
        Serial.println(testW.getVar1());
    } 
    ...
    void loop() {
       initwtf(random(0,100));
    }
    
    0 讨论(0)
  • 2020-12-21 17:35

    This next code works for me as in Arduino 1.6.3:

    typedef struct S
    {
        int a;
    }S;
    
    void f(S * s, int v);
    
    
    
    void f(S * s, int v)
    {
        s->a = v;
    }
    
    void setup() {
    }
    
    void loop() {
        S anObject;
        // I hate global variables
    
        pinMode(13, OUTPUT);
        // I hate the "setup()" function
    
        f(&anObject, 0);
        // I love ADTs
    
        while (1) // I hate the "loop" mechanism
        {
            // do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题