Reputation: 218
There are no errors when compiling/uploading to MCU. The desired behavior is for the motors to move. The difference is creating each motor control/command into compartmentalized functions.
I made declarations and divided the various motor commands (forward, backward, etc) into functions.
I've interchanged the contents of void startup()
in and out of main()
. I'm confused on why just transferring the contents of main()
into functions did not work. It compiles and runs when everything is in main, and when each motor command (backward, forward, etc) is put into isolated functions, it only compiles. It does not cause the motors to actually move when loaded onto the board.
Did I do some incorrect ordering? I defined L6470 **motors
as a global variable. Do some more things need to be defined as a global variables? If this C++ program cannot be broken up into functions, why not?
Here is a minimal reproducible example, broken up into one function:
#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);
}
If you don't think this question is clear, please suggest why.
Upvotes: 1
Views: 137
Reputation: 120011
You declared a global variable motors
. Then you decided one isn't good enough and declared another variable named motors
, local in main
. You have initialised that second variable, perhaps correctly. The global variable remains zero iniitialised, and when your other function tries to access it, you get undefined behaviour.
As a tangentially related piece of advice, avoid global variables altogether.
Upvotes: 2
Reputation: 77324
Because you never initialized your global variable, but instead created an additional local variable your function does not know about:
This:
L6470 **motors = x_nucleo_ihm02a1->get_components();
needs to be
motors = x_nucleo_ihm02a1->get_components();
to use your global variable.
Upvotes: 3