Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Adafruit_Sensor.h>
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include <Arduino.h>
- #include <U8g2lib.h>
- #include <RH_ASK.h>
- RH_ASK driver(2000, 2,5, 0);
- #ifdef U8X8_HAVE_HW_SPI
- #include <SPI.h>
- #endif
- #ifdef U8X8_HAVE_HW_I2C
- #include <Wire.h>
- #endif
- U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
- uint8_t buf[32];
- uint8_t buflen = 32;
- const char* ssid = "Nackademin-IOT";
- const char* password = "Nack@!pr";
- const char* mqtt_server = "172.20.216.18"; //Raspberry mac: dc:a6:32:0a:e9:10
- const char* subscribeTopic = "iot/publish";
- const char* publishTopic = "iot/publish";
- WiFiClient espClient;
- PubSubClient client(espClient);
- long lastMsg = 0;
- char msg[50];
- void setup_wifi() {
- 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(".");
- }
- randomSeed(micros()); //Viktigt för att alla inte ska kopplas upp samtidigt.
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- //Serial.print("Message arrived [");
- //Serial.print(topic);
- //Serial.print("] ");
- char annanCharArray[50];
- for (int i = 0; i < length; i++) {
- //Serial.print((char)payload[i]);
- annanCharArray[i] = payload[i];
- }
- //Serial.println(annanCharArray);
- // Här kan man skriva ut på displayen. Spara payload i en annan chararray.
- u8g2.clearBuffer(); // clear the internal memory
- u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
- u8g2.drawStr(0,10, (char*) annanCharArray); // write something to the internal memory
- u8g2.sendBuffer(); // transfer internal memory to the display
- //}
- //Serial.println();
- }
- void reconnect() {
- while (!client.connected()) {
- String clientId = "ESP8266Client-";
- clientId += String(random(0xffff), HEX);
- if (client.connect(clientId.c_str())) {
- client.subscribe(subscribeTopic);
- } else {
- delay(5000);
- }
- }
- }
- void setup() {
- driver.init();
- u8g2.begin();
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- /*if(driver.recv(buf, &buflen)) {
- Serial.println((char*)buf);
- }*/
- client.loop();
- long now = millis();
- if(driver.recv(buf, &buflen)) {
- if(now - lastMsg > 2000) {
- lastMsg = now;
- snprintf (msg, 50, "Temp: ");
- uint8 *uint8_pointer = buf;
- const char *char_pointer = (char*)uint8_pointer;
- strcat(msg, char_pointer);
- client.publish(publishTopic, msg);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement