クラップセンサで遊んでみる
やりたいこと
クラップセンサであそんでみる
Hand Clap Sensor VM-Clap1 - Elmwood Electronics
クラップセンサを動かしてみる
Clap on 👏👏, Clap off 👏👏 - Elmwood Electronics
ここにすべてのっていた👆
抜粋
/* Verbal Machines VM-CLAP1 sensor test clap twice within ¼ second to turn Arduino LED on or off by scruss - 2017-06 for Elmwood Electronics - https://elmwood.to/ Sensor wiring: OUT → Arduino Pin 2 (use INPUT_PULLUP) PWR → 5V or 3.3V GND → GND */ #define CLAPIN 2 // pin must be interrupt-capable #define CLAP_DELAY 250 // max gap between claps to trigger volatile boolean clap = false; // clap detected state boolean led_state = false; // LED on/off state unsigned long clap_time, last_clap_time = 0; // clap time records void setup() { pinMode(CLAPIN, INPUT_PULLUP); pinMode(LED_BUILTIN, OUTPUT); // control built-in LED by clapping Serial.begin(9600); Serial.println("# Clap sensor test ..."); attachInterrupt( // register Interrupt Service Routine (ISR): digitalPinToInterrupt(CLAPIN), // pin to watch for interrupt heard_clap, // void function to call on interrupt FALLING // trigger interrupt on HIGH → LOW change ); } void loop() { digitalWrite(LED_BUILTIN, led_state); // set LED based on clap status if (clap) { // we heard a clap from ISR clap = false; // make sure we don't trigger again too soon last_clap_time = clap_time; // store old clap time clap_time = millis(); // note current clap time if (clap_time - last_clap_time < CLAP_DELAY) { // if two claps heard in ¼ s: Serial.println("clap clap!"); // notify led_state = !led_state; // and switch LED state } else { Serial.println("clap!"); // notify of only one clap } } } void heard_clap() { clap = true; // just set clap state in ISR }
シリアルモニタで確認
雑音にも強くて、いい感じ♪
PC側の実装
空ならempty、clapが発生したらclapを表示するスクリプト。
スレッドにして、mainで処理をしつつ、clapが来たらQueueに値が入りmainに渡している。
#!/usr/bin/env python # coding: utf-8 import serial import time import threading from Queue import Queue, Empty class Thread_cls(threading.Thread): def run(self): while True: read_ser = ser.readline().rstrip() q.put(read_ser) if __name__ == '__main__': print "hello serial!" ser = serial.Serial() ser.port = '/dev/ttyUSB0' ser.baudrate = 9600 ser.open() time.sleep(3.0) q = Queue() th = Thread_cls() th.daemon = True th.start() while True: try: task = q.get(False) print task except Empty: print "empty"