c - 制作arduino备用功能

标签 c arduino

我正在尝试为 arduino 编写一些 c 代码,通过使用切换变量在两个不同的函数之间切换。谁能帮我完成这项工作?

int hold = 1;
void setup() {
}

void loop() {
       Serial.println(hold);
     if (hold == 1){
     hold = 2;
       }
     if (hold == 2){
     hold = 1;
       }              
}

最佳答案

是这样的吗?

int hold = 1;

// ...

if (hold)
    functionA();
else
    functionB();
hold = !hold;

编辑 这里有两种方法可以做到这一点。第一个更简单,使用 switch 语句,这实际上只是执行 if...else..

的另一种方式
#include <stdio.h>

#define NUMFUNCS    4

int funcA(void);
int funcB(void);
int funcC(void);
int funcD(void);

int main(void){
    int action = 0;
    int res;
    while(1) {
        switch(action) {
            case 0:  res = funcA();
                     break;
            case 1:  res = funcB();
                     break;
            case 2:  res = funcC();
                     break;
            default: res = funcD();
                     break;
        }
        printf ("Function returned %d\n", res);
        action = (action + 1) % NUMFUNCS;
    }
    return 0;
}

int funcA(void) {
    return 1;
}
int funcB(void) {
    return 2;
}
int funcC(void) {
    return 3;
}
int funcD(void) {
    return 4;
}

稍微复杂一点的是使用函数指针数组。如果要将参数传递给函数,则还需要更改数组声明。缺点是除非您有可变参数函数,否则它们必须都具有相同的参数。

#include <stdio.h>

#define NUMFUNCS    4

int funcA(void);
int funcB(void);
int funcC(void);
int funcD(void);

int (*funcarry[NUMFUNCS])(void) = {     // array of function pointers
    funcA, funcB, funcC, funcD
};

int main(void){
    int action = 0;
    int res;
    while(1) {
        res = (*funcarry[action])();
        printf ("Function returned %d\n", res);
        action = (action + 1) % NUMFUNCS;
    }
    return 0;
}

int funcA(void) {
    return 1;
}
int funcB(void) {
    return 2;
}
int funcC(void) {
    return 3;
}
int funcD(void) {
    return 4;
}

关于c - 制作arduino备用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32597021/

相关文章:

c - scanf() 是如何工作的?

c - 输出不正确,简单的字符串练习 - C

c - 转动方向

Python串口通信

c - Arduino编译器在C库中找不到已实现的方法

bluetooth - HC-05 蓝牙 RSSI 无法与 Arduino 配合使用

c++ - 函数指针的意义何在?

objective-c - uint16_t 与 UInt16

c - 为什么 _exit 会失败?

timer - 如何从 DS3231 RTC 获得毫秒分辨率