![](/media/cache/profiles/20200518_163046.jpg.50x50_q85.jpg)
CITY3032-wifi-mqtt
main.cpp
- Committer:
- reedas
- Date:
- 2021-11-13
- Revision:
- 3:62825c5f3cd7
- Parent:
- 2:3dabedbecf5e
File content as of revision 3:62825c5f3cd7:
/* mbed Microcontroller Library * Copyright (c) 2019 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * I2C Master code for Cypress PSoC 6 communicating with Arduino * ============================================================= * * This module sets the PSoC 6 up as the master on the I2C bus * and periodically collects a set of environment data from an arduino * running the code below: */ // // //I2C SLAVE CODE // //I2C Communication between Two Arduino // //CircuitDigest // //Pramoth.T // // #include<Wire.h> //Library for I2C Communication // // functions // #include <Adafruit_Sensor.h> // #include <DHT.h> // #include <DHT_U.h> // // #define DHTPIN 4 // Digital pin connected to the DHT sensor // // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 -- // // Pin 15 can work but DHT must be disconnected during program upload. // // // Uncomment the type of sensor in use: // #define DHTTYPE DHT11 // DHT 11 // //#define DHTTYPE DHT22 // DHT 22 (AM2302) // //#define DHTTYPE DHT21 // DHT 21 (AM2301) // // // See guide for details on sensor wiring and usage: // // https://learn.adafruit.com/dht/overview // // DHT_Unified dht(DHTPIN, DHTTYPE); // // uint32_t delayMS; // #include <PreciseLM35.h> // #define TESTING false // // const int pinLM35 = A2; // PreciseLM35 lm35(pinLM35, DEFAULT); // // // unsigned char txDataPacket[10]; // unsigned char rxCommandPacket[8]; // unsigned char rxCommandNum; // unsigned char rxCommand = 0; // bool SW1Pressed = 0; // bool SW2Pressed = 0; // // int blueLed = 13; // int SW1Pin = 2; // int SW2Pin = 3; // // void setup() // // { // pinMode(SW1Pin, INPUT); // pinMode(SW2Pin, INPUT); // pinMode(blueLed, OUTPUT); // dht.begin(); // sensor_t sensor; // dht.temperature().getSensor(&sensor); // dht.humidity().getSensor(&sensor); // delayMS = sensor.min_delay / 1000; // Serial.begin(115200); //Begins Serial Communication at // 9600 baud rate // Wire.begin(8); //Begins I2C communication with // // Slave Address as 8 at pin (A4,A5) // Wire.onReceive(receiveEvent); //Function call when Slave receives // value from master // Wire.onRequest(requestEvent); //Function call when Master request // value from Slave // } // // void loop(void) // { // unsigned char SW1Debounced; // unsigned char SW2Debounced; // int temperature = 20; // while (1) { // if (rxCommandNum || TESTING) { // // // Serial.println("Slave Received Command From Master:"); //Prints in // // Serial Monitor // Serial.print(rxCommand); // Serial.print(" - "); // Serial.println(rxCommandNum); // for (int i = 0; i < 8; i++) { // Serial.print( rxCommandPacket[i] ); // Serial.print( " - " ); // } // Serial.println(" "); // for (int i = 0; i < 10; i++) { // Serial.print( txDataPacket[i] ); // Serial.print( " - " ); // } // Serial.println(" "); // rxCommandNum = 0; // } // sensors_event_t event; // int potvalue = map( analogRead(A0), 0, 1023, 0, 100); // // Reads analog value from POT (0-5V) // int lightlevel = map(analogRead(A1), 0, 1023, 0, 100); // // Ambient light level // int humidityInt = 101; // temperature = ((int)((lm35.readCelsius()) * 10)); // // // Ambient Temperature // dht.humidity().getEvent(&event); // if (isnan(event.relative_humidity)) { // Serial.println(F("Error reading humidity!")); // } // else { // humidityInt = (int)event.relative_humidity; // Serial.print(F("Humidity: ")); // Serial.print(humidityInt); // Serial.println(F("%")); // } // txDataPacket[0] = potvalue; // txDataPacket[1] = 0; // or potvalue >> 8; // txDataPacket[2] = lightlevel; // txDataPacket[3] = 0; // or lightlevel >> 8; // txDataPacket[4] = temperature; // txDataPacket[5] = temperature >> 8; // SW1Debounced = (SW1Debounced << 1) | digitalRead(SW1Pin); // if (SW1Debounced == 0) SW1Pressed = 1; // SW2Debounced = (SW2Debounced << 1) | digitalRead(SW2Pin); // if (SW2Debounced == 0) SW2Pressed = 1; // txDataPacket[6] = SW1Pressed; // txDataPacket[7] = SW2Pressed; // txDataPacket[8] = humidityInt; // txDataPacket[9] = 0; // digitalWrite(blueLed, rxCommandPacket[1] & 1); // delay(delayMS); // if (TESTING) delay(2000); // } // } // // void receiveEvent (int howMany) //This Function is called // when Slave receives value from master // { for (int i = 0; i < howMany; i++) { // rxCommandPacket[i] = Wire.read(); //Used to read value // received from master and store in variable SlaveReceived // } // rxCommandNum = howMany; // rxCommand = rxCommandPacket[0]; // } // void requestEvent() //This Function is called when Master wants data from slave // { // Wire.write(txDataPacket, 10); // sends eight bytes of data to master // SW1Pressed = 0; // Clear key presses on send to master // SW2Pressed = 0; // } #include "mbed.h" #include "platform/mbed_thread.h" #include "GUI.h" #include "cy8ckit_028_tft.h" #define UNO_CMD (0x10) // Command byte to Uno #define UNO_CMD_CONF (0x01) // Configuration data #define UNO_ADDR (0x10) // LM75 address //I2C i2c(P8_1, P8_0); I2C i2c(I2C_SDA, I2C_SCL); DigitalOut myled(LED1); #include <MQTTClientMbedOs.h> //NetworkInterface* network; //Serial pc(SERIAL_TX, SERIAL_RX); Serial pc(USBTX, USBRX); #define APP_INFO( x ) pc.printf x volatile char TempCelsiusDisplay[] = "+abc.d C"; int lastLightDisplay = 101; int lthresh = 50; int arrivedcount = 0; void messageArrived(MQTT::MessageData& md) { // char buf[80]; MQTT::Message &message = md.message; APP_INFO(("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id)); APP_INFO(("Payload %.*s\r\n", message.payloadlen, (char*)message.payload)); // lthresh = stoi((string)message.payload); // } arrivedcount++; APP_INFO(("Arrived = %d\r\n",arrivedcount)); } int main() { char data_write[8]; char data_read[10]; char buffer[120]; int rc; /* Initialise display */ GUI_Init(); GUI_Clear(); APP_INFO(("Connecting to the network using Wifi...\r\n")); // network = NetworkInterface::get_default_instance(); NetworkInterface *network = NetworkInterface::get_default_instance(); nsapi_error_t net_status = -1; for (int tries = 0; tries < 10; tries++) { net_status = network->connect(); if (net_status == NSAPI_ERROR_OK) { break; } else { APP_INFO(("Unable to connect to network. Retrying...\r\n")); } } if (net_status != NSAPI_ERROR_OK) { APP_INFO(("ERROR: Connecting to the network failed (%d)!\r\n", net_status)); // return -1; } APP_INFO(("Connected to the network successfully. IP address: %s\n", network->get_ip_address())); MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.clientID.cstring = (char *)"my_thing"; data.keepAliveInterval = 20; data.cleansession = 1; data.username.cstring = (char *)""; data.password.cstring = (char *)""; // char *host = "10.0.0.2"; char *host = (char *)"192.168.1.174"; int port = 1883; TCPSocket socket; MQTTClient client(&socket); socket.open(network); socket.connect(host, port); client.connect(data); MQTT::Message message; sprintf(buffer, "Hello World! from My Thang\r\n"); message.qos = MQTT::QOS0; message.retained = false; message.dup = false; message.payload = (void*)buffer; message.payloadlen = strlen(buffer)+1; client.publish( "mytopic/announce", message); rc = client.subscribe("mytopic/lthresh", MQTT::QOS0, messageArrived); if (rc) APP_INFO(("Subscription Error %d", rc)); else APP_INFO(("Subscribed to mytopic/lthresh")); sprintf(buffer, "%d",lthresh); message.payload = (void*)buffer; message.payloadlen = strlen(buffer)+1; client.publish("mytopic/lthresh", message); data_write[0] = UNO_CMD; data_write[1] = 0x08; GUI_SetFont(GUI_FONT_10_1); GUI_SetTextAlign(GUI_TA_LEFT); int status = i2c.write(UNO_ADDR, data_write, 2, 0); // if (status != 0) { // Error // GUI_DispStringAt("I2C Error", 0, 220); // pc.printf("I2C connect error\n"); // while (1) { // myled = !myled; // ThisThread::sleep_for(200); // } // } pc.printf("I2C connected"); GUI_SetFont(GUI_FONT_20B_1); GUI_DispStringAt("Data from Arduino", 0, 0); int lightDisplay; int potValue; int humidity; while (1) { // Read Arduino data data_write[0] = UNO_CMD; i2c.write(UNO_ADDR, data_write, 2, 1); // no stop // if (i2c.read(UNO_ADDR, data_read, 10, 0)) { // GUI_SetFont(GUI_FONT_10_1); // GUI_DispStringAt("I2C receive error ", 0, 220); // pc.printf("I2C Rx Error\n"); // } else { i2c.read(UNO_ADDR, data_read, 10, 0); for (int i; i < 10; i++) pc.printf("%2x - ", data_read[i]); pc.printf("\n"); GUI_SetFont(GUI_FONT_10_1); sprintf(buffer, "I2c Data Received, IP address is: %s arrived %d", network->get_ip_address(), arrivedcount); GUI_DispStringAt(buffer, 0, 220); pc.printf("I2C Rx data recevied\n"); // read eight bytes // pot value - msb-0, lsb-1 // light level - msb-2, lsb-3 // temperature - msb-4, lsb-5 // sw1 state - 6 - 0-255 based on how long pressed // sw2 state - 7 - 0-255 based on how long pressed // Humidity - msb-9, lsb-8 // Calculate temperature value in Celcius int tempval = (int)((int)data_read[5] << 8) | data_read[4]; if (tempval < 0) { TempCelsiusDisplay[0] = '-'; } else { TempCelsiusDisplay[0] = '+'; } // Integer part TempCelsiusDisplay[1] = (tempval / 1000) + 0x30; TempCelsiusDisplay[2] = ((tempval % 1000) / 100) + 0x30; TempCelsiusDisplay[3] = ((tempval % 1000) % 100 / 10) + 0x30; TempCelsiusDisplay[5] = ((tempval % 1000) % 100 % 10) + 0x30; //Switches unsigned char SW1State = data_read[6]; unsigned char SW2State = data_read[7]; //light level lightDisplay = (int)((int)data_read[3] << 8) | data_read[2]; //potentiometer value potValue = (int)((int)data_read[1] << 8) | data_read[0]; // humidity value humidity = (int)((int)data_read[9] << 8) | data_read[8]; // Display result pc.printf("temp = %s, Light is %3d%%, Hum is %3d%%%s%s\n", TempCelsiusDisplay, lightDisplay, humidity, SW1State?", SW1 pressed":"", SW2State?", SW2 pressed":""); sprintf(buffer,"Temp is %2dC \nLight Level is %2d%c \nPot Value is %2d%c \nHumidity is %2d%c \n%s \n%s ", tempval/10, lightDisplay, 0x25, potValue, 0x25, humidity, 0x25, SW1State?"SW1 Pressed ":"SW1 Released", SW2State?"SW2 Pressed ":"SW2 Released"); GUI_SetFont(GUI_FONT_20_1); GUI_DispStringAt(buffer, 0, 40); } sprintf(buffer, "Light Level is %d\r\n", lightDisplay); message.payload = (void*)buffer; message.payloadlen = strlen(buffer)+1; // if (lightDisplay != lastLightDisplay) { client.publish( "mytopic/light", message); lastLightDisplay = lightDisplay; // } myled = !myled; data_write[1] = data_write[1] ^ 0x01; thread_sleep_for(1000); } }