2017-12-18 4 views
0

Windows IoT 코어가있는 Arduino Uno와 Raspberry Pi 3가 있습니다. 나는 핀을 초기화하거나 문자열을 파싱하고 구문 분석하도록 알리는 것과 같이, Arduino에 정보를 전달하기 위해 this method을 사용하려고했습니다. 이 방법은 Arduino에서 정보를 얻는 데 완벽하게 작동합니다 (센서 매개 변수처럼).UWP 프로젝트에서 I2C를 사용하여 Arduino와 연결된 Raspberry Pi IoT로 LED를 켜고 끄는 방법은 무엇입니까?

Arduino에 바이트를 보내고 Arduino 코드 내에서 액션을 수행 할 수 있습니다 (숫자 2를 얻을 때 init 핀 7처럼). 하지만 그것은 한 번만 작동합니다. Arduino를 리셋해야만 Raspberry Pi의 바이트를 다시 받아 들일 수 있습니다. (내 Raspberry Pi에서 Arduino에 연결된 LED를 켤 수는 있지만 그걸 되돌릴 수는 없습니다.) 그 반대로도 마찬가지입니다. 일을 제어하기 위해 라스베리 파이 안에 웹 사이트를 만드는 것입니다.하지만 UWP를 사용하고 있습니다. 라스베리 파이 3에서 실행중인 IoT 코어의 데이터를 Arduino Uno (역방향이 아닌)로 전달하거나 관리하려고합니다. 및 I2C 연결로 아두 이노 우노 핀을 제어

내에서 MainPage.xaml을 :.

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.I2c; 
using System.Threading.Tasks; 
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 

namespace I2CComm { 
    /// <summary> 
    /// An empty page that can be used on its own or navigated to within a Frame. 
    /// </summary> 
    public sealed partial class MainPage : Page { 
     private I2cDevice arduio; // Used to Connect to Arduino 
     private DispatcherTimer timer = new DispatcherTimer(); 
     public MainPage() { 
      this.InitializeComponent(); 
      Initialiasecom(); 
     } 
     public async void Initialiasecom() { 
      var settings = new I2cConnectionSettings(0x40); 
      // Slave Address of Arduino Uno 
      settings.BusSpeed = I2cBusSpeed.FastMode; 
      // this bus has 400Khz speed 
      string aqs = I2cDevice.GetDeviceSelector("I2C1"); 
      // This will return Advanced Query String which is used to select i2c device 
      var dis = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs); 
      arduio = await I2cDevice.FromIdAsync(dis[0].Id, settings); 
      timer.Tick += Timer_Tick; 
      // We will create an event handler 
      timer.Interval = new TimeSpan(0,0,0,0,500); 
      // Timer_Tick is executed every 500 milli second 
      timer.Start(); 
     } 

     private async void Timer_Tick(object sender, object e) { 
      byte[] response = new byte[2]; 
      try { 
       arduio.Read(response); 
       // this function will read data from Arduino 
      } 
      catch (Exception p) { 
       Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog(p.Message); 
       await msg.ShowAsync(); 
       // this will show error message(if any) 
      } 
     } 

     private void TurnOn_Click(object sender, RoutedEventArgs e) { 
      try { 
       byte[] sendpos; 
       sendpos = BitConverter.GetBytes(2); 
       arduio.Write(sendpos); 
      } 
      catch (Exception p) { 
       Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog(p.Message); 
      } 
     } 

     private void TurnOff_Click(object sender, RoutedEventArgs e) { 
      try { 
       byte[] sendpos; 
       sendpos = BitConverter.GetBytes(1); 
       arduio.Write(sendpos); 
      } 
      catch (Exception p) { 
       Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog(p.Message); 
      } 
     } 
    } 
} 

내 아두 이노 코드는 다음과 같습니다

#include <Wire.h> 
// Library that contains functions to have I2C Communication 
#define SLAVE_ADDRESS 0x40 
// Define the I2C address to Communicate to Uno 

byte response[2]; // this data is sent to PI 
volatile short LDR_value; // Global Declaration 
const int LDR_pin=A0; //pin to which LDR is connected A0 is analog A0 pin 
const int ledPin = 7; 

void setup() { 
    Serial.begin(9600); 
    pinMode(ledPin, OUTPUT); 
    Wire.begin(SLAVE_ADDRESS); 
    // this will begin I2C Connection with 0x40 address 
    Wire.onRequest(sendData); 
    // sendData is a function called when Pi requests data 
    Wire.onReceive(I2CReceived); 
    pinMode(LDR_pin,INPUT); 
    digitalWrite(ledPin, HIGH); 
} 

void loop() { 
    delay(500); 
} 

void I2CReceived(int NumberOfBytes) { 
    /* WinIoT have sent data byte; read it */ 
    byte ReceivedData = Wire.read(); 
    Serial.println(ReceivedData); 
    if (ReceivedData == 2) { 
    digitalWrite(ledPin, HIGH); 
    return; 
    } else if (ReceivedData == 1) { 
    digitalWrite(ledPin, LOW); 
    return; 
    } 
} 

void sendData() { 
    LDR_value=analogRead(LDR_pin); 
    // Arduino returns 10-bit data but we need to convert it to 8 bits 
    LDR_value=map(LDR_value,0,1023,0,255); 
    response[0]=(byte)LDR_value; 
    Wire.write(response,2); // return data to PI 
} 
+0

동일한 코드를 두 번 게시하셨습니까? – dda

+0

고마워 .. 고쳤어 – Alborz

+0

UWP에서 웹 서버를 호스팅 할 수 있습니까? 지난 번에 나는 그것을 볼 수 없었다. – Pawel

답변

0

라즈베리 파이는 1 바이트 대신 4 바이트 (2이 int)를 전송합니다. Arduino에서 모든 바이트를 수신해야합니다. 다음과 같이 할 수 있습니다.

void I2CReceived(int NumberOfBytes) { 
    /* WinIoT have sent data byte; read it */ 
    byte ReceivedData = Wire.read(); 
    Serial.println(ReceivedData); 

    while (0 < Wire.available()) { 
    byte UselessData = Wire.read(); 
    Serial.println(UselessData); 
    } 

    if (ReceivedData == 2) { 
    digitalWrite(ledPin, HIGH); 
    return; 
    } else if (ReceivedData == 1) { 
    digitalWrite(ledPin, LOW); 
    return; 
    } 
} 
+0

정말 멋지다 .. 감사합니다. – Alborz