Control Arduino ports via Serial communication

I need to control some wall outlets to turn them on or off at different moments in the day. I will use this to control the events in the fish tank of my wife. To tell the Arduino when to turn on or off ports, which are connected to relays, I have a PHP script that sends commands to the COM port which is connected to the Arduino.

The commands that I am sending are: 3:255&4:0&8:180. This puts the level on the analog port 3 (C02 gas) on the maximum, turns port 4 (bubbles) off and puts port 8 (Lights) at level 180. During the day, different values are sent.

This is the Arduino script that is behind this:

// Example input=3:255&4:0&8:180
void setup() {
  Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}

void loop() {
#define INPUT_SIZE 300
  // Get next command from Serial
  if (Serial.available())
  {
    char input[INPUT_SIZE + 1];
    byte size = Serial.readBytes(input, INPUT_SIZE);

    // Add the final 0 to end the string
    input[size] = 0;

    // Read each command pair
    char* command = strtok(input, "&");
    while (command != 0)
    {
      // Split the command in two values
      char* separator = strchr(command, ':');
      if (separator != 0)
      {
        // Actually split the string in 2: replace ':' with 0
        *separator = 0;
        int portId = atoi(command);
        Serial.print("Port:");
        Serial.print(portId);
        ++separator;
        int valuePar = atoi(separator);
        Serial.print(", Value:");
        // for the digital ports
        if (portId == 2 || portId == 4 || portId == 7 || portId == 8 || portId == 12 || portId == 13)
        {
          if (valuePar == 0)
          {
            digitalWrite(portId, LOW);
            Serial.println(LOW);
          }
          else
          {
            digitalWrite(portId, HIGH);
            Serial.println(HIGH);
          }
        }
        // for the analog ports
        if (portId == 3 || portId == 5 || portId == 6 || portId == 9 || portId == 102 || portId == 11)
        {
          if (valuePar == 0)
          {
            analogWrite(portId, valuePar);
            Serial.println("Off");
          }
          else
          {
            analogWrite(portId, valuePar);
            Serial.print("On with level:");
            Serial.println(valuePar);
          }
        }
      }
      command = strtok(0, "&");
      Serial.println("=====");
    }
  }
}
Posted in Uncategorized.

Leave a Reply

Your email address will not be published.