Yahoo 網站提供免費的氣象資訊,包括溫度、濕度、風速、風向、能見度和大氣壓力...等,我們可以使用 Processing 取回這些資訊,將它顯示在電腦螢幕上,或是傳給 Arduino 等互動裝置。
下載 Library
切換到網頁 https://github.com/onformative/YahooWeather ,點選右下角落的「Download ZIP」按鈕。或是點按網址 http://www.onformative.com/uploads/googleWeather/YahooWeather.zip 直接下載。
下載後解壓縮,並將他複製到 <Processing>/libraries 資料夾內。最後,別忘了要退出 Processing 再重新啟動。
開啟範例圖檔
內建的範例程式可以讓您快速感受到取得氣象資訊是多麼容易的一件事。
點按下拉功能表 File > Examples...,再展開 Contributed Libraries > Yahoo Weather 並雙擊 WeatherSimpleExample。
程式碼如下:
import com.onformative.yahooweather.*;
YahooWeather weather;
int updateIntervallMillis = 30000;
void setup() {
size(700, 300);
fill(0);
textFont(createFont("Arial", 14));
// 2442047 = the WOEID of Berlin
// use this site to find out about your WOEID : http://sigizmund.info/woeidinfo/
weather = new YahooWeather(this, 638242, "c", updateIntervallMillis);
}
void draw() {
weather.update();
background(255);
text("City: "+weather.getCityName()+"; Region: "+weather.getRegionName()+"; Country: "+weather.getCountryName()+"; Last updated: "+weather.getLastUpdated(), 20, 20);
text("Lon: "+weather.getLongitude()+" Lat: "+weather.getLatitude(), 20, 40);
text("WindTemp: "+weather.getWindTemperature()+" WindSpeed: "+weather.getWindSpeed()+" WindDirection: "+weather.getWindDirection(), 20, 60);
text("Humidity: "+weather.getHumidity()+" visibility: "+weather.getVisibleDistance()+" pressure: "+weather.getPressure()+" rising: "+weather.getRising(), 20, 80);
text("Sunrise: "+weather.getSunrise()+" sunset: "+weather.getSunset(), 20, 100);
}
public void keyPressed() {
if (key == 'q') {
weather.setWOEID(638242);
}
if (key == 'r') {
weather.setWOEID(44418);
}
}
點擊「Run」按鈕執行程式,就可以看到如下畫面:
目前顯示的是德國柏林(Berlin)的天氣,按下鍵盤的 'r' 鍵可以顯示英國倫敦(London)的天氣,按下鍵盤的 'q' 鍵可以再顯示柏林的天氣。
顯示台灣城市天氣資訊
要顯示各地區氣象資訊的關鍵是甚麼? 答案是「WOE ID」,只要改變 WOE ID 就可以顯示不同區域的氣象資訊。
範例程式中德國柏林(Berlin)的 WOEID 是 638242,英國倫敦(London)的 WOE ID 是 44418,那麼台北的 WOE ID 是多少呢? 您可以到這個網頁
https://weather.yahoo.com/taiwan/
選擇清單中的台灣各地區城市。
我們以台北為例,請您點按 Taipei City,在新頁面內再點按一次 Taipei City,網頁會跳到
https://weather.yahoo.com/taiwan/taipei-city/taipei-city-2306179/
網址最後面的數字就是台北的 WOE ID。
您可以用這組數字取代掉程式碼中的 638242,如下兩行:
weather = new YahooWeather(this, 638242, "c", updateIntervallMillis);
和
weather.setWOEID(638242);
如果要查其他地方的 WOEID,可以直接在搜尋欄位內鍵入地名或郵遞區號。
我們再以桃園為例,在搜尋欄位內鍵入「taoyuan」,就可以得到網址
https://weather.yahoo.com/taiwan/taoyuan-county/taoyuan-city-2298866/
所以桃園的 WOE ID 為 2298866。
最後,我們要顯示台北和桃園的氣象資訊,程式碼如下:
import com.onformative.yahooweather.*;
YahooWeather weather;
int updateIntervallMillis = 30000;
void setup() {
size(700, 300);
fill(0);
textFont(createFont("Arial", 14));
weather = new YahooWeather(this, 2298866, "c", updateIntervallMillis);
}
void draw() {
weather.update();
background(255);
text("City: "+weather.getCityName()+"; Region: "+weather.getRegionName()+"; Country: "+weather.getCountryName()+"; Last updated: "+weather.getLastUpdated(), 20, 20);
text("Lon: "+weather.getLongitude()+" Lat: "+weather.getLatitude(), 20, 40);
text("WindTemp: "+weather.getWindTemperature()+" WindSpeed: "+weather.getWindSpeed()+" WindDirection: "+weather.getWindDirection(), 20, 60);
text("Humidity: "+weather.getHumidity()+" visibility: "+weather.getVisibleDistance()+" pressure: "+weather.getPressure()+" rising: "+weather.getRising(), 20, 80);
text("Sunrise: "+weather.getSunrise()+" sunset: "+weather.getSunset(), 20, 100);
}
public void keyPressed() {
if (key == 'q') {
weather.setWOEID(2298866);
}
if (key == 'r') {
weather.setWOEID(2306179);
}
}
相關文章
Onformative http://www.onformative.com/lab/google-weather-library-for-processing/
Python Weather API https://code.google.com/p/python-weather-api/
2015年5月5日 星期二
2014年10月9日 星期四
啟動 Boa Constructor 時出現「AttributeError: 'module' object has no attribute 'NO_3D'」錯誤的解決方案
無法順利啟動 Boa Constructor 除了是 Python 、wxPython 和 Boa Constructor 這三者的版本匹配有問題之外,另外一個問題就是會出現「AttributeError: 'module' object has no attribute 'NO_3D'」這樣的錯誤訊息,這個應該是 Boa Constructor 本身的 Bug,原因是它無法對 wx.NO_3D 這個變數做解析。
解決的方法是到 Boa Constructor 資料夾內逐一對每一個 .py 程式檔找出有 wx.NO_3D 的文字將它用 wx.DEFAULT_FRAME_STYLE 來置換掉。
可能有wx.NO_3D 文字的程式如下:
boa.py
Preferences.py
prefs.rc.py
要注意的是千萬別使用編輯器(不管您使用的是何種編輯器)的置換功能,因為 Boa Constructor 的眾多程式當中有些程式碼使用到字典,例如:
style = {'wx.NO_3D': wx.NO_3D, ....}
此時你應該把值置換掉即可,如下:
style = {'wx.NO_3D': wx.DEFAULT_FRAME_STYLE, ....}
我的方法
我是使用 pyScripter 編輯器打開 Boa.py 然後執行它,在執行的過程當中若有出現錯誤,pyScripter 會將有問題的程式檔案開啟並標註錯誤的位置,此時就可以很容易找到 wx.NO_3D 的位置,於是您就可以用 wx.DEFAULT_FRAME_STYLE 置換它。
解決的方法是到 Boa Constructor 資料夾內逐一對每一個 .py 程式檔找出有 wx.NO_3D 的文字將它用 wx.DEFAULT_FRAME_STYLE 來置換掉。
可能有wx.NO_3D 文字的程式如下:
boa.py
Preferences.py
prefs.rc.py
要注意的是千萬別使用編輯器(不管您使用的是何種編輯器)的置換功能,因為 Boa Constructor 的眾多程式當中有些程式碼使用到字典,例如:
style = {'wx.NO_3D': wx.NO_3D, ....}
此時你應該把值置換掉即可,如下:
style = {'wx.NO_3D': wx.DEFAULT_FRAME_STYLE, ....}
我的方法
我是使用 pyScripter 編輯器打開 Boa.py 然後執行它,在執行的過程當中若有出現錯誤,pyScripter 會將有問題的程式檔案開啟並標註錯誤的位置,此時就可以很容易找到 wx.NO_3D 的位置,於是您就可以用 wx.DEFAULT_FRAME_STYLE 置換它。
2014年9月22日 星期一
安裝 ConfigObj
ConfigObj Library 可以幫您很容易存取 .ini 檔。
官網 https://pypi.python.org/pypi/configobj
下載
切換網頁到 https://pypi.python.org/pypi/configobj/5.0.6,點擊「Download」綠色按鈕。
安裝
解壓縮 configobj-5.0.6.tar.gz,開啟「命令提示字元」視窗,鍵入
cd \configobj-5.0.6
再鍵入
python setup.py install
參考網站
http://www.voidspace.org.uk/python/configobj.html#configobj-in-the-real-world
官網 https://pypi.python.org/pypi/configobj
下載
切換網頁到 https://pypi.python.org/pypi/configobj/5.0.6,點擊「Download」綠色按鈕。
安裝
解壓縮 configobj-5.0.6.tar.gz,開啟「命令提示字元」視窗,鍵入
cd \configobj-5.0.6
再鍵入
python setup.py install
參考網站
http://www.voidspace.org.uk/python/configobj.html#configobj-in-the-real-world
2014年9月19日 星期五
安裝 kivy - python for android
從現在起,您可以在 KIVY 架構下使用 Python 語言建立 Android App 了。
官網 http://kivy.org/#home
下載
https://github.com/kivy/python-for-android
教學影片
https://www.youtube.com/watch?v=F7UKmK9eQLY
官網 http://kivy.org/#home
下載
https://github.com/kivy/python-for-android
教學影片
https://www.youtube.com/watch?v=F7UKmK9eQLY
2014年9月13日 星期六
安裝 wxGlade
wxGlade 是一個利用 wxPython 工具箱製作而成的使用者圖形介面建構器。目前,它也可以產生 Python、C + +、Perl、Lisp 和 XRC(wxWidgets的“XML資源)的使用者圖形介面代碼。
官網 http://wxglade.sourceforge.net/
下載
切換網頁到 http://sourceforge.net/projects/wxglade/,點擊螢幕中央的「Download」綠色按鈕。
安裝
雙擊 wxGlade-SAE-0.6.8-setup.exe,然後依照視窗指示進行即可。
教學
官網 http://wxglade.sourceforge.net/tutorial.php
程式語言教學誌 http://pydoing.blogspot.tw/2009/01/docsdemowxglade.html
官網 http://wxglade.sourceforge.net/
下載
切換網頁到 http://sourceforge.net/projects/wxglade/,點擊螢幕中央的「Download」綠色按鈕。
安裝
雙擊 wxGlade-SAE-0.6.8-setup.exe,然後依照視窗指示進行即可。
教學
官網 http://wxglade.sourceforge.net/tutorial.php
程式語言教學誌 http://pydoing.blogspot.tw/2009/01/docsdemowxglade.html
2014年9月12日 星期五
安裝 Win32 Extensions
Win32 Extensions 提供一些讓您存取 Windows 作業系統的功能,例如讀取磁碟機資訊...等。
官網 http://starship.python.net/crew/mhammond/
下載
切換網頁到 http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/,點擊 pywin32-219.win32-py3.5.exe 。
安裝
雙擊 pywin32-219.win32-py3.5.exe ,然後依照視窗內的指示安裝即可。
官網 http://starship.python.net/crew/mhammond/
下載
切換網頁到 http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/,點擊 pywin32-219.win32-py3.5.exe 。
安裝
雙擊 pywin32-219.win32-py3.5.exe ,然後依照視窗內的指示安裝即可。
2014年9月9日 星期二
安裝 PyKE
PyKE(Python Knowledge Engine) 是一個知識引擎套件,無論是正向鏈接或反向鏈規則(包括Python代碼)都可以被編譯成 Python,還可以自動組合成 Python 函數以外的程式,並且附加到反向鏈規則之中。
官網 http://pyke.sourceforge.net/
下載
切換網頁到 http://sourceforge.net/projects/pyke/?source=typ_redirect,點擊螢幕中央的「Download」綠色按鈕。
安裝
將 pyke-1.1.1.zip 解壓縮,開啟「命令列提示視窗」,鍵入 python setup.py install。
官網 http://pyke.sourceforge.net/
下載
切換網頁到 http://sourceforge.net/projects/pyke/?source=typ_redirect,點擊螢幕中央的「Download」綠色按鈕。
安裝
將 pyke-1.1.1.zip 解壓縮,開啟「命令列提示視窗」,鍵入 python setup.py install。
2014年9月4日 星期四
安裝 Visual Tkinter Python IDE
這是一個視覺化的整合操作環境,您可以用它來建立圖形化的使用者介面。
下載
切換至網頁 http://sourceforge.net/projects/visualtkinter/,點擊畫面中央的「Download」綠色按鈕。
安裝
解壓縮 Visual Python 2v0.12.2554.zip,雙擊 setup.exe,然後依照視窗指示進行即可。
安裝完成後會在桌面產生一個捷徑圖示,如下圖:
雙擊捷徑您就可以看到 Visual Tkinter 的整合介面,如下圖:
下載
切換至網頁 http://sourceforge.net/projects/visualtkinter/,點擊畫面中央的「Download」綠色按鈕。
安裝
解壓縮 Visual Python 2v0.12.2554.zip,雙擊 setup.exe,然後依照視窗指示進行即可。
安裝完成後會在桌面產生一個捷徑圖示,如下圖:
安裝 PythonCard
PythonCard 是一個以 wxPython 為基礎的使用者介面建構器。
官網 http://pythoncard.sourceforge.net/index.html
下載
切換網頁至 http://sourceforge.net/projects/pythoncard/files/,然後點擊淡藍色的 Download PythonCard-0.8.2.win32.exe (3.5 MB) 字樣。
安裝
快擊兩下 PythonCard-0.8.2.win32.exe,然後依照視窗指示安裝即可。
檢查是否已正確安裝
開啟範例檔案 <Python>\Lib\site-packages\PythonCard\samples\minimal\minimal.py 並執行它,如果有看到如下視窗表示已正確安裝。
查看所有的視窗工具
開啟範例檔案 <Python>\Lib\site-packages\PythonCard\samples\widgets\widgets.py 並執行它,您將可以看到如下視窗。
或是您也可以到這兒逐一檢視視窗工具有哪些:
http://pythoncard.sourceforge.net/samples/addresses.html
官網 http://pythoncard.sourceforge.net/index.html
下載
切換網頁至 http://sourceforge.net/projects/pythoncard/files/,然後點擊淡藍色的 Download PythonCard-0.8.2.win32.exe (3.5 MB) 字樣。
安裝
快擊兩下 PythonCard-0.8.2.win32.exe,然後依照視窗指示安裝即可。
檢查是否已正確安裝
開啟範例檔案 <Python>\Lib\site-packages\PythonCard\samples\minimal\minimal.py 並執行它,如果有看到如下視窗表示已正確安裝。
查看所有的視窗工具
開啟範例檔案 <Python>\Lib\site-packages\PythonCard\samples\widgets\widgets.py 並執行它,您將可以看到如下視窗。
http://pythoncard.sourceforge.net/samples/addresses.html
2014年9月2日 星期二
註解
註解是不會被執行的,為代碼加註說明是一件好的習慣,這些註解能夠讓您的程式更容易閱讀和維護。
單行註解
假設您有如下之代碼:
a = 5
b = 2
c = a + b
print c
您想把 c = a + b 這一行改成 c = a - b,但又不想把 c = a + b 這一行刪除掉,則您可以在該行前面加一個「 #」字元,如下:
a = 5
b = 2
#c = a + b
c = a - b
print c
註解區塊
假設您有如下之代碼:
a = 5
b = 2
print a + b
print a - b
print a * b
print a / b
而您想把一整個區塊的代碼做註解,則您可以在該區塊首尾各加一個「'''」字元,如下:
a = 5
b = 2
'''
print a + b
print a - b
print a * b
'''
print a / b
單行註解
假設您有如下之代碼:
a = 5
b = 2
c = a + b
print c
您想把 c = a + b 這一行改成 c = a - b,但又不想把 c = a + b 這一行刪除掉,則您可以在該行前面加一個「 #」字元,如下:
a = 5
b = 2
#c = a + b
c = a - b
print c
註解區塊
假設您有如下之代碼:
a = 5
b = 2
print a + b
print a - b
print a * b
print a / b
而您想把一整個區塊的代碼做註解,則您可以在該區塊首尾各加一個「'''」字元,如下:
a = 5
b = 2
'''
print a + b
print a - b
print a * b
'''
print a / b
2014年9月1日 星期一
Python-Arduino-Command-API
Python-Arduino-Command-API 提供您另外一種方式讓 Python 與 Arduino 通訊。
下載
切換網頁到 https://github.com/thearn/Python-Arduino-Command-API,點擊右下角落的 Download ZIP 按鈕。
安裝
下載後解壓縮,然後開啟「命令提示字元」視窗,切換到你解壓縮後的路徑,鍵入
python setup.py build install
範例
讓 Arduino 的 pin13 LED 閃爍。
Python Code
#!/usr/bin/env python
"""
Blinks an LED on digital pin 13
in 1 second intervals
"""
from Arduino import Arduino
import time
board = Arduino('9600') #plugged in via USB, serial com at rate 9600
while True:
board.digitalWrite(13, "LOW")
time.sleep(1)
board.digitalWrite(13, "HIGH")
time.sleep(1)
Arduino Code
下載
切換網頁到 https://github.com/thearn/Python-Arduino-Command-API,點擊右下角落的 Download ZIP 按鈕。
安裝
下載後解壓縮,然後開啟「命令提示字元」視窗,切換到你解壓縮後的路徑,鍵入
python setup.py build install
範例
讓 Arduino 的 pin13 LED 閃爍。
Python Code
#!/usr/bin/env python
"""
Blinks an LED on digital pin 13
in 1 second intervals
"""
from Arduino import Arduino
import time
board = Arduino('9600') #plugged in via USB, serial com at rate 9600
while True:
board.digitalWrite(13, "LOW")
time.sleep(1)
board.digitalWrite(13, "HIGH")
time.sleep(1)
Arduino Code
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Servo.h>
#include <EEPROM.h>
SoftwareSerial *sserial = NULL;
Servo servos[8];
int servo_pins[] = {0, 0, 0, 0, 0, 0, 0, 0};
boolean connected = false;
int Str2int (String Str_value)
{
char buffer[10]; //max length is three units
Str_value.toCharArray(buffer, 10);
int int_value = atoi(buffer);
return int_value;
}
void split(String results[], int len, String input, char spChar) {
String temp = input;
for (int i=0; i<len; i++) {
int idx = temp.indexOf(spChar);
results[i] = temp.substring(0,idx);
temp = temp.substring(idx+1);
}
}
void Version(){
Serial.println("version");
}
uint8_t readCapacitivePin(String data) {
int pinToMeasure = Str2int(data);
// readCapacitivePin
// Input: Arduino pin number
// Output: A number, from 0 to 17 expressing
// how much capacitance is on the pin
// When you touch the pin, or whatever you have
// attached to it, the number will get higher
// http://playground.arduino.cc/Code/CapacitiveSensor
//
// Variables used to translate from Arduino to AVR pin naming
volatile uint8_t* port;
volatile uint8_t* ddr;
volatile uint8_t* pin;
// Here we translate the input pin number from
// Arduino pin number to the AVR PORT, PIN, DDR,
// and which bit of those registers we care about.
byte bitmask;
port = portOutputRegister(digitalPinToPort(pinToMeasure));
ddr = portModeRegister(digitalPinToPort(pinToMeasure));
bitmask = digitalPinToBitMask(pinToMeasure);
pin = portInputRegister(digitalPinToPort(pinToMeasure));
// Discharge the pin first by setting it low and output
*port &= ~(bitmask);
*ddr |= bitmask;
delay(1);
// Make the pin an input with the internal pull-up on
*ddr &= ~(bitmask);
*port |= bitmask;
// Now see how long the pin to get pulled up. This manual unrolling of the loop
// decreases the number of hardware cycles between each read of the pin,
// thus increasing sensitivity.
uint8_t cycles = 17;
if (*pin & bitmask) { cycles = 0;}
else if (*pin & bitmask) { cycles = 1;}
else if (*pin & bitmask) { cycles = 2;}
else if (*pin & bitmask) { cycles = 3;}
else if (*pin & bitmask) { cycles = 4;}
else if (*pin & bitmask) { cycles = 5;}
else if (*pin & bitmask) { cycles = 6;}
else if (*pin & bitmask) { cycles = 7;}
else if (*pin & bitmask) { cycles = 8;}
else if (*pin & bitmask) { cycles = 9;}
else if (*pin & bitmask) { cycles = 10;}
else if (*pin & bitmask) { cycles = 11;}
else if (*pin & bitmask) { cycles = 12;}
else if (*pin & bitmask) { cycles = 13;}
else if (*pin & bitmask) { cycles = 14;}
else if (*pin & bitmask) { cycles = 15;}
else if (*pin & bitmask) { cycles = 16;}
// Discharge the pin again by setting it low and output
// It's important to leave the pins low if you want to
// be able to touch more than 1 sensor at a time - if
// the sensor is left pulled high, when you touch
// two sensors, your body will transfer the charge between
// sensors.
*port &= ~(bitmask);
*ddr |= bitmask;
//return cycles;
Serial.println(cycles);
}
void Tone(String data){
int idx = data.indexOf('%');
int len = Str2int(data.substring(0,idx));
String data2 = data.substring(idx+1);
int idx2 = data2.indexOf('%');
int pin = Str2int(data2.substring(0,idx2));
String data3 = data2.substring(idx2+1);
String melody[len*2];
split(melody,len*2,data3,'%');
for (int thisNote = 0; thisNote < len; thisNote++) {
int noteDuration = 1000/Str2int(melody[thisNote+len]);
int note = Str2int(melody[thisNote]);
tone(pin, note, noteDuration);
int pause = noteDuration * 1.30;
delay(pause);
noTone(pin);
}
}
void ToneNo(String data){
int pin = Str2int(data);
noTone(pin);
}
void DigitalHandler(int mode, String data){
int pin = Str2int(data);
if(mode<=0){ //read
Serial.println(digitalRead(pin));
}else{
if(pin <0){
digitalWrite(-pin,LOW);
}else{
digitalWrite(pin,HIGH);
}
//Serial.println('0');
}
}
void AnalogHandler(int mode, String data){
if(mode<=0){ //read
int pin = Str2int(data);
Serial.println(analogRead(pin));
}else{
String sdata[2];
split(sdata,2,data,'%');
int pin = Str2int(sdata[0]);
int pv = Str2int(sdata[1]);
analogWrite(pin,pv);
}
}
void ConfigurePinHandler(String data){
int pin = Str2int(data);
if(pin <=0){
pinMode(-pin,INPUT);
}else{
pinMode(pin,OUTPUT);
}
}
void shiftOutHandler(String data) {
String sdata[4];
split(sdata, 4, data, '%');
int dataPin = sdata[0].toInt();
int clockPin = sdata[1].toInt();
String bitOrderName = sdata[2];
byte value = (byte)(sdata[3].toInt());
if (bitOrderName == "MSBFIRST") {
shiftOut(dataPin, clockPin, MSBFIRST, value);
} else {
shiftOut(dataPin, clockPin, LSBFIRST, value);
}
}
void shiftInHandler(String data) {
String sdata[3];
split(sdata, 3, data, '%');
int dataPin = sdata[0].toInt();
int clockPin = sdata[1].toInt();
String bitOrderName = sdata[2];
int incoming;
if (bitOrderName == "MSBFIRST") {
incoming = (int)shiftIn(dataPin, clockPin, MSBFIRST);
} else {
incoming = (int)shiftIn(dataPin, clockPin, LSBFIRST);
}
Serial.println(incoming);
}
void SS_set(String data){
delete sserial;
String sdata[3];
split(sdata,3,data,'%');
int rx_ = Str2int(sdata[0]);
int tx_ = Str2int(sdata[1]);
int baud_ = Str2int(sdata[2]);
sserial = new SoftwareSerial(rx_, tx_);
sserial->begin(baud_);
Serial.println("ss OK");
}
void SS_write(String data) {
int len = data.length()+1;
char buffer[len];
data.toCharArray(buffer,len);
Serial.println("ss OK");
sserial->write(buffer);
}
void SS_read(String data) {
char c = sserial->read();
Serial.println(c);
}
void pulseInHandler(String data){
int pin = Str2int(data);
long duration;
if(pin <=0){
pinMode(-pin, INPUT);
duration = pulseIn(-pin, LOW);
}else{
pinMode(pin, INPUT);
duration = pulseIn(pin, HIGH);
}
Serial.println(duration);
}
void pulseInSHandler(String data){
int pin = Str2int(data);
long duration;
if(pin <=0){
pinMode(-pin, OUTPUT);
digitalWrite(-pin, HIGH);
delayMicroseconds(2);
digitalWrite(-pin, LOW);
delayMicroseconds(5);
digitalWrite(-pin, HIGH);
pinMode(-pin, INPUT);
duration = pulseIn(-pin, LOW);
}else{
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(2);
digitalWrite(pin, HIGH);
delayMicroseconds(5);
digitalWrite(pin, LOW);
pinMode(pin, INPUT);
duration = pulseIn(pin, HIGH);
}
Serial.println(duration);
}
void SV_add(String data) {
String sdata[3];
split(sdata,3,data,'%');
int pin = Str2int(sdata[0]);
int min = Str2int(sdata[1]);
int max = Str2int(sdata[2]);
int pos = -1;
for (int i = 0; i<8;i++) {
if (servo_pins[i] == pin) { //reset in place
servos[pos].detach();
servos[pos].attach(pin, min, max);
servo_pins[pos] = pin;
Serial.println(pos);
return;
}
}
for (int i = 0; i<8;i++) {
if (servo_pins[i] == 0) {pos = i;break;} // find spot in servo array
}
if (pos == -1) {;} //no array position available!
else {
servos[pos].attach(pin, min, max);
servo_pins[pos] = pin;
Serial.println(pos);
}
}
void SV_remove(String data) {
int pos = Str2int(data);
servos[pos].detach();
servo_pins[pos] = 0;
}
void SV_read(String data) {
int pos = Str2int(data);
int angle;
angle = servos[pos].read();
Serial.println(angle);
}
void SV_write(String data) {
String sdata[2];
split(sdata,2,data,'%');
int pos = Str2int(sdata[0]);
int angle = Str2int(sdata[1]);
servos[pos].write(angle);
}
void SV_write_ms(String data) {
String sdata[2];
split(sdata,2,data,'%');
int pos = Str2int(sdata[0]);
int uS = Str2int(sdata[1]);
servos[pos].writeMicroseconds(uS);
}
void sizeEEPROM() {
Serial.println(E2END + 1);
}
void EEPROMHandler(int mode, String data) {
String sdata[2];
split(sdata, 2, data, '%');
if (mode == 0) {
EEPROM.write(Str2int(sdata[0]), Str2int(sdata[1]));
} else {
Serial.println(EEPROM.read(Str2int(sdata[0])));
}
}
void SerialParser(void) {
char readChar[64];
Serial.readBytesUntil(33,readChar,64);
String read_ = String(readChar);
//Serial.println(readChar);
int idx1 = read_.indexOf('%');
int idx2 = read_.indexOf('$');
// separate command from associated data
String cmd = read_.substring(1,idx1);
String data = read_.substring(idx1+1,idx2);
// determine command sent
if (cmd == "dw") {
DigitalHandler(1, data);
}
else if (cmd == "dr") {
DigitalHandler(0, data);
}
else if (cmd == "aw") {
AnalogHandler(1, data);
}
else if (cmd == "ar") {
AnalogHandler(0, data);
}
else if (cmd == "pm") {
ConfigurePinHandler(data);
}
else if (cmd == "ps") {
pulseInSHandler(data);
}
else if (cmd == "pi") {
pulseInHandler(data);
}
else if (cmd == "ss") {
SS_set(data);
}
else if (cmd == "sw") {
SS_write(data);
}
else if (cmd == "sr") {
SS_read(data);
}
else if (cmd == "sva") {
SV_add(data);
}
else if (cmd == "svr") {
SV_read(data);
}
else if (cmd == "svw") {
SV_write(data);
}
else if (cmd == "svwm") {
SV_write_ms(data);
}
else if (cmd == "svd") {
SV_remove(data);
}
else if (cmd == "version") {
Version();
}
else if (cmd == "to") {
Tone(data);
}
else if (cmd == "nto") {
ToneNo(data);
}
else if (cmd == "cap") {
readCapacitivePin(data);
}
else if (cmd == "so") {
shiftOutHandler(data);
}
else if (cmd == "si") {
shiftInHandler(data);
}
else if (cmd == "eewr") {
EEPROMHandler(0, data);
}
else if (cmd == "eer") {
EEPROMHandler(1, data);
}
else if (cmd == "sz") {
sizeEEPROM();
}
}
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
void loop() {
SerialParser();
}
the Micro Python board
Micro Python 控制板是由劍橋大學理論物理學家喬治·達米安(Damien George)所研發出來的, 它比 Arduino 更強大,比 Raspberry PI 更簡易,你只要將 Python 的程式貼到控制板內即可。
它提供一個 USB 接口,可以讓您連接電腦,因為它是屬於跨平台的,所以 Windows、Mac 或 Linux 作業系統都可以使用。
原文詳 http://www.wired.co.uk/news/archive/2013-12/06/micro-python
安裝 MySQL for Python
如果您想有計畫地處理大量資料,我想您需要一個資料庫軟體來處理這件事情,而 MySQL 就是最佳的選擇之一。
目前 MySQL 為 3.23 版,支援 Python 2.4~2.7 版,未來才會支援 Python 3.x 版。
下載
切換到下載頁 http://sourceforge.net/projects/mysql-python/?source=dlp,點擊綠色的 Download 按鈕。
安裝
雙擊 MySQL-python-1.2.4b4.win32-py2.7.exe,然後依照視窗內的指示進行安裝。
首先用 MySQL 建立一個含有溫濕度數據的氣象資料表,如下:
create table weatherData (
weatherDataID int(11) AUTO_INCREMENT NOT NULL,
humidity decimal(4,2) NOT NULL,
tempC decimal(4,2) NOT NULL,
constraint weatherData_PK primary key (weatherDataID)
);
Python Code
#!/usr/bin/python
import serial
import MySQLdb
#establish connection to MySQL. You'll have to change this for your database.
dbConn = MySQLdb.connect("localhost","database_username","password","database_name") or die ("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()
device = 'COM5' #this will have to be changed to the serial port you are using
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline() #read the data from the arduino
pieces = data.split("\t") #split the data by the tab
#Here we are going to insert the data into the Database
try:
cursor.execute("INSERT INTO weatherData (humidity,tempC) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit() #commit the insert
cursor.close() #close the cursor
except MySQLdb.IntegrityError:
print "failed to insert data"
finally:
cursor.close() #close just incase it failed
except:
print "Failed to get data from Arduino!"
目前 MySQL 為 3.23 版,支援 Python 2.4~2.7 版,未來才會支援 Python 3.x 版。
下載
切換到下載頁 http://sourceforge.net/projects/mysql-python/?source=dlp,點擊綠色的 Download 按鈕。
安裝
雙擊 MySQL-python-1.2.4b4.win32-py2.7.exe,然後依照視窗內的指示進行安裝。
首先用 MySQL 建立一個含有溫濕度數據的氣象資料表,如下:
create table weatherData (
weatherDataID int(11) AUTO_INCREMENT NOT NULL,
humidity decimal(4,2) NOT NULL,
tempC decimal(4,2) NOT NULL,
constraint weatherData_PK primary key (weatherDataID)
);
Python Code
#!/usr/bin/python
import serial
import MySQLdb
#establish connection to MySQL. You'll have to change this for your database.
dbConn = MySQLdb.connect("localhost","database_username","password","database_name") or die ("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()
device = 'COM5' #this will have to be changed to the serial port you are using
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline() #read the data from the arduino
pieces = data.split("\t") #split the data by the tab
#Here we are going to insert the data into the Database
try:
cursor.execute("INSERT INTO weatherData (humidity,tempC) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit() #commit the insert
cursor.close() #close the cursor
except MySQLdb.IntegrityError:
print "failed to insert data"
finally:
cursor.close() #close just incase it failed
except:
print "Failed to get data from Arduino!"
2014年8月29日 星期五
安裝 Boa Constructor
Boa Constructor 是一個以 wxPython 為基礎的使用者介面建構器。
官網 http://boa-constructor.sourceforge.net/
下載
切換至下載頁面 http://sourceforge.net/projects/boa-constructor/files/,點擊淡藍色的「Download boa-constructor-0.6.1.src.win32.exe (13.9 MB)」字樣。
安裝
雙擊 boa-constructor-0.6.1.src.win32.exe,然後依照指示安裝。
接著在 C:\Python27 內新增一個文字文件,在裏面鍵入
python C:\Python27\Lib\site-packages\boa-constructor\Boa.py
如下圖
儲存檔案並將「新增文字文件.txt」更名為「Boa.bat」。
最後再為 Boa.bat 建立一個桌面捷徑,以後只要雙擊 Boa 捷徑圖示,即可啟動 Boa Constructor。
溫馨提示:
1. 如果您的作業系統是 Windows7 (含)以上版本,則您應該以系統管理者身分執行 Boa 捷徑。
2. 如果在啟動過程中顯示無法找到 wx.NO_3D 模組,則您可以分別找出模組內文中有 「wx.NO_3D」文字的地方以「wx.DEFAULT_FRAME_STYLE」取代。
3. 如果無法存取「C:\Documents and Settings」資料夾,您可以依照網頁 http://www.minwt.com/pc/5502.html 的指示解除這個限制。
教學影片
1. https://www.youtube.com/watch?v=Im2odZllHXM
2. https://www.youtube.com/watch?v=_vqZeyZfap8
3. http://showmedo.com/videotutorials/video?name=4010000&fromSeriesID=401
官網 http://boa-constructor.sourceforge.net/
下載
切換至下載頁面 http://sourceforge.net/projects/boa-constructor/files/,點擊淡藍色的「Download boa-constructor-0.6.1.src.win32.exe (13.9 MB)」字樣。
安裝
雙擊 boa-constructor-0.6.1.src.win32.exe,然後依照指示安裝。
接著在 C:\Python27 內新增一個文字文件,在裏面鍵入
python C:\Python27\Lib\site-packages\boa-constructor\Boa.py
如下圖
儲存檔案並將「新增文字文件.txt」更名為「Boa.bat」。
最後再為 Boa.bat 建立一個桌面捷徑,以後只要雙擊 Boa 捷徑圖示,即可啟動 Boa Constructor。
溫馨提示:
1. 如果您的作業系統是 Windows7 (含)以上版本,則您應該以系統管理者身分執行 Boa 捷徑。
2. 如果在啟動過程中顯示無法找到 wx.NO_3D 模組,則您可以分別找出模組內文中有 「wx.NO_3D」文字的地方以「wx.DEFAULT_FRAME_STYLE」取代。
3. 如果無法存取「C:\Documents and Settings」資料夾,您可以依照網頁 http://www.minwt.com/pc/5502.html 的指示解除這個限制。
教學影片
1. https://www.youtube.com/watch?v=Im2odZllHXM
2. https://www.youtube.com/watch?v=_vqZeyZfap8
3. http://showmedo.com/videotutorials/video?name=4010000&fromSeriesID=401
2014年8月28日 星期四
安裝 wxEasyGUI
wxEasyGUI 可以讓您更簡單地使用 wxPython 的視窗工具。
以 MessageBox 為例,如果要顯示如下畫面
使用 wxPython 需要寫這麼多行:
而使用 WxEasyGUI 只需要 2 行:
import wxEasyGUI as eg
s = eg.MessageDialog('aaaa\nbbb') # s = 'ok'
由此可見 wxEasyGUI 的確是非常地好用。
安裝需求
1. Python
2. WxPython
下載
切換網頁到 http://sourceforge.net/projects/wxeasygui/?source=typ_redirect,點擊綠色的 Download 按鈕。
安裝
以 MessageBox 為例,如果要顯示如下畫面
使用 wxPython 需要寫這麼多行:
import wx
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
wx.FutureCall(5000, self.ShowMessage)
self.SetSize((300, 200))
self.SetTitle('Message box')
self.Centre()
self.Show(True)
def ShowMessage(self):
wx.MessageBox('aaaa\nbbb', 'Info',
wx.OK | wx.ICON_INFORMATION)
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
wx.FutureCall(5000, self.ShowMessage)
self.SetSize((300, 200))
self.SetTitle('Message box')
self.Centre()
self.Show(True)
def ShowMessage(self):
wx.MessageBox('aaaa\nbbb', 'Info',
wx.OK | wx.ICON_INFORMATION)
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
而使用 WxEasyGUI 只需要 2 行:
import wxEasyGUI as eg
s = eg.MessageDialog('aaaa\nbbb') # s = 'ok'
由此可見 wxEasyGUI 的確是非常地好用。
安裝需求
1. Python
2. WxPython
下載
切換網頁到 http://sourceforge.net/projects/wxeasygui/?source=typ_redirect,點擊綠色的 Download 按鈕。
安裝
將 wxEasyGUI.py 複製到 python2.7\Lib 底下即可。
範例程式
範例程式
這裡有許多範例程式 http://sourceforge.net/projects/wxeasygui/files/,您可以下載並執行它。
2014年8月27日 星期三
安裝 pyVISA
pyVISA 的 VISA 全名是「虛擬儀器軟體架構(Virtual Instrument Software Architecture)」,您可以透過 GPIB、 RS232、以太網路和 USB 等裝置跟其他量測設備作溝通。
官網 https://pypi.python.org/pypi/PyVISA
安裝需求
您必須先安裝下列軟體,才能安裝 pyVISA。
1. VISA (NI-VISA3.2,Win XP)
2. Python ( Python 2.6~3.2 版之間)
下載
切換網頁至 https://pypi.python.org/pypi/PyVISA,點擊綠色的 Download 按鈕。
安裝
將下載下來的檔案 PyVISA-1.5.zip 解壓縮,然後開啟「命令提示字元視窗」,切換路徑到 pyVISA 裏(註A),鍵入 python setup.py install 即可。如下圖所示:
註A:我的 pyVISA 解壓縮檔案是放在路徑「D:\download\PyVISA-1.5\」。
測試是否已正確安裝
啟動 Python,然後你可以鍵入下列程式碼,如果沒有出現錯誤訊息,表示已正確安裝。
>>> import visa
>>> lib = visa.ResourceManager()
Q&A
Q:鍵入 import visa 時會出現下列錯誤訊息:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\visa.py", line 18, in <module>
from pyvisa import logger, __version__, log_to_screen
File "C:\Python27\lib\site-packages\pyvisa\__init__.py", line 20, in <module>
import pkg_resources
ImportError: No module named pkg_resources
A:這是缺少 pkg_resources 模組所致,請到是德科技網站 http://www.keysight.com/ 下載 IO Libraries Suite 軟體,下載頁 http://www.keysight.com/main/software.jspx?ckey=1184883&lc=cht&cc=TW&nid=-11143.0.00&id=1184883
程式碼範例
import visa
rm = visa.ResourceManager()
my_instrument = rm.open_resource('GPIB::14')
my_instrument.write("*IDN?")
print(my_instrument.read())
安裝 NI-VISA 3.2
切換網頁到 http://www.ni.com/download/ni-visa-3.2/389/en/ ,點擊 visa320full.exe。它會要求您建立使用者帳號,如下圖。
如果您已經註冊過那麼就點擊「登入」,輸入正確的使用者名稱和密碼,然後再次點擊 visa320full.exe。
接著再雙擊下載的檔案 visa320full.exe,然後依照安裝視窗指示進行即可。
您可能會喜歡
1. pyVISA 參考文件 https://pyvisa.readthedocs.org/en/latest/
官網 https://pypi.python.org/pypi/PyVISA
安裝需求
您必須先安裝下列軟體,才能安裝 pyVISA。
1. VISA (NI-VISA3.2,Win XP)
2. Python ( Python 2.6~3.2 版之間)
下載
切換網頁至 https://pypi.python.org/pypi/PyVISA,點擊綠色的 Download 按鈕。
安裝
將下載下來的檔案 PyVISA-1.5.zip 解壓縮,然後開啟「命令提示字元視窗」,切換路徑到 pyVISA 裏(註A),鍵入 python setup.py install 即可。如下圖所示:
註A:我的 pyVISA 解壓縮檔案是放在路徑「D:\download\PyVISA-1.5\」。
測試是否已正確安裝
啟動 Python,然後你可以鍵入下列程式碼,如果沒有出現錯誤訊息,表示已正確安裝。
>>> import visa
>>> lib = visa.ResourceManager()
Q&A
Q:鍵入 import visa 時會出現下列錯誤訊息:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\lib\site-packages\visa.py", line 18, in <module>
from pyvisa import logger, __version__, log_to_screen
File "C:\Python27\lib\site-packages\pyvisa\__init__.py", line 20, in <module>
import pkg_resources
ImportError: No module named pkg_resources
A:這是缺少 pkg_resources 模組所致,請到是德科技網站 http://www.keysight.com/ 下載 IO Libraries Suite 軟體,下載頁 http://www.keysight.com/main/software.jspx?ckey=1184883&lc=cht&cc=TW&nid=-11143.0.00&id=1184883
Q:Windows ERROR 126
A:詳 http://sourceforge.net/p/pyvisa/bugs/15/
A:詳 http://sourceforge.net/p/pyvisa/bugs/15/
程式碼範例
import visa
rm = visa.ResourceManager()
my_instrument = rm.open_resource('GPIB::14')
my_instrument.write("*IDN?")
print(my_instrument.read())
安裝 NI-VISA 3.2
切換網頁到 http://www.ni.com/download/ni-visa-3.2/389/en/ ,點擊 visa320full.exe。它會要求您建立使用者帳號,如下圖。
如果您已經註冊過那麼就點擊「登入」,輸入正確的使用者名稱和密碼,然後再次點擊 visa320full.exe。
接著再雙擊下載的檔案 visa320full.exe,然後依照安裝視窗指示進行即可。
您可能會喜歡
1. pyVISA 參考文件 https://pyvisa.readthedocs.org/en/latest/
2014年8月23日 星期六
安裝 pyFirmata
pyFirmata 可以讓 Python 透過 Firmata 通訊協定和 Arduino 溝通。您可以在 Python 程式碼裡直接控制 Arduino port 的 HIGH 與 LOW。
下載
切換到下載頁面 https://github.com/tino/pyFirmata,點擊右下角落的「Download ZIP」,之後將 pyfirmata-master.zip 解壓縮。
安裝
安裝的首選方法是使用 PIP,語法如下:
下載
切換到下載頁面 https://github.com/tino/pyFirmata,點擊右下角落的「Download ZIP」,之後將 pyfirmata-master.zip 解壓縮。
安裝
安裝的首選方法是使用 PIP,語法如下:
pip install pyfirmata或是您也可以開啟「命令提示字元」視窗,切換到 pyfirmata-master.zip 解壓縮後的路徑,然後鍵入
python setup.py install如下圖所示:
安裝 pySerial
您可以使用 pySerial 透過 COM port 與 Arduino 聯繫。
官網 http://pyserial.sourceforge.net/#
下載
切換至下載頁面 https://pypi.python.org/pypi/pyserial,點擊 pyserial-2.7-win32.exe (md5)。
安裝
雙擊 pyserial-2.7-win32.exe,然後依照視窗提示安裝即可。它會被安裝到 C:\Python27\Lib\site-packages\serial\ 這個位置。
開啟 COM4 並送出訊息
COM port 的編號是從 0 開始,所以 serial.Serial(3) 表開啟 COM4。
import serial
ser = serial.Serial(3) # open COM4 port
print ser.name # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
以名稱方式開啟 COM port 並讀取訊息
超時設為 1 秒,讀取資料時如果時間超過 1 秒沒接收到資料就中斷接收。
import serial
ser = serial.Serial('COM4', 19200, timeout=1)
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
line = ser.readline() # read a '\n' terminated line
ser.close()
稍後才設定 COM 的參數
您不必一開始就指定某個特定的 COM port 必須使用多少鮑率等參數,而是可以隨著程式的進行隨時改變參數,方法如下所示:
>>> import serial
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False
獲取可用的 COM port
coms=serial.tools.list_ports.comports()
for a in coms:
print a
讓 Arduino 板子 pin 13 的 LED 閃爍
Python code:
import serial
def main():
sp = serial.Serial()
sp.port = 'COM4'
sp.baudrate = 9600
sp.timeout = 5
sp.open()
sp.readline() #to give the hardware handshake time to happen
sp.write(chr(1))
value = sp.readline()
print value
sp.write(chr(0))
sp.close()
if __name__ == "__main__":
main()
Arduino code:
const int ledPin = 13;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop(){
while(Serial.available()){
switch(Serial.read()) {
case 0:
digitalWrite(ledPin, LOW);
break;
case 1:
digitalWrite(ledPin, HIGH);
break;
}
delay(20);
}
}
您可能也喜歡
Arduino and Python
http://playground.arduino.cc/interfacing/python
pyFirmata
https://github.com/tino/pyFirmata
Python Arduino Prototyping API
https://github.com/vascop/Python-Arduino-Proto-API-v2
<Python Serial Port Extension>
官網 http://pyserial.sourceforge.net/#
下載
切換至下載頁面 https://pypi.python.org/pypi/pyserial,點擊 pyserial-2.7-win32.exe (md5)。
安裝
雙擊 pyserial-2.7-win32.exe,然後依照視窗提示安裝即可。它會被安裝到 C:\Python27\Lib\site-packages\serial\ 這個位置。
開啟 COM4 並送出訊息
COM port 的編號是從 0 開始,所以 serial.Serial(3) 表開啟 COM4。
import serial
ser = serial.Serial(3) # open COM4 port
print ser.name # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
以名稱方式開啟 COM port 並讀取訊息
超時設為 1 秒,讀取資料時如果時間超過 1 秒沒接收到資料就中斷接收。
import serial
ser = serial.Serial('COM4', 19200, timeout=1)
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
line = ser.readline() # read a '\n' terminated line
ser.close()
稍後才設定 COM 的參數
您不必一開始就指定某個特定的 COM port 必須使用多少鮑率等參數,而是可以隨著程式的進行隨時改變參數,方法如下所示:
>>> import serial
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False
獲取可用的 COM port
import serial.tools.list_ports
coms=serial.tools.list_ports.comports()
for a in coms:
print a
讓 Arduino 板子 pin 13 的 LED 閃爍
Python code:
import serial
def main():
sp = serial.Serial()
sp.port = 'COM4'
sp.baudrate = 9600
sp.timeout = 5
sp.open()
sp.readline() #to give the hardware handshake time to happen
sp.write(chr(1))
value = sp.readline()
print value
sp.write(chr(0))
sp.close()
if __name__ == "__main__":
main()
Arduino code:
const int ledPin = 13;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop(){
while(Serial.available()){
switch(Serial.read()) {
case 0:
digitalWrite(ledPin, LOW);
break;
case 1:
digitalWrite(ledPin, HIGH);
break;
}
delay(20);
}
}
您可能也喜歡
Arduino and Python
http://playground.arduino.cc/interfacing/python
pyFirmata
https://github.com/tino/pyFirmata
Python Arduino Prototyping API
https://github.com/vascop/Python-Arduino-Proto-API-v2
<Python Serial Port Extension>
1. wxTerminal.py
http://sourceforge.net/p/pyserial/code/HEAD/tree/trunk/pyserial/examples/wxTerminal.py
2. wxSerialConfigDialog.py
http://sourceforge.net/p/pyserial/code/HEAD/tree/trunk/pyserial/examples/wxSerialConfigDialog.py安裝 PyBluez
PyBluez 是給桌上型電腦使用的藍芽函式庫,您可以用它來跟附近的藍芽裝置溝通。如果是手機或平板,您可以安裝 LightBlue。
下載
切換至下載頁面 https://code.google.com/p/pybluez/downloads/list
點擊 PyBluez-0.20-win32.py2.7.exe。
安裝
雙擊 PyBluez-0.20-win32.py2.7.exe,然後依照視窗內的提示安裝即可。
官網說要在「命令提示視窗」內進行如下安裝
python setup.py install
但我發現這個動作可以省略。
搜尋藍芽裝置
本程式碼會搜尋並顯示附近的藍芽裝置的名稱和位址。
import bluetooth
print("performing inquiry...")
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
print(" %s - %s" % (addr, name))
執行過程如下:
performing inquiry...
found 2 devices
Ray's Nokia - 00:12:D2:5A:BD:E4
Ray's MacBook - 00:1E:C2:93:DA:6F
RFCOMM 服務
以下是基本的客戶端和伺服器端的程式,為了讓事情變得簡單,我們手動輸入伺服器藍牙設備的位址(00:12:D2:5A:BD:E4)和埠口;在下文中,客戶端連接到伺服器上的埠口為 3。
程式運作的方式如下圖:
客戶端(從)程式
from bluetooth import *
# Create the client socket
client_socket=BluetoothSocket( RFCOMM )
client_socket.connect(("00:12:D2:5A:BD:E4", 3))
client_socket.send("Hello World")
print "Finished"
client_socket.close()
伺服器端(主)程式
from bluetooth import *
server_socket=BluetoothSocket( RFCOMM )
server_socket.bind(("", 3 ))
server_socket.listen(1)
client_socket, address = server_socket.accept()
data = client_socket.recv(1024)
print "received [%s]" % data
client_socket.close()
server_socket.close()
下載
切換至下載頁面 https://code.google.com/p/pybluez/downloads/list
點擊 PyBluez-0.20-win32.py2.7.exe。
安裝
雙擊 PyBluez-0.20-win32.py2.7.exe,然後依照視窗內的提示安裝即可。
官網說要在「命令提示視窗」內進行如下安裝
python setup.py install
但我發現這個動作可以省略。
搜尋藍芽裝置
本程式碼會搜尋並顯示附近的藍芽裝置的名稱和位址。
import bluetooth
print("performing inquiry...")
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
print(" %s - %s" % (addr, name))
執行過程如下:
performing inquiry...
found 2 devices
Ray's Nokia - 00:12:D2:5A:BD:E4
Ray's MacBook - 00:1E:C2:93:DA:6F
RFCOMM 服務
以下是基本的客戶端和伺服器端的程式,為了讓事情變得簡單,我們手動輸入伺服器藍牙設備的位址(00:12:D2:5A:BD:E4)和埠口;在下文中,客戶端連接到伺服器上的埠口為 3。
程式運作的方式如下圖:
客戶端(從)程式
from bluetooth import *
# Create the client socket
client_socket=BluetoothSocket( RFCOMM )
client_socket.connect(("00:12:D2:5A:BD:E4", 3))
client_socket.send("Hello World")
print "Finished"
client_socket.close()
伺服器端(主)程式
from bluetooth import *
server_socket=BluetoothSocket( RFCOMM )
server_socket.bind(("", 3 ))
server_socket.listen(1)
client_socket, address = server_socket.accept()
data = client_socket.recv(1024)
print "received [%s]" % data
client_socket.close()
server_socket.close()
安裝 pyScripter
pyScripter 是 Python 眾多編輯器其中一種。
官網 https://code.google.com/p/pyscripter/
安裝需求
1. 您必須先安裝 Python。
下載與安裝
切換到下載頁面 https://code.google.com/p/pyscripter/downloads/list
請點擊 PyScripter-v2.5.3-Setup.exe,下載後請快擊兩下並依視窗指示安裝。
安裝時,請勾選在桌面產生捷徑圖示,捷徑如下圖示:
執行 pyScripter
以後我們可以快擊兩下 pyScripter 捷徑,就可以開啟 pyScripter 編輯器,用它來寫 Python 程式。
官網 https://code.google.com/p/pyscripter/
安裝需求
1. 您必須先安裝 Python。
下載與安裝
切換到下載頁面 https://code.google.com/p/pyscripter/downloads/list
請點擊 PyScripter-v2.5.3-Setup.exe,下載後請快擊兩下並依視窗指示安裝。
安裝時,請勾選在桌面產生捷徑圖示,捷徑如下圖示:
執行 pyScripter
以後我們可以快擊兩下 pyScripter 捷徑,就可以開啟 pyScripter 編輯器,用它來寫 Python 程式。
訂閱:
文章 (Atom)















