Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   Motor drive function? (http://www.chiefdelphi.com/forums/showthread.php?t=44038)

Mike 14-02-2006 21:45

Motor drive function?
 
Lets say I want to have a function, that somehow modifies an inputted speed and sets an inputted motor to that speed. Instinct tells me it would be something similar to
Code:

void Drive(int motor, unsigned char speed)
{
        // modify inputted speed
        motor = speed;
}

Drive(pwm01, 100);

However, I've tried that and it doesn't seem to work. The motors just don't spin. I'm assuming it is because when you read pwm01, it gives you the current speed that pwm01 is running at. So Drive(pwm01, 100) is similar to, say, Drive(127, 100)

What is the cause of this problem? How can I fix it?

Mark McLeod 14-02-2006 21:58

Re: Motor drive function?
 
You need to pass the parameter that will be changed in by address rather than value.
Code:

void Drive(int *motor, unsigned char speed)
{
        // modify inputted speed
        *motor = speed;
}
 
Drive(&pwm01, 100);


Mike Betts 15-02-2006 05:04

Re: Motor drive function?
 
Quote:

Originally Posted by Keith Watson
The original code just modifies a local copy of the argument passed in. You need to "pass by reference". Typical usage is:
Code:

void Drive(int& motor, unsigned char speed)
{
        // modify inputted speed
        motor = speed;
}
 
Drive(pwm01, 100);

Mark's example works but is less common in usage. It takes the address of the variable, passes it in as a pointer, then dereferences the pointer.

Keith,

I think that you are mixing C++ with C. in C++, "int&" is a pass by reference. In C there is no pass by reference only pass by value and a pointer is the only way to do it.

Mike



To All,

Mark's post is correct. Please read K&R chapter 5 before sliding down the perilous and provocative path of pointers.

Mike

Keith Watson 15-02-2006 11:55

Re: Motor drive function?
 
Quote:

Originally Posted by Mike Betts
Keith,

I think that you are mixing C++ with C. in C++, "int&" is a pass by reference. In C there is no pass by reference only pass by value and a pointer is the only way to do it.

Mike

Oops, I stand corrected. I've been using C++ for so long (since 1988) I forgot! I removed my post.


All times are GMT -5. The time now is 18:13.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi