Original: Win10 IoT C # development 4-uart serial Communication
Windows IoT Core is one of Microsoft's key products for the internet of things, enabling both the development of UI and user interaction, as well as the ability to control interfaces such as Gpio, making the original embedded cumbersome development simple. The remote Debug function allows for breakpoint tracing and debugging. The C # language itself also has a good user base, believing that Win10 IoT will fire up in the near future.
Last month to help friends solve some of the technical issues about WIN10 IoT, there are also many companies are trying to use Win10 IoT for development, may also encounter these problems, the relevant documents are still very few, written here for your reference.
Because to do a Java web and restful self-hosting framework and a lot of other things, this article also dragged for half a month, the framework has just finished, and later can get rid of tomcat these httpserver, now calm down to write this article.
WIN10 IoT installation and deployment process I will write the article to supplement, the following direct introduction of serial communication development process.
1. Connecting the device
First connect the Raspberry Pi 2 to the sensor. GND,5V Docking, TX and RX Cross Connect.
Raspberry Pi 2 GPIO interface
Sensor-to-device connection
2. Start the device
Connect the raspberry to the LAN and start. Open Windows IoT Core watcher to see the status of your device. Contains information such as name, MAC address, IP address, current online, and so on.
3. Create a project
Open VS2015 to create the project and select the Windows IoT Core template under the C # classification.
4. Configure permissions
The Package.appxmanifest file's node joins the read network and the serial port communication permission, this step is like the Android Uses-permission.
<Capabilities> <CapabilityName= "Internetclient" /> <CapabilityName= "Internetclientserver" /> <CapabilityName= "Privatenetworkclientserver" /> <devicecapabilityName= "Serialcommunication"> <DeviceId= "any"> <FunctionType= "Name:serialport" /> </Device> </devicecapability></Capabilities>
5. Module code
Create the UART serial device and set the parameters.
stringAqsfilter = Serialdevice.getdeviceselector ("UART0");D eviceinformationcollection dis=awaitDeviceinformation.findallasync (aqsfilter);//Get serial device_derialport =awaitSerialdevice.fromidasync (dis[0]. ID);//whether the serial device has been successfully acquiredif(NULL!=_derialport) {_derialport.readtimeout= Timespan.frommilliseconds ( +);//timed out_derialport.baudrate =9600;//baud rate_derialport.parity = Serialparity.none;//Checksum Check_derialport.stopbits = Serialstopbitcount.one;//Stop Bit_derialport.databits =8;//Data bits_derialport.handshake = Serialhandshake.none;//Handshake Mode//set Read input stream_datareader =NewDataReader (_derialport.inputstream);}
Read serial data
task<uint32> Loadasynctask;_datareader.inputstreamoptions = inputstreamoptions.partial; // read data loadasynctask = _datareader.loadasync (_ Readbufferlength). AsTask (); uint bytesread = Loadasynctask; // judge get data length if (Bytesread > 0 // convert hex data string Res = LoadData (bytesread); Sendmsg (res);}
New StringBuilder (); // Conversion buffer data is 16 binary while 0 ) { str_builder. Append (_datareader.readbyte (). ToString ("x2"));}
Push data
New HttpClient (); Httpclient.getasync (thenew Uri (string. Format ("http://192.168.1.9:8099/{0}", res));
6. Debugging code
On another computer (ip:192.168.1.9), first created an HTTP listening service simulator server, listening to the serial data sent by the device on port 8099, and printing to the console.
In the VS2015 toolbar, select remote machine for debugging, IP address input device corresponding address, can be found in Windows IoT Core watcher. When you click Run, it is automatically deployed to your device.
7. Running Results
After the code deployment is complete, the task is started, and the Output window prints the serial data obtained.
Nodejs the simulated server to print the received push data. You can see that the data sent and received is consistent from the printed results.
Consistent with the data protocol conventions of the sensor.
Full code:
usingSystem;usingSystem.Diagnostics;usingSystem.Text;usingSystem.Threading.Tasks;usingWindows.ApplicationModel.Background;usingWindows.Devices.Enumeration;usingWindows.Devices.SerialCommunication;usingWindows.Storage.Streams;usingWindows.Web.Http;namespacecloudtechiot3{//Http://www.cnblogs.com/cloudtech //[email protected] Public Sealed classStartuptask:ibackgroundtask {#regionFiledsPrivateDataReader _datareader; PrivateSerialdevice _derialport; //Buffer size Private UINT_readbufferlength =Ten; #endregion #regionMain Method Public Async voidRun (ibackgroundtaskinstance taskinstance) {awaitListen (); Close (); } #endregion #regionPrivate Methods//Monitor serial port Private AsyncTask Listen () {Try { stringAqsfilter = Serialdevice.getdeviceselector ("UART0"); Deviceinformationcollection Dis=awaitDeviceinformation.findallasync (Aqsfilter); //Get serial device_derialport =awaitSerialdevice.fromidasync (dis[0]. ID); //whether the serial device has been successfully acquired if(NULL!=_derialport) {_derialport.readtimeout= Timespan.frommilliseconds ( +);//timed out_derialport.baudrate =9600;//baud rate_derialport.parity = Serialparity.none;//Checksum Check_derialport.stopbits = Serialstopbitcount.one;//Stop Bit_derialport.databits =8;//Data bits_derialport.handshake = Serialhandshake.none;//Handshake Mode//set Read input stream_datareader =NewDataReader (_derialport.inputstream); //Looping through data while(true) { awaitReadasync (); } } Else { //TODO } } Catch(Exception ex) {//TODO } finally{Close (); } } //Read Data asynchronously Private AsyncTask Readasync () {Task<UInt32>Loadasynctask; _datareader.inputstreamoptions=inputstreamoptions.partial; //reading DataLoadasynctask =_datareader.loadasync (_readbufferlength). AsTask (); Task.delay (Timespan.fromseconds (2.1)). Wait (); UINTBytesread =awaitLoadasynctask; //determine the length of the data obtained if(Bytesread >0) { //Convert hexadecimal data stringres =LoadData (bytesread); Sendmsg (RES); } Else { //TODO } } //Output Results Private voidSendmsg (stringRes) { //PrintDebug.WriteLine (RES); //push to serverHttpClient HttpClient =NewHttpClient (); Httpclient.getasync (NewUri (string. Format ("http://192.168.1.9:8099/{0}", RES))); } //converting Data Private stringLoadData (UINTbytesread) {StringBuilder Str_builder=NewStringBuilder (); //Conversion buffer data is 16 binary while(_datareader.unconsumedbufferlength >0) {Str_builder. Append (_datareader.readbyte (). ToString ("X2")); } returnStr_builder. ToString (). ToUpper (); } //Freeing Resources Private voidClose () {if(NULL!=_datareader) {_datareader.detachstream (); } if(NULL!=_derialport) {_derialport.dispose (); } } #endregion }}
Here the entire data read send process is complete, if the code has optimized suggestions, welcome to leave a message or email me ([email protected]).
You can also add my number to view the previous article.
Project Source GitHub Https://github.com/CloudTechx/CloudTechIot under the CLOUDTECHIOT3 directory.
WIN10 IoT C # development 4-uart serial Communication