2010年10月11日 星期一

[C++]輸入變數i到s的加總

平常書本都是撰寫輸入1到10的總和

現在改成由使用者自行輸入 起始值與末始值進行加總

【While版本】
#include <iostream>
int main()
{
int sum=0,i,s,st;
std::cout<<"請輸入起始值:"<<std::endl;
std::cin>>i;
std::cout<<"請輸入末始值:"<<std::endl;
std::cin>>s;

st=i;

while(i<=s)
{
sum+=i;
i++;
}
std::cout<<st<<"加到"<<s<<"的總合是:"<<sum<<std::endl;
system("PAUSE");
return 0;

}


【for回圈版本】
#include <iostream>
int main()
{
int sum=0,i,s,st;
std::cout<<"請輸入起始值:"<<std::endl;
std::cin>>i;
std::cout<<"請輸入末始值:"<<std::endl;
std::cin>>s;

st=i;
for(i;i<=s;i++){
sum+=i;
}
std::cout<<st<<"加到"<<s<<"的總合是:"<<sum<<std::endl;
system("PAUSE");
return 0;

}



以上程式是否發現會有bug出現?


當使用者先輸入大值再輸入小值程式就會出現bug

因此我們需加入if判斷式判斷使用者輸入值是先輸入大值還小值

#include <iostream>
int main()
{
int sum=0,i,s,st;
std::cout<<"此程式會將您輸入的值由小加到大"<<std::endl;
std::cout<<"==============================="<<std::endl;

std::cout<<"請輸入起始或末始值:"<<std::endl;
std::cin>>i;

std::cout<<"請輸入末始或起始值:"<<std::endl;
std::cin>>s;

int lower,upper;
if(i<=s){
lower=i;
upper=s;
}else{
upper=i;
lower=s;
}

st=lower;

for(lower;lower<=upper;lower++){
sum+=lower;

}
std::cout<<st<<"加到"<<upper<<"的總合是:"<<sum<<std::endl;
system("PAUSE");
return 0;

}



如果您認為上述程式這樣就結束了

那你就錯了

此程式是有一個bug存在

若使用者打入兩數相等

是否就出現了問題了呢

所以程式需再加入判斷兩數相等的程式

#include <iostream>
int main()
{
int sum=0,i,s,st;
std::cout<<"此程式會將您輸入的值由小加到大"<<std::endl;
std::cout<<"==============================="<<std::endl;

std::cout<<"請輸入起始或末始值:"<<std::endl;
std::cin>>i;

std::cout<<"請輸入末始或起始值:"<<std::endl;
std::cin>>s;

int lower,upper;
if(i==s)
{
std::cout<<i<<"加到"<<i<<"的總合是:0"<<std::endl;
}else
{
if(i<s)
{
lower=i;
upper=s;
}else
{
upper=i;
lower=s;
}

st=lower;
for(lower;lower<=upper;lower++)
{
sum+=lower;
}
std::cout<<st<<"加到"<<upper<<"的總合是:"<<sum<<std::endl;
}
system("PAUSE");
return 0;

}

2010年10月9日 星期六

[C++]計算兩數相乘

#include <iostream>
int main(){
int v1;
int v2;
std::cout<<"請輸入兩個值"<<std::endl;
std::cout<<"第一個值:";
std::cin>>v1;
std::cout<<"第二個值:";
std::cin>>v2;
std::cout<<"兩數相乘 " << v1 << "*" << v2 << "=" << v1 * v2 << std::endl;
// std::cout <<"Hello,World" << std::endl;

system("PAUSE");
return 0;

}

2010年10月8日 星期五

ARToolkit 與OpenGL於Visual C++6的設定(July 15, 2010 )

到ARToolkit官網選download
http://www.hitl.washington.edu/artoolkit/download/#windows
下載


ARToolkit-2.72.1.tgz (988KB)
DSVL-0.0.8b.zip (2.57MB)
OpenVRML-0.14.3-win32.zip (10.8MB)
這三個檔案
點選官網 ARToolKit-2.72.1.tgz 下載完會發現副檔名是.gz
解壓縮出來是沒有副檔名的
自行加上副檔名改為.tgz
又會變成另個壓縮檔
將他解壓縮即為ARToolkit的程式

接下來AR需要OpenGL支援
ARToolkit官網沒有提供
所以到
http://www.xmission.com/~nate/glut.html
下載glut-3.7.6-bin.zip

然後將glut-3.7.6-bin.zip解壓縮後
把下面資料放置WIndows XP相關資料夾裡

glut32.dll 放在C:\windows\system32

glut32.lib放在C:\Program Files\Microsoft Visual Studio\VC98\Lib

glut.h放在C:\Program Files\Microsoft Visual Studio\VC98\Include\GL

C:\Program Files\ARToolKit加入DSVL和OpenVRML資料夾

C:\Program Files\ARToolKit\DSVL\bin\DSVL.dll
C:\Program Files\ARToolKit\DSVL\bin\DSVLd.dll
C:\Program Files\ARToolKit\OpenVRML\bin\js32.dll

以上三個DLL放到C:\Program Files\ARToolKit\bin裡

點兩下Configure.win32.bat

==================================================
在Visual C++6的設定


tool→options→directories:
Include files中加入C:\PROGRAM FILES\ARTOOLKIT\INCLUDE

Library files中加入C:\PROGRAM FILES\ARTOOLKIT\LIB

打開C:\Program Files\ARToolKit\ARToolKit.dsw

點選
build-batch build
→build


project seeting:
【input】

Object/library modules:
libAR.lib libARgsub.lib libARvideo.lib libARmulti.lib libARvideod.lib libARgsub_lite.lib


ignore libraries:
libcmt.lib

Additional library path:
C:\Program Files\ARToolKit\lib


C/C++:
Category:【preprocessor】
Additional include directories:
C:\Program Files\ARToolKit\include

Debug:
working directory:
C:\Program Files\ARToolKit\bin



http://flash.tarotaro.org/blog/2008/12/14/artoolkit-marker-generator-online-released/

laser marker 找不到javax.vecmath library問題(May 23, 2010 )

感謝有人在背後為我打氣

讓我有動力去解決一些問題:)

如果去找雷射塗鴉的processing程式 ( http://blog.graffitiresearchlab.at/ )

會發現抓下來的programe會無法compile

會出現 javax.vecmath library missing的問題

這個原因就是少了java 3d的library

先到sun抓java3d

抓完安裝後 會發現還是無法compile

我用windows平台

我們到C:\Program Files\Java\Java3D\1.4.0_01\lib\ext 裡頭 將.jar 檔copy起來

再到processing的程式

processing-1.0.7\libraries\vecmath\library

如果你的libraries裡沒有vecmath的資料夾 就自己建一個

把剛才copy的 .jar檔通通丟到library裡

再將processing重新開

就可以順利run laser marker的program 囉:)

good lucky

Arduino 與 Flash as3連接(May 18, 2010 )

離上次發文章是去年了也

時間過真快

看來記錄些東西是必要的

之前記錄了Flash 接 arduino也是在去年的事

那時好像也沒有真的接出來

今年這個時候又要用到結果一直沒有解答

網路找的範例怎都try不出來喏@@~

後來認真的思考自己寫一個 不知是自己進步了還是巧合呢(笑)

其實也沒有很難 囧..但花了我一些時間找資料

arduino <-------> Flash 要透過中介軟體

因為Flash好像不能讀Serial的資料?! (有錯請指正)

中介軟體找到兩種

一種為 TinkerProxy (紅色背景的中介小程式) 但我一直沒找到這個軟體 =.=

後來死心改回找serproxy 我用0.1.3版的 ,其他0.1.1好像也可以通啦

然後第一步就是要先傳pde檔到arduino

pde的內容是什麼呢

以下為基本的範例 就是我們用Flash AS3來讀可變電阻的類比數值讓他顯示在Flash上囉

==================先用Arduino程式 upload 這個pde檔=======================


int potPin = 0;
int val = 0;

void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
Serial.begin(9600);
}

void loop() {
val = analogRead(potPin);
Serial.print(val,DEC);
delay(100);
Serial.print(0,BYTE);
delay(100);

}
===============================================================
網路找的範例很多都是寫printByte 那個要改成Serial.print
Serial.print(val,DEC);
Serial.print(0,BYTE);
好像不能用println的樣子 我忘記了 好像跟那個XML有關

第二步呢
就是要執行serproxy
如果不是0.1.3版的好像要改裡面的port和net_port的值

我的serproxy.cfg的內容長這樣 0.1.3好像不用改

=====================
# Config file for serproxy
# See serproxy's README file for documentation

# Transform newlines coming from the serial port into nils
# true (e.g. if using Flash) or false
newlines_to_nils=true

# Comm ports used
comm_ports=1,2,3,4

# Default settings
comm_baud=19200
comm_databits=8
comm_stopbits=1
comm_parity=none

# Idle time out in seconds
timeout=300

# Port 1 settings (ttyS0)
net_port1=5331

# Port 2 settings (ttyS1)
net_port2=5332

# Port 3 settings (ttyS2)
net_port3=5333

# Port 4 settings (ttyS3)
net_port4=5334

===============================
也就是說上面只支援到Port 4

你要先看一下裝置管理員裡面 你USB的port到幾
如果超果4的話
請在裝置管理員COM和LPT的USB Serial Port按右鍵→內容→port setting→advanced→com port number選4以內
這樣後面比較不會麻煩啦

上面燒pde進arduino後
再來開serproxy的軟體
這個中介軟體不可以關唷

再來就是Flash AS3的部份了!!!

這個as3檔也是網路找的
開一個Arduino.as放以下內容
===============================================================================
/*
* Class : Arduino v1.0 - 30-JAN-2008
* This Actionscript3 class makes it easier to connect Flash to the Arduino Board (www.arduino.cc)
* And, this script is based on beltran berrocal's ARDUINO CLASS v1.0(written in AS2).
* # copyleft Mr. Excuse, 2008 - mrexcuse@hotmail.com
* # visit http://november.idv.tw for more information.
*
* If you need AS2 version, see www.progetto25zero1.com/b/tools/Arduino
*
* # credits must also be given to:
* Yaniv Steiner and the instant soup crew (instantsoup.interaction-ivrea.it) for generating the original flash client
*
* # you will also need the serialProxy developed by Stefano Busti(1999) and David A. Mellis(2005)
* that can be found either on the Arduino Site (www.arduino.cc) or redistributed with this example (see update url)
*
*---------------------------------------------------------------
*
* # METHODS & DESCRIPTIONS
*
* @@ CONSTRUCTOR
* @@ creates the Arduino Object inside Flash
* usage:
* var var ArduinoInstance:Arduino = new Arduino([port], [host]);
*
* // port: default is 5331, read the serialProxy documentation to understand this
* // host: default is "127.0.0.1"
*
* @@ CONNECT
* @@ connects to the XMLSocket server, you must have provided a port and a host adress via the constructor
* usage:
* ArduinoInstance.connect()
*
* @@ DISCONNECT
* @@ disconnects from the XMLSocket server
* usage:
* ArduinoInstance.disconnect()
*
* @@ SEND
* @@ sends data to Arduino via the XMLSocket server(the serialProxy)
* usage:
* ArduinoInstance.send("some data here");
*
* ## EVENT: onDataReceived
* ## handler of a listener object that listens to data sent from Arduino through the XMLSocket server(the serial Proxy)
* usage:
* Arduino_Listener = new Object(); //create a listener object
* Arduino_Listener.onDataReceived = function() {
* //handle the received data in here
* }
* ArduinoInstance.addEventListener("onReceiveData",Arduino_Listener); //register to listen to the events
*
* ## OTHER EVENTS: onConnect, onConnectError, onDisconnect
* usage: use in the same way as the onDataReceived event
*
*-----------------------------------------------------------------------------
* LICENCE
* Copyright (C) 2008 Mr. Excuse | mrexcuse@hotmail.com
* http://november.idv.tw
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of the License
*
* You should have received a copy of the GNU Lesser General Public License along with this library;
* Alternatively you can find it here http://www.gnu.org/licenses/lgpl.html
*
* Brief Explanation of the Licence:
* - you can you use, redistribute, modify this software for free,
* - you can put it into commercial projects
* - but if you modify/enhance this Library you should release it under the same licence or alternatively under the GPL licence
* - in all cases you should also credit the original author and all contributors
*
*-----------------------------------------------------------------------------
*/
package {
//import mx.events.EventDispatcher;
import flash.display.Sprite;
import flash.net.XMLSocket;
import flash.events.*;


//class Arduino extends XMLSocket {
public class Arduino extends XMLSocket{

private var _connected :Boolean = false; // 是否已連結
private var _host :String = "127.0.0.1"; // 主機名稱或是IP位址
private var _port :int = 5332; // 設定連結埠號
//private var socket :XMLSocket;


//constructor - provide a port number and a host ip adress
//read the documentation of the SerialProxy to better understandwhat this means
public function Arduino(port:int = 5331, host:String = "127.0.0.1") {
//initialize

//socket = new XMLSocket();
super();
//flash.events.EventDispatcher.initialize(this);

if((port < 1024) || (port > 65536)){
trace("** Arduino ** Port must be from 1024 to 65535 ! read the Flash Documentation and the serProxy config file to better understand");
}else{
_port = port;
}



//check for host or set default
//if(strHost != undefined) {
_host = host;
//}

//register and override responder functions
//this.onConnect = onConnectToSocket;
//this.onClose = onDisconnectSocket;
//this.onData = onDataReceived;


// 重新設定監聽者
configListener(this);

//autoconnect
xconnect();
}

// 重新設定監聽者
private function configListener(dispatcher:IEventDispatcher):void{
dispatcher.addEventListener(Event.CLOSE, closeHandler);
dispatcher.addEventListener(Event.CONNECT, connectHandler);
dispatcher.addEventListener(DataEvent.DATA, dataHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
//dispatcher.addEventListener('onData', onDataReceived);
//dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
// dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);

}

//---------------------------------------
// CONNECT and DISCONNECT + responders
//---------------------------------------

//connect to the XMLsocket
public function xconnect ():void {
super.connect(_host, _port);
}

//disconnects from the xmlsocket (not Arduino itself)
public function disconnect () {
if (_connected) {
super.close();
_connected = false;
}
}

// connect handler
private function connectHandler(event:Event):void{
trace("** Arduino ** Connecting to "+_host+":"+_port+" . . .");
}

// close handler
private function closeHandler(event:Event):void{
trace("** Arduino ** disconnected");
}

// data handler
private function dataHandler(event:DataEvent):void{
//trace("dataHandler:" + event.data);
//dispatchEvent('onData');
//onDataReceived(event.data);
//e_onReceiveData(str);

}

// io error handler
private function ioErrorHandler(event:IOErrorEvent):void{
trace ("** Arduino ** Connection failed! you must launch the serialProxy first");
}


//---------------------------------------
// SEND and receive data from server
//---------------------------------------

/*
//sends data to arduino
override public function send(dataStr:String) {
trace("** Arduino ** send:" + dataStr)
if (_connected) {
if (dataStr.length) {
trace("** Arduino ** Sending \""+dataStr+"\"");
super.send(dataStr);
}
}
}
*/

//overrides XMLSocket.onData in order to have pure string and not the full XML object
private function onDataReceived (str:String) {
//trace("** Arduino ** onDataReceived str:"+str);
//launch event
e_onReceiveData(str);
}



/*
//---------------------------------------
// EVENTS
//---------------------------------------

private function e_connectToSocket(){
var evt = {target:this, type:"onConnect"};
dispatchEvent(evt);
}

private function e_connectToSocketError(){
var evt = {target:this, type:"onConnectError"};
dispatchEvent(evt);
}

private function e_disconnectSocket(){
var evt = {target:this, type:"onDisconnect"};
dispatchEvent(evt);
}
*/
private function e_onReceiveData (str:String){
trace("** Arduino ** onDataReceived str:"+str);
var evt = {target:this, type:"onReceiveData"};
evt.data = str;
dispatchEvent(new Event(evt));
}

}
}

===================================================================
記得 上面有一行
private var _port :int = 5332; // 設定連結埠號

這個部份要改
像我是Port 2所以是5332

如果你是Port 3 就要改5333唷

再來請開啟你的fla檔囉~
先建一個動態文字欄位
把屬性名稱命名為:arduinoval
然後到影格按F9開啟動作面版
把以下程式打進去
====================================================================
//建立port :port2→5332
//中介軟體也的也要改
var test:int=0;
var a:Arduino = new Arduino(5332);
a.addEventListener(DataEvent.DATA, receiveData);

//接收Arduino傳的數值
function receiveData(event:DataEvent):void{
trace(event.data);
arduinoval.text=event.data;

}

======================================================================
記得上面的5332也要改成你的Port對應的net port號碼
然後按下ctrl enter發佈
轉轉你的可變電阻就可以看到類比數值囉^___^
至於可變電阻的線路圖就麻煩自己找資料了
我的是插analog in 0
其他就5V和GND
至於深入的部份
就看AS3功力怎麼設計囉:P

Processing連接Camera(October 3, 2009 )

http://processing.org/learning/libraries/gettingstartedcapture.html

以下為官網的程式

import processing.video.*;

Capture cam;

void setup() {
size(640, 480);

// If no device is specified, will just use the default.
cam = new Capture(this, 320, 240);

// To use another device (i.e. if the default device causes an error),
// list all available capture devices to the console to find your camera.
//String[] devices = Capture.list();
//println(devices);

// Change devices[0] to the proper index for your camera.
//cam = new Capture(this, width, height, devices[0]);

// Opens the settings page for this capture device.
//camera.settings();
}


void draw() {
if (cam.available() == true) {
cam.read();
image(cam, 160, 100);
// The following does the same, and is faster when just drawing the image
// without any additional resizing, transformations, or tint.
//set(160, 100, cam);
}
}



=============

看起來好像可以接連到camera

但後來發現會出現VDIG的error

於是到 http://www.eden.net.nz/7/20071008/ 下載VDIG來安裝

安裝前有先裝完了quicktime 因為好像需要

下載1.0.5版的好像不能使用@~@

後來抓了1.0.1版本後 就正常可以連接上camera了

OpenCV與Dev C++的安裝(October 3, 2009 )

1. 在工具->編譯器選項->編譯器->在連結器命令列中加入以下命令
-lhighgui -lcv -lcxcore -lcvaux -lcvcam
2. 工具->編譯器選項->目錄->函式庫加入OpenCV的lib資料夾路
C:\Program Files\OpenCV\lib
3. 工具->編譯器選項->目錄->C引入檔(include)
C:\Program Files\OpenCV\cxcore\include
C:\Program Files\OpenCV\cv\include
C:\Program Files\OpenCV\otherlibs\highgui
C:\Program Files\OpenCV\cvaux\include
C:\Program Files\OpenCV\otherlibs\cvcam\include
4. 工具->編譯器選項->目錄->C++引入檔(include)
C:\Program Files\OpenCV\cxcore\include
C:\Program Files\OpenCV\cv\include
C:\Program Files\OpenCV\otherlibs\highgui
C:\Program Files\OpenCV\cvaux\include
C:\Program Files\OpenCV\otherlibs\cvcam\include


VISTA

工具 -> 編譯器選項 -> 目錄 -> 二進位檔 加入 C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2

工具 -> 編譯器選項 -> 目錄 -> 外部程式 每一個程式名稱前面加入這個C:\Dev-Cpp\bin\

Arduino連接Flash(October 3, 2009)

首先我們要先把程式燒進Arduino裡頭

而網路找的程式有部份要修改

原本的程式compile會卡在printByte這裡 把這都改成Serial.print就可以compile過燒進arduino裡頭

所以正常的pde程式為
==============================================
int activeLED ;
int switchState = 0;
int lastSwitchState = 0;
int switchPin = 13;

void setup()
{
Serial.begin(19200);
pinMode(switchPin, INPUT);
for (int i = 2; i <= 9; i++) {
pinMode(i, OUTPUT);
}
}

void loop ()
{
switchState = digitalRead(switchPin);
if (switchState != lastSwitchState) {
if (switchState == 1){
sendStringToFlash("switchOn");
} else if (switchState == 0){
sendStringToFlash("switchOff");
}
}
lastSwitchState = switchState;

if(Serial.available() > 0) {
activeLED = Serial.read();
}

if(activeLED >= 50 && activeLED <= 57) {
int outputPort = activeLED - 48;

Serial.print("LED port ");
Serial.println(outputPort);

if(outputPort >= 2 && outputPort <= 9) {
for (int i = 2; i <= 10; i++) {
digitalWrite(i,LOW);
}
digitalWrite(outputPort, HIGH);
}
activeLED = 0;
} else if (activeLED) {
Serial.print("Invalid LED port ");
Serial.println(activeLED,BYTE);
}

delay(50);
}

void sendStringToFlash (char *s)
{
while (*s) {
Serial.print(*s ++);
}
Serial.print(0);
}

===============================================

再來要開啟serproxy的程式

連接flash中 這個程式都要一直開啟

有正常就會出現wait client..

接下來連接成功arduino後

要記得看你的COM是多少

在控制台連接埠可以看

我們是COM3的話Flash裡頭的程式var port:Number = 5333;後面就為5333

記得import的.as檔也要修改成5333

再接好你的arduino的LED後

發佈Flash 就可以由Flash來控制你的LED亮燈在哪幾顆

AS3漸進公式 (August 17, 2009)

漸進公式

移動值=(目標值-現在值)/漸進係數;
現在值=現在值+移動量;

→ 現在值=現在值+(目標值-現在值)/漸進係數

→現在值+=(目標值-現在值)/漸進係數

LED Art ~Bugs (May 31, 2009)



做好了

小小一隻

其實還滿花時間的

大約要一個晚上@@

因為小小的不太好焊

下面是半成品



被壓扁的 還沒彎腳



背面這樣子



成品







有沒有發現上面幾張是沒有八隻腳的XD

下面是後來做的第二隻蜘蛛

裝上電池發亮





後來把第一隻焊線上去當絲

不過中間要多加一個二百多的電阻

不然LED會燒掉

然後再用熱縮管包起來美觀一下




兩隻放一起打開就這樣




原創的在這
http://mitchbox.wordpress.com/2007/06/15/led-art-blinkybug/

不過我們做的和原創的不同:P

我們多加LED在每個腳上

晚上發光就比原本的漂亮 :)