Pages: [1]   Go Down
Author Topic: Change sign  (Read 941 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 17
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 smiley






Logged

Norway@Oslo
Offline Offline
Edison Member
*
Karma: 12
Posts: 2033
loveArduino(true);
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

x = -x;
[edit]I was jinxed  :o[/edit]
« Last Edit: September 21, 2010, 01:42:25 pm by AlphaBeta » Logged

Global Moderator
Dallas
Online Online
Shannon Member
*****
Karma: 200
Posts: 12779
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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

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

@AlphaBeta: 15 seconds apart.  I'd say that's close enough for ... JINX!
« Last Edit: September 21, 2010, 01:33:09 pm by bcook » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 17
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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 );

Logged

Norway@Oslo
Offline Offline
Edison Member
*
Karma: 12
Posts: 2033
loveArduino(true);
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Yes it is smiley
Logged

Austin, TX
Offline Offline
Faraday Member
**
Karma: 71
Posts: 6137
Baldengineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

abs() (absolute) would also work:

Code:
analogWrite( pwmPin, abs(MyValue) );

Just don't call any other functions inside of abs().
Logged

Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

0
Offline Offline
Newbie
*
Karma: 0
Posts: 17
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks...
Logged

Pages: [1]   Go Up
Jump to: