Go Down

Topic: if statements , sonar servo (Read 851 times) previous topic - next topic


hello , me and my tutor wrote/cobbled this code together (I'm on a media course and arduino isn't really part of the syllabus to write sonar sensor values to a servo arm.
however it turns out what I need is more simply an if statement so that when the sonar reads in a particular range the servo rotates it's full 180 degrees.

#include <Servo.h>  //include servo library

int configPin = 13;                 //Set the sonar Calibration Pin
Servo myservo;                      // create servo object to control a servo
                                    // a maximum of eight servo objects can be created
int pos = 0;                        // variable to store the servo position           

void setup() {                    //begin of program

Serial.begin(9600);             //serial baud rate 9600
pinMode(configPin,OUTPUT);       //make Calibration pin output

myservo.attach(8);  // attaches the servo on pin 8 to the servo object


void loop(){                     //looping of program

digitalWrite(configPin,HIGH);    //raise the reset pin high
delay(120);                      //start of calibration ring

float sensorvalue = analogRead(0); //get analog sensor value from pin 0

float inchvalue = (254.0/1024.0) *2.0* sensorvalue; //convert to inches

pos = map(sensorvalue, 0, 1023, 0, 179);


myservo.write(pos);                  // sets the servo position according to the scaled value

Serial.print("Sensed a-d value:"); //print a-d text
Serial.println(sensorvalue);       //print a-d value
Serial.print("Inch value=");      //print inch text
Serial.println(inchvalue);        //print inch value

delay(1000);                      //optional delay 1 second
digitalWrite(configPin,LOW);      //turn off Calibration ring and sensor
delay(1000);                      //delay 1 second


I'm relatively sure I cut the mapping portion but I'm not clear where or how to write the if statement. sorry if this is too basic a question if so just direct me a page where I can work it out myself. cheers


How to use this forum - please read.

yes please read it will tell you how to post code to increase readabilty.
From Idea To Invention




and this


and finally this

From Idea To Invention

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131