Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: "Microcontroller Control"
- - Source Code NOT compiled for: ESP32 DevKit V1
- - Source Code created on: 2024-09-26 22:59:06
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Enhance the code functionality by integrating */
- /* specific libraries for sensor data processing and */
- /* communication protocols to ensure seamless */
- /* interaction with connected components. */
- /****** END SYSTEM REQUIREMENTS *****/
- /****** DEFINITION OF LIBRARIES *****/
- #include <SoftwareSerial.h>
- #include <Adafruit_GFX.h> // Core graphics library
- #include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
- #include <EEPROM.h>
- #include <WiFi.h> // Include WiFi library for communication
- #include <DHT.h> // Include DHT sensor library for temperature and humidity
- #include <AllThingsTalk_WiFi.h> // Include AllThingsTalk library for enhanced communication
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- // HC12 connections
- #define HC12_TX 16 // --> HC-12 TX Pin (GPIO16)
- #define HC12_RX 17 // --> HC-12 RX Pin (GPIO17)
- EspSoftwareSerial::UART HC12(HC12_TX, HC12_RX);
- // ST7789 TFT module connections
- #define TFT_DC 21 // TFT DC pin is connected to GPIO21
- #define TFT_RST 22 // TFT RST pin is connected to GPIO22
- #define TFT_CS -1 // TFT CS pin is not used
- // initialize ST7789 TFT library with hardware SPI module
- Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
- // DHT Sensor setup
- #define DHTPIN 4 // Pin where the DHT sensor is connected
- #define DHTTYPE DHT11 // DHT 11 (change to DHT22 if using that sensor)
- DHT dht(DHTPIN, DHTTYPE); // Create an instance of the DHT sensor
- // AllThingsTalk WiFi credentials
- auto wifiCreds = WifiCredentials("Your-WiFi-SSID", "Your-WiFi-Password"); // Replace with your WiFi credentials
- auto deviceCreds = DeviceConfig("Your-Device-ID", "Your-Device-Token"); // Replace with your Device ID and Token
- auto device = Device(wifiCreds, deviceCreds); // Create "device" object
- // KY040 - Set encoder pins as inputs
- #define CLK 10 // GPIO10 --> D10
- #define DT 34 // GPIO34 (input only)
- #define SW 35 // GPIO35 (input only)
- #define SHORT_PRESS_TIME 50
- #define ROTARY_FAST 10 // [ms] rotary speed fast
- #define ROTARY_SLOW 200 // [ms] rotary speed slow
- #define INCREMENT_SLOW 1
- #define INCREMENT_FAST 10
- int counter = 0;
- int currentStateCLK;
- int lastStateCLK;
- unsigned long lastButtonPress = 0;
- unsigned long lastButtonReleased = 0;
- unsigned long enc_rotated_time = 0;
- bool buttonPressed = false;
- // Display data for sleep
- #define TIME_TO_DISPLAY_OFF 10000 // 10s
- bool displayOff = false;
- bool requestToTurnOnDisplay = true;
- unsigned long lastTimeDisplayOff = millis();
- // STATE MACHINE
- // CURRENT_PAGE state
- #define LONG_PRESS_TIME 10000 // Long press time in milliseconds
- unsigned long lastButtonLongPress = 0;
- // WAIT to move to MAIN_PAGE
- #define DELAY_TIME 2000
- unsigned long waitToMoveMainPageTime = 0;
- // SETUP_COMPLETE_PAGE state
- #define COMPLETE_DISPLAY_TIME 3000 // Time to display setup complete page in milliseconds
- unsigned long lastCompleteDisplayTime = 0;
- // Define states
- enum State {
- START_PAGE,
- WAIT_TO_MOVE_MAIN_PAGE,
- MAIN_PAGE,
- DEBOUNCING_SETTING_LOWER_BOUND_PAGE,
- SETTING_LOWER_BOUND_PAGE,
- DEBOUNCING_SETTING_UPPER_BOUND_PAGE,
- SETTING_UPPER_BOUND_PAGE,
- SETUP_COMPLETE_PAGE
- };
- enum MAIN_State {
- HC12READ,
- ENCODER_SW_UPDATE,
- ENCODER_KNOB_UPDATE,
- DISPLAY_UPDATE,
- HC12WRITE,
- EEPROM_WRITE,
- DISPLAY_OFF
- };
- State currentState = START_PAGE;
- MAIN_State mainState = HC12READ;
- #define MIN_CURRENT 0
- #define MAX_CURRENT 500
- int current_setpoint = MIN_CURRENT;
- int min_current_setpoint = MIN_CURRENT;
- int max_current_setpoint = MAX_CURRENT;
- #define EEPROM_DATA_UPDATE_TIME 10000
- typedef struct eeprom_data {
- int current_setpoint;
- int min_current_setpoint;
- int max_current_setpoint;
- } EEPROM_DATA;
- EEPROM_DATA myEEPROMData;
- int current_feedback = -1;
- bool receiverDisconnected = true;
- #define RECEIVER_DISCONNECTED_TIME 5000
- #define HC12_DATA_REPETITION_TIME 1000
- volatile bool readDataEncoder = false;
- void IRAM_ATTR rotaryEncoderStatus() {
- readDataEncoder = true;
- }
- void updateRotaryEncoderStatus() {
- if(readDataEncoder == true) {
- // Read the current state of CLK
- currentStateCLK = digitalRead(CLK);
- // If last and current state of CLK are different, then pulse occurred
- // React to only 1 state change to avoid double count
- if (currentStateCLK != lastStateCLK && currentStateCLK == 1) {
- // If the DT state is different than the CLK state then
- // the encoder is rotating CCW so decrement
- int dt = digitalRead(DT); // Changed to digitalRead for compatibility
- if (dt != currentStateCLK) {
- if((millis() - enc_rotated_time) > ROTARY_SLOW) {
- counter = INCREMENT_SLOW;
- }
- else if((millis() - enc_rotated_time) > ROTARY_FAST) {
- counter = INCREMENT_FAST;
- }
- enc_rotated_time = millis();
- funcRequestToTurnOnDisplay();
- } else {
- // Encoder is rotating CW so increment
- if((millis() - enc_rotated_time) > ROTARY_SLOW) {
- counter = -INCREMENT_SLOW;
- }
- else if((millis() - enc_rotated_time) > ROTARY_FAST) {
- counter = -INCREMENT_FAST;
- }
- enc_rotated_time = millis();
- funcRequestToTurnOnDisplay();
- }
- }
- // Remember last CLK state
- lastStateCLK = currentStateCLK;
- readDataEncoder = false;
- }
- }
- void updateSwitchRotaryEncoder() {
- int btnState = digitalRead(SW);
- // If we detect LOW signal, button is pressed
- if (buttonPressed == false && btnState == LOW) {
- if (millis() - lastButtonPress > SHORT_PRESS_TIME) {
- Serial.println("Button pressed!");
- buttonPressed = true;
- funcRequestToTurnOnDisplay();
- }
- }
- else if(buttonPressed == true && btnState != LOW) {
- if (millis() - lastButtonReleased > SHORT_PRESS_TIME) {
- Serial.println("Button released!");
- buttonPressed = false;
- funcRequestToTurnOnDisplay();
- }
- }
- else {
- lastButtonPress = millis();
- lastButtonReleased = millis();
- }
- }
- void readEEPROMData() {
- EEPROM.begin(sizeof(myEEPROMData)); // Initialize EEPROM
- EEPROM.get(0x00, myEEPROMData);
- if(myEEPROMData.current_setpoint < MIN_CURRENT || myEEPROMData.current_setpoint > MAX_CURRENT) {
- myEEPROMData.current_setpoint = MIN_CURRENT;
- }
- if(myEEPROMData.min_current_setpoint < MIN_CURRENT || myEEPROMData.min_current_setpoint > MAX_CURRENT || myEEPROMData.min_current_setpoint > myEEPROMData.max_current_setpoint) {
- myEEPROMData.min_current_setpoint = MIN_CURRENT;
- }
- if(myEEPROMData.max_current_setpoint < MIN_CURRENT || myEEPROMData.max_current_setpoint > MAX_CURRENT || myEEPROMData.max_current_setpoint < myEEPROMData.min_current_setpoint) {
- myEEPROMData.max_current_setpoint = MAX_CURRENT;
- }
- current_setpoint = myEEPROMData.current_setpoint;
- min_current_setpoint = myEEPROMData.min_current_setpoint;
- max_current_setpoint = myEEPROMData.max_current_setpoint;
- }
- void setup(void) {
- Serial.begin(115200);
- Serial.println("Hello");
- pinMode(CLK, INPUT_PULLUP);
- pinMode(DT, INPUT_PULLUP);
- pinMode(SW, INPUT_PULLUP);
- readEEPROMData();
- // Initialize ST7789 display 240x240 pixel
- tft.init(240, 240, SPI_MODE3);
- tft.setRotation(2); // if the screen is flipped, remove this command
- HC12.begin(9600);
- // Initialize DHT sensor
- dht.begin(); // Start the DHT sensor
- // Initialize AllThingsTalk
- device.init(); // Initialize AllThingsTalk communication
- // Attach interrupts to rotary encoder pins
- attachInterrupt(digitalPinToInterrupt(CLK), rotaryEncoderStatus, CHANGE);
- }
- void loop() {
- updateTaskStateMachine();
- readDHTSensor(); // Read DHT sensor data in the loop
- device.loop(); // Keep AllThingsTalk & WiFi alive
- }
- void readDHTSensor() {
- // Read temperature and humidity
- float h = dht.readHumidity();
- float t = dht.readTemperature(); // Read temperature as Celsius
- // Check if any reads failed and exit early (to try again).
- if (isnan(h) || isnan(t)) {
- Serial.println("Failed to read from DHT sensor!");
- return;
- }
- // Print the values to Serial Monitor
- Serial.print("Humidity: ");
- Serial.print(h);
- Serial.print(" %\t");
- Serial.print("Temperature: ");
- Serial.print(t);
- Serial.println(" *C");
- // Send DHT sensor data to AllThingsTalk
- device.send("dht-humidity", h);
- device.send("dht-temperature", t);
- }
- void updateTaskStateMachine() {
- switch(mainState) {
- case HC12READ:
- receiveDataOverHC12();
- mainState = ENCODER_SW_UPDATE;
- break;
- case ENCODER_SW_UPDATE:
- updateSwitchRotaryEncoder();
- mainState = ENCODER_KNOB_UPDATE;
- break;
- case ENCODER_KNOB_UPDATE:
- updateRotaryEncoderStatus();
- mainState = DISPLAY_UPDATE;
- break;
- case DISPLAY_UPDATE:
- updateDisplayStateMachine();
- mainState = HC12WRITE;
- break;
- case HC12WRITE:
- sendDataOverHC12();
- mainState = EEPROM_WRITE;
- break;
- case EEPROM_WRITE:
- updateEEPROMData();
- mainState = DISPLAY_OFF;
- break;
- case DISPLAY_OFF:
- displaySleep();
- mainState = HC12READ;
- break;
- default:
- Serial.println("error mainState");
- break;
- }
- }
- void updateDisplayStateMachine() {
- // Handle state-specific actions
- switch (currentState) {
- case START_PAGE:
- // tft.drawRGBBitmap(0,0, image, 240, 240); // Uncomment if image is defined
- waitToMoveMainPageTime = millis();
- currentState = WAIT_TO_MOVE_MAIN_PAGE;
- break;
- case WAIT_TO_MOVE_MAIN_PAGE:
- if(millis() - waitToMoveMainPageTime > DELAY_TIME) {
- currentState = MAIN_PAGE;
- clearScreen();
- }
- break;
- case MAIN_PAGE:
- updateSetpoint();
- displayCurrentPage();
- if(buttonPressed == true) {
- if ((millis() - lastButtonLongPress) > LONG_PRESS_TIME) {
- currentState = DEBOUNCING_SETTING_LOWER_BOUND_PAGE;
- clearScreen();
- }
- } else {
- lastButtonLongPress = millis();
- }
- break;
- case DEBOUNCING_SETTING_LOWER_BOUND_PAGE:
- updateMinSetpoint();
- displaySettingLowerBoundPage();
- if(buttonPressed == false) {
- currentState = SETTING_LOWER_BOUND_PAGE;
- }
- break;
- case SETTING_LOWER_BOUND_PAGE:
- updateMinSetpoint();
- displaySettingLowerBoundPage();
- if(buttonPressed == true) {
- currentState = DEBOUNCING_SETTING_UPPER_BOUND_PAGE;
- clearScreen();
- }
- break;
- case DEBOUNCING_SETTING_UPPER_BOUND_PAGE:
- updateMaxSetpoint();
- displaySettingUpperBoundPage();
- if(buttonPressed == false) {
- currentState = SETTING_UPPER_BOUND_PAGE;
- }
- break;
- case SETTING_UPPER_BOUND_PAGE:
- updateMaxSetpoint();
- displaySettingUpperBoundPage();
- if(buttonPressed == true) {
- currentState = SETUP_COMPLETE_PAGE;
- lastCompleteDisplayTime = millis();
- clearScreen();
- }
- break;
- case SETUP_COMPLETE_PAGE:
- displaySetupCompletePage();
- if(millis() - lastCompleteDisplayTime > COMPLETE_DISPLAY_TIME) {
- currentState = MAIN_PAGE;
- clearScreen();
- }
- break;
- default:
- Serial.println("error machine state");
- break;
- }
- }
- void displaySleep() {
- if(requestToTurnOnDisplay == true) {
- lastTimeDisplayOff = millis();
- }
- if(millis() - lastTimeDisplayOff > TIME_TO_DISPLAY_OFF && displayOff == false) {
- displayOff = true;
- turnOffDisplay();
- Serial.println("TURN OFF DISPLAY");
- }
- else if (displayOff == true && requestToTurnOnDisplay == true) {
- displayOff = false;
- turnOnDisplay();
- Serial.println("TURN ON DISPLAY");
- }
- requestToTurnOnDisplay = false;
- }
- void funcRequestToTurnOnDisplay() {
- requestToTurnOnDisplay = true;
- }
- void turnOffDisplay() {
- tft.writeCommand(ST77XX_DISPOFF); // Turn off display
- tft.writeCommand(ST77XX_SLPIN); // Enter sleep mode
- }
- void turnOnDisplay() {
- tft.writeCommand(ST77XX_SLPOUT); // Exit sleep mode
- tft.writeCommand(ST77XX_DISPON); // Turn on display
- }
- void updateEEPROMData() {
- static unsigned long lastTimeUpdateData = millis();
- if(millis() - lastTimeUpdateData > EEPROM_DATA_UPDATE_TIME) {
- if( current_setpoint != myEEPROMData.current_setpoint || min_current_setpoint != myEEPROMData.min_current_setpoint || max_current_setpoint != myEEPROMData.max_current_setpoint) {
- myEEPROMData.current_setpoint = current_setpoint;
- myEEPROMData.min_current_setpoint = min_current_setpoint;
- myEEPROMData.max_current_setpoint = max_current_setpoint;
- EEPROM.put(0x00, myEEPROMData);
- EEPROM.commit();
- Serial.println("EEPROM updated");
- lastTimeUpdateData = millis();
- }
- lastTimeUpdateData = millis();
- }
- }
- void sendDataOverHC12() {
- static unsigned long lastTimeSendData = millis();
- if(millis() - lastTimeSendData > HC12_DATA_REPETITION_TIME) {
- // Send the string over HC-12
- HC12.println(String(current_setpoint));
- lastTimeSendData = millis();
- Serial.print("TX: ");
- Serial.println(current_setpoint);
- }
- }
- void receiveDataOverHC12() {
- static unsigned long lastReceivedPacketTime = millis();
- if (HC12.available()) {
- // Read until the end of the line (until '\n')
- String receivedData = HC12.readStringUntil('\n');
- // Split the received data into separate variables
- current_feedback = receivedData.toInt();
- Serial.print("RX: ");
- Serial.println(current_feedback);
- lastReceivedPacketTime = millis();
- receiverDisconnected = false;
- }
- if (millis() - lastReceivedPacketTime > RECEIVER_DISCONNECTED_TIME) {
- receiverDisconnected = true;
- }
- }
- void updateSetpoint() {
- if(counter > 0) {
- Serial.print("+");
- Serial.println(counter);
- current_setpoint = min(current_setpoint + counter, max_current_setpoint);
- counter = 0;
- } else if(counter < 0) {
- Serial.println(counter);
- current_setpoint = max(current_setpoint + counter, min_current_setpoint);
- counter = 0;
- }
- }
- void updateMinSetpoint() {
- if(counter > 0) {
- Serial.print("+");
- Serial.println(counter);
- min_current_setpoint = min(min_current_setpoint + counter, max_current_setpoint);
- current_setpoint = max(current_setpoint, min_current_setpoint);
- counter = 0;
- } else if(counter < 0) {
- Serial.println(counter);
- min_current_setpoint = max(min_current_setpoint + counter, MIN_CURRENT);
- current_setpoint = max(current_setpoint, min_current_setpoint);
- counter = 0;
- }
- }
- void updateMaxSetpoint() {
- if(counter > 0) {
- Serial.print("+");
- Serial.println(counter);
- max_current_setpoint = min(max_current_setpoint + counter, MAX_CURRENT);
- current_setpoint = min(current_setpoint, max_current_setpoint);
- counter = 0;
- } else if(counter < 0) {
- Serial.println(counter);
- max_current_setpoint = max(max_current_setpoint + counter, min_current_setpoint);
- current_setpoint = min(current_setpoint, max_current_setpoint);
- counter = 0;
- }
- }
- bool fillOneTime = true;
- bool displayReceiverDisconnected = false;
- void clearScreen() {
- tft.fillScreen(ST77XX_BLACK);
- fillOneTime = true;
- displayReceiverDisconnected = false;
- }
- void displayCurrentPage() {
- static int temp_current_setpoint = -1000;
- static int temp_current_feedback = -1000;
- if(current_setpoint != temp_current_setpoint || fillOneTime) {
- tft.fillRect(0, 30, 240, 80, ST77XX_BLACK); // Clear the top portion of the screen
- tft.setTextColor(ST77XX_BLUE);
- tft.setTextSize(10);
- tft.setCursor(30, 30); // Set cursor to the beginning of the first line
- tft.print((float)current_setpoint, 0); // Print the current value with 0 decimal places
- temp_current_setpoint = current_setpoint;
- }
- if(fillOneTime == true) {
- // Set cursor to the beginning of the second line
- tft.setCursor(0, 120); // Adjust '30' based on your text size and display dimensions
- tft.setTextSize(10);
- tft.print("AMPS"); // Print "AMPS" on the second line
- }
- if(current_feedback != temp_current_feedback || fillOneTime) {
- tft.fillRect(0, 200, 80, 40, ST77XX_BLACK); // Clear the portion of the screen
- tft.setTextColor(ST77XX_YELLOW);
- tft.setTextSize(2);
- tft.setCursor(0, 200);
- tft.print((float)current_feedback, 0); // Print feedback
- temp_current_feedback = current_feedback;
- }
- if(receiverDisconnected == true && displayReceiverDisconnected == false) {
- tft.fillRect(80, 200, 160, 40, ST77XX_BLACK); // Clear the portion of the screen
- tft.setTextColor(ST77XX_YELLOW);
- tft.setTextSize(2);
- tft.setCursor(80, 200);
- tft.print(F("DISCONNECTED")); // Print feedback
- displayReceiverDisconnected = true;
- } else if(receiverDisconnected == false && displayReceiverDisconnected == true) {
- tft.fillRect(80, 200, 160, 40, ST77XX_BLACK); // Clear the portion of the screen
- displayReceiverDisconnected = false;
- }
- fillOneTime = false;
- }
- void displaySettingLowerBoundPage() {
- static int temp_min_current_setpoint = -1000;
- if(fillOneTime == true) {
- tft.setTextColor(ST77XX_WHITE);
- tft.setTextSize(2);
- tft.setCursor(10, 10);
- tft.print("SET LOWER BOUND");
- }
- if(min_current_setpoint != temp_min_current_setpoint || fillOneTime) {
- tft.fillRect(0, 30, 240, 80, ST77XX_BLACK); // Clear the top portion of the screen
- tft.setTextColor(ST77XX_BLUE);
- tft.setTextSize(10);
- tft.setCursor(30, 30); // Set cursor to the beginning of the first line
- tft.print((float)min_current_setpoint, 0); // Print the current value with 0 decimal places
- temp_min_current_setpoint = min_current_setpoint;
- }
- if(fillOneTime == true) {
- // Set cursor to the beginning of the second line
- tft.setCursor(0, 120); // Adjust '30' based on your text size and display dimensions
- tft.setTextSize(10);
- tft.print("AMPS"); // Print "AMPS" on the second line
- }
- fillOneTime = false;
- }
- void displaySettingUpperBoundPage() {
- static int temp_max_current_setpoint = -1000;
- if(fillOneTime == true) {
- tft.setTextColor(ST77XX_WHITE);
- tft.setTextSize(2);
- tft.setCursor(10, 10);
- tft.print("SET UPPER BOUND");
- }
- if(max_current_setpoint != temp_max_current_setpoint || fillOneTime) {
- tft.fillRect(0, 30, 240, 80, ST77XX_BLACK); // Clear the top portion of the screen
- tft.setTextColor(ST77XX_BLUE);
- tft.setTextSize(10);
- tft.setCursor(30, 30); // Set cursor to the beginning of the first line
- tft.print((float)max_current_setpoint, 0); // Print the current value with 0 decimal places
- temp_max_current_setpoint = max_current_setpoint;
- }
- if(fillOneTime == true) {
- // Set cursor to the beginning of the second line
- tft.setCursor(0, 120); // Adjust '30' based on your text size and display dimensions
- tft.setTextSize(10);
- tft.print("AMPS"); // Print "AMPS" on the second line
- }
- fillOneTime = false;
- }
- void displaySetupCompletePage() {
- if(fillOneTime == true) {
- tft.setTextColor(ST77XX_WHITE);
- tft.setTextSize(4);
- tft.setCursor(10, 10);
- tft.print("SETUP");
- tft.setCursor(10, 80);
- tft.print("COMPLETE");
- }
- fillOneTime = false;
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement