Raspberry尝试读取或写入受保护的内存。这通常表明其他内存已损坏

时间:2016-06-21 17:03:33

标签: c# raspberry-pi windowsiot

我有以下代码和StopWatch对象,当我尝试重新启动它时,它会抛出此异常:

尝试读取或写入受保护的内存。这通常表明其他内存已损坏

代码如下:

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);
        }
    }

1 个答案:

答案 0 :(得分:0)

在你的代码剪辑中,我没有看到任何针对秒表sw的初始化。

尝试添加

sw = new Stopwatch();

在构造函数中或Timer_Tick执行之前的某个地方。