0
0

ESP32を用いたSPI通信(マスター)

Posted at

ESP32を用いたSPI通信

Masterにした理由

本当は、スレーブで通信を行いたかったのだが、自作のプログラムでは動かず、先達のプログラムをコピペしてもスレーブが一切動かなかったため、仕方なくマスターとして通信を行う。
ESP32の利用途が、センサのデータを統合して、メインマイコンに送信し、メインマイコンでデータ処理を行うことを想定していたため、ESP32はメインマイコンからの送信リクエストを受け取り、必要なデータを送るという動作を行わせたかった。

testプログラムの処理内容

スループットで0に数をひたすら足して、それを送信するプログラムである。
テストプログラムを作るのは、マスターだと簡単だった。

プログラム

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_log.h"
#include "driver/spi_slave.h"
#include "driver/spi_master.h"
#include "driver/gpio.h"
#include <Arduino.h>
#include <SPI.h>

#define GPIO_MOSI           12
#define GPIO_MISO           13
#define GPIO_SCLK           15
#define GPIO_CS             14

#define GPIO_MOSI GPIO_NUM_12
#define GPIO_MISO GPIO_NUM_13
#define GPIO_SCLK GPIO_NUM_15
#define GPIO_CS GPIO_NUM_14

spi_device_handle_t handle;
float rxdata = 0;
float txdata = 0;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  int ret = 0; //診断用バッファ
  

  spi_bus_config_t buscfg = {
        .mosi_io_num = GPIO_MOSI,
        .miso_io_num = GPIO_MISO,
        .sclk_io_num = GPIO_SCLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
    };

    spi_device_interface_config_t spicfg = {
      .command_bits = 0,
      .address_bits = 0,
      .dummy_bits = 0,
      .mode = 0,
      .duty_cycle_pos = 128,
      .clock_speed_hz = 1000000,
      .input_delay_ns = 0,
      .spics_io_num = GPIO_CS,
      .queue_size = 2,
    };

    ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
    assert(ret == ESP_OK);
    ret = spi_bus_add_device(SPI2_HOST, &spicfg,&handle);
    assert(ret == ESP_OK);

}

void loop() {
  // put your main code here, to run repeatedly:
    int ret = 0;

    spi_transaction_t t;
    memset(&t, 0, sizeof(t));
    t.length = 32;
    
    t.rx_buffer = &rxdata;
    t.tx_buffer = &txdata;
    
      ret = spi_device_transmit(handle,&t);
      
      Serial.printf("%f\n",txdata);

      txdata = txdata+0.0001; 
      delay(1);

}

参考文献

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