ClearCore Library
Loading...
Searching...
No Matches
EthernetTcpClientHelloWorld.cpp

Return to SDK Examples for Microchip Studio

1/*
2 * Title: EthernetTcpClient
3 *
4 * Objective:
5 * This example demonstrates how to configure a ClearCore as a TCP client to
6 * send and receive TCP datagrams (packets).
7 *
8 * Description:
9 * This example configures a ClearCore device to act as a TCP client. This client
10 * connects to another device acting as a TCP server to exchange data over
11 * ethernet TCP. This simple example connects to a server, sends a simple "Hello server"
12 * message, and receives and prints incoming data from the server.
13 *
14 * Partner projects, EthernetTcpServer_autoClientManagement and EthernetTcpServer_manualClientManagement
15 * are available to configure another ClearCore to act as a server.
16 *
17 * Setup:
18 * 1. Identify the IP address of the server and specify it (as serverIp) below. When
19 * using either of the EthernetTcpServer examples, the server's IP address will print to a
20 * connected serial terminal upon startup.
21 * 2. Set the usingDhcp boolean as appropriate. If not using DHCP, specify static
22 * IP address and network information.
23 * 3. The server and client must be connected to the same network.
24 * If server and client devices are connected to each other directly (as opposed to connection through a switch)
25 * an ethernet crossover cable may be required.
26 * 4. It may be helpful to use a terminal application such as PuTTY to view serial output from each device. https://www.putty.org/
27 *
28 * Links:
29 * ** ClearCore Documentation: https://teknic-inc.github.io/ClearCore-library/
30 * ** ClearCore Manual: https://www.teknic.com/files/downloads/clearcore_user_manual.pdf
31 *
32 * Copyright (c) 2022 Teknic Inc. This work is free to use, copy and distribute under the terms of
33 * the standard MIT permissive software license which can be found at https://opensource.org/licenses/MIT
34 */
35
36
37#include "ClearCore.h"
38#include "EthernetTcpClient.h"
39#include "SysTiming.h"
40
41// The IP address of the server you want to connect to
42IpAddress serverIp = IpAddress(192, 168, 0, 123);
43
44// The port number over which packets will be sent/received
45#define PORT_NUM 8888
46
47// The maximum number of characters allowed per incoming packet
48#define MAX_PACKET_LENGTH 100
49// Buffer for holding received packets.
50unsigned char packetReceived[MAX_PACKET_LENGTH];
51
52// Set usingDhcp to false to use user defined network settings
53bool usingDhcp = true;
54
55
56int main(void) {
57 // Set up serial communication between ClearCore and PC serial terminal
58 ConnectorUsb.Mode(Connector::USB_CDC);
59 ConnectorUsb.Speed(9600);
60 ConnectorUsb.PortOpen();
61 uint32_t timeout = 5000;
62 uint32_t startTime = Milliseconds();
63 while (!ConnectorUsb && Milliseconds() - startTime < timeout) {
64 continue;
65 }
66
67 // Set connector IO0 as a digital output
68 // When IO0 state is true, its associated LED will turn on
69 // indicating a successful connection to a server
70 ConnectorIO0.Mode(Connector::OUTPUT_DIGITAL);
71
72 // Make sure the physical link is active before continuing
73 while (!EthernetMgr.PhyLinkActive()) {
74 ConnectorUsb.SendLine("The Ethernet cable is unplugged...");
75 Delay_ms(1000);
76 }
77
78 // Configure with an IP address assigned via DHCP
80 if (usingDhcp) {
81 // Use DHCP to configure the local IP address
82 bool dhcpSuccess = EthernetMgr.DhcpBegin();
83 if (dhcpSuccess) {
84 ConnectorUsb.Send("DHCP successfully assigned an IP address: ");
86 } else {
87 ConnectorUsb.SendLine("DHCP configuration was unsuccessful!");
88 while (true) {
89 // TCP will not work without a configured IP address
90 continue;
91 }
92 }
93 } else {
94 // Configure with a manually assigned IP address
95
96 // Set ClearCore IP address
97 IpAddress ip = IpAddress(192, 168, 0, 103);
99 ConnectorUsb.Send("Assigned manual IP address: ");
101
102 // Optional: set additional network addresses if needed
103
104 //IpAddress gateway = IpAddress(192, 168, 1, 1);
105 //IpAddress netmask = IpAddress(255, 255, 255, 0);
106 //EthernetMgr.GatewayIp(gateway);
107 //EthernetMgr.NetmaskIp(netmask);
108 }
109
110 // Initialize a client object
111 // The ClearCore will operate as a TCP client using this object
112 EthernetTcpClient client;
113
114 // Attempt to connect to a server
115 if (!client.Connect(serverIp, PORT_NUM)) {
116 ConnectorUsb.SendLine("Failed to connect to server. Retrying...");
117 }
118
119 // Connect to server, and send/receive packets
120 while(true){
121
122 // Make sure the physical link is active before continuing
123 while (!EthernetMgr.PhyLinkActive()) {
124 ConnectorUsb.SendLine("The Ethernet cable is unplugged...");
125 Delay_ms(1000);
126 }
127
128 // Attempt to connect to server
129 if(!client.Connected()){
130 // Turn off LED if the client is not connected
131 ConnectorIO0.State(false);
132
133 uint32_t delay = 1000;
134 if (!client.Connect(serverIp, PORT_NUM)) {
135 if(Milliseconds() - startTime > delay){
136 ConnectorUsb.SendLine("Failed to connect to server. Retrying...");
137 startTime = Milliseconds();
138 }
139 }
140 } else {
141 // Turn on LED if client is connected
142 ConnectorIO0.State(true);
143
144 // If connection was successful, send and receive packets
145 if( client.Send("Hello server") >0)
146 {
147 ConnectorUsb.Send("Sent 'Hello server'. Response from server: ");
148 bool receivedMessage = false;
149
150 // Read any incoming packets from the server over the next second
151 uint32_t delay = 1000;
152 startTime = Milliseconds();
153 while((Milliseconds() - startTime) < delay){
154 if (client.Read(packetReceived, MAX_PACKET_LENGTH) > 0)
155 {
156 receivedMessage = true;
157 ConnectorUsb.Send((char *)packetReceived);
158
159 // Clear the message buffer for the next iteration of the loop
160 for(int i=0; i<MAX_PACKET_LENGTH; i++){
161 packetReceived[i]=NULL;
162 }
163 }
165 }
166 // If no packets were received, inform the user via serial message
167 if (!receivedMessage){
168 ConnectorUsb.SendLine("Didn't receive message.");
169 }else{
171 }
172 }
173 else
174 {
175 client.Close();
176 }
177 }
178 // Perform any necessary periodic ethernet updates
179 // Must be called regularly when actively using ethernet
181 }
182
183}
ClearCore timing profiling utility functions.
void Delay_ms(uint32_t ms)
Blocks operations for ms milliseconds.
Definition SysTiming.h:287
uint32_t Milliseconds(void)
Number of milliseconds since the ClearCore was initialized.
int16_t State() override
Get connector's last sampled digital value.
virtual ConnectorModes Mode() override
Get the connector's operational mode.
Definition DigitalInOutAnalogOut.h:70
volatile const bool & PhyLinkActive()
Check the link status from the PHY.
Definition EthernetManager.h:136
IpAddress LocalIp()
Get the local IP address.
void Refresh()
Perform any necessary periodic Ethernet and LwIP updates.
bool DhcpBegin()
Set up DHCP connection to retrieve local IP.
void Setup()
Setup LwIP with the local network interface.
bool SendLine()
Send carriage return and newline characters.
Definition ISerial.h:162
virtual bool Speed(uint32_t bitsPerSecond)=0
Change the baud rate for the port.
bool Send(const char *buffer, size_t bufferSize)
Send the array of characters out the port.
Definition ISerial.h:173
char * StringValue()
Returns a string representation of the IP Address.
Definition IpAddress.h:96
void PortOpen() override
virtual ConnectorModes Mode() override
Get the connector's operational mode.
Definition SerialUsb.h:210
DigitalInOutAnalogOut ConnectorIO0
IO-0 connector instance.
SerialUsb ConnectorUsb
USB connector instance.
EthernetManager & EthernetMgr
Ethernet manager.