Pages: [1]   Go Down
Author Topic: How to use sensor to stopping servo motor  (Read 184 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
[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:
if(sensor1>400)
{
    stretch.detach();
    motion=3;
    Serial.println(motion);
}

Or change data value.
Code:
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]
Logged

UK
Offline Offline
Tesla Member
***
Karma: 134
Posts: 7576
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Your logic seems very confusing.

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

...R
Logged

0
Offline Offline
Shannon Member
****
Karma: 214
Posts: 12390
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

[ I won't respond to messages, use the forum please ]

Pages: [1]   Go Up
Jump to: