i am trying to increment a variable everytime the Hall Sensor detects the magnet but its not working . I am very new in the field windows iot c# with raspi 3.
So my code looks like:
public sealed partial class MainPage : Page
{
private int count = 5;
private const int SENSOR_PIN = 5; //SENSOR PIN
private GpioPin sensorPin;
public MainPage()
{
this.InitializeComponent();
InitGPIO();
}
private void InitGPIO()
{
var gpio = GpioController.GetDefault();
if (gpio == null)
{
GpioStatus.Text = "No Gpio Pins!";
return;
}
sensorPin = gpio.OpenPin(SENSOR_PIN);
sensorPin.SetDriveMode(GpioPinDriveMode.Input);
sensorPin.ValueChanged += sensorPin_ValueChanged;
GpioStatus.Text = "GPIO pins initialized correctly.";
}
//INTERRUPT HANDLER
private void sensorPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
// Increment
if (e.Edge == GpioPinEdge.FallingEdge)
{
count++;
}
}
}
}
Here is a simple test to narrow down the issue.
Connect GPIO5 and GPIO6 together like this:
Here I simulate Hall Sensor using GPIO6. Every time you click the button the GPIO6 output value will change. The following is the code sample you can test to see if the sensorPin_ValueChanged
hander can be triggered or not.
public sealed partial class MainPage : Page
{
private int count = 5;
private const int SENSOR_PIN = 5; //SENSOR PIN
private GpioPin sensorPin;
private GpioPin OutputPin;
private const int OPinNum = 6;
public MainPage()
{
this.InitializeComponent();
InitGPIO();
}
private void InitGPIO()
{
var gpio = GpioController.GetDefault();
if (gpio == null)
{
GpioStatus.Text = "No Gpio Pins!";
return;
}
sensorPin = gpio.OpenPin(SENSOR_PIN);
sensorPin.SetDriveMode(GpioPinDriveMode.Input);
sensorPin.ValueChanged += sensorPin_ValueChanged;
GpioStatus.Text = "GPIO pins initialized correctly.";
OutputPin = gpio.OpenPin(OPinNum);
OutputPin.SetDriveMode(GpioPinDriveMode.Output);
}
//INTERRUPT HANDLER
private void sensorPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
{
// Increment
if (e.Edge == GpioPinEdge.FallingEdge)
{
count++;
}
}
// Simulate Hall Sensor
private void Button_Click(object sender, RoutedEventArgs e)
{
if(OutputPin.Read() == GpioPinValue.Low)
OutputPin.Write( GpioPinValue.High);
else
OutputPin.Write(GpioPinValue.Low);
}
}
XAML code:
<StackPanel VerticalAlignment="Center" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Name="GpioStatus" />
<Button Content="Change output value" Click="Button_Click"/>
</StackPanel>