TMotionSensor is a component in the FireMonkey library in Delphi that allows you to detect and respond to changes in device orientation and movement. To use it in your Delphi application, you will first need to add the FMX.Sensors unit to your uses clause. Then, you can drop a TMotionSensor component onto your form and configure its properties, such as the type of sensor and the interval at which it should update. Finally, you can handle the OnSensorChange event to respond to changes in device orientation or movement.
Here is an example of using a TMotionSensor component in Delphi:
1 2 3 4 5 6 7 8 9 10 11 12 |
uses FMX.Sensors; procedure TForm1.FormCreate(Sender: TObject); begin MotionSensor1.Active := True; end; procedure TForm1.MotionSensor1SensorChange(Sender: TObject; const OldState, NewState: TSensorState); begin Label1.Text := Format(‘X: %f, Y: %f, Z: %f’, [NewState.AccelerationX, NewState.AccelerationY, NewState.AccelerationZ]); end; |
This code will activate the motion sensor when the form is created, and then updates the label with the new acceleration values in X, Y, Z axis each time the sensor is changed.
You can also use the SensorType
property to specify the type of sensor you want to use, such as an accelerometer, gyroscope, or magnetometer. For example, to use the accelerometer sensor:
1 |
MotionSensor1.SensorType := TSensorType.Accelerometer; |
Additionally, you can use the Interval
property to specify the interval at which the sensor should update. For example, to update the sensor every 50 milliseconds:
1 |
MotionSensor1.Interval := 50; |
It’s worth noting that not all devices have all the types of sensors, so you should check the IsSensorSupported
method before using a specific sensor type.
1 2 3 4 |
if MotionSensor1.IsSensorSupported(TSensorType.Accelerometer) then begin MotionSensor1.SensorType := TSensorType.Accelerometer; end; |
You can also use the Sensor
property to check if the current selected sensor is available and working on the device, otherwise you can change to another sensor type.
1 2 |
if MotionSensor1.Sensor = nil then ShowMessage(‘Accelerometer sensor is not supported.’); |
You can also use the OnActivate / OnDeactivate events to know when the sensor is available or not.
1 2 3 4 5 6 7 8 9 |
procedure TForm1.MotionSensor1Activate(Sender: TObject); begin ShowMessage(‘Sensor activated’); end; procedure TForm1.MotionSensor1Deactivate(Sender: TObject); begin ShowMessage(‘Sensor deactivated’); end; |
In summary, the TMotionSensor component in Delphi allows you to easily detect and respond to changes in device orientation and movement. You can use the properties and events of the component to configure and handle the sensor.
Leave a Reply