Created
September 20, 2012 16:32
-
-
Save mia-0032/3756932 to your computer and use it in GitHub Desktop.
赤外線でシリアル通信(送信)クラス(Arduino)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 赤外線でシリアル通信(送信)クラス | |
* 注:このクラスを使うとPORTBのピンは使えなくなる | |
* 受信するときは赤外線受光モジュールのVoutをシリアル送信ピンとして扱えばOK | |
*/ | |
class IrTransmitter{ | |
private: | |
//赤外線の1周期ごとの時間(us) | |
unsigned int irCycleTime; | |
//半周期 | |
unsigned int irHalfCycle; | |
//シリアル通信の1周期ごとの時間(us) | |
unsigned int serialCycleTime; | |
//1bitごとに赤外線LEDを点滅させる回数 | |
unsigned int irCycleCountLimit; | |
/** | |
* 赤外線LEDを指定した周波数で発振してビットを出力する関数 | |
* @param int val ビット(0か1) | |
*/ | |
void irBitSend(int val){ | |
//赤外線通信はHIGHとLOWが逆 | |
if(val == 0){ | |
for (int i = 0; i < irCycleCountLimit; i++){ | |
PORTB = B00110000; | |
delayMicroseconds(irHalfCycle); | |
PORTB = B00000000; | |
delayMicroseconds(irHalfCycle); | |
} | |
} | |
else{ | |
for (int i = 0; i < irCycleCountLimit; i++){ | |
PORTB = B00000000; | |
delayMicroseconds(irHalfCycle); | |
PORTB = B00000000; | |
delayMicroseconds(irHalfCycle); | |
} | |
} | |
} | |
public: | |
/** | |
* 赤外線発振周波数とシリアル通信の速度を設定 | |
* @param unsigned int irFrequency 赤外線LEDの発振周波数(Hz) | |
* @param unsigned int serialBps シリアル通信の速度(bps) | |
*/ | |
IrTransmitter(unsigned int irFrequency, unsigned int serialBps){ | |
irCycleTime = 1000000 / irFrequency; | |
irHalfCycle = irCycleTime / 2; | |
serialCycleTime = 1000000 / serialBps; | |
irCycleCountLimit = serialCycleTime / irCycleTime; | |
//ポートを直接いじっているのでハードコーディング | |
pinMode(13, OUTPUT); | |
pinMode(12, OUTPUT); | |
} | |
/** | |
* 1バイトのデータとバイトあたりのビット数を指定して送信 | |
* @param int byteData[] データ配列 | |
* @param int byteBit バイトあたりのビット数 | |
*/ | |
void irSend(int byteData[], int byteBit){ | |
byteBit = byteBit - 1; | |
//シリアル通信は逆順にビットを送る | |
for(int i = byteBit; i >= 0; i--){ | |
if(i == byteBit){ | |
//スタートビット | |
IrTransmitter::irBitSend(0); | |
} | |
IrTransmitter::irBitSend(byteData[i]); | |
if(i == 0){ | |
//ストップビット | |
IrTransmitter::irBitSend(1); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment