> For the complete documentation index, see [llms.txt](https://docs.andymark.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.andymark.com/frc-electronics/can-sensors/can-magnetic-switch-am-5746/examples.md).

# Examples

## Use case

This example reads the CAN Magnetic Switch and publishes the detected state and timestamp to SmartDashboard. Use it to verify CAN communication, determine the repeatable trigger point, and test the magnet’s orientation and working gap on the actual mechanism.

{% hint style="info" %}
The snippets use CAN bus 2 and device ID 0. Change both values to match the controller and sensor configuration.
{% endhint %}

## Setup

Install the [AndyMark WPILib vendor library](/frc-electronics/wpilib-am-vendor-library-setup.md) before using these examples. See [Device API](/frc-electronics/can-sensors/can-magnetic-switch-am-5746/device-api.md) for all available methods.

{% tabs %}
{% tab title="Java" %}

```java
import com.andymark.jni.AM_CAN_Mag_Switch;
import com.andymark.jni.AM_CAN_Mag_Switch.AM_MagSwitchData;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

// CAN bus 2, device ID 0
AM_CAN_Mag_Switch magSwitch = new AM_CAN_Mag_Switch(2, 0);

// Restore the default 100 ms report period.
magSwitch.resetReportPeriod();

AM_MagSwitchData data = magSwitch.getData();

SmartDashboard.putBoolean(
    "MagSwitch/MagnetDetected",
    data.magnetDetected
);
SmartDashboard.putNumber(
    "MagSwitch/Timestamp",
    data.timeStamp
);
```

{% endtab %}

{% tab title="C++" %}

```cpp
#include "AM_CAN_Mag_Switch.h"
#include <frc/smartdashboard/SmartDashboard.h>

// CAN bus 2, device ID 0
AM_CAN_Mag_Switch magSwitch{2, 0};

// Restore the default 100 ms report period.
magSwitch.ResetReportPeriod();

AM_MagSwitchData data = magSwitch.GetData();

frc::SmartDashboard::PutBoolean(
    "MagSwitch/MagnetDetected",
    data.magnetDetected
);
frc::SmartDashboard::PutNumber(
    "MagSwitch/Timestamp",
    data.timeStamp
);
```

{% endtab %}
{% endtabs %}

## Validation steps

1. Move the magnet toward and away from the sensing face while watching the reported state.
2. Repeat from both travel directions to identify any difference between activation and release points.
3. Test the complete tolerance stack, including mechanism play and vibration.
4. Confirm that nearby steel, current-carrying conductors, or other magnets do not create unexpected behavior.
5. Add software debouncing or persistence if a single sample should not change the mechanism state.
