2016年3月29日 星期二

Windows IoT Core - Light Sensor sample


這篇介紹在 Windows IoT Core 下, Raspberry Pi 3 如何接收光敏電阻的訊號!

而光敏電阻的訊號是類比訊號,
由於 Raspberry Pi 3 沒有接收類比訊號的 pin 腳,
所以必須先將類比訊號轉成數位訊號,
那該如何做?

 ADC0832 模組,它可以將類比訊號轉為數位訊號,
而在 Windows IoT Core 類別庫,也有相對應的函式庫支援,
所以使用這個模組是十分方便的,

流程簡單來說,就是 Raspberry Pi 連接 ADC0832,ADC0832 連接 Light Sensor

Raspberry Pi ←→ ADC0832 ←→ Light Sensor

先來看看 ADC0832,共 8 個腳位






腳位說明:
Pin Number Description
1 CS - Chip Select (Active Low)
2 CH0 - Analog Input Channel 0
3 CH1 - Analog Input Channel 1
4 GND - Ground
5 DI - Data Input
6 DO - Data Output
7 CLK - Clock
8 Vcc - Positive Supply


ADC0832 connect Light Sensor:
  • Signal ( OUT ) → CH0
  • VCC → VCC
  • GND → GND


ADC0832 connect Raspberry Pi 3:
  • CS → GPIO 18
  • GND → GND
  • DO → GPIO 24
  • DI → GPIO 24 (or just connect DO and DI together)
  • CLK → GPIO 23
  • VCC → 3.3V

電路圖:

Windows IoT Core Library:
  1. 建立 AdcProviderManager 物件
  2. 建立 ADC0832 物件,並指定 ChipSelectPin, ClockPin, DataPin 腳位,
    再加入 AdcProviderManager
  3. 透過 adcManager.GetControllersAsync 取得  adcControllers 物件
  4. 建立 AnalogSensor 物件,同時設定更新頻率
  5. 透過 AnalogSensor ReadingChanged 事件,即可取得訊號( Value, Ratio ),
    由於 ADC0832 是將類比訊號轉為 8bit 數位訊號,所以:
    1. Value  為 0 ~ 255
    2. Ratio 為比例

// Create ADC manager
var adcManager = new AdcProviderManager();

// Add ADC chips
adcManager.Providers.Add(
 new ADC0832()
 {
  ChipSelectPin = gpioController.OpenPin(18),
  ClockPin = gpioController.OpenPin(23),
  DataPin = gpioController.OpenPin(24),
 }
);

// Get the well-known controller collection back
var adcControllers = await adcManager.GetControllersAsync();

// Create light sensor
var lightSensor1 = new AnalogSensor()
{
 AdcChannel = adcControllers[0].OpenChannel(0),
 ReportInterval = 250,
};

// Subscribe to events
lightSensor1.ReadingChanged += LightSensor1_ReadingChanged;

AnalogSensor ReadingChanged event:
private async void LightSensor1_ReadingChanged(IAnalogSensor sender,
 AnalogSensorReadingChangedEventArgs args)
{
 // Invert
 var ratio = 1 - args.Reading.Ratio;
 var value = args.Reading.Value;
 // Update UI
 await Dispatcher.RunIdleAsync((s) =>
 {
  // do something

 });
}

AnalogSensorReading 定義:
public sealed class AnalogSensorReading : IAnalogSensorReadingClass
{
 public AnalogSensorReading(int val, double ratio);

 public double Ratio { get; }
 public double Value { get; }
}


DEMO:


沒有留言:

張貼留言