LoginSignup
0
0

More than 1 year has passed since last update.

STM32G031でArduino同士でI2C通信する方法

Last updated at Posted at 2022-03-26

x 非営利、研究目的で記事を参考にして移植しました。
x PA0を使う時は、OBでGPIOモードにする

目的
I2Cのテスト

o_con290.jpg

移植元の参考記事

Arduino同士でI2C通信する方法

スレーブのプログラム




#include <Wire.h>

byte b=0;

void setup() {

  //I2Cの初期化
  //Wire.begin(PA12, PA11); //stm32g031
  Wire.setSDA(PA12);
  Wire.setSCL(PA11);
  Wire.begin(); //pa12 pa11


  Wire.begin(8);// Slave ID #8
  Wire.onRequest(requestEvent);
}

void loop() {
}

void requestEvent() {
  Wire.write(b++);
}




マスターのプログラム
主にセンサーからのデータを受信する
マスターモードで受信



//I2C_Master_ino_031_1

#include <Arduino.h>
#include <Wire.h>

//10の割り算 0から1028までは、正しい。主に0から999
#define DIV10(n) ((n*205)>>11)

#define in7      PA0  // 4pin

#define DW   digitalWrite

#define UART_DELAY 106   // 002-110 9600bps ok 031


//仮想シリアルへの一文字出力 9600bps
int pc_putc(char ch) {

  DW(in7, HIGH);

  DW(in7, LOW);//START
  delayMicroseconds(UART_DELAY);

  for (int ii = 0; ii < 8; ii++) {
    DW(in7, (ch >> ii) & 1  );
    delayMicroseconds(UART_DELAY);
  }//for

  DW(in7, HIGH);//Stop
  delayMicroseconds(UART_DELAY);

  return (0);

}//pc_putc


//文字列の表示
int pc_printf(char *str1) {

  //文字の中身がゼロか
  while (*str1) {

    //一文字出力
    pc_putc(*str1 ++);

  } //while

  //戻り値
  return (0);

}//pc_printf


//初期化
void setup()
{

  //ポートをhiにする 初期化
  pinMode(in7, OUTPUT);
  DW(in7, HIGH);

  //I2Cの初期化
  //Wire.begin(PA12, PA11); //stm32g031
  Wire.setSDA(PA12);
  Wire.setSCL(PA11);
  Wire.begin(); //pa12 pa11

} //setup


//メインループ
void loop()
{

  //読み込み
  Wire.requestFrom(8, 1);

  char data_read[8]; //バッファー

  while(Wire.available())  {    // 要求より短いデータが来る可能性あり
    unsigned char b = Wire.read();       // 1バイトを受信

    //表示
    data_read[5] = 0;
    data_read[4] = '\n';
    data_read[3] = '\r';
    data_read[2] = '0' + (  b - (DIV10(b) * 10)  );  // '0'+(b%10)
    b = DIV10(b);
    data_read[1] = '0' + (  b - (DIV10(b) * 10)  );  // '0'+(b%10)
    data_read[0] = '0' +  DIV10(b);                  // '0'+(s/10)
    pc_printf(data_read); //031

  }//while

  //1秒の待ち
  delay(1000);

} //loop



0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0