由於大學部學弟們的畢製要使用超音波,再度把去年寫的程式挖出來,
此版本可透過 Max/MSP 簡單使用 [u d] 指令送給 SimpleMessageSystem,即回傳接在 Arduino 的兩組 PING))) UltraSonic Range Finder 資訊(測距遠近)。
請先將以下程式碼燒錄至 Arduino 單晶片中,按照範例所設定,兩枚PING)))超音波的SGN(訊號腳位)請插在 Arduino 之 6 及 8 腳位
/*
Ultrasonic Sensor for SimpleMessageSystem
by dk
*/
#include "SimpleMessageSystem.h"
int ultraSoundSignal = 6; // Ultrasound signal pin
int ultraSoundSignal2 = 8; // Ultrasound signal pin
int val = 0;
int value, value2 = 0;
int ultrasoundValue = 0;
int timecount = 0; // Echo counter
int ledPin = 13; // LED connected to digital pin 13
void setup() {
beginSerial(9600); // Sets the baud rate to 9600
pinMode(ledPin, OUTPUT); // Sets the digital pin as output
}
void loop() {
finder(ultraSoundSignal, 'A');
finder(ultraSoundSignal2,'B');
if (messageBuild() > 0) {
// Checks to see if the message is complete and erases any previous messages
switch (messageGetChar()) { // Gets the first word as a character
case 'u': // Read value of ultrasonic range finder
readfinder();
break;
}
}
delay(100);
}
void finder(int pin, char identifier) {
timecount = 0;
val = 0;
pinMode(pin, OUTPUT); // Switch signalpin to output
/* Send low-high-low pulse to activate the trigger pulse of the sensor
* -------------------------------------------------------------------
*/
digitalWrite(pin, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(pin, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(pin, LOW); // Holdoff
/* Listening for echo pulse
* -------------------------------------------------------------------
*/
pinMode(pin, INPUT); // Switch signalpin to input
val = digitalRead(pin); // Append signal value to val
while(val == LOW) { // Loop until pin reads a high value
val = digitalRead(pin);
}
while(val == HIGH) { // Loop until pin reads a low value
val = digitalRead(pin);
timecount = timecount +1; // Count echo pulse time
}
/* Writing out values to the serial port
* -------------------------------------------------------------------
*/
ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue
switch(identifier) {
case 'A':
value = ultrasoundValue;
break;
case 'B':
value2 = ultrasoundValue;
break;
}
}
void readfinder(){
switch (messageGetChar()) { // Gets the next word as a character
case 'd': // READ digital pins
// read ultra range finder by dk
messageSendInt(value);
messageSendInt(value2);
messageEnd(); // Terminate the message being sent
break; // Break from the switch
}
}
Ultrasonic Sensor 讀取頻率為 100ms 一次,可自由更改。
關於超音波讀取這方式是參考 Arduino Playground 中的 Ping Ultrasonic Range Finder。
而以上程式碼為本站改寫前者與 SimpleMessageSystem,整合後部分程式碼。[下載] (此版本為測試用,使用 SimpleMessageSystem 的函式庫所撰寫,若需使用SimpleMessageSystem 其他功能如r d 1這種用法的函式,請參考 SimpleMessageSystem 範例原始碼自行加入)
。若有使用及修改之需求,請尊重作者並註明出處。