Created
January 24, 2020 04:10
-
-
Save ti-nspire/c2422d8e16abe0f7e80cbaaba1053740 to your computer and use it in GitHub Desktop.
myI2C_library_for_ATmega328P
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
#include "myI2C.h" | |
void myI2CClass::waitForComplete(){ | |
loop_until_bit_is_set(TWCR, TWINT); | |
} | |
void myI2CClass::enable(uint16_t div){ | |
// i2cビットレート=システムクロック÷(16 + 2 * TWBR * PrescalerValue)。 | |
// PrescalerValueは4にしておく。 | |
TWSR &= ~(1 << TWPS1); | |
TWSR |= (1 << TWPS0); | |
TWBR = ((div >> 3) - 2); // システムクロックの分周比からTWBR (ビットレートレジスタ)の値を求める。 | |
TWCR |= (1 << TWEN); // 念のため真っ先にI2Cを有効化しておく。 | |
} | |
void myI2CClass::disable(){ | |
TWCR &= ~(1 << TWEN); | |
} | |
void myI2CClass::start(){ | |
TWCR = (1 << TWINT | 1 << TWEN | 1 << TWSTA); | |
waitForComplete(); | |
} | |
void myI2CClass::stop(){ | |
TWCR = (1 << TWINT | 1 << TWEN | 1 << TWSTO); | |
} | |
uint8_t myI2CClass::readACK(){ | |
TWCR = (1 << TWINT | 1 << TWEN | 1 << TWEA); | |
waitForComplete(); | |
return TWDR; | |
} | |
uint8_t myI2CClass::readNACK(){ | |
TWCR = (1 << TWINT | 1 << TWEN); | |
waitForComplete(); | |
return TWDR; | |
} | |
void myI2CClass::send(uint8_t data){ | |
TWDR = data; | |
TWCR = (1 << TWINT | 1 << TWEN); | |
waitForComplete(); | |
} | |
// コンストラクタ | |
myI2CClass::myI2CClass(){} | |
// 実装ファイルの中で先に実体化しておく。 | |
myI2CClass myI2C; | |
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
#include <avr/io.h> | |
#include <inttypes.h> | |
#ifndef myI2C_H | |
#define myI2C_H | |
class myI2CClass{ | |
private: | |
void waitForComplete(); // 送受信処理の終了を待つ。 | |
public: | |
void enable(uint16_t div); // システムクロックの分周比を指定してI2Cモジュールを開始する。8刻みで指定する。8刻みでなくてもよい。 | |
// 分周比divは16から2056まで8刻みで指定する。 | |
// 8刻みにしなかった場合は、分周比が指定値よりも少し低くなる(I2Cクロックが少し高くなる)。 | |
void disable(); | |
void start(); // スタートコンディションを生成する。 | |
void stop(); // ストップコンディションを生成する。 | |
uint8_t readACK(); // 1バイトを受信したらACKを返す。 | |
uint8_t readNACK(); // 1バイトを受信したらNACKを返す。 | |
void send(uint8_t data); // 1バイトを送信する。 | |
// コンストラクタ | |
myI2CClass(); | |
}; | |
// インスタンスの外部参照宣言 | |
extern myI2CClass myI2C; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment