2017-02-21 232 views
1

我目前正在使用c#制作一个覆盆子pi机器人车的东西。我完全没有C#的知识,所以这是我学习它的方式。GPIO在树莓派c#

汽车使用L298N来控制电机,所以我需要弄清楚如何让pi从一个引脚输出高电平,然后从另一个引脚输出低电平,然后我可以制定如何控制它。

但重点是,我写了一些代码,希望它会激活其中一个电机,但似乎并不如此。我希望能够更好地理解c#和GPIO引脚的人能够指出错误。

感谢,卡勒姆

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 
using Windows.Foundation; 
using Windows.Foundation.Collections; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 
using Windows.Devices.Gpio; 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 

namespace App4 
{ 
    /// <summary> 
    /// An empty page that can be used on its own or navigated to within a Frame. 
    /// </summary> 
    public sealed partial class MainPage : Page 
    { 
     public void GPIO() 
     { 
      GpioController gpio = GpioController.GetDefault(); 
      if (gpio == null) 
       return; 
      using (GpioPin pin1 = gpio.OpenPin(5)) 
      { 
       pin1.Write(GpioPinValue.High); 
       pin1.SetDriveMode(GpioPinDriveMode.Output); 
      } 
      using (GpioPin pin2 = gpio.OpenPin(6)) 
      { 
       pin2.Write(GpioPinValue.Low); 
       pin2.SetDriveMode(GpioPinDriveMode.Output); 
      } 
     } 
    } 
} 
+1

我对C#没有任何关于GPIO的知识,但是您可能想在写入之前先调用SetDriveMode输出,对吗? – MrZander

回答

0

如果你不能完全肯定的GPIO引脚是正确的,你可以使用这个GPIO引脚图:https://www.raspberrypi.org/documentation/usage/gpio-plus-and-raspi2/

正如你可以看到GPIO引脚5是在位置29.

如果你确定你有正确的引脚,那么我看不出你的代码有太大的错误。我能想到的唯一的问题是,你正在使用using语句:

using (GpioPin pin1 = gpio.OpenPin(5)) 
{ 
    pin1.Write(GpioPinValue.High); 
    pin1.SetDriveMode(GpioPinDriveMode.Output); 
} 

这样做什么是开放的脚,写微博,然后立即关闭引脚,这可能导致在写没有在引脚闭合之前完成。

不幸的是我无法在文档https://docs.microsoft.com/en-us/uwp/api/windows.devices.gpio.gpiopin中找到关于写入过程是否立即执行的任何内容。

您可以尝试稍后手动删除using语句,并调用pin1.Dispose()(当你即将关闭例如程序)

在这种情况下,它应该是这样的:

GpioPin pin1 = gpio.OpenPin(5); 
pin1.Write(GpioPinValue.High); 
pin1.SetDriveMode(GpioPinDriveMode.Output); 

... 

pin1.Dispose();