Go Down

Topic: Removing USB cable while sending between Arduino and Computer (Read 563 times) previous topic - next topic

duplo

Hi,

I made a servo controller of my Arduino Nano which gets commands from my computer and moves the servos.
But I want to make a security feature, so that the servos are moving into a failsave position if the controll program on the computer crashs, the computer itself crashs or someone removes the usb cable.
The Arduino and the servos have an additional power supply. So they can work even if the cable was removed.
But how can I program this function ?

I made the following the check if the incomming data is valid:

    int a = Serial.read();
   
    if(a >= 0 && a <= 180){
      servo.write(a);
    }else{
      servo.write(0);
    }

But after removing the cable, the servos move to random positions. Not to 0.

PaulS

Quote
But after removing the cable, the servos move to random positions. Not to 0.

Removing the cable reset the Arduino. Some other code is manipulating the servos (in ways you appear not to care for).

This is why snippets of code don't cut it here.

duplo

This is the full code:

Code: [Select]
#include <Servo.h>

Servo drehen;
Servo neigen;
long lastReceived;


void setup(){
  Serial.begin(9600);
  drehen.attach(2); 
  neigen.attach(3);
}

void loop(){
  if(millis() - lastReceived > 5000){
     drehen.write(0);
     neigen.write(0);
  }
  if(Serial.available() > 0){
     int a = Serial.read();
     int b = Serial.read();
     
     if(a >= 0 && a <= 180){
       drehen.write(a);
     }else{
       drehen.write(0);
     }
     
     if(b >= 0 && b <= 180){
       neigen.write(b);
     }else{
       neigen.write(0);
     }
     
     Serial.write(1); 
     lastReceived = millis();
  }   
  delay(50); 
}


So the only chance is to measure the time of the last command from the computer like in the code above ?

PaulS

Quote
So the only chance is to measure the time of the last command from the computer like in the code above ?

No.

Code: [Select]
void setup(){
  Serial.begin(9600);
  drehen.attach(2); 
  neigen.attach(3);
}

You can write a value to a servo before you attach it. Then, when you do attach it, the servo will go to that position.

So, write where you want the servo to start. On reset (when the computer crashes or the cable is pulled), the servo will go to that position.


Go Up