Pages: [1]   Go Down
Author Topic: Removing USB cable while sending between Arduino and Computer  (Read 548 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 631
Posts: 50115
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

This is the full code:

Code:
#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 ?
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 631
Posts: 50115
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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.

Logged

Pages: [1]   Go Up
Jump to: