程序编译,但当分解为函数时实际上不会移动电机

Program compiles, but when broken into functions does not actually move motors

本文关键字:实际上 电机 移动 函数 编译 分解 程序      更新时间:2023-10-16

编译/上传到MCU时没有错误。所需的行为是电机移动。不同之处在于将每个电机控制/命令创建为分隔的功能。

我做了声明,并将各种电机命令(前进、后退等(划分为函数。

我已经将void startup()的内容互换main()。我很困惑为什么只是将main()的内容转移到函数中不起作用。当一切都在 main 中时,它编译并运行,当每个电机命令(向后、前进等(放入隔离函数时,它只编译。它不会导致电机在加载到板上时实际移动。

我是否做了一些错误的排序?我将L6470 **motors定义为全局变量。还需要将更多东西定义为全局变量吗?如果这个C++程序不能分解成函数,为什么不呢?

下面是一个最小的可重现示例,分为一个函数:

#include "mbed.h"
#include "DevSPI.h"
#include "XNucleoIHM02A1.h"
#define DELAY_1 1000
   L6470 **motors;
/* Motor Control Expansion Board. */
XNucleoIHM02A1 *x_nucleo_ihm02a1;
void forward(); // declaration 
int main()
{
    /* Initializing SPI bus. */
#ifdef TARGET_STM32F429
    DevSPI dev_spi(D11, D12, D13);
#else
    DevSPI dev_spi(D11, D12, D13);
#endif
    /* Initializing Motor Control Expansion Board. */
    x_nucleo_ihm02a1 = new XNucleoIHM02A1(&init[0], &init[1], A4, A5, D4, A2, &dev_spi);
    L6470 **motors = x_nucleo_ihm02a1->get_components();
    motors[0]->set_home();    
    wait_ms(DELAY_1);    
    position = motors[0]->get_position();
    forward();
}  
void forward()
{
        motors[0]->move(StepperMotor::FWD, STEPS_1);
        motors[0]->wait_while_active();    
        position = motors[0]->get_position();
        motors[0]->set_mark();    
    wait_ms(DELAY_1);
}

如果您认为这个问题不清楚,请说明原因。

因为您从未初始化过全局变量,而是创建了一个函数不知道的附加局部变量:

这:

L6470 **motors = x_nucleo_ihm02a1->get_components();

需要

motors = x_nucleo_ihm02a1->get_components();

以使用全局变量。

您声明了一个全局变量motors 。然后你决定一个不够好,并声明了另一个名为 motors 的变量,在 main 中是本地的。您已经初始化了第二个变量,也许是正确的。全局变量保持零启动状态,当您的其他函数尝试访问它时,您将获得未定义的行为。

作为一个切线相关的建议,完全避免全局变量。