USB not connected code?

Hi, I am trying to have this code do seperate things when USB is connected and disconnected. At the moment I am using

However, even when USB is connected and I am sending serial data, it keeps running the disconnected code, but also runs the connected code at the same time?

Is there another way to do this?

int z = 0;
float h;
int h_int;
int val = 0;
int fdelay = 20;
int R = 10;
int G = 6;
int B = 9;
int rprev = 0;
int gprev = 0;
int bprev = 0;
void setup(){
  Serial.begin(115200);
  pinMode(12, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
}

void h2rgb(float H, int& R, int& G, int& B) {

  int var_i;
  float S=1, V=1, var_1, var_2, var_3, var_h, var_r, var_g, var_b;

  if ( S == 0 )                       //HSV values = 0 ÷ 1
  {
    R = V * 255;
    G = V * 255;
    B = V * 255;
  }
  else
  {
    var_h = H * 6;
    if ( var_h == 6 ) var_h = 0;      //H must be < 1
    var_i = int( var_h ) ;            //Or ... var_i = floor( var_h )
    var_1 = V * ( 1 - S );
    var_2 = V * ( 1 - S * ( var_h - var_i ) );
    var_3 = V * ( 1 - S * ( 1 - ( var_h - var_i ) ) );

    if      ( var_i == 0 ) {
      var_r = V     ;
      var_g = var_3 ;
      var_b = var_1 ;
    }
    else if ( var_i == 1 ) {
      var_r = var_2 ;
      var_g = V     ;
      var_b = var_1 ;
    }
    else if ( var_i == 2 ) {
      var_r = var_1 ;
      var_g = V     ;
      var_b = var_3 ;
    }
    else if ( var_i == 3 ) {
      var_r = var_1 ;
      var_g = var_2 ;
      var_b = V     ;
    }
    else if ( var_i == 4 ) {
      var_r = var_3 ;
      var_g = var_1 ;
      var_b = V     ;
    }
    else                   {
      var_r = V     ;
      var_g = var_1 ;
      var_b = var_2 ;
    }

    R = (1-var_r) * 255;                  //RGB results = 0 ÷ 255
    G = (1-var_g) * 255;
    B = (1-var_b) * 255;
  }
}

void loop()
{
  if(Serial.available > 0){
   if(z == 1){
     if(val < 1023){
     val = val++;
     delay(fdelay);
    h = ((float)val)/1024;
    h_int = (int) 360*h;
    int redvar;
    int bluevar;
    int greenvar;
    h2rgb(h, redvar, greenvar, bluevar);
    analogWrite(R, redvar);
    analogWrite(G, greenvar);
    analogWrite(B, bluevar);
    }
    else{ val = 0; }
   }
  char c, t;
   int nnn;

   if(Serial.available() > 0) // If there is data to read
   {
       c = Serial.read(); // Get a character

       delay(50);

       if(c >= 'a' && c <= 'z') // If it's a command
       {
          nnn = 0;
          while(Serial.available() > 0) // While there is still data
          {
             t = Serial.read(); // Read next character

             if(t == ',' || t == ' ')
               continue; // Skip commas and spaces
             if(t >= '0' && t <= '9') // If it's a number
             {
                nnn *= 10; // Multiply previous value by 10
                nnn += t - '0'; // Add the new digit
             }
             else
                break;

             delay(50);
          }
       }
   }

   // Now, do something with c and nnn
   switch(c)
   {
      case 's':
        analogWrite(5,nnn);
        break;
      case 'f':
        analogWrite(3,nnn);
        break;
        case 'u':
          if (nnn > 100){
            digitalWrite(12, HIGH);
          }
          if (nnn < 100){
            digitalWrite(12, LOW);
          }
          break;
        case 'r':
          analogWrite(R,nnn);
          rprev = nnn;
          break;
        case 'g':
          analogWrite(G,nnn);
          gprev = nnn;
          break;
        case 'b':
          analogWrite(B,nnn);
          bprev = nnn;
          break;
        case 'z':
          if(nnn > 100){
            z = 1;
          }
          if(nnn < 100){
            z = 0;
          }
          break;
        case 'x':
          fdelay = nnn;
          break;
        case 'l':
          lightning();
          break;
        case 'a':
          analogWrite(3, nnn);
          analogWrite(6, nnn);
          analogWrite(9, nnn);
          analogWrite(10, nnn);
          analogWrite(11, nnn);
          digitalWrite(12, LOW);
          break;
      // Add other letters here, with break after each one
   }
  }
  else{
      digitalWrite(12, HIGH);
      analogWrite(11, 255);
      analogWrite(10, 255);
      analogWrite(9, 255);
      analogWrite(6, 255);
      analogWrite(5, 255);
      analogWrite(3, 100);
  }
}

void lightning(){
  int del = 0;
  analogWrite(R, 255);
  analogWrite(G, 255);
  analogWrite(B, 255);
  del = random(10, 150);
  delay (del);
  analogWrite(R, 0);
  analogWrite(G, 0);
  analogWrite(B, 0);
  del = random(10, 150);
  delay(del);
  analogWrite(R, 255);
  analogWrite(G, 255);
  analogWrite(B, 255);
  del = random(10, 150);
  delay(del);
  analogWrite(R, 0);
  analogWrite(G, 0);
  analogWrite(B, 0);
  del = random(10, 150);
  delay(del);
  analogWrite(R, 255);
  analogWrite(G, 255);
  analogWrite(B, 255);
  del = random(10, 150);
  delay(del);
  analogWrite(R, 0);
  analogWrite(G, 0);
  analogWrite(B, 0);
  delay(20);
  analogWrite(R, rprev);
  analogWrite(G, gprev);
  analogWrite(B, bprev);
 }

As i understand it the arduino only detects if there is power coming from the USB or not and can switch to the appropriate power source as needed. But that is not tied into the ATmega chip at all. If the arduino has data to send it will try and send it weather USB is connected or not. Serial communications is pretty basic and doesn't have any means of verifying connectivity. The Arduino doesn't have a very interactive link to the USB side of the board. The serial communication just goes to it.

You may be able to set up your own verification. Have your code look for verification that it has a connection. For example you can have it look for a certain message to be sent from the PC. You could send "connected" threw the serial monitor to the arduino. Once it sees that or some other phrase it knows it has a PC connection. Then you'll need to send a disconnect command to tell it to stop comunicating with the PC.

If your a Windows guy then think back to the Win 95 days. If you old enough. Back then you couldn't just plug in and unplug USB devices. You had to go into the task manager and click on safely remove hardware before pulling a USB device from the system. Otherwise windows would go all screwy and possibly crash. Now day the OS can handle it without a problem.

Things,

Serial.available does not tell you if the USB port is connected or not. It tells you whether any characters have been received. If it returns 0, it might be because the port is not connected, or the port may be connected and there are no unread characters.

You may be able to connect from the USB power circuit to a digital input pin to determine if the board is being powered from USB, but this would still be no guarantee that there is an active serial connection over the USB port.

As digimike pointed out, the surest way is to handshake over the serial port between the PC and the Arduino.

Regards,

-Mike