Main Site Documentation

PWM and OutputPort [Newbie]


#1

Helo guys, can someone explain to me why, I have set _dir1 to false, when LeftWheelSpeed >= 0 and why I have to calculate “100 - Math.Ab(LeftWheelSpeed)” when LeftWheelSpeed <0?

Should I wirte _dir1 at first, or set _pwm1? Does it matterr? What is the relationship between those two fields?

Thank you!




PWM _pwm1 = new PWM((PWM.Pin)FEZ_Pin.PWM.Di5);
OutputPort _dir1 = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di3, false);
....
if (LeftWheelSpeed < 0)
{
	_dir1.Write(true);
	_pwm1.Set(1000, (byte)(100 - Math.Ab(LeftWheelSpeed)));
}
else
{
	_dir1.Write(false);
	_pwm1.Set(1000, (byte)LeftWheelSpeed);
}




#2

It has to do with how hbridge works. Google hbridge


#3

Perfect! Thank you!


#4

It would be easier if you explained what’s connected to those pins. but since _dir1 is a digital port it’s probably connected to something which controls the direction of the motor, lets say true is clockwise and false is ccw.

Math.Abs (i dont know which namespace you are using but there is no Math.Ab in mine… just math.abs so i guess it’s the same) Abs returns the absolute value. so if you give it -40 it will return 40.

so if left wheel speed is -40 it probably means the wheel is going backwards. now we set direction to backwards and set the speed to 40 since you cannot have a negative pwm duty.

it should not matter when you set direction but if you do it with a running motor it will change direction really fast and brake real hard.

and oh -i’m just guessing since i dont know what you are connecting it to :slight_smile:


#5

Hello!

Connected to the to the pins are motors.

Why is the difference between the values in the Set method?

_pwm1.Set(1000, (byte)(100 - Math.Ab(LeftWheelSpeed)));
and
pwm1.Set(1000, (byte)LeftWheelSpeed);

Thanks!


#6

Sign of the speed value controls the direction. It is just a matter of using one variable in the code for direction and speed. You can have boolean for direction and unsigned for speed as well.

Also you might use just absolute value instead of subtracting it from 100.


#7

as Gus said it has to do with how HBridge work, consider the image, when input A and B are the same, motor doesnt turn, when A is high and B is low, motor turns one way, B is low and A is high, motor turns other way.
so if you set B to high, (in this example B is your _Dir, true is high) motor will turn when the PWM signal is low. so if you set speed to 60. the signal will be low for 40%, thus you have to subtract speed from 100 to have it low for 60%. else it would be speed 40.
i hope this makes sense :slight_smile:

EDIT: i mixed up B high/low in the text on the image.