作者 :alajl
日期: 2011-4-18
标题: Arduino第四次实验 —自动垃圾清除车 -中断代码调式
原文链接: http://blog.csdn.net/alajl
关于 attachInterrupt(),我想说点什么:
这个是一个中断函数,由于许多数字传感器的状态只有 0, 1,两种状态,所以用这个方法来触发一个事件,是相当好不过了,例如:
1、寻线传感器,从线内到了线外, 0到 1的改变,或者是 1到 0的改变,这个改变取决于你线的颜色,一般黑色是 0,白色是 1
2、红外障碍传感器:有障碍和没障碍的感应,同样是 0到 1的改变,或者是 1到 0的改变
所以这个函数,可以异步处理这些传感器的值,因此你不用不断的去轮询那些传感器的状态了,而把主程序释放出来去控制别的逻辑。
而 Arduino的控制板,只提供了 2个数字口的中断,请看红色的标注部分,所以如果你想用中断,那么 D2和 D3就不要被占用了。
它支持 4种模式的触发,如下:
LOW :只要是低电平就触发 CHANGE 只要电平的值改变了就出发,不管是 0到 1,还是 1到 0RISING 由低电平到高电平触发 FALLING 当高电平到低电平触发
该函数文档如下:(摘自 http://arduino.cc/en/Reference/AttachInterrupt)
Specifies a function to call when an external interrupt occurs. Replaces any previous function that was attached to the interrupt. Most Arduino boards have two external interrupts: numbers 0 (on digital pin 2) and 1 (on digital pin 3). The Arduino Mega has an additional four: numbers 2 (pin 21), 3 (pin 20), 4 (pin 19), and 5 (pin 18).
interrupt : the number of the interrupt (int )
function : the function to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine.
mode defines when the interrupt should be triggered. Four contstants are predefined as valid values:
LOW to trigger the interrupt whenever the pin is low, CHANGE to trigger the interrupt whenever the pin changes value RISING to trigger when the pin goes from low to high, FALLING for when the pin goes from high to low.
写在最后:
当我真机测试时,晕倒!由于电机的干扰,我的中断完全乱序,当我停止电机时,中断工作良好, google 一下,有可能是因为,我的电机板和传感板公用的一块电源,导致了这个原因,只是可能啊,所以建议是分开供电,而我手上确没有单独的多余供电模块(也就是 9V 电池和电池盒),所以就只好把代码改回了轮询的方式了,以后有机会在试试这个方式