实践中理解接口概念,进而理解abstract class的概念,从串口接收命令,
数字1代表要发送数字按键信号,
数字2代表要发送raw原始wave信号(即类似正弦波信号),
数字3代表要发送模拟按键信号。
先上代码:
int const D_pin=2;
int const A_pin=A0;
int const A_pinKey=A1;
int g_inputIO=0; //init input IO
//get the value of wave from pin
byte D_valueOfWave(int pin){
byte sendByte;
if(digitalRead(pin)){
if(digitalRead(pin))
sendByte=100;
}
else {
sendByte=0;
}
return sendByte;
}
byte A_valueOfWave(int pin){
return map(analogRead(pin),0,1023,0,200);
}
void setup()
{
Serial.begin(9600);
pinMode(8,OUTPUT);
}
int recvByte=0;
byte sendByte;
void loop(){
// sendByte=map(analogRead(0),0,1023,0,200);//200以上的是其他的格式
// Serial.write(DvalueOfWave(g_inputIO));
//发送的是byte类型数据,0-255,当然可以0-200
//Serial.write(0xFF);
//Serial.write(sendByte);
//发送字符串201
// Serial.write(201);
// Serial.print("hello world");
// Serial.write('\n');
if(Serial.available()>0){
recvByte=Serial.read();
}
// lastRecvByte=recvByte;
switch(recvByte){
case 1:
digitalWrite(8,1);
g_inputIO=D_pin; //select pin9 as input IO
Serial.write(D_valueOfWave(g_inputIO));
break;
case 2:
digitalWrite(8,0);
g_inputIO=A_pin;
Serial.write(A_valueOfWave(g_inputIO));
break;
case 3:
digitalWrite(8,0);
g_inputIO=A_pinKey;
Serial.write(A_valueOfWave(g_inputIO));
break;
default:
// Serial.write(map(analogRead(0),0,1023,0,200));
Serial.write(D_valueOfWave(2));
break;
}
}
明显上面的代码不够优化,我们可以对上面的代码进行优化,把上面的程序分成几个模块:
1. 接收模块
2.信号产生模块
3.信号发送模块
在2.信号产生模块显然可以有 优化的空间,可以看到:在信号产生模块,信号都是从IO口出来的,我们可以定义一个接口interface:接口中有valueOfWave()函数,目的是使D_valueOfWave()和A_valueOfWave()函数都变成 valueOfWave(),将valueOfWave()函数在interface中不实现方法,而让另外两个类(一个数字发生器,一个模拟信号发生器)去继承这个接口,这样就可以让这两个类去实现valueOfWave()函数,也就是这两个类有了同样的方法valueOfWave()。这样就实现了接口了。
同样的也可以用abstract class来做这样的事情,因为抽象类是可以代替接口的。 interface和abstract class 的区别可以再网上搜搜。
next :就是实现这个接口。just do it !