Project requirements
Many times, we want to send commands to our MCU through the upper computer. We can control the MCU to carry out some operations. Generally, we have several methods, including serial port transmission, Bluetooth transmission, WIFI transmission such as UDP and TCP, etc.
In this paper, C# is used to write the upper computer, and UDP is used to send Json format data to the single chip microcomputer for data transmission.
Programming environment
Technology used
UDP
Internet protocol set supports a connectionless transmission protocol, which is called User Datagram Protocol (UDP). UDP provides a method for applications to send encapsulated IP packets without establishing a connection.
The transport layer of Internet has two main protocols, which complement each other. Connectionless is UDP, which does little special except to send packets to applications and allow them to architecture their own protocols at the required level. Connection oriented is TCP, which does almost everything.
UDP protocol is the same as TCP protocol for processing data packets. In the OSI model, both are located at the transport layer and the upper layer of IP protocol. UDP does not provide packet Grouping, assembly and sorting. That is to say, after the message is sent, it is impossible to know whether it arrives safely and completely. UDP is used to support network applications that need to transfer data between computers. Many client / server mode network applications, including network video conference system, need to use UDP protocol. UDP protocol has been used for many years since it came out. Although its initial glory has been covered by some similar protocols, UDP is still a very practical and feasible network transport layer protocol even today.
Method description
Close close UDP connection
Connect establishes a connection to a remote host
DropMulticastGroup exit multicast group
JoinMulticastGroup adds UdpClient to multicast group
Receive returns the UDP datagram sent by the remote host
Send sends the UDP datagram to the remote host
method | explain |
---|---|
Close | Close UDP connection |
Connect | Establish connection with remote host |
DropMulticastGroup | Exit multicast group |
JoinMulticastGroup | Add UdpClient to multicast group |
Receive | Returns the UDP datagram sent by the remote host |
Send | Send UDP datagram to remote host |
Create listening example:
UdpClient udpserver; private void udpListen() { udpserver = new UdpClient(8888);//The parameter is the port for UDP listening }
Examples of received data:
private void getMsg()//Start an asynchronous thread to execute the method { //Define an IPEndPoint object to load the IP and port information of the data source IPEndPoint remoteIpAndPort = new IPEndPoint(IPAddress.Any, 0); while (true) { //Wait for the message. Note that using this method will block the thread while waiting for the message byte[] msgBytes = udpserver.Receive(ref remoteIpAndPort) string receivedStr = System.Text.Encoding.UTF8.GetString(msgBytes); } }
Example of sending data:
private void buttonSend_Click(object sender, EventArgs e) { //Convert the data to be sent into byte array byte[] b = System.Text.Encoding.UTF8.GetBytes("Hello"); //Create target IP port information IPEndPoint sendTo = new IPEndPoint(IPAddress.Parse("192.168.1.233"),1234); //send data this.udpserver.Send(b, b.Length, sendTo); }
JSON
JSON introduction
JSON (JavaScript object notation) is a lightweight data exchange format. Based on a subset of ECMAScript (js specification formulated by the European Computer Association), it uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.
JSON syntax rules
JSON is a sequence of tags. This set of tags contains six construction characters, strings, numbers, and three literal names.
JSON is a serialized object or array.
- Six construction characters:
begin-array = ws %x5B ws ; [left square bracket]
begin-object = ws %x7B ws ; {left brace
end-array = ws %x5D ws ; ] Right square bracket
end-object = ws %x7D ws ; } Right brace
name-separator = ws %x3A ws ; : colon
value-separator = ws %x2C ws ; , comma - Meaningless white space (ws) is allowed before or after these six construction characters:
ws = * (% x20 /; space
%x09 /; Horizontal label
%x0A /; Line feed or line feed
%x0D); return trip - JSON value
Composition of JSON: ws value ws [1]
The value can be an object, an array, a number, a string, or one of three literals (false, null, true). Literals in values must be lowercase in English.
The object is composed of comma separated members enclosed in curly braces. The members are string keys and the values described above, which are composed of comma separated key value pairs, such as:
1
{"name": "John Doe", "age": 18, "address": {"country" : "china", "zip-code": "10000"}}
An array is a set of values enclosed in square brackets, such as:
[3, 1, 4, 1, 5, 9, 2, 6]
Strings are very similar to C or Java strings. A string is a collection of any number of Unicode characters surrounded by double quotes, escaped with a backslash. A character is a single character string.
Numbers are also very similar to those in C or Java. Remove unused octal and hexadecimal formats. Remove some coding details.
Some legal JSON instances:
{"a": 1, "b": [1, 2, 3]}
[1, 2, "3", {"a": 4}]
3.14
"wulianwangzhishi"
C # routine
JavaScriptSerializer ser = new JavaScriptSerializer(); CtrlJson rcj = new CtrlJson() { cmd = "YELLOW" }; string outputJson = ser.Serialize(rcj); byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson);
Key procedures
private void button1_Click(object sender, EventArgs e) { IPAddress Adrr; if (string.IsNullOrEmpty(textBox1.Text)) { Adrr = IPAddress.Parse("255.255.255.255"); } else { Adrr = IPAddress.Parse(textBox1.Text); } IPEndPoint remoteIpep = new IPEndPoint(Adrr, 50001); ; JavaScriptSerializer ser = new JavaScriptSerializer(); CtrlJson rcj = new CtrlJson() { cmd = "RED" }; string outputJson = ser.Serialize(rcj); byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson); //send out ctrludpcRecv.Send(sendByte, sendByte.Length, remoteIpep); }
Page design
follow-up
Complete source code, you can pay attention to my Programming column.
Or focus on WeChat official account, send "C# UDP" to get.
It's not easy to write. Thank you for your support.