Home » Projects » Software Projects » Setup Your Code – Ready to Run

Setup Your Code – Ready to Run

setup your code

Be prepared. Use the setup routine to setup your code ever time your IoT controller boots up.

Every time you write an Arduino or NodeMCU program, you need to program the “setup” routine. This runs once when your IoT controller boots. I find this a very useful routine.

Among other things, you can setup your code by defining things your program needs to know. You can read stored settings from the EEPROM (read only memory). You can test GPIO pins to change the behavior of your code before it runs. For example, you can ground a digital pin to signify a certain kind of behavior. With the NodeMCU, you can use a GPIO pin to denote running as a station on your network. Or you can have the wireless setup a stand-alone network.

Here is my setup for the relay controller.

void setup()
{
  delay(500);
#ifdef DEBUG
  Serial.begin(SERIAL_BAUDRATE);
  Serial.flush();
#endif

/* Enable over the air firmware changes */
ArduinoOTA.begin();
delay(100);

/* Configure controller for first use */
Initialize();

/* Connect to local network */
wl_status_t b = wifiConnect(ssid, password);
if (b == WL_CONNECTED) {
  server.begin();
#ifdef DEBUG
  Respond("ONLINE");
  Respond(WiFi.localIP().toString());
#endif 
}

/* Make relay banks available for control */
  B_RX.begin();
  B_LOOP.begin();delay(100);
}

If you want feedback over the serial port during startup, you can use a DEBUG definition to make sure your NodeMCU is on track. You can prepare the device for over-the-air firmware updates. Also, you can do a separate routing for initialize all key variables and objects to their proper settings.

void Initialize() {

  /* Turn all Relays Off */
  B_RX.write8(255);
  B_LOOP.write8(255);
  Status.Connected = false;
  Status.Receiver = 0;
  Status.Filter = 0;
  Status.Loop1Mode = 0;
  Status.Loop2Mode = 0;
}

Setup Your Code for Wireless Communications

Perhaps most important, you need to make sure your WiFi over the local network is connected. You do this with a call to “wifiConnect”, passing your network ID and password.

wl_status_t wifiConnect(const char* id, const char* pass)
{
  WiFi.disconnect();
  /* Set up on LAN with a Static Server IP Address */
  WiFi.mode(WIFI_STA);
  WiFi.config(SERVERIP, GATEWAY, SUBNET, DNS1, DNS2);
  WiFi.begin(id, pass);
  int counter = 0;
  /* Wait up to 3 seconds for connection */
  while (WiFi.status() != WL_CONNECTED)
    {
    delay(250);
    counter++;
    if (counter > 12)
    {
      break;
    }
  }
  return WiFi.status();
}

You need to include some delays to provide enough time for your NodeMCU to be accepted on the network. Check the return code to make sure everything worked ok.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.