You are on page 1of 14

5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

   

0
   

  PROJECTS, MIKROC PROJECTS, INTERNET OF THINGS PROJECTS  ETHERNET UDP-BASED CONTROL AND MONITORING WITH PIC MICROCONTROLLER – MIKROC

29 Ethernet UDP-Based Control and Monitoring with PIC


Nov
Microcontroller – MikroC
 By Bitahwa Bindu  Internet of Things Projects, MikroC Projects, Projects

 B.Tech Projects, B.Tech projects for ECE/CSE/Computer Science Students, B.tech./M.Tech Final Year Projects, BTech final year projects, C#, ENC28J60,
Ethernet, Ethernet Communication, Final Year Projects for Electronics, Final Year Projects For Engineering Students, GUI, HMI, Home Automation, Human-
Machine Interface, Internet of Things, IoT, Microcontroller, Microcontroller GUI, MikroC, PIC, Projects, Proteus, Relay, SCADA, simulate ENC28J60, Simulate
Ethernet, UDP, UDP Based Control, Visual Studio, Visual Studio 2015, Visual Studio 2017, winpcap

Watch the video Tutorial part 1:

mikroC Pro for PIC Tutorial -81- Project 16 Ethernet UDP-Based Control and Monitoring, part 1

ZA R

EU R

US D

GBP

BWP

Ethernet is the leading wired standard for networking as it enables to connect a very large number of computers, microcontrollers and other
computer-based equipment to one another.

In this project we are going to learn how to control any device like an LED, a relay, a light bulb or a motor connected to a PIC Microcontroller from
a remote location using a customized computer Graphical User Interface (GUI) software designed with C#.

A number of client computers from different locations can be used to control the field devices from anywhere. Communication between the client
computer and the microcontroller is via UDP protocol. With the help of a router connected to the internet, these devices can be controlled or
monitored anywhere in the world in real time.

This project can be used as a base for Final Year Project For electronic and Computer Science Engineering Students.

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 1/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

Figure 1: Controlling and Monitoring devices from a PC GUI Software

In this project a PC GUI Software is designed with C# to control a motor and a light bulb connected to a PIC microcontroller using relays. We’re
gonna also read periodically the temperature and display it graphically on the screen and plot a live chart of temperature variations.

With a GUI Software unlike a simple web browser as we learned from Web-Based Control and Monitoring with PIC Microcontroller project, we will
have more flexibility how we can design the GUI software. We could easily create some sort of SCADA software by directly interacting with devices
such as sensors, valves, pumps, motors and more through Human-Machine Interface (HMI) software.

It’s easy to also record events into a log file, send notification messages via email or SMS or raise some audible alarms.
ZA R

TCP vs. UDP


EU R
A number of client computers from different locations can be used to control the field devices from anywhere. In the Web-Based Control and
Monitoring with PIC Microcontroller project, we demonstrated how to use TCP protocol with mikroC to control devices connected to a PIC
US D
microcontroller, in this example we’re gonna learn how to use the UDP protocol. Here are some few differences between these two protocols:

GBP
TCP protocol provides reliable ordered delivery of packets. It uses error detection, re-transmissions and acknowledgements. Typical TCP
applications include email and web browsing.
UDP protocol doesn’t care if every packet is received. This enables faster transmissions. Typical UDP applications include VoIP and music BWP

streaming.
TCP is strictly used for point to point or unicast transmissions
UDP can be used for unicast (one to one), multicast (one to many) and broadcast (one to all) transmissions.

Computer Graphical User Interface (GUI)  software


The figure 2 below shows the PC GUI Software.

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 2/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

Figure 2: Computer Graphical User Interface (GUI)  software

We are using two buttons to control the devices connected to PIC microcontroller. By clicking on the BULB button, it will change the color to a lit
BULB and Switch ON the BULB connected to the PIC. Clicking it again with turn the BULB OFF.

The FAN button controls the FAN connected to the PIC, clicking it will turn it ON and clicking it again will turn it OFF.

A Temperature Gauge displays the temperature graphically every 2 seconds and a live chart plots the temperature variations continuously.

To enhance the display, we also created an analog clock. A File menu has buttons to Connect/Disconnect, Settings and Exit.

Figure 3: GUI Settings

In the Settings dialog box, the skin of the application can be set from Blue, Light Blue, Dark, Gray, Black, White, Dark, Coffee, Sky
Blue, Caramel, Silver, Green and Pink.
ZA R

You can also set the IP address of the PIC microcontroller and the Port number we’re gonna communicate with.
EU R

Port numbers are used to identify processes running in the applications on a host. For example in one PC, more than one applications that require
TCP/IP communications can run at the same time like a web browser and an email client and both will send and receive packets with the same IP US D

address. The Transport layer will differentiate a web browser packet from an email packet using port numbers.
Some well-know port numbers have been reserved for specific applications, typically for server application. GBP

Here are some of them:


BWP

Port 21: FTP


Port 23: Telnet
Port 25: SMTP (email outgoing)
Port 53: DNS
Port 67: DHCP
Port 80: HTTP (Web)
Port 110: POP3 (email, incoming)
Port 143: IMAP (email, incoming)

Client side port numbers are generated and assigned by the Transport layer. They could be any number from 1024 to 65535. These port numbers
are typically allocated for short term use, our application uses port 10001

Creating Simple UDP Server And Client to Transfer Data Using C#


By using simple network applications, we can send files or messages over the internet. A socket is a low-level connection point to the IP stack. This
socket can be opened or closed or one of a set amount of intermediate states. A socket can deliver and receive data down this connection. Data is
generally sent in blocks of a few kilobytes at a time and are called packets.

All packets that travel on the web must use the Internet communications protocol. This means that the source IP address, destination address
must be provided in the packet. Some data packets also contain a port number like TCP/IP and UDP.

This simple code below shows the steps to send UDP data from client to server. In this example we are sending a ‘2’ to the PIC microcontroller.

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 3/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

1 using System.Net.Sockets;
2 using System.Net;
3  
4 public byte[] Txt = new byte[1];
5 public UdpClient ClientSocket = new UdpClient();
6         
7 //Load IP Address and Port number from settings
8 public string ServerIPAddress = Properties.Settings.Default.IPaddress.ToString();
9 public int PortNumber =Convert.ToInt16( Properties.Settings.Default.PortNumber);
10  
11 ClientSocket.Connect(ServerIPAddress, PortNumber); //Connect
12 Txt[0] = 2;
13 ClientSocket.Send(Txt, 1);    //Send number 2

The first task is to create a UDP Client object (public UdpClient ClientSocket = new UdpClient();). This is a socket that can send UDP packets.
ClientSocket.Connect() takes two arguments, the server IP address and the port number, these values are saved in application settings. A port
number is selected arbitrarily. Here, the port number 10001 will be read from the application settings, remember this number it is not in the first
1024 port numbers reserved for specific use by IANA.


To detect incoming data, the application will become a server, the code below shows the steps to receive a temperature data from the PIC.

1 private void Form1_Load(object sender, EventArgs e)


2         {
3             Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
4             CheckForIllegalCrossThreadCalls = false;
5             thdUDPServer.Start();
6         }
7         float temp;
8         public void serverThread()
9         {
10             UdpClient udpClient = new UdpClient(PortNumber);
11             while (true)
12             {
13                 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
14                 byte[] receiveBytes;
15                 receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
16  
17                 if (connected)
18                 {
19                     try
ZA R
20                     {
21                         string returnData = Encoding.ASCII.GetString(receiveBytes);
22                         temp = float.Parse(returnData, System.Globalization.CultureInfo.InvariantCulture);
23                         linearScaleComponent1.Value = temp; EU R
24                     }
25                     catch (Exception ex)
26                     { US D
27                         XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
28                     }
29                     
GBP
30                 }
31             }
32         }
BWP

A key feature of servers is multi-threading, they can handle hundreds of simultaneous requests. In this case, we must have at least two threads:
one deals with incoming UDP data, and the other one the main thread to execute the rest of the program like buttons click events or sending data
to PIC. This will make sure the user interface does not appear hung.

Below is the complete code of the application. You can also download the full Visual studio project and the end of this article.

1 using System;
2 using System.Text;
3 using System.Windows.Forms;
4 using DevExpress.XtraEditors;
5 using System.Net.Sockets;
6 using System.Net;
7 using DevExpress.XtraGauges.Win.Gauges.Circular;
8 using DevExpress.XtraGauges.Core.Model;
9 using System.Threading;
10 using DevExpress.XtraCharts;
11  
12 namespace UDP_Control_Monitoring
13 {
14     public partial class Form1 : DevExpress.XtraBars.Ribbon.RibbonForm
15     {
16         public byte[] Txt = new byte[1];  
17         public UdpClient ClientSocket = new UdpClient();
18         
19         //Load IP Address and Port number
20         public string ServerIPAddress = Properties.Settings.Default.IPaddress.ToString();
21         public int PortNumber =Convert.ToInt16( Properties.Settings.Default.PortNumber);
22  
23         //Clock
24         ArcScaleComponent scaleMinutes, scaleSeconds;
25         int lockTimerCounter = 0;
26         public Form1()
27         {
28             InitializeComponent();
29  
30             //clock
31             scaleMinutes = Clock.AddScale();
32             scaleSeconds = Clock.AddScale();
33   Privacy - Terms
34             scaleMinutes.Assign(scaleHours);
https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 4/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

35             scaleSeconds.Assign(scaleHours);
36  
37             arcScaleNeedleComponent2.ArcScale = scaleMinutes;
38             arcScaleNeedleComponent3.ArcScale = scaleSeconds;
39             timer1.Start();
40             timer1_Tick(null, null);
41             
42             linearScaleComponent1.Value = 0; //initialize scale to 0
43  
44             //chart
45             timer2.Interval = interval;
46         }
47         
48         void UpdateClock(DateTime dt, IArcScale h, IArcScale m, IArcScale s)
49         {
50             int hour = dt.Hour < 12 ? dt.Hour : dt.Hour - 12;
51             int min = dt.Minute;
52             int sec = dt.Second;
53             h.Value = (float)hour + (float)(min) / 60.0f;
54             m.Value = ((float)min + (float)(sec) / 60.0f) / 5f;
55             s.Value = sec / 5.0f;
 56         }
57  
58         private void btnExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
59         {
60             ClientSocket.Close();
61             Environment.Exit(Environment.ExitCode);
62         }
63         bool connected = false;
64         private void btnConnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
65         {
66           
67                 try
68                 {
69                 ClientSocket.Connect(ServerIPAddress, PortNumber);
70                 btnDisconnect.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
71                 btnConnect.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
72                 barStaticConnect.Caption = "Connected!";
73                 btnDisconnectImage.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
74                 btnConnectImage.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
75  
76                 groupBoxLightBulb.Enabled = true;
77                 groupBoxFan.Enabled = true;
78   ZA R
79                 connected = true;
80                }
81                 catch (Exception ex)
EU R
82                 {
83                     XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
84                 }
85              US D
86  
87         }
88   GBP
89         private void btnDisconnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
90         {
91             try
BWP
92             {
93                 btnDisconnect.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
94                 btnConnect.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
95                 barStaticConnect.Caption = "Disconnected!";
96                 btnDisconnectImage.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
97                 btnConnectImage.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
98  
99                 btnFanON.Visible = false;
100                 btnFanOFF.Visible = true;
101                     btnLightON.Visible = false;
102                 btnLightOff.Visible = true;
103                 groupBoxLightBulb.Enabled = false;
104                 groupBoxFan.Enabled = false;
105  
106                 Txt[0] = 0;
107                 ClientSocket.Send(Txt, 1);
108                 PauseResume();
109             }
110             catch (Exception ex)
111             {
112                 XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
113             }
114         }
115         
116         bool LightON = false;
117         bool MotorON = false;      
118         private void btnLightOff_Click(object sender, EventArgs e)
119         {
120             if (MotorON== true)
121             {
122                 Txt[0] = 3;
123                 ClientSocket.Send(Txt, 1);
124                 btnLightOff.Visible = false;
125                 btnLightON.Visible = true;
126                 LightON = true;
127             }
128             else
129             {
130                 Txt[0] =  1;
131                 ClientSocket.Send(Txt, 1);
132                 btnLightOff.Visible = false ;
133                 btnLightON.Visible = true;
Privacy - Terms
134                 LightON = true;

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 5/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

135             }
136             
137             
138         }
139  
140         private void btnLightON_Click(object sender, EventArgs e)
141         {
142             if (MotorON == true)
143             {
144                 Txt[0] = 2;
145                 ClientSocket.Send(Txt, 1);
146                 btnLightOff.Visible = true;
147                 btnLightON.Visible = false;
148                 LightON = false;
149             }
150             else
151             {
152                 Txt[0] = 0;
153                 ClientSocket.Send(Txt, 1);
154                 btnLightOff.Visible =  true;
155                 btnLightON.Visible = false;
 156                 LightON = false;
157             }
158         }
159  
160         private void btnFanOFF_Click(object sender, EventArgs e)
161         {
162             if (LightON == true)
163             {
164                 Txt[0] = 3;
165                 ClientSocket.Send(Txt, 1);
166                 btnFanOFF.Visible = false;
167                 btnFanON.Visible =  true;
168                 MotorON = true;
169             }
170             else
171             {
172                 Txt[0] = 2;
173                 ClientSocket.Send(Txt, 1);
174                 btnFanOFF.Visible = false;
175                 btnFanON.Visible = true;
176                 MotorON = true;
177             }
178         } ZA R
179  
180         private void btnFanON_Click(object sender, EventArgs e)
181         {
EU R
182             if (LightON == true)
183             {
184                 Txt[0] = 1;
185                 ClientSocket.Send(Txt, 1); US D
186                 btnFanOFF.Visible = true;
187                 btnFanON.Visible = false;
188                 MotorON = false; GBP
189             }
190             else
191             {
BWP
192                 Txt[0] = 0;
193                 ClientSocket.Send(Txt, 1);
194                 btnFanOFF.Visible = true;
195                 btnFanON.Visible = false;
196                 MotorON = false;
197             }
198         }
199  
200         private void timer1_Tick(object sender, EventArgs e)
201         {
202             if (lockTimerCounter == 0)
203             {
204                 lockTimerCounter++;
205                 UpdateClock(DateTime.Now, scaleHours, scaleMinutes, scaleSeconds);
206                 lockTimerCounter--;
207             }
208         }
209  
210         private void btnSettings_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
211         {
212             frmSettings frm = new frmSettings();
213             frm.ShowDialog();
214         }
215         
216         private void Form1_Load(object sender, EventArgs e)
217         {
218             Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
219             CheckForIllegalCrossThreadCalls = false;
220             thdUDPServer.Start();
221         }
222         float temp;
223         public void serverThread()
224         {
225             UdpClient udpClient = new UdpClient(PortNumber);
226             while (true)
227             {
228                 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
229                 byte[] receiveBytes;
230                 receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
231  
232                 if (connected)
233                 {
Privacy - Terms
234                     try

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 6/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

235                     {
236                         string returnData = Encoding.ASCII.GetString(receiveBytes);
237                         temp = float.Parse(returnData, System.Globalization.CultureInfo.InvariantCulture);
238                         linearScaleComponent1.Value = temp;
239                     }
240                     catch (Exception ex)
241                     {
242                         XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
243                     }
244                     
245                 }
246             }
247         }
248  
249         const int interval = 3;
250  
251         static RegressionLine GetRegressionLine(Series series)
252         {
253             if (series != null)
254             {
255                 SwiftPlotSeriesView swiftPlotView = series.View as SwiftPlotSeriesView;
 256                 if (swiftPlotView != null)
257                     foreach (Indicator indicator in swiftPlotView.Indicators)
258                     {
259                         RegressionLine regressionLine = indicator as RegressionLine;
260                         if (regressionLine != null)
261                             return regressionLine;
262                     }
263             }
264             return null;
265         }
266         
267       
268         int TimeInterval { get { return Convert.ToInt32(spnTimeInterval.EditValue); } }
269         Series Series1 { get { return chart.Series.Count > 0 ? chart.Series[0] : null; } }
270         RegressionLine Regression1 { get { return GetRegressionLine(Series1); } }    
271  
272        void SetPauseResumeButtonText()
273         {
274             btnPauseResume.Text = timer2.Enabled ? "Pause" : "Resume";
275         }
276         
277         private void timer2_Tick(object sender, EventArgs e)
278         { ZA R
279             if (Series1 == null )
280                 return;
281             DateTime argument = DateTime.Now;
EU R
282             SeriesPoint[] pointsToUpdate1 = new SeriesPoint[interval];          
283             for (int i = 0; i < interval; i++)
284             {
285                 pointsToUpdate1[i] = new SeriesPoint(argument, temp);               US D
286                 argument = argument.AddMilliseconds(1);            
287             }
288             DateTime minDate = argument.AddSeconds(-TimeInterval); GBP
289             int pointsToRemoveCount = 0;
290             foreach (SeriesPoint point in Series1.Points)
291                 if (point.DateTimeArgument < minDate)
BWP
292                     pointsToRemoveCount++;
293             if (pointsToRemoveCount < Series1.Points.Count)
294                 pointsToRemoveCount--;
295             AddPoints(Series1, pointsToUpdate1);        
296             if (pointsToRemoveCount > 0)
297             {
298                 Series1.Points.RemoveRange(0, pointsToRemoveCount);          
299             }
300             SwiftPlotDiagram diagram = chart.Diagram as SwiftPlotDiagram;
301             if (diagram != null && (diagram.AxisX.DateTimeScaleOptions.MeasureUnit == DateTimeMeasureUnit.Millisecond || diagram
302                 diagram.AxisX.WholeRange.SetMinMaxValues(minDate, argument);
303         }
304         void AddPoints(Series series, SeriesPoint[] pointsToUpdate)
305         {
306             if (series.View is SwiftPlotSeriesViewBase)
307                 series.Points.AddRange(pointsToUpdate);
308         }
309         private void PauseResume()
310         {
311             timer2.Enabled = !timer2.Enabled;
312             SetPauseResumeButtonText();
313         }
314         private void btnPauseResume_Click(object sender, EventArgs e)
315         {
316             PauseResume();
317         }
318  
319         
320  
321         private void chRegression_CheckedChanged_1(object sender, EventArgs e)
322         {
323             if (Regression1 != null)
324                 Regression1.Visible = chRegression.Checked;
325           
326         }
327  
328     }
329 }

Circuit Diagram
Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 7/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

Figure 4 below shows the circuit diagram. The interface between the PIC18F45K22 microcontroller and the ENC28J60 Ethernet controller chip is
based on the SPI bus protocol, The SI, SO, and SCK pins of the Ethernet chip are connected to SPI pins (SDO, SDI and SCLK) of the microcontroller.
The Ethernet controller chip operates at 3.3V, its output SO pin  cannot drive the microcontroller input pin without a voltage translator if the
microcontroller is operated at 5V.

Figure 4: ENC28J60 Ethernet Controller Connections

To make the design of Ethernet applications easy, there are ready made boards that include the EC28J60 controller, voltage translation chip and an
RJ45 connector. Figure 5 below shows the the mikroElektronika Serial Ethernet Board. This is a small board that plugs in directly to PORTC of
the EasyPI CV7 development board via a 10-way IDC plug simplifying the development of embedded  Ethernet  projects. This board is equipped
with an EC28J60 Ethernet controller chip, a 74HCT245 voltage translation chip, three LEDs, a 5 to 3.3 voltage regulator and an RJ45 connector with
an integrated transformer.

ZA R

EU R

US D

GBP

BWP

Figure 5: Connecting the Serial Ethernet Board to EasyPIC7 V7 development board

Relay 1 and Relay 2 are connected to the microcontroller RD0 and RD1 output pins. A control signal to energize or de-energize  these relays, will
also control the devices connected to them like a light bulb, a fan or a gate motor.

To learn more on how to interface a relay with a PIC Microcontroller read:

Interfacing a Relay with PIC-Microcontroller 

If the PC and the Ethernet controller are on the same network and close to each other, then the two can be connected together using a crossover
Ethernet cable, otherwise a hub or a switch may be required. In this case a straight cable can be used to connect the PC to the hub/switch and
another straight cable to connect the Microcontroller to the hub/switch. If the PC and the microcontroller are located on different networks and
are not close to each other, then routers may be required to establish connectivity between them.

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 8/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

Figure 6: Project Circuit diagram

You can easily create a PCB for this project as we have learned in our PCB start to finish tutorials, all you need is to get a good PCB prototyping
company that will offer your good quality PCBs at a good price. We recommend PCBWay.com, a China Shenzhen-based manufacturer specializing ZA R

in PCB prototyping, small-volume production and PCB Assembly service all under one.
EU R

They are now running a PCB contest until 12 December to provide a platform for hardware hackers, makers, Electronic Engineers, Hobbyists and
artists to compete to build a better future with open hardware. You could also win cash prize money of $1000. So hurry-up now, post your project US D
or vote for your favorite project before the deadline.

GBP
To learn more, please read this article:

BWP

Join PCB Design Contest and Stand a Chance to Win $1000 in Cash

or click on the image below to visit the PCB Design Contest Page to get all the information.

To learn how to simulate the ENC28J60 wit Proteus, please watch the video below for all the steps:

mikroC Pro for PIC Tutorial -80- Project 15 Web-Based Control and Monitoring, part 2
Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 9/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

This project is fairly easy to understand, these are basically the few steps to control a device from a remote PC:

Step 1:
Set the MAC Address and IP Address. To access your PIC outside your loacal network or from internet, the DNS, Gateway address and Subnet may
also be defined here. Our local network parameters are as follows:

1 // Define ENC28J60 MAC Address, and IP address to be used for communication


2 // ZA R
3 unsigned char MACAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ;
4 unsigned char IPAddr[4] = {192,168,8,5};
5 unsigned char DestIpAddr[4]  = {192, 168, 8,103 };  // remote IP address EU R

Step 2:
US D

In the main program, set PORTD pins as Digital input/output pins and pin RA0 as analog input pin for the LM35 temperature sensor.
Initialize Timer0 to generate a timer interrupt every 2 second. GBP

Initialize the SPI module of the microcontroller and Initialize the Serial Ethernet module chip ENC28J60
BWP
Step 3:
Write the code within the Spi_Ethernet_userUDP function that will interpret the commands from the UDP client then energize/de-energize the
relays on PORTD by checking any data recieved on port 10001

Step 4:
Read received data in an endless loop using the function “SPI_Ethernet_doPacket()”. When a timer interrupt occurs every 2 seconds, read the
temperature value and send it to remote PC using the function “SPI_Ethernet_sendUDP()”.

To learn more how to use the ENC28J60 Ethernet Controller library read:

Interfacing ENC28J60 Ethernet Controller with PIC MicroController

Step 5:
Generate 2 Second timer interrupt using the Timer Calculator.

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 10/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

Figure 7: Timer Calculator

Full Project Source Code


1 /*********************************************************************
2 Project Name: UDP-Based Ethernet Control and Monitoring
3 Author: Bitahwa Bindu
4 (c) www.studentcompanion.co.za , November 2018
5 Test configuration:
6      MCU: PIC18F45K22
7      Oscillator: 8MHz
8      Compiler: mikroC Pro for PIC v7.1.0
9 **********************************************************************/ ZA R
10  
11 //ENC28J60 Ethernet Controller Connection
12 //
EU R
13 sfr sbit SPI_Ethernet_Rst at RC0_bit;
14 sfr sbit SPI_Ethernet_CS  at RC1_bit;
15 sfr sbit SPI_Ethernet_Rst_Direction at TRISC0_bit;
16 sfr sbit SPI_Ethernet_CS_Direction  at TRISC1_bit; US D
17 //
18 // Define ENC28J60 MAC Address, and IP address to be used for communication
19 // GBP
20 unsigned char MACAddr[6] = {0x00, 0x14, 0xA5, 0x76, 0x19, 0x3f} ;
21 unsigned char IPAddr[4] = {192,168,8,5};
22 unsigned char DestIpAddr[4]  = {192, 168, 8,103 };  // remote IP address
BWP
23 unsigned char getRequest[10];
24  
25 typedef struct
26 {
27   unsigned canCloseTCP:1;
28   unsigned isBroadcast:1;
29 }TethPktFlags;
30  
31 //
32 // SPI routine. Must be declared even though it is not used
33 //
34 unsigned int SPI_Ethernet_UserTCP(unsigned char *remoteHost,
35                                   unsigned int remotePort, unsigned int localPort,
36                                   unsigned int reqLength, TEthPktFlags *flags)
37 {
38    return(0);
39 }
40  
41 //
42 // UDP routine. This is where the user requests are processed
43 //
44 unsigned int SPI_Ethernet_UserUDP(unsigned char *remoteHost,
45                                   unsigned int remotePort, unsigned int destPort,
46                                   unsigned int reqLength, TEthPktFlags *flags)
47 {
48    char Txt[10];
49    char len=0;
50   
51    if (destport != 10001) return(0);  //Check that correct port is used
52    while(reqLength--)
53      {
54       Txt[len++]=SPI_Ethernet_getByte();  //Extract the received bytes
55      }
56      PORTD = Txt[0];                  //Switch ON required Relay
57      return;
58 }
59  
60 bit flag;   //Declare local Flag variable
61 //Timer0
62 //Prescaler 1:64; TMR0 Preload = 3036; Actual Interrupt Time : 2 s
63  
64 //Place/Copy this part in declaration section
65 void InitTimer0(){ Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 11/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

66   T0CON         = 0x85;
67   TMR0H         = 0x0B;
68   TMR0L         = 0xDC;
69   GIE_bit         = 1;
70   TMR0IE_bit         = 1;
71 }
72  
73 void Interrupt(){
74   if (TMR0IF_bit){
75     TMR0IF_bit = 0;
76     TMR0H         = 0x0B;
77     TMR0L         = 0xDC;
78     flag = 1;
79   }
80 }
81  
82  
83 //
84 // Start of MAIN program
85 //
86 void main()
 87 {
88 unsigned int temperature;
89 float mV;
90 unsigned char txt[15];
91 flag = 0;
92 InitTimer0();               //// Initialize Timer0
93  
94      ANSELA = 1;            // Configure PORTA as Analog
95      ANSELC = 0;            // Configure PORTC as Digital I/O
96      ANSELD = 0;            // Configure PORTD as Digital I/O
97      TRISD = 0;             // Configure PORTD as output
98      PORTD = 0;             // Clear PORTD to start with
99      TRISA.RA0 = 1;         //Configure RA0 as input
100     
101      SPI1_Init();           // Initialize SPI module
102      SPI_Ethernet_Init(MACAddr, IPAddr, 0x01); // Initialize Ethernet module
103  
104      ADC_Init();            // Initialize ADC
105      while(1)                // Loop forever
106      {
107         SPI_Ethernet_doPacket(); // Process next received packet
108  
109         //Get temperature value and send it to remote PC every 2 seconds ZA R
110         if (flag) //Check if there is an Interrupt call
111         {
112          // LATD.F1 =   ~LATD.F1 ;
EU R
113         temperature = ADC_Read(0);  //Get 10-bit results of AD Conversion
114         mV= temperature * 5000.0/1023.0; // Convert to mV
115         mV = mV/10.0;         //Convert mV to temperature in Celcius
116         FloatToStr( mV,txt);  //Convert Temperature to string US D
117         txt[4]=0;
118         // send Temperature to remote PC, from UDP port 10001 to UDP port 10001
119         SPI_Ethernet_sendUDP(DestIpAddr, 10001, 10001, txt, 4); GBP
120         flag=0;
121  
122         }
BWP
123      }
124 }

You can download the full project files below. All the files are zipped, you will need to unzip them (Download a free version of the Winzip utility to
unzip files).

Proteus Schematic Project: UDP_Ethernet_Proteus_Project

MikroC Source Code: UDP_Ethernet-MikroC-Project

PC GUI Software Project: UDP_Control_Monitoring_PC_GUI_Software_Project

 Share this post

     

 Author

Bitahwa Bindu

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 12/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

What do you think?


2 Responses

Upvote Funny Love Surprised Angry Sad

0 Comments Student Companion 


1 Login

 Recommend t Tweet f Share Sort by Newest

Start the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Be the first to comment.

ALSO ON STUDENT COMPANION

10 Golden Rules for a Job Interview Digital Clock using PIC Microcontroller and the DS1307 Real
2 comments • 4 years ago Time Clock – XC8 Compiler
keshena — Great article indeed. Very useful. Thanks 15 comments • 4 years ago
Student Companion — In your error message you posted, it shows
PIC16F877a

Interfacing DC Motor with PIC Microcontroller – MikroC Interfacing The PCF8583 Real Time Clock With PIC
ZA R
10 comments • 3 years ago Microcontroller – MikroC
Student Companion — Yes you can use that code with PIC16F877A 7 comments • 4 years ago
but you'll have to do some minor changes. To find out what to change, Student Companion — Be specific about your question, and write it inEU R
please ask your question in … the forum, not in comments: https://www.studentcompanio...

US D
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy

GBP

BWP

RELATED POSTS

Digital Frequency Share Serial Port


06 Counter with an LCD 08 Devices Over Ethernet
Automatic Temperature Mar Display using PIC Feb with Eltima Serial to
10 Control System using Microcontroller – Ethernet Connector
Apr PIC Microcontroller – mikroC Serial to Ethernet Connector
Flowcode In these series of allows sharing of numerous
An automatic temperature measurement projects with RS232/RS422/RS485 serial
control system has the ability PIC microcontroller, we're interface devices over
to monitor and control the gonna discuss several projects network, be it Ethernet LAN
temperature of a specified like how to measure DC... or...
space without... read more  read more 
read more 

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 13/14
5/19/2019 UDP Control and Monitoring with PIC Microcontroller | StudentCompanion

LEGAL & ACCOUNT COMPANY


Privacy Policy My Account About us
Tems & Conditions Order history Contact us
Sales & Returns Policy Login Help center

Mon - Sat / 9:00AM - 17:00PM

© StudentCompanion. 2019. All Rights Reserved

ZA R

EU R

US D

GBP

BWP

Privacy - Terms

https://www.studentcompanion.co.za/ethernet-udp-based-control-and-monitoring-with-pic-microcontroller-mikroc/ 14/14

You might also like