我想通过串口将命令从MATLAB发送到Arduino,但我遇到了一些问题。我有一个需要左右旋转的步进电机,应该检查传感器是否到达应该的位置。
MATLAB连接代码:
function arduino = conn()
arduino = serial('COM4','BaudRate', 19200);
fopen(arduino);
pause(3);
end
和Arduino:
int pin = 2;
int pinValue;
int pinHuman = 3;
const int stepPin = A5;
const int dirPin = A4;
int readV;
int valueHuman;
int tim = 10000;
String vl1 = "";
String vl2 = "";
String vl = "";
void setup()
{
Serial.begin(19200);
Serial.setTimeout(10);
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(pin,INPUT_PULLUP);
pinMode(pinHuman,INPUT_PULLUP);
}
void loop()
{
valueHuman= digitalRead(pinHuman);
pinValue= digitalRead(pin);
vl1 = (String)valueHuman;
vl2 = (String)pinValue;
vl = "2" +vl1 + "" + vl2 + "3";
Serial.println(vl);
if (Serial.available() > 0)
{
readV= Serial.read();
if(readV== 48)
{
digitalWrite(dirPin,1);
rotateBase();
rotate(1);
}
if(readV== 49)
{
digitalWrite(dirPin,0);
rotateBase();
rotate(0);
}
}
}
void rotate(int d)
{
pinValue= digitalRead(pin);
while(pinValue== 0)
{
pinValue= digitalRead(pin);
digitalWrite(dirPin,d);
digitalWrite(stepPin,HIGH);
delay(5);
digitalWrite(stepPin,LOW);
delay(5);
pinValue= digitalRead(pin);
vl2 = (String)pinValue;
vl = "2" +vl1 + "" + vl2 + "3";
Serial.println(vl);
}
}
void rotateBase()
{
for(int i = 0; i<120; i++)
{
digitalWrite(stepPin,HIGH);
delayMicroseconds(tim);
tim = tim - 32;
digitalWrite(stepPin,LOW);
delayMicroseconds(tim);
tim = tim - 32;
pinValue= digitalRead(pin);
vl2 = (String)pinValue;
vl = "2" +vl1 + "" + vl2 + "3";
Serial.println(vl);
}
delayMicroseconds(tim-10);
for(int i = 0; i<560; i++)
{
digitalWrite(stepPin,HIGH);
delayMicroseconds(2300);
digitalWrite(stepPin,LOW);
delayMicroseconds(2300);
pinValue= digitalRead(pin);
vl2 = (String)pinValue;
vl = "2" +vl1 + "" + vl2 + "3";
Serial.println(vl);
}
delayMicroseconds(tim-10);
for(int i = 0; i<120; i++)
{
digitalWrite(stepPin,HIGH);
delayMicroseconds(tim);
tim = tim + 32;
digitalWrite(stepPin,LOW);
delayMicroseconds(tim);
tim = tim + 32;
pinValue= digitalRead(pin);
vl2 = (String)pinValue;
vl = "2" +vl1 + "" + vl2 + "3";
Serial.println(vl);
}
tim = 10000;
}
从MALAB通过序列写入Arduino:
function rotateBase(arduino,d)
sensors = [0,0];
fprintf(arduino,'%i',d);
pause(1)
readR = native2unicode(fread(arduino));
while sensors(2)~= 1
sensors =decodeMessage(readR); //decodeMessage(array) updates sensors array based on arduino output
readR = native2unicode(fread(arduino));
end
end
所以,如果我创建arduino连接:
arduino = conn;
如果我尝试沟通:
rotateBase(arduino,0);
命令后电机开始旋转3-5秒
fprintf(arduino,'%i',d);
已执行。我无法解决这个延迟问题,任何帮助都将不胜感激。