BRLAB DOCS
HomeTutorialsHardware
Control Relays with the Nextion HMI and Arduino
Control Relays with the Nextion HMI and Arduino
  • Introduction
  • GETTING STARTED
    • What You Will Need
    • Wiring
  • HMI GUI
    • Nextion HMI Setup
    • GUI Design
    • HMI Code
    • Load Code on the HMI
  • NANO EVERY CODE
    • Task to Complete
    • Writing the Code
      • Comment Header
      • Define Global Variables
      • void setup()
      • void loop()
      • void serial_input()
    • Application Code
    • Files
Powered by GitBook
On this page
  1. NANO EVERY CODE

Application Code

Here is the entire code put together.

/*
Title: Control Relays with Nextion HMI
Written By: (put your name here)
Date: 03/11/2023
Description:
This code can read messages from the Nextion HMI over serial. 
The code will then turn these messages into commands for the Arduino
Nano Every to perfrom. Thus turning on or off the 2 relays based on
the state of the switch widgets on the HMI.
*/
const int relay1 = 7; // relay 1 is on digital pin 7
const int relay2 = 8; // relay 2 is on digital pin 8

String cmd =""; // string variable to store messages in

void setup() {
  // open serial port with computer; use for debugging  
  //Serial.begin(9600); 
  
  // open serial port between HMI and Arduino Nano Every; recieve and send messages
  Serial1.begin(9600); 

  pinMode(relay1, OUTPUT); // configure relay 1 pin as an output
  pinMode(relay2, OUTPUT); // configure relay 2 pin as an output
}

void loop() {
  if(Serial1.available()){ // is there any bytes on the serial 1 port buffer
    cmd = "";
    delay(5);
    serial_input(); // custom function to handle the messages over serial 
  }
}

void serial_input() {
  while (Serial1.available()) {
    cmd += char(Serial1.read()); // read avaialbe bytes into dfd string
  }
  if (cmd.substring(0, 3) == "R1:") { // does the substring = R1:
    String relay1_cmd = cmd.substring(3, cmd.length()); // read the cmd into relay1_cmd string variable
    if (relay1_cmd == "ON") { // if true then turn on relay 1
      digitalWrite(relay1, HIGH); // set the digital pin high
    } else { // if false then run this statement and set the digital pin low
      digitalWrite(relay1, LOW);
    }
  }
  if (cmd.substring(0, 3) == "R2:") { // does the substring = R2:
    String relay2_cmd = cmd.substring(3, cmd.length()); // read the cmd into relay2_cmd string variable
    if (relay2_cmd == "ON") { // if true then turn on relay 2
      digitalWrite(relay2, HIGH); // set the digital pin high
    } else { // if false then run this statement and set the digital pin low
      digitalWrite(relay2, LOW);
    }
  }
}
Previousvoid serial_input()NextFiles

Last updated 2 years ago