{"id":658,"date":"2016-12-02T16:48:12","date_gmt":"2016-12-02T16:48:12","guid":{"rendered":"https:\/\/ibex.tech\/windows-iot\/?p=209"},"modified":"2016-12-02T16:48:12","modified_gmt":"2016-12-02T16:48:12","slug":"rpi-using-the-uart","status":"publish","type":"post","link":"https:\/\/ibex.tech\/csharp\/uwp-programming-in-c\/uart-serial-port\/rpi-using-the-uart","title":{"rendered":"RPi Using The UART"},"content":{"rendered":"<h4>\n\tHardware UART and USB UART Adapters<br \/>\n<\/h4>\n<p>\n\tBoth are usable\n<\/p>\n<h4>\n\tEnabling The UART For Your Application<br \/>\n<\/h4>\n<p>\n\tAt the time of writing in Visual Studio the UART isn&#039;t an option in&nbsp;Package.appxmanifest &gt; Capabilities and it has to be enabled for you app manually:\n<\/p>\n<p>\n\tRight click the Package.appxmanifest file &gt; Open with&#8230; &gt; XML (Text) Editor\n<\/p>\n<p>\n\tAdd the following to the&nbsp;&lt;Capabilities&gt; section:\n<\/p>\n<pre>\n<code>\n  &lt;Capabilities&gt;\n    &lt;DeviceCapability Name=&quot;serialcommunication&quot;&gt;\n      &lt;Device Id=&quot;any&quot;&gt;\n        &lt;Function Type=&quot;name:serialPort&quot; \/&gt;\n      &lt;\/Device&gt;\n    &lt;\/DeviceCapability&gt;\n  &lt;\/Capabilities&gt;\n<\/code><\/pre>\n<h4>\n\tUsing the UART in your code<br \/>\n<\/h4>\n<pre>\n<code>\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Windows.Storage.Streams;\nusing Windows.Devices.Enumeration;\nusing Windows.Devices.SerialCommunication;\n<\/code><\/pre>\n<pre>\n<code>\n\tprivate SerialDevice UartPort;\n\tprivate DataReader DataReaderObject = null;\n\tprivate DataWriter DataWriterObject;\n\tprivate CancellationTokenSource ReadCancellationTokenSource;\n<\/code><\/pre>\n<pre>\n<code>\n\n\t\/\/********************************\n\t\/\/********************************\n\t\/\/********** INITIALISE **********\n\t\/\/********************************\n\t\/\/********************************\n\tpublic async Task Initialise(uint BaudRate)\t\t\/\/NOTE - THIS IS AN ASYNC METHOD!\n\t{\n\t\ttry\n\t\t{\n\t\t\tstring aqs = SerialDevice.GetDeviceSelector(&quot;UART0&quot;);\n\t\t\tvar dis = await DeviceInformation.FindAllAsync(aqs);\n\t\t\tUartPort = await SerialDevice.FromIdAsync(dis[0].Id);\n\n\t\t\t\/\/Configure serial settings\n\t\t\tUartPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);    \/\/mS before a time-out occurs when a write operation does not finish (default=InfiniteTimeout).\n\t\t\tUartPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);     \/\/mS before a time-out occurs when a read operation does not finish (default=InfiniteTimeout).\n\t\t\tUartPort.BaudRate = 9600;\n\t\t\tUartPort.Parity = SerialParity.None;\n\t\t\tUartPort.StopBits = SerialStopBitCount.One;\n\t\t\tUartPort.DataBits = 8;\n\n\t\t\tDataReaderObject = new DataReader(UartPort.InputStream);\n\t\t\tDataReaderObject.InputStreamOptions = InputStreamOptions.Partial;\n\t\t\tDataWriterObject = new DataWriter(UartPort.OutputStream);\n\n\t\t\tStartReceive();\n\t\t}\n\t\tcatch (Exception ex)\n\t\t{\n\t\t\tthrow new Exception(&quot;Uart Initialise Error&quot;, ex);\n\t\t}\n\t}\n\n\n\n\n\t\/\/***********************************\n\t\/\/***********************************\n\t\/\/********** RECEIVE BYTES **********\n\t\/\/***********************************\n\t\/\/***********************************\n\t\/\/This is all a bit complex....but necessary if you want receive to happen asynchrously and for your app to be notified instead of your code having to poll it (this code is basically polling it to create a receive event)\n\n\t\/\/ASYNC METHOD TO CREATE THE LISTEN LOOP\n\tpublic async void StartReceive()\n\t{\n\n\t\tReadCancellationTokenSource = new CancellationTokenSource();\n\n\t\twhile (true)\n\t\t{\n\t\t\tawait Listen();\n\t\t\tif ((ReadCancellationTokenSource.Token.IsCancellationRequested) || (UartPort == null))\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/LISTEN FOR NEXT RECEIVE\n\tprivate async Task Listen()\n\t{\n\t\tconst int NUMBER_OF_BYTES_TO_RECEIVE = 1;\t\t\t\/\/&lt;&lt;&lt;&lt;&lt;SET THE NUMBER OF BYTES YOU WANT TO WAIT FOR\n\n\t\tTask&lt;UInt32&gt; loadAsyncTask;\n\t\tbyte[] ReceiveData;\n\t\tUInt32 bytesRead;\n\n\t\ttry\n\t\t{\n\t\t\tif (UartPort != null)\n\t\t\t{\n\t\t\t\twhile (true)\n\t\t\t\t{\n\t\t\t\t\t\/\/###### WINDOWS IoT MEMORY LEAK BUG 2017-03 - USING CancellationToken WITH LoadAsync() CAUSES A BAD MEMORY LEAK.  WORKAROUND IS\n\t\t\t\t\t\/\/TO BUILD RELEASE WITHOUT USING THE .NET NATIVE TOOLCHAIN OR TO NOT USE A CancellationToken IN THE CALL #####\n\t\t\t\t\t\/\/bytesRead = await DataReaderObject.LoadAsync(NUMBER_OF_BYTES_TO_RECEIVE).AsTask(ReadCancellationTokenSource.Token);\t\/\/Wait until buffer is full\n\t\t\t\t\tbytesRead = await DataReaderObject.LoadAsync(NUMBER_OF_BYTES_TO_RECEIVE).AsTask();\t\/\/Wait until buffer is full\n\n\t\t\t\t\tif ((ReadCancellationTokenSource.Token.IsCancellationRequested) || (UartPort == null))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\tif (bytesRead &gt; 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tReceiveData = new byte[NUMBER_OF_BYTES_TO_RECEIVE];\n\t\t\t\t\t\tDataReaderObject.ReadBytes(ReceiveData);\n\n\t\t\t\t\t\tforeach (byte Data in ReceiveData)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/-------------------------------\n\t\t\t\t\t\t\t\/\/-------------------------------\n\t\t\t\t\t\t\t\/\/----- RECEIVED NEXT BYTE ------\n\t\t\t\t\t\t\t\/\/-------------------------------\n\t\t\t\t\t\t\t\/\/-------------------------------\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\/\/Do something with it\n\n\t\t\t\t\t\t} \/\/foreach (byte Data in ReceiveData)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception)\n\t\t{\n\t\t\t\/\/We will get here often if the USB serial cable is removed so reset ready for a new connection (otherwise a never ending error occurs)\n\t\t\tif (ReadCancellationTokenSource != null)\n\t\t\t\tReadCancellationTokenSource.Cancel();\n\t\t\tSystem.Diagnostics.Debug.WriteLine(&quot;UART ReadAsync Exception: {0}&quot;, e.Message);\n\t\t}\n\t}\n\n\n\t\/\/********************************\n\t\/\/********************************\n\t\/\/********** SEND BYTES **********\n\t\/\/********************************\n\t\/\/********************************\n\tpublic async void SendBytes(byte[] TxData)\n\t{\n\t\ttry\n\t\t{\n\t\t\t\/\/Send data to UART\n\t\t\tDataWriterObject.WriteBytes(TxData);\n\t\t\tawait DataWriterObject.StoreAsync();\n\t\t}\n\t\tcatch (Exception ex)\n\t\t{\n\t\t\tthrow new Exception(&quot;Uart Tx Error&quot;, ex);\n\t\t}\n\t}\n<\/code><\/pre>\n<p>\n\t&nbsp;\n<\/p>\n<p>\n\t&nbsp;\n<\/p>\n<p>\n\t&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hardware UART and USB UART Adapters Both are usable Enabling The UART For Your Application At the time of writing in Visual Studio the UART isn&#039;t an option in&nbsp;Package.appxmanifest &gt; Capabilities and it has to be enabled for you app manually: Right click the Package.appxmanifest file &gt; Open with&#8230; &gt; XML (Text) Editor Add the [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79],"tags":[],"class_list":["post-658","post","type-post","status-publish","format-standard","hentry","category-uart-serial-port"],"_links":{"self":[{"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/posts\/658","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/comments?post=658"}],"version-history":[{"count":0,"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/posts\/658\/revisions"}],"wp:attachment":[{"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/media?parent=658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/categories?post=658"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibex.tech\/csharp\/wp-json\/wp\/v2\/tags?post=658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}