没人解答, 只好自力更生, 尝试了几种方案, 终于可以了, 但是还是有个bug, 就是当slider快速滑动时, 输出的数据不正常, 不知道为什么. 估计是上位机的原因. 以下是控制三盏灯的程序:- #include <SoftwareSerial.h>
- /*
- this sample tells us how to get the specific format demand from the Serial.
- Letter+intNum+@ different letter leads to different command, and how to pick up
- the intNum data from the string and then send it to the PWM pin.
- initiated by Jerry Zhong Jan-27-14
- */
- SoftwareSerial mySerial(2,3);
- String comdata = "";
- int numdata=0;
- int pinLED1=12;
- int pinLED2=11;
- int pinLED3=10;
- void setup(){
- Serial.begin(9600);
- mySerial.begin(9600);
- pinMode(pinLED1,OUTPUT);
- }
- void loop(){
- int i=0,j=1;
- while(mySerial.available()>0){
- comdata+=char(mySerial.read());
- delay(2);
- i++;
- //Serial.println(comdata);
- switch(comdata[0]){
- case 'a'://check if the first letter is 'a', if yes, get the PWM data
- if(comdata[i-1]=='@'){//to check if the string command is over
- //Serial.println(comdata);
- for (j=1;j<(comdata.length()-1);j++){
- numdata=numdata*10+(comdata[j]-'0');
- }//transfer the character into integer number which could be recognized by analogWrite();
- // Serial.println(j);
- Serial.println(numdata); //print out the data to check if it's correct
- analogWrite(pinLED1,numdata);//write the PWM data to the output pinLED.
- comdata="";//clean out the varial
- numdata=0;//clean out the numdata vairal
- }
- break;
- case 'b':
- if(comdata[i-1]=='@'){
- Serial.println(comdata);
- for(j=1;j<(comdata.length()-1);j++){
- numdata=numdata*10+(comdata[j]-'0');
- }
- Serial.println(numdata);
- analogWrite(pinLED2,numdata);
- comdata="";
- numdata=0;
- }
- break;
- case 'c':
- if(comdata[i-1]=='@'){
- Serial.println(comdata);
- for(j=1;j<(comdata.length()-1);j++){
- numdata=numdata*10+(comdata[j]-'0');
- }
- Serial.println(numdata);
- analogWrite(pinLED3,numdata);
- comdata="";
- numdata=0;
- }
- break;
-
- //default:
- //Serial.println(comdata);
- }
- }
- }
复制代码
点按slider运行正常, 输出的数据也是正常的. 快速滑动有时会出现非正常数据. |