Reputation: 179
I have the following code, and the StopWatch object, when I try to restart it, it throws this exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt
The code is as follows:
public sealed partial class MainPage : Page
{
private const int ECHO_PIN = 23;
private const int TRIGGER_PIN = 18;
private GpioPin pinEcho;
private GpioPin pinTrigger;
private DispatcherTimer timer;
private Stopwatch sw;
public MainPage()
{
this.InitializeComponent();
InitGPIO();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(400);
timer.Tick += Timer_Tick;
if (pinEcho != null && pinTrigger != null)
{
timer.Start();
}
}
private async void Timer_Tick(object sender, object e)
{
pinTrigger.Write(GpioPinValue.High);
await Task.Delay(10);
pinTrigger.Write(GpioPinValue.Low);
while (pinEcho.Read() == GpioPinValue.Low)
{
sw.Restart();
}
while (pinEcho.Read() == GpioPinValue.High)
{
}
sw.Stop();
var elapsed = sw.Elapsed.TotalSeconds;
var distance = elapsed * 34000;
distance /= 2;
distancetb.Text = "Distance: " + distance + " cm";
}
private async void InitGPIO()
{
var gpio = GpioController.GetDefault();
if (gpio == null)
{
pinEcho = null;
pinTrigger = null;
gpioStatus.Text = "no hay controlador GPIO en este dispositivo";
return;
}
pinEcho = gpio.OpenPin(ECHO_PIN);
pinTrigger = gpio.OpenPin(TRIGGER_PIN);
pinTrigger.SetDriveMode(GpioPinDriveMode.Output);
pinEcho.SetDriveMode(GpioPinDriveMode.Input);
gpioStatus.Text = "controlador GPIO inicializado";
pinTrigger.Write(GpioPinValue.Low);
await Task.Delay(100);
}
}
Upvotes: 0
Views: 279
Reputation: 2030
In your code snipped, I don't see any initialization for Stopwatch sw.
Try adding
sw = new Stopwatch();
in your constructor or somewhere before the Timer_Tick gets executed.
Upvotes: 0