Go Down

Topic: How to use sensor to stopping servo motor (Read 207 times) previous topic - next topic

riki256596

Hello, everyone
Thanks to read this post.
I have a problem about I can't stop my servo motor by using sensor.
My condition as below.

[Circuit]
My base is Arduino Mega 2560.
I'm using variable resistor to be a sensor and connect to Analog(A0).
Then use a 360 degree servo motor connect to PWM Pin2.

Code: [Select]

[code]#include <Servo.h>
Servo stretch;
int motion=0;
//Initial
void setup()
{
   //Motor Pins
   stretch.attach(2);  //PWM Pin2
   //Motor stop
   stretch.writeMicroseconds(1500);   
   //Baud Rate
   Serial.begin(9600); 
}

void loop()
{
   int sensor1 = analogRead(0);

   if (Serial.available() > 0)          // Check data
   {
     int data = Serial.read();    // read byte
     if(data=='1')      //Motion 1 : STOP
     {           
         stretch.writeMicroseconds(1500);
         motion=1;
         Serial.println(motion);
         
     }
     else if(data=='2')   //Motion 2 : Forward
     {
       stretch.writeMicroseconds(1450);
       motion=2;
       Serial.println(motion);
       if(sensor1>400)
       {
         stretch.writeMicroseconds(1500);
         motion=3;
         Serial.println(motion);
       }
     }
   }
   delay(100);
}


My motor is 360 degree, so I use writeMicroseconds to control speed.
The problem is my motor can't stop when the sensor value higher than 400.
But, I use serial monitor to check the motion is 3.
So I don't know what happen.

I also try the function detach().
Code: [Select]
if(sensor1>400)
{
    stretch.detach();
    motion=3;
    Serial.println(motion);
}


Or change data value.
Code: [Select]
if(sensor1>400)
{
    data='1';
    motion=3;
    Serial.println(motion);
}

The motor still doesn't  stop.

I don't know that the code has problem or my think has problem.
Does someone have the experience like this. Please help me.
Thanks a lot.[/code]

Robin2

Your logic seems very confusing.

I think you have if(sensor1>400) in the wrong place.

...R

MarkT

Yes, you only test the sensor at the exact moment of reading a '2'.

Presume you want to check the sensor every time round the loop.
[ I won't respond to messages, use the forum please ]

Go Up