I want to send PWM signal through an analog pin on Arduino Mega 2560 but MATLAB code is too slow
8 次查看(过去 30 天)
显示 更早的评论
Hi,
I want to make a code for controlling an stepper motor by an Arduino Mega 2560 and RAMPS 1.4 Shield, here is the mapping![RAMPS1.4schematic.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/217124/RAMPS1.4schematic.png)
![RAMPS1.4schematic.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/217124/RAMPS1.4schematic.png)
I want to control the X-motor for example, but it is controlled by analog pins. I programmed this code in Arduino IDE and it run very well, controlling the velocity of the stepper motor correctly:
// defines pins numbers
const int stepPin = A0;
const int dirPin = A1;
const int enablePin= 38;
void setup() {
// Sets the two pins as Outputs
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(enablePin,OUTPUT);
}
void loop() {
digitalWrite(enablePin,LOW);
digitalWrite(dirPin,HIGH);
// Makes 200 pulses for making one full cycle rotation
for(int x = 0; x < 16*200; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(150);
digitalWrite(stepPin,LOW);
delayMicroseconds(150);
}
digitalWrite(dirPin,LOW); //Changes the rotations direction
for(int x = 0; x < 16*200; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(150);
digitalWrite(stepPin,LOW);
delayMicroseconds(150);
}
}
But when i programmed this code in MATLAB, the stepper motor not run at the same velocity:
clear all;
a=arduino()
s=serial('COM7')
s.BaudRate=1000000
%A0 Step
configurePin(a,'A0','DigitalOutput');
%A1 Dir
configurePin(a,'A1','DigitalOutput');
%D38 Enable
configurePin(a,'D38','DigitalOutput');
writeDigitalPin(a, 'D38', 0);
writeDigitalPin(a, 'A0', 1);
PWM=150e-6;
for i=1:1:200*16
writeDigitalPin(a, 'A0', 1);
pause(PWM);
writeDigitalPin(a, 'A0', 0);
pause(PWM);
end
Someone knows how i could optimize the code ? or how i could use analog pins for digital outputs in functions as writePWMDutyCycle or PWM blocks in Simulink?
0 个评论
回答(1 个)
社区
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Arduino Hardware 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!