最近买了个cubieboard和arduino,还不是很熟悉,今天下午就手头的东西,尽量多的用上,做了个很简单的功能----天亮自动播放音乐(其实就是闹钟。。。)
主要思路是这样的:
继电器接到arduino的pin2,光敏电阻触发继电器,向pin2发送一个高电平(其实这一步继电器完全是多余的,用光敏电阻自己就可以了,我就是想试试继电器。。。)
arduino检测到高电平后,向serial输出一个字符
cubieboard与arduino通过usb连接,在cubieboard上执行一段python程序,从serial端口读取数据,发现有内容,就播放音乐
好了,总体就是这么简单
连接图(好乱。。。):
arduino代码:
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
Serial.write('1');
delay(10000);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
python代码:
# -*- coding: utf-8 -*-
import os
import serial
def check_and_play(ser, music, max):
loop = 0
while loop < max:
data = ser.read(1)
n = ser.inWaiting() # look if there is more
if n:
data = data + ser.read(n) # and get as much as possible
os.system('mplayer '+music)
loop = loop + 1
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(
usage = "%prog [options] music_file_name",
description = "Play music when some char come from the serial port."
)
parser.add_option("-m", "--max_loop",
dest = "max_loop",
action = "store",
type = 'int',
help = "max loop times",
default = 5
parser.add_option("-b", "--baud",
dest = "baud",
action = "store",
type = 'int',
help = "serial baud",
default = 9600
)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error('music file name required as argument')
ser = serial.Serial('/dev/ttyACM0', options.baud)
music = args[0]
check_and_play(ser, music, options.max_loop)
print 'Exit...'
在cubieboard上执行下面的命令:
python2 play.py /root/music.mp3 -m 1
其中-m表示只播放一次音乐就退出
OK,当第一缕光线照射在桌面上时(我用的是手电筒测试的:D),动听的音乐就会自动想起来~~起床吧~~哈哈