Getting a servo to move based on a color sensor

Hi,

I'm currently in the development of a project where I need to have the servo to move based on the values gathered by a color sensor. I am fairly new to coding and I'm struggling a bit.

Specifically, I want the servo to move 90 degrees clockwise if the color red is detected. If there is no red detected, I want the servo to either stay at 0 degrees if it is already there or move back counterclockwise 90 degrees back to 0 degrees.

I have typed the following code:

#include<Servo.h>
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8
Servo motor;
int redfrequency = 0;
int greenfrequency =0;
int color=0;
int pos;
int servoPin=9;
void setup() {
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
  motor.attach(servoPin);
  digitalWrite(S0,HIGH);
  digitalWrite(S1,LOW);
}

void loop() {
 if(redfrequency<25)
  {
    delay(100);
    for(pos=0;pos<=180;pos=pos+5)
{
 motor.write(pos);
delay(50);
}
  }
  else(redfrequency>25);
 {
  delay(100);
  for(pos=180;pos>=0;pos=pos-5)

{
 motor.write(pos);
 delay(50);
}  
 }
}

So far, the servo just moves continuously if the color red is detected. I have been trying to figure this out for a while and I've run out of ideas. Any and all help is appreciated.

Thanks

Is it a true servo, or a continuous rotation ex-servo?

The code you posted doesn't seem to read any sensor. Post a link to the product page for the sensor you have.

Start by learning how to use the sensor. You will probably need to download a library, which will have some example code. Connect the sensor as instructed and run the example code to test it.

That doesn't do what you think.

https://www.openimpulse.com/blog/products-page/product-category/tcs230-tcs3200-color-sensor-module/
This is the product page. I tested it out previously a little and was able to read the values that it produced.

I’m using the mg996r servo. I looked it up and it said it was continuous.

What exactly does this do, and how could I get it to move if it detects the color red?

The standard MG996R servo is not continuous, and you will need a separate power supply for it, because the Arduino cannot be used to power servos. A fresh 4xAA battery pack will work to power one MG996R servo.

The posted code does not read the TCS3200 sensor. This tutorial might help you get started.

Example servo wiring:

This does nothing useful:
else(redfrequency>25);

That code does not seem to do any actual detection.

The test code you used might show a clue. Also maybe read

to see what is invloved with such detecting.

HTH

a7

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.