我是Arduino和Matlab的新手。最近我正在用Arduino和Matlab做一个项目,当我尝试从Matlab向Arduino发送一些数据时,我发现了一个奇怪的事情。
这是我的代码
delete(instrfind({'Port'},{'COM3'}))
clear all
s = serial('COM3','BaudRate',9600);
% set(s,'BytesAvailableFcnCount',10);
set(s,'Terminator','CR');
fopen(s);
% sss=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
sss=2 ;
fwrite(s,sss,'char');
ss = fscanf(s,'%s');
ss
fclose(s);
我得到了这个
当我取消sss=input
行的注释时,无论我在数据中输入什么,都会成功发送。像这样:
我想知道如何在没有任何输入操作的情况下将数据发送到我的Arduino。
这是Arduino代码
int incomingByte = 0;
int motor2= 2 ;
int motor3= 3 ;
int motor4= 4 ;
int motor5= 5 ;
int motor6= 6 ;
int motor7= 7 ;
int motor8= 8 ;
int motor9= 9 ;
int matlabSignal;
int motorDir= 30 ;
void setup() {
// put your setup code here, to run once:
pinMode(motor2,OUTPUT);
pinMode(motor3,OUTPUT);
pinMode(motor4,OUTPUT);
pinMode(motor5,OUTPUT);
pinMode(motor6,OUTPUT);
pinMode(motor7,OUTPUT);
pinMode(motor8,OUTPUT);
pinMode(motor9,OUTPUT);
//en pin
pinMode(motorDir,OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>0){
incomingByte = Serial.read();
Serial.println(incomingByte,DEC);
matlabSignal = incomingByte;
}
/*
digitalWrite(motor2,HIGH);
digitalWrite(motor3,HIGH);
digitalWrite(motor4,HIGH);
*/
switch (matlabSignal){
case 1:
digitalWrite(motor9,HIGH);
break;
case 2:
digitalWrite(motor2,HIGH);
break;
case 3:
digitalWrite(motor3,HIGH);
break;
case 4:
digitalWrite(motor4,HIGH);
break;
case 5:
digitalWrite(motor5,HIGH);
break;
case 6:
digitalWrite(motor6,HIGH);
break;
case 7:
digitalWrite(motor7,HIGH);
break;
case 8:
digitalWrite(motor8,HIGH);
break;
}
}