1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| /*************************************
Simple Arduino sweep sketch in microseconds
Note: The code is written in a simple blocking way and not optimized. It's a terrible
startingpoint to use in your own code!
PREREQUISITES:
- Know the lower, higher, and middle values of a servo
INSTRUCTIONS
- Fill in 'LowerPos', 'UpperPos' and 'MiddlePos'
- Upload sketch
- Set Serial Monitor to 115200 baud
- Set Serial Monitor to "Both NL & CR"
- Connect a servo to 'ServoPin' (default: pin 9)
- Press "Send" when the servo is positioned at Middle when you are asked
*************************************/
#include <Servo.h>
const byte ServoPin = 9;
//Enter the minimum limit pulse width (in ms)
const unsigned int LowerPos = 710;
//Enter the lower maximum pulse width (ms)
const unsigned int UpperPos = 2300;
//Middle Calculate Formula
const unsigned int MiddlePos = ((UpperPos - LowerPos) / 2) + LowerPos;
// 10,3 Microseconds = 1°
//####
// How to declare 10.3?
// const float StepSizeUs = 10,3;
// in void loop()=> for => pos += 10,3 and pos -= 10 don't work
//####
Servo testServo;
// variable to store the servo position
int pos = MiddlePos;
void setup() {
Serial.begin(115200);
testServo.writeMicroseconds(MiddlePos);
testServo.attach(ServoPin, LowerPos, UpperPos);
Serial.print("Lower value set to ");
Serial.println(LowerPos);
Serial.print("Upper value set to ");
Serial.println(UpperPos);
Serial.print("Middle value set to ");
Serial.println(MiddlePos);
Serial.println();
Serial.println("Servo on central location");
Serial.println("Press \"Send\" to continue");
while(!Serial.available());
clearSerialBuffer();
}
void loop() {
Serial.println("");
// goes from MiddlePos to UpperPos.
//#### (10,3 don't work result like 10) I would like to use StepSizeUs ####
//for (pos = MiddlePos; pos <= UpperPos; pos = (float)pos + 10.3) {
for (pos = MiddlePos; pos <= UpperPos; pos += 10) {
// in steps of 10 µS
testServo.writeMicroseconds(pos); // tell servo to go to position in variable 'pos'
delay(550);
Serial.print(pos);
//Serial.print(pos,2); //number after the decimal point
Serial.print(" ");
}
Serial.println("");
// goes from MiddlePos to LowerPos.
//#### (10,3 don't work result like 10) I would like to use StepSizeUs ####
//for (pos = MiddlePos; pos <= LowerPos; pos = (float)pos - 10.3) {
for (pos = MiddlePos; pos >= LowerPos; pos -= 10) {
testServo.writeMicroseconds(pos); // tell servo to go to position in variable 'pos'
delay(550);
Serial.print(pos);
//Serial.print(pos,2); //number after the decimal point
Serial.print(" ");
}
delay(6000);
}
void clearSerialBuffer(){
//clear serial buffer (but do nothing with it)
while(Serial.available()){
Serial.read();
}
} |
Partager