STM32F103を使ってみる

i2cのTowWireとSoftWire


こちらに BluePillのPinOutが公開されています。
これを見るとPB8/PB9 と PB10/PB11 がi2cとして使えそうです。
やっとこれらの使い方が分かりましたので紹介します。
動作確認は24C02のEEPROMを使い、以下のコードで確認しました。
先頭のdefineを変更することで、TowWireやSoftWaireに切り替えることができます。
i2cのremapも試しましたが動きませんでした。
//#define Hard_i2c
//#define Hard_i2c_remap
#define Two_i2c1
//#define Two_i2c2
//#define Soft_i2c1
//#define Soft_i2c2

#if defined(Hard_i2c)
  #include <Wire.h> // SCL=PB6 SDA=PB7
  #define TEXT "Hardware Wire"
#endif

//動かない
#if defined(Hard_i2c_remap)
  #include <Wire.h> // SCL=PB8 SDA=PB9
  #define TEXT "Hardware Wire REMAP"
#endif

#if defined(Two_i2c1)
  #include <Wire.h>
  #define Wire Wire2
  TwoWire Wire(1,I2C_FAST_MODE); // SCL=PB6 SDA=PB7
  #define TEXT "TwoWire Wire(1,I2C_FAST_MODE)"
#endif

#if defined(Two_i2c2)
  #include <Wire.h>
  #define Wire Wire2
  TwoWire Wire(2,I2C_FAST_MODE); // SCL=PB10 SDA=PB11
  #define TEXT "TwoWire Wire(2,I2C_FAST_MODE)"
#endif

#if defined(Soft_i2c1)
  #include <SoftWire.h>
  #define Wire Wire2
  SoftWire Wire(PB8, PB9, SOFT_FAST); // SCL=PB8 SDA=PB9
  #define TEXT "SoftWire Wire(PB8, PB9, SOFT_FAST)"
#endif

#if defined(Soft_i2c2)
  #include <SoftWire.h>
  #define Wire Wire2
  SoftWire Wire(PB10, PB11, SOFT_FAST); // SCL=PB10 SDA=PB11
  #define TEXT "SoftWire Wire(PB10, PB11, SOFT_FAST)"
#endif

#define EEPROM_ADDRESS 0x50

byte readByte(byte m_deviceAddress, word address){
    Wire.beginTransmission((byte)(m_deviceAddress | ((address >> 8) & 0x07)));
    Wire.write((byte)(address & 0xFF));
    Wire.endTransmission();
    Wire.requestFrom((byte)(m_deviceAddress | ((address >> 8) & 0x07)), (byte)1);
    byte data = 0;
    if (Wire.available())
    {
        data = Wire.read();
    }
    return data;
}

void setup()
{
    // Initialize serial communication.
    delay(1000);Serial.begin(9600);
    Serial.println(TEXT);
#if defined(Hard_i2c_remap)
    afio_remap(AFIO_REMAP_I2C1); // remap I2C1 
#endif
    Wire.begin();
    // Print read bytes.
    Serial.println("Read bytes:");
    for (byte i = 0; i < 94; i++)
    {
        Serial.write(readByte(EEPROM_ADDRESS,i));
        Serial.print(" ");
    }
    Serial.println("");
}


void loop(){}


TwoWireオブジェクト

以下のコードで(SCL=PB6/SDA=PB7)をi2cとして使うことができます。
  #include <Wire.h>
  #define Wire Wire2
  TwoWire Wire(1,I2C_FAST_MODE); // SCL=PB6 SDA=PB7

以下のコードで(SCL=PB10/SDA=PB11)をi2cとして使うことができます。
  #include <Wire.h>
  #define Wire Wire2
  TwoWire Wire(2,I2C_FAST_MODE); // SCL=PB10 SDA=PB11


SoftWireオブジェクト

以前はTwoWireオブジェクトでしたが、新しいTwoWireが作られたので、SoftWireに名前が変わりました。
古い資料ではTwoWireとなっていることが有ります。

以下のコードで(SCL=PB8/SDA=PB9)をi2cとして使うことができます。
  #include <SoftWire.h>
  #define Wire Wire2
  SoftWire Wire(PB8, PB9, SOFT_FAST); // SCL=PB8 SDA=PB9

以下のコードで(SCL=PB10/SDA=PB11)をi2cとして使うことができます。
  #include <SoftWire.h>
  #define Wire Wire2
  SoftWire Wire(PB10, PB11, SOFT_FAST); // SCL=PB10 SDA=PB11



いずれも
  #define Wire Wire2
で、WireをWire2に置き換えています。
これをしないとコンパイルエラーとなります。

またライブラリ内部でWire.hをインクルードしているライブラリは正しく動きません。

続く...