Unplugging usb cable gives weird results.


i building first robot.
it has hc-sr04 , arduino motor shield(official) newping library , own library.
before unplug usb cable, program works intended(turns when there obstacle).
but, after unplug, robot spins in circles.
any suggestions?
examine code:

main code:
code: [select]

#include <newping.h>
#include <motor.h>
#define sonar_pin 2 // arduino pin tied echo pin on ultrasonic sensor.
#define max_distance 400 // maximum distance want ping (in centimeters). maximum sensor distance rated @ 400-500cm.

newping sonar(sonar_pin,sonar_pin, max_distance); // newping setup of pins , maximum distance.
motor motor;
int cm;

void setup() {
 // put setup code here, run once:
serial.begin(9600);

}

void loop() {
 // put main code here, run repeatedly:
 while(!(sonar.ping_cm() < 30 )){
   motor.movea(255); // go foward
   motor.moveb(255);
   show();
 }
 motor.movea(255); //turn: causes spin in circles
 motor.moveb(-255);
 delay(50);
 show();
 
}
void show(){
 serial.println(sonar.ping_cm());
}

motor.h

code: [select]

#ifndef morse_h
#define morse_h

#include "arduino.h"
#define dira 12
#define brakea 9
#define dirb 13
#define brakeb 8
class motor
{
 public:
   motor();
   void movea(short amounta);
   void moveb(short amountb);
};
#endif // morse_h


motor.cpp
code: [select]

#include "arduino.h"
#include "motor.h"

motor::motor(){
   pinmode(dira,output);
   pinmode(brakea,output);
   pinmode(dirb,output);
   pinmode(brakeb,output);
}
void motor::movea(short amounta){
   boolean stopa = false;
   byte speeda = abs(amounta);
   if (speeda > 255){
       speeda = speeda % 255;
       //add: throw exception
   }
       if (amounta < 0 ){
           digitalwrite(dira, high);
       }else if(amounta > 0){
           digitalwrite(dira, low);
       }else{
           stopa = true;
       }
       analogwrite(3, speeda);
       digitalwrite(brakeb, stopa);
}
void motor::moveb(short amountb){
   boolean stopb = false;
   byte speedb = abs(amountb);
   if (speedb > 255){
       speedb = speedb % 255;
       //add: throw exception
   }
       if (amountb < 0 ){
           digitalwrite(dirb, high);
       }else if(amountb > 0){
           digitalwrite(dirb, low);
       }else{
           stopb = true;
       }
       analogwrite(11, speedb);
       digitalwrite(brakeb, stopb);
}


almost ping detects close or maybe quit running proper?
by chance non-usb power arduino 9v battery?


Arduino Forum > Using Arduino > Programming Questions > Unplugging usb cable gives weird results.


arduino

Comments

Popular posts from this blog

Connecting Raspberry Pi 2 to P10(1R)-V706 LED Dot Matrix - Raspberry Pi Forums

TypeError: <unknown> is not a numpy array - Raspberry Pi Forums

datso and removing imagetitle - Joomla! Forum - community, help and support