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
  2. Writing the Code

void serial_input()

This custom function is where I am actually going to read the data from the Nextion HMI into the cmd string until there is no more data to be read.

Then I am going to parse the string data into sections using String() functions to deciphor the commands that where sent. Once it has determined which command has been sent I will turn off or on the requested relay.

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 loop()NextApplication Code

Last updated 2 years ago