Go Down

Topic: Change sign (Read 2101 times) previous topic - next topic


Hi  friends.

I'm making some code for a motorcontroller.  The arduino receives a negative number when the motor is supposed to spin backwards.
The value tells the desired speed as well.
To my understanding I can't write: analogwrite(pwmPin, -155), so
I  need to make an integer value change sign.

Like, if I have an integer called "x", and the value of x is -135.

How do I write the software to change the sign to + so the new value will be 135?

Thanks in advance :)


Sep 21, 2010, 08:30 pm Last Edit: Sep 21, 2010, 08:42 pm by AlphaBeta Reason: 1
x = -x;
[edit]I was jinxed  :o[/edit]

Coding Badly

Sep 21, 2010, 08:31 pm Last Edit: Sep 21, 2010, 08:33 pm by bcook Reason: 1

Assuming "MyValue" stores the value to be written...

Code: [Select]
if ( MyValue >= 0 )
 // Make the motor go forward here
 analogWrite( pwmPin, MyValue );
 // Make the motor go backware here
 analogWrite( pwmPin, [glow]-[/glow]MyValue );

@AlphaBeta: 15 seconds apart.  I'd say that's close enough for ... JINX!


Thank you very much!

I knew there was an easy answer for this.

Just out of curiosity. Is this a possible solution as well?

analogWrite( pwmPin, MyValue*-1 );


James C4S

abs() (absolute) would also work:

Code: [Select]
analogWrite( pwmPin, abs(MyValue) );

Just don't call any other functions inside of abs().
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131