Institute of Computer Science
  1. Courses
  2. 2019/20 fall
  3. Mobile Computing and Internet of Things (LTAT.06.009)
ET
Log in

Mobile Computing and Internet of Things 2019/20 fall

  • Main
  • Lectures
  • Labs
  • Homeworks & Home Assignments
  • Projects
    • Teams & Topics
    • Presentations & Report
    • Grading & Submission
  • Google Group
  • Task submission
  • Results
  • Other
/*
* Connects to a WiFi network and MQTT broker, then publishes analog sensor readings
*
*/

#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid     = "your-ssid";
const char* password = "your-password";
const char* mqtt_server = "your_broker_ip";


WiFiClient wifiClient;
PubSubClient client(wifiClient);


long lastMsg = 0;


void setup() {
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    // Set up MQTT
    client.setServer(mqtt_server, 1883);

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected");
      // Connected - do something useful - subscribe to topics, publish messages, etc.
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

int val = 0;
void loop() {
  if (!client.connected()) {
    reconnect();
  }

  client.loop();

  // Read a value
  long now = millis();
  if (now - lastMsg > 100) {
    lastMsg = now;

    val = analogRead(32);
    client.publish("foo",  String(val).c_str());
    Serial.println(val);

  }
}
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment