Read rotary encoder data from Arduino

30 vues (au cours des 30 derniers jours)
Alison
Alison le 20 Avr 2017
Hi all, I'm having trouble with setting up a Matlab program that will continuously read data from an Arduino. I have Arduino code for a quad encoder that outputs the angular displacement of a sphere that is fixed to rotate in one axis. I also have a line which will print the angle value to the Serial Monitor (Serial.print). I want Matlab to receive the angle values and trigger an LED when the sphere has moved the correct amount (e.g., once the ball has successfully rotated 30 degrees to the right from some reference point, an LED will flash).
My specific issue is getting Matlab to read this data. I know how to access Arduino from Matlab using arduino() and serial(), but I'm not sure how I can get Matlab to continuously read these angle values until I want it to stop. Do I use a while loop?
Here is my Arduino code, if it helps:
// Angle counter variables
#define chA A0
#define chB A1
int counter_pos = 0;
int angle = 0;
int aState;
int aLastState;
void setup() {
pinMode (chA,INPUT);
pinMode (chB,INPUT);
Serial.begin (9600);
aLastState = digitalRead(chA); // Reads the initial state of the chA
}
void loop() {
aState = digitalRead(chA); // Reads the "current" state of the chA
// If the previous and the current states of chA are different,
// then a pulse has occured.
if (aState != aLastState){
// If chB state != chA state, then the encoder is rotating CW
if (digitalRead(chB) != aState) {
counter_pos ++;
}
// If chB state = chA state, then the encoder is rotating CCW.
else {
counter_pos --;
}
// Reset counter_pos to 0 after 1 full revolution
if (abs(counter_pos) >= 100) {
counter_pos = 0;
}
// 1 cycle / CPR = 360 / 100 = 3.6
// Multiply by -3.6 b/c CW rotation moves counter ++, but angle --
angle = counter_pos * (-3.6);
// Reset angle to 0 after 1 full revolution
if (abs(angle) >= 360) {
if (angle < 0) {
angle = angle + 360;
}
else if (angle > 0) {
angle = angle - 360;
}
else {
angle = angle;
}
}
Serial.print("Angle: ");
Serial.println(angle);
}
aLastState = aState; // Updates previous state of chA with current state
}

Réponses (1)

Prashant Arora
Prashant Arora le 28 Avr 2017
Modifié(e) : Prashant Arora le 28 Avr 2017
You can use the functions like readDigitalPin to read data and can use a while loop to read it continuously. A very simple example can be
a = arduino();
value = readDigitalPin(a,pin);
while value
% Your code
end

Catégories

En savoir plus sur MATLAB Support Package for Arduino Hardware dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by