Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Reddit Arduino Servo attempt
- July 2, 2019
- { wayward parentheses, mostly }
- */
- #include <Servo.h>
- Servo myservo; // create servo object to control a servo
- const int trigPin = 2;
- const int echoPin = 4;
- // { void setup() // -- This curly brace should be after the parentheses, not at the start of the whole line.
- void setup() { // -- corrected line
- // initialize serial communication:
- Serial.begin(9600);
- myservo.attach(9); // attaches the servo on pin 9 to the servo object
- }
- // { void loop() // -- This curly brace should be after the parentheses, not at the start of the whole line.
- void loop() { // -- corrected line
- // and the distance result in centimeters:
- long duration, cm;
- pinMode(trigPin, OUTPUT);
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2); // This isn't going to work like you think it will.
- // If I remember correctly, the smallest unit of time that the Uno and Mega chips can normally clock is 4 microseconds.
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(20);
- digitalWrite(trigPin, LOW);
- pinMode(echoPin, INPUT);
- duration = pulseIn(echoPin, HIGH);
- // convert the time into a distance
- cm = microsecondsToCentimeters(duration); // I do not know why it said that "cm was not declared in this scope"...???
- // When I fixed the other curly braces errors, it no longer gave that message.
- // the condition for the distance
- if (cm > 7 && cm < 14) {
- myservo.write(140); // sets the servo position according to the scaled value
- delay(4000);
- }
- else if (cm < 8) {
- myservo.write(40); // sets the servo position according to the scaled value
- delay(100);
- }
- else {
- myservo.write(40); // sets the servo position according to the scaled value
- delay(100);
- }
- Serial.print(cm);
- Serial.print("cm");
- Serial.println();
- delay(100);
- }
- //{ long microsecondsToCentimeters(long microseconds) // -- This curly brace should be after the parentheses, not at the start of the whole line.
- long microsecondsToCentimeters(long microseconds) { // -- corrected line
- // The speed of sound is 340 m/s or 29 microseconds per centimeter.
- // The ping travels out and back, so to find the distance of the
- // object we take half of the distance travelled.
- /*
- The error given for the line below ( sketch_jun29a:103:1: error: a function-definition is not allowed here before 'return' )
- may have been related to the incorrectly-placed curly brace at the beginning of the function.
- When I moved that curly brace to the proper location, this error message was no longer present.
- */
- return microseconds / 29 / 2; // If this doesn't give a correct answer, you may need to use parentheses to establish the order of operation.
- }
Add Comment
Please, Sign In to add comment