在另一个类中使用对象(需要参数)及其方法
Using objects (that require a parameter) and their methods within another class
我正在尝试用BeagleBone Black编程一个全方位机器人。我发现BlackLib库在控制引脚方面工作得很好,但我在将它集成到更大的方案中遇到了一点麻烦。如果我简单地创建与引脚相关的对象并将它们设置为高或低(或介于两者之间),我就能够按需控制电机。但是当我尝试创建一个包含BlackLib对象的对象时,我遇到了困难。在我看来,这样做的一个好方法是创建一个包含GPIO和PWM BlackLib对象的电机对象。然后我可以用
创建一个函数来方便地设置功率和方向rightMotor(50); //Should set the power to 50% in one direction
我已经得到了一些工作,但我有困难访问BlackLib对象内的函数是在我自己的马达类。
这是我现在正在使用的代码。
#include "BlackLib/BlackLib.h"
struct Motors
{
BlackPWM* pwm;
BlackGPIO* gpio;
void drive(int power)
{
if(power >= 0)
{
gpio.setValue(low);
//gpio.setValue(low); generates the error described below. I'm not familiar enough with the intricacies of pointers to know how to handle this
//motors.cpp: In member function ‘void Motors::drive(int)’:
//motors.cpp:15:10: error: request for member ‘setValue’ in ‘((Motors*)this)->Motors::gpio’, which is of non-class type ‘BlackGPIO*’
// pwm.setDutyPercent(power);
}
else
{
// gpio.setValue(high);
// pwm.setDutyPercent(100+power);
}
}
};
int main()
{
struct Motors rightMotor;
rightMotor.pwm = new BlackPWM(P9_16);
rightMotor.gpio = new BlackGPIO(GPIO_49,output);
//Give the BeagleBone a little time to create the objects
usleep(10000);
rightMotor.pwm.setPeriodTime(500000);
//I will eventually need to set the period time but I'm not sure how. I'm guessing this is the incorrect syntax
//Ideally, I would create a function so that I could simply write rightMotor.setPeriodTime(500000);
rightMotor.drive(50);
sleep(1);
rightMotor.drive(0);
}
如果我完全错了,有更好的方法,请让我知道。我的最终目标是能够轻松控制多个电机。最后,我想创建函数和类,如
robot.turn(30);
或
robot.forward(100);
从阿拉斯加费尔班克斯大学的计算机科学教授那里得到了以下解决方案。现在可以正常工作了
struct Motors
{
BlackPWM pwm;
BlackGPIO gpio;
Motors(pwm_pin_name pwmPin,gpio_name gpioPin) //motor constructor parameters
: pwm(pwmPin),gpio(gpioPin,output) //member initializer list
{
pwm.setPeriodTime(500000);
}
void drive(int power)
{
if(power >= 0)
{
gpio.setValue(low);
pwm.setDutyPercent(power);
}
else
{
gpio.setValue(high);
pwm.setDutyPercent(100+power);
}
}
};
int main()
{
//User interface pins
BlackGPIO button(GPIO_44,input);
Motors rightMotor(P9_16,GPIO_49);
while(!button.isHigh())
{
rightMotor.drive(0);
}
//The BeagleBone needs a little time to create the PWM object
usleep(10000);
rightMotor.drive(-50);
sleep(1);
rightMotor.drive(0);
}
相关文章:
- 使用在用于SFINAE的void_t中具有参数的方法
- 如何制作一个将函数作为参数的类方法
- c++方法参数只能在linux的发布模式下自行更改
- 使用用户定义的参数调用future/async并调用类方法
- 将成员函数指针作为参数传递给模板方法
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 具有字符串化的可变参数宏的现代/通用方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何在方法中传递结构参数
- 如何将类成员方法的参数列表自动填充写入可变参数?
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- C++接口继承不同的参数方法
- C++ 模板:重载时找不到基类类型参数方法
- 如何使用迭代器作为参数方法?
- 具有不同亚型的参数方法
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何将 C 中声明的可选参数方法转换为 c++
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?