Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: C12832 MQTT_MbedOS
main.cpp
00001 #include "mbed.h" 00002 #include "C12832.h" 00003 #include "MQTTEthernet.h" 00004 #include "MQTTClient.h" 00005 00006 // LCD Pinout 00007 C12832 lcd(D11, D13, D12, D7, D10); 00008 00009 // MQTT Variables 00010 char* MqttHostname = "broker.hivemq.com"; 00011 int MqttPort = 1883; 00012 char* MqttTopic = "mbed-sample"; 00013 char* MqttClientId = "changeme"; 00014 00015 int main() 00016 { 00017 // Clear LCD and print a welcome message from row 0, col 0. 00018 lcd.cls(); 00019 lcd.locate(0,0); 00020 lcd.printf("Example MQTT client\n"); 00021 00022 // Brings up the network interface 00023 MQTTEthernet eth = MQTTEthernet(); 00024 const char *ip = eth.get_ip_address(); 00025 00026 lcd.cls(); 00027 lcd.locate(0,0); 00028 lcd.printf("IP address is: %s\n", ip ? ip : "No IP"); 00029 00030 // Create Mbed Client Interface 00031 MQTT::Client<MQTTEthernet, Countdown> client = MQTT::Client<MQTTEthernet, Countdown>(eth); 00032 00033 // Create TCP connection 00034 eth.open(eth.getEth()); 00035 int rc = eth.connect(MqttHostname, MqttPort); 00036 lcd.printf("TCP Status: %s\n", (rc == 0) ? "Success" : "Failure"); 00037 00038 // Wait for a short length of time to allow user to see output messages. 00039 Thread::wait(2000); 00040 00041 if(rc == 0){ 00042 00043 lcd.cls(); 00044 lcd.locate(0,0); 00045 lcd.printf("Starting MQTT Client"); 00046 00047 MQTTPacket_connectData data = MQTTPacket_connectData_initializer; 00048 data.MQTTVersion = 3; 00049 data.clientID.cstring = MqttClientId; 00050 rc = client.connect(data); 00051 00052 lcd.cls(); 00053 lcd.locate(0,0); 00054 lcd.printf("MQTT Client: %s\n", (rc == 0) ? "Connected" : "Failed"); 00055 00056 while(rc == 0){ 00057 MQTT::Message message; 00058 00059 // QoS 0 00060 char buf[100]; 00061 sprintf(buf, "Hello World!"); 00062 message.qos = MQTT::QOS0; 00063 message.retained = false; 00064 message.dup = false; 00065 message.payload = (void*)buf; 00066 message.payloadlen = strlen(buf)+1; 00067 rc = client.publish(MqttTopic, message); 00068 00069 Thread::wait(5000); 00070 00071 } 00072 } 00073 00074 // It is good practice to close the socket 00075 eth.disconnect(); 00076 } 00077
Generated on Mon Jul 18 2022 12:28:23 by
1.7.2