Win10 IoT C # development 3,

Source: Internet
Author: User
Tags sendmsg

Win10 IoT C # development 3,

Windows 10 IoT Core is an important product of Microsoft for the IoT market. It can develop device UIS and interactive user operations, and control GPIO and Other interfaces, making complicated embedded development easy. The Remote Debug function allows you to Debug breakpoint tracing. C # language itself also has a good user base. I believe that Win10 IoT will become popular in the near future.
Last month, I helped my friends solve some technical problems related to Win10 IoT. At present, many companies are trying to use Win10 IoT for development. These problems may also occur. There are still few related documents, this is for your reference.
This article also took about half a month to build a self-host framework for Java Web and Restful and many other things. The framework has just been completed, and you can get rid of the HttpServer such as Tomcat in the future, now let's calm down and write this article.
I will write articles to supplement the installation and deployment process of Win10 IoT. The following describes the development process of serial communication.
1. Connect the device

First, connect Raspberry Pi 2 to the sensor. GND, 5 V docking, TX and RX crossover.

Raspberry Pi 2 GPIO Interface

Sensor and device connection

2. Start the device
Connect Raspberry to the LAN and start it. Open Windows IoT Core Watcher to view the working status of the device. Including name, mac address, IP address, and current online information.

3. Create a project
Open VS2015 to create a project and select the Windows IoT Core template under the C # category.

4. Configure permissions
The node in the Package. appxmanifest file has the permission to read the network and communicate with the serial port. This step is similar to the Android uses-permission.

<Capabilities>    <Capability Name="internetClient" />    <Capability Name="internetClientServer" />    <Capability Name="privateNetworkClientServer" />    <DeviceCapability Name="serialcommunication">      <Device Id="any">        <Function Type="name:serialPort" />      </Device>    </DeviceCapability></Capabilities>

5. module code
Create a serial port device for UART and set parameters.

String aqsFilter = SerialDevice. getDeviceSelector ("UART0"); DeviceInformationCollection dis = await DeviceInformation. findAllAsync (aqsFilter); // get the serial device _ derialPort = await SerialDevice. fromIdAsync (dis [0]. id); // whether the serial port device has been obtained successfully if (null! = _ DerialPort) {_ derialPort. readTimeout = TimeSpan. fromMilliseconds (1000); // timeout _ derialPort. baudRate = 9600; // baud rate _ derialPort. parity = SerialParity. none; // check _ derialPort. stopBits = SerialStopBitCount. one; // stop bit _ derialPort. dataBits = 8; // data bit _ derialPort. handshake = SerialHandshake. none; // handshaking method // you can specify _ dataReader = new DataReader (_ derialPort. inputStream );}

Reading serial data

Task <UInt32> loadAsyncTask; _ dataReader. inputStreamOptions = InputStreamOptions. partial; // read data loadAsyncTask = _ dataReader. loadAsync (_ readBufferLength ). asTask (); uint bytesRead = await loadAsyncTask; // determine the length of the retrieved data if (bytesRead> 0) {// convert the hexadecimal data string res = LoadData (bytesRead ); sendMsg (res );}
StringBuilder str_builder = new StringBuilder (); // convert the buffer data to hexadecimal while (_ dataReader. unconsumedBufferLength> 0) {str_builder.Append (_ dataReader. readByte (). toString ("x2 "));}

Push data

HttpClient httpClient = new HttpClient();httpClient.GetAsync(new Uri(string.Format("http://192.168.1.9:8099/{0}", res)));

6. debug the code
First create an http listening service simulation server using Nodejs, listen to the serial data sent by the device on port 8099, and print it to the Console.

In the toolbar of VS2015, select Remote Machine for debugging. Enter the IP address of the device, which can be viewed in Windows IoT Core Watcher. Click "run" to automatically deploy the device.

 

7. Running result
After the code deployment is complete, run the task and print the obtained serial port data in the Output window.

The node. js simulated server prints the received push data. The printed result shows that the sent and received data are consistent.

It is consistent with the data protocol of the sensor.

Complete code:

Using System; using System. diagnostics; using System. text; using System. threading. tasks; using Windows. applicationModel. background; using Windows. devices. enumeration; using Windows. devices. serialCommunication; using Windows. storage. streams; using Windows. web. http; namespace CloudTechIot3 {// http://www.cnblogs.com/cloudtech // librastarwing@hotmail.com public sealed class StartupTask: IBackgroundTask {# regi On Fileds private DataReader _ dataReader; private SerialDevice _ derialPort; // buffer size private uint _ readBufferLength = 10; # endregion # region Main Method public async void Run (ibackgroundkintasstance taskInstance) {await Listen (); Close () ;}# endregion # region Private Methods // Listen to the serial private async Task Listen () {try {string aqsFilter = SerialDevice. getDeviceSelector ("UART0"); DeviceInformationColl Ection dis = await DeviceInformation. findAllAsync (aqsFilter); // get the serial device _ derialPort = await SerialDevice. fromIdAsync (dis [0]. id); // whether the serial port device has been obtained successfully if (null! = _ DerialPort) {_ derialPort. readTimeout = TimeSpan. fromMilliseconds (1000); // timeout _ derialPort. baudRate = 9600; // baud rate _ derialPort. parity = SerialParity. none; // check _ derialPort. stopBits = SerialStopBitCount. one; // stop bit _ derialPort. dataBits = 8; // data bit _ derialPort. handshake = SerialHandshake. none; // handshaking method // you can specify _ dataReader = new DataReader (_ derialPort. inputStream); // read data cyclically while (true) {await ReadAsync () ;} Else {// TODO} catch (Exception ex) {// TODO} finally {Close () ;}// asynchronously reads private async Task ReadAsync () {Task <UInt32> loadAsyncTask; _ dataReader. inputStreamOptions = InputStreamOptions. partial; // read data loadAsyncTask = _ dataReader. loadAsync (_ readBufferLength ). asTask (); Task. delay (TimeSpan. fromSeconds (2.1 )). wait (); uint bytesRead = await loadAsyncTask; // determine the length of the retrieved data if (bytesRead> 0 ){ // Convert the hexadecimal data string res = LoadData (bytesRead); SendMsg (res);} else {// TODO} // output result private void SendMsg (string res) {// print Debug. writeLine (res); // push to the server HttpClient httpClient = new HttpClient (); httpClient. getAsync (new Uri (string. format ("http: // 192.168.1.9: 8099/{0}", res);} // convert the data private string LoadData (uint bytesRead) {StringBuilder str_builder = new StringBuilder (); // convert the buffer data to hexadecimal while (_ DataReader. unconsumedBufferLength> 0) {str_builder.Append (_ dataReader. readByte (). toString ("x2");} return str_builder.ToString (). toUpper ();} // release the resource private void Close () {if (null! = _ DataReader) {_ dataReader. DetachStream () ;}if (null! = _ DerialPort) {_ derialPort. Dispose () ;}# endregion }}

Here the entire data reading and sending process is complete, if you have optimization suggestions for the code, welcome to leave a message or mail me (librastarwing@hotmail.com ).
You can also add my number to view previous articles.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.