Advertisement
zaguoba

App.xaml.cs [Raspberry Pi 3B omnimeter]

Sep 14th, 2018
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.39 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices.WindowsRuntime;
  6. using System.Diagnostics;
  7. using System.Threading.Tasks;
  8.  
  9. using Windows.ApplicationModel;
  10. using Windows.ApplicationModel.Activation;
  11. using Windows.Foundation;
  12. using Windows.Foundation.Collections;
  13. using Windows.UI.Xaml;
  14. using Windows.UI.Xaml.Controls;
  15. using Windows.UI.Xaml.Controls.Primitives;
  16. using Windows.UI.Xaml.Data;
  17. using Windows.UI.Xaml.Input;
  18. using Windows.UI.Xaml.Media;
  19. using Windows.UI.Xaml.Navigation;
  20. using Windows.Devices;
  21. using Windows.Devices.Gpio;
  22. using Windows.Devices.Spi;
  23. using Windows.Devices.Enumeration;
  24.  
  25.  
  26. namespace projektSyzyf3
  27. {
  28.     // contains definitions of custom gpio names for serial communication with ADC and init method
  29.     public class SimpleSerialProtocol
  30.     {
  31.         //GENERAL
  32.         public GpioPin testPin; //BCM19
  33.         public GpioPin _PD;     //BCM26
  34.  
  35.         ////CHANNEL1
  36.         //public GpioPin CLK1;    //BCM4
  37.         //public GpioPin FSO1;    //BCM25
  38.         //public GpioPin DOUT1;   //BCM6
  39.         //public GpioPin SCLK1;   //BCM13
  40.         //public GpioPin OTR1;    //BCM23
  41.         //public GpioPin SYNC1;   //BCM18
  42.  
  43.         //CHANNEL2
  44.         public GpioPin CLK2;    //BCM27
  45.         public GpioPin FSO2;    //BCM24
  46.         public GpioPin DOUT2;   //BCM5
  47.         public GpioPin SCLK2;   //BCM12
  48.         public GpioPin OTR2;    //BCM22
  49.         public GpioPin SYNC2;   //BCM17
  50.  
  51.         //bit-bang SPI
  52.         public GpioPin _CS0;    //BCM8
  53.         public GpioPin aSCLK;    //BCM11
  54.         public GpioPin DIO;     //BCM10  
  55.  
  56.         //AUX
  57.         private const byte F_ = 0b11110000; //falling edge detected by handler
  58.         private const byte _R = 0b00001111; //rising edge detected by handler
  59.         private byte CLKedge = 0;
  60.         private byte SCLKedge = 0;
  61.         private byte FSOedge = 0;
  62.  
  63.         //STOPWATCH
  64.         public long StoperOne = 0;
  65.         public long[] StoperArr = new long[22];
  66.         public uint StoperCnt = 0;
  67.  
  68.         public SimpleSerialProtocol()
  69.         {
  70.  
  71.         }
  72.  
  73.         public void InitGPIO()
  74.         {
  75.             // Get the default GPIO controller on the system
  76.             GpioController gpio = GpioController.GetDefault();
  77.             if (gpio == null)
  78.                 return; // GPIO not available on this system
  79.  
  80.             // Open GPIO 25
  81.             testPin = gpio.OpenPin(19);
  82.             // Latch HIGH value first. This ensures a default value when the pin is set as output
  83.             testPin.Write(GpioPinValue.High);
  84.             // Set the IO direction as output
  85.             testPin.SetDriveMode(GpioPinDriveMode.Output);
  86.  
  87.             // Open GPIO 27 - CLK listener
  88.             CLK2 = gpio.OpenPin(27);
  89.             CLK2.SetDriveMode(GpioPinDriveMode.Input);
  90.             //CLK2.ValueChanged += EdgeDetCLKOnValueChanged; //listen to edges on CLK
  91.  
  92.             // Open GPIO 24 - FSO input
  93.             FSO2 = gpio.OpenPin(24);
  94.             FSO2.SetDriveMode(GpioPinDriveMode.InputPullDown);
  95.  
  96.             // Open GPIO 5 - DOUT input
  97.             DOUT2 = gpio.OpenPin(5);
  98.             DOUT2.SetDriveMode(GpioPinDriveMode.InputPullDown);
  99.  
  100.             // Open GPIO 12 - SCLK input
  101.             SCLK2 = gpio.OpenPin(12);
  102.             SCLK2.SetDriveMode(GpioPinDriveMode.InputPullDown);
  103.  
  104.             // Open GPIO 22 - OTR input
  105.             OTR2 = gpio.OpenPin(22);
  106.             OTR2.SetDriveMode(GpioPinDriveMode.InputPullDown);
  107.  
  108.             // Open GPIO 17 - issue SYNC pulse to ADC
  109.             SYNC2 = gpio.OpenPin(17);
  110.             SYNC2.Write(GpioPinValue.Low);
  111.             SYNC2.SetDriveMode(GpioPinDriveMode.Output);
  112.  
  113.             //Set PowerDown pin high to enable opamp and ADC
  114.             _PD = gpio.OpenPin(26);
  115.             _PD.Write(GpioPinValue.High);
  116.             _PD.SetDriveMode(GpioPinDriveMode.Output);
  117.         }
  118.  
  119.         public byte InitConversion()
  120.         {
  121.             byte initProgress = 0;
  122.             ushort initTimeout = 0;
  123.  
  124.             long startInitProcess = 0, elapsedInitProcess = 0;
  125.  
  126.  
  127.             CLK2.ValueChanged += EdgeDetCLKOnValueChanged; //listen to edges on CLK
  128.            
  129.             while (initProgress != 0b11111111)
  130.             {
  131.                 if (CLKedge == F_ && initProgress == 0)
  132.                 {
  133.                     CLKedge = 0;
  134.                     SYNC2.Write(GpioPinValue.High);
  135.                     startInitProcess = Stopwatch.GetTimestamp();
  136.                     initProgress |= 0b00000001;
  137.                 }
  138.                 if (CLKedge == F_ && initProgress == 1)
  139.                 {
  140.                     CLKedge = 0;
  141.                     SYNC2.Write(GpioPinValue.Low);
  142.                     elapsedInitProcess = Stopwatch.GetTimestamp() - startInitProcess;
  143.                     initProgress |= 0b00000010;
  144.                 }
  145.                 if (FSO2.Read().Equals(GpioPinValue.Low) && initProgress == 3)
  146.                     initProgress = 0; //startOver
  147.                 if (FSO2.Read().Equals(GpioPinValue.High) && initProgress == 3)
  148.                 {
  149.                     FSO2.ValueChanged += EdgeDetFSOOnValueChanged; //listen to edges on FSO
  150.                     initProgress |= 0b00001100;
  151.                 }
  152.                 if (FSOedge == F_ && initProgress == 15)
  153.                 {
  154.                     FSOedge = 0;
  155.                     initProgress |= 0b00110000;
  156.                 }
  157.                 if (FSOedge == _R && initProgress == 63)
  158.                 {
  159.                     FSOedge = 0;
  160.                     initProgress |= 0b11000000;
  161.                 }
  162.  
  163.                 //escape while if init is taking too long
  164.                 if (CLKedge == _R)
  165.                 {
  166.                     CLKedge = 0;
  167.                     initTimeout++;
  168.                 }
  169.                 if (initTimeout >= 1000)
  170.                     return initProgress; //ignominious failure
  171.             }
  172.  
  173.             CLK2.ValueChanged -= EdgeDetCLKOnValueChanged; //cease to listen CLK
  174.             SCLK2.ValueChanged += EdgeDetSCLKOnValueChanged; //listen to edges on SCLK
  175.  
  176.             return initProgress;
  177.         }
  178.  
  179.         public short CollectFrame()
  180.         {
  181.             ushort theFrame = 0;
  182.             ushort collectProgress = 0x8001;
  183.             FSOedge = 0;
  184.  
  185.             while (collectProgress != 0)
  186.             {
  187.                 if (FSOedge == F_ && collectProgress == 0x8001)
  188.                 {
  189.                     FSOedge = 0; //restore edgeDet marker
  190.                     collectProgress = 0x8000;
  191.                     SCLKedge = 0;
  192.                 }
  193.                 if (SCLKedge == F_ && collectProgress < 0x8001)
  194.                 {
  195.                     SCLKedge = 0;
  196.                     if (DOUT2.Read().Equals(GpioPinValue.High))
  197.                     {
  198.                         theFrame |= collectProgress; //if data line is high, set current bit high
  199.                     }
  200.                     collectProgress >>= 1; //shift to next bit (less significant)
  201.                 }
  202.             }
  203.             return (short)theFrame;
  204.         }
  205.  
  206.         public float toVolts(short theFrame)
  207.         {
  208.             return ((float)theFrame * 4.8f) / 65536.0f;
  209.         }
  210.  
  211.         public void HoldConversion()
  212.         {
  213.             _PD.Write(GpioPinValue.Low);
  214.         }
  215.  
  216.         private void EdgeDetCLKOnValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
  217.         {
  218.             if (args.Edge.Equals(GpioPinEdge.FallingEdge))
  219.                 CLKedge = F_;
  220.             if (args.Edge.Equals(GpioPinEdge.RisingEdge))
  221.                 CLKedge = _R;
  222.         }
  223.  
  224.         private void EdgeDetSCLKOnValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
  225.         {
  226.             if (args.Edge.Equals(GpioPinEdge.FallingEdge))
  227.                 SCLKedge = F_;
  228.             if (args.Edge.Equals(GpioPinEdge.RisingEdge))
  229.                 SCLKedge = _R;
  230.         }
  231.  
  232.         private void EdgeDetFSOOnValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
  233.         {
  234.             if (args.Edge.Equals(GpioPinEdge.FallingEdge))
  235.                 FSOedge = F_;
  236.             if (args.Edge.Equals(GpioPinEdge.RisingEdge))
  237.                 FSOedge = _R;
  238.         }
  239.  
  240.  
  241.  
  242.     }
  243.  
  244.     public static class PGA113SPI
  245.     {
  246.         public const byte readCmd = 0b01101010;
  247.         public const byte writeCmd = 0b00101010;
  248.  
  249.         public static async Task<SpiDevice> InitSPI0(int chipSelect)
  250.         {
  251.             var spi0Aqs = SpiDevice.GetDeviceSelector("SPI0");
  252.             var devicesInfo = await DeviceInformation.FindAllAsync(spi0Aqs);
  253.             var settings = new SpiConnectionSettings(chipSelect)
  254.             {
  255.                 ClockFrequency = 100000,
  256.                 DataBitLength = 8,
  257.                 Mode = SpiMode.Mode0,
  258.                 SharingMode = SpiSharingMode.Shared
  259.             };
  260.             return await SpiDevice.FromIdAsync(devicesInfo[0].Id, settings);
  261.         }
  262.     }
  263.  
  264.     /// <summary>
  265.     /// Zapewnia zachowanie specyficzne dla aplikacji, aby uzupełnić domyślną klasę aplikacji.
  266.     /// </summary>
  267.     sealed partial class App : Application
  268.     {
  269.         /// <summary>
  270.         /// Inicjuje pojedynczy obiekt aplikacji. Jest to pierwszy wiersz napisanego kodu
  271.         /// wykonywanego i jest logicznym odpowiednikiem metod main() lub WinMain().
  272.         /// </summary>
  273.         public App()
  274.         {
  275.             this.InitializeComponent();
  276.             this.Suspending += OnSuspending;
  277.         }
  278.  
  279.         /// <summary>
  280.         /// Wywoływane, gdy aplikacja jest uruchamiana normalnie przez użytkownika końcowego. Inne punkty wejścia
  281.         /// będą używane, kiedy aplikacja zostanie uruchomiona w celu otworzenia określonego pliku.
  282.         /// </summary>
  283.         /// <param name="e">Szczegóły dotyczące żądania uruchomienia i procesu.</param>
  284.         protected override void OnLaunched(LaunchActivatedEventArgs e)
  285.         {
  286.             Frame rootFrame = Window.Current.Content as Frame;
  287.  
  288.             // Nie powtarzaj inicjowania aplikacji, gdy w oknie znajduje się już zawartość,
  289.             // upewnij się tylko, że okno jest aktywne
  290.             if (rootFrame == null)
  291.             {
  292.                 // Utwórz ramkę, która będzie pełnić funkcję kontekstu nawigacji, i przejdź do pierwszej strony
  293.                 rootFrame = new Frame();
  294.  
  295.                 rootFrame.NavigationFailed += OnNavigationFailed;
  296.  
  297.                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
  298.                 {
  299.                     //TODO: Załaduj stan z wstrzymanej wcześniej aplikacji
  300.                 }
  301.  
  302.                 // Umieść ramkę w bieżącym oknie
  303.                 Window.Current.Content = rootFrame;
  304.             }
  305.  
  306.             if (e.PrelaunchActivated == false)
  307.             {
  308.                 if (rootFrame.Content == null)
  309.                 {
  310.                     // Kiedy stos nawigacji nie jest przywrócony, przejdź do pierwszej strony,
  311.                     // konfigurując nową stronę przez przekazanie wymaganych informacji jako
  312.                     // parametr
  313.                     rootFrame.Navigate(typeof(MainPage), e.Arguments);
  314.                 }
  315.                 // Upewnij się, ze bieżące okno jest aktywne
  316.                 Window.Current.Activate();
  317.             }
  318.         }
  319.  
  320.         /// <summary>
  321.         /// Wywoływane, gdy nawigacja do konkretnej strony nie powiedzie się
  322.         /// </summary>
  323.         /// <param name="sender">Ramka, do której nawigacja nie powiodła się</param>
  324.         /// <param name="e">Szczegóły dotyczące niepowodzenia nawigacji</param>
  325.         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
  326.         {
  327.             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
  328.         }
  329.  
  330.         /// <summary>
  331.         /// Wywoływane, gdy wykonanie aplikacji jest wstrzymywane. Stan aplikacji jest zapisywany
  332.         /// bez wiedzy o tym, czy aplikacja zostanie zakończona, czy wznowiona z niezmienioną zawartością
  333.         /// pamięci.
  334.         /// </summary>
  335.         /// <param name="sender">Źródło żądania wstrzymania.</param>
  336.         /// <param name="e">Szczegóły żądania wstrzymania.</param>
  337.         private void OnSuspending(object sender, SuspendingEventArgs e)
  338.         {
  339.             var deferral = e.SuspendingOperation.GetDeferral();
  340.             //TODO: Zapisz stan aplikacji i zatrzymaj wszelkie aktywności w tle
  341.             deferral.Complete();
  342.         }
  343.     }
  344. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement