Thank you, the information you give me is very few.
I use your suggestions to edit this code:
#include <SD.h>
#include <SPI.h>
#include <Servo.h>
Servo myservo;
File myFile;
int pinCS = 10;
char record[360];
byte index = 0;
//int pos ;
#define outputA 2
#define outputB 3
int counter = 0;
int aState;
int aLastState;
void setup() {
myservo.attach(9);
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (9600);
pinMode(pinCS, OUTPUT);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
if (SD.begin())
{
Serial.println("SD card is ready to use.");
} else
{
Serial.println("SD card initialization failed");
return;
}
}
void loop() {
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
} else {
counter --;
}
Serial.print("Position: ");
Serial.println(counter);
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.println("Pulse out");
// Write to file
myFile.println(counter);
myFile.close(); // close the file
Serial.println("Done.");
}
// if the file didn't open, print an error:
else {
Serial.println("error opening test.txt");
}
}
char c = myFile.read();
if(c != '\r' && c != '\n') // Don't store the carriage return or line feed
{
if(index < 360) // Make sure that there is room to save the data
{
record[index++] = c;
record[index] = '\0'; // Add a NULL at the end
}
}
else
{
// Use the stored data
// Reset for the next record
index = 0;
record[index] = '\0';
}
int pos = atoi(record);
myservo.write(pos);
Serial.println(pos);
aLastState = aState;
}
But I do not understand why the value of the variable "pos" is always 0. I think the reason is because "pos" is variable and "record" is array. Can you help me?
Like you said, I would like to repeat the servo motions, but just the right angle and the time of movement is not important, I can regulate the speed of the servo when repeating. And I am very headache on this issue.