Right. so we have initialized the unit, and now its time to make them motors spin.
Step 2 : SetMotors
To do this we need to talk to the SetMotors function in the DLL, so once again we need a new custom type to tell Delphi what arguments the dll is expecting.
TInitMotorBee = function():Boolean ;stdcall;
TSetMotors = function(b1,b2,b3,b4,b5,b6,b7,b8,b9 : Integer) : Boolean;stdcall;
This time we're passing a bunch of integers (b1,b2,b3 .. etc) to the SetMotors function, can you guess what those are ? The first (b1) is motor1 on/off, the second (b2) is motor1 speed, the third (b3) is motor 2 on/off etc.. are you getting the idea ? But wait, theres a NINTH argument but only four motors ? This is for the servo. We will look at that later. So now we need another little procedure to instantiate our variable and call the function
procedure SetMot(b1,b2,b3,b4,b5,b6,b7,b8,b9:Integer);
var
Handle: THandle;
SetMotors: TSetMotors;
i : boolean;
begin
Handle := LoadLibrary('mtb.DLL');
if Handle <> 0 then begin
@SetMotors := GetProcAddress(Handle, 'SetMotors');
if @SetMotors <> nil then begin
i := SetMotors(b1,b2,b3,b4,b5,b6,b7,b8,b9);
if i then Form1.Memo1.Lines.Add('Setmotors succeeded');
//Form1.Memo1.Lines.Add(IntToStr());
end else
Form1.Memo1.Lines.Add('Could not find setmotors proc address');
end Else Form1.Memo1.Lines.Add('Could not load DLL');
end;
The SetMotors function will return a boolean to indicate success or failure just like the init function did.
What I did to test was add a slider with a range from 0 - 255 and a checkbox for motors 2 and 3 to the form and chained the following code to the "onChange" event of the controls,
that way the speed of the motor changes as you move the slider up and down , pretty cool huh? You can see I'm casting the Checked property of the Checkbox as an integer
and using it to switch the motor on or off.
procedure TForm1.ChangeMotors;
begin
setMot(
0,0,
Integer(Form1.CheckBox1.Checked),Form1.TrackBar1.Position,
Integer(Form1.CheckBox2.Checked),Form1.TrackBar2.Position,
0,0,
0
);
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
changemotors;
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
changemotors;
end;
It's pertinent to mention at this point, that under normal circumstances I'd free the handle for the library after the first (initialization) call, but when I tried this, the motors wouldn't start, so load the library, initialize, set the motors and you're good. There may be a better way to do this, but thats a different article.
Thats all for this article. Next time I'll look at setting and getting the digital inputs and outputs.
|