Read rotary encoder data from Arduino

조회 수: 7 (최근 30일)
Alison
Alison 2017년 4월 20일
편집: Prashant Arora 2017년 4월 28일
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
}

답변 (1개)

Prashant Arora
Prashant Arora 2017년 4월 28일
편집: Prashant Arora 2017년 4월 28일
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

카테고리

Help CenterFile Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by