Created
September 24, 2019 20:44
-
-
Save marijnfs/a3ae2e2cd6e71597a50cff240cf49960 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Copyright 2019 SiFive, Inc */ | |
/* SPDX-License-Identifier: Apache-2.0 */ | |
#include <stdio.h> | |
#include <metal/spi.h> | |
#include <metal/gpio.h> | |
struct metal_spi *spi = 0; | |
struct metal_gpio *gpio_device = 0; | |
struct metal_spi_config config = { | |
.protocol = METAL_SPI_SINGLE, | |
.polarity = 0, | |
.phase = 0, | |
.little_endian = 0, | |
.cs_active_high = 0, | |
.csid = 0, | |
}; | |
void wait_handshake() { | |
while (1) { | |
int handshake = metal_gpio_get_input_pin(gpio_device, 10); | |
if (handshake) | |
printf("waiting\n"); | |
else | |
break; | |
} | |
} | |
void transfer_4(char *tx_buf, char *rx_buf) { | |
metal_gpio_set_pin(gpio_device, 9, 0); //chip select? | |
printf("Sending\n"); | |
int code = metal_spi_transfer(spi, &config, 4, tx_buf, rx_buf); | |
printf("%i %i %i %i\n", rx_buf[0], rx_buf[1], rx_buf[2], rx_buf[3]); | |
printf("Done, code: %i\n", code); | |
metal_gpio_set_pin(gpio_device, 9, 1); | |
} | |
int init() { | |
//set CS enable? (low is active?) | |
gpio_device = metal_gpio_get_device(0); | |
metal_gpio_enable_output(gpio_device, 9); | |
//set handshape pin to input | |
metal_gpio_enable_input(gpio_device, 10); | |
/* Get SPI 1 */ | |
printf("Trying to get device\n"); | |
while (spi == NULL) { | |
spi = metal_spi_get_device(1); | |
} | |
if(spi == NULL) { | |
printf("Failed to get spi device\n"); | |
return 0; | |
} | |
/* Initialize the SPI device to 100_000 baud */ | |
metal_spi_init(spi, 1000); | |
return 1; | |
} | |
int main() { | |
printf("METAL SPI Driver ESP32 Demo\n"); | |
if (!init()) { | |
printf("init fail\n"); | |
return -1; | |
} | |
wait_handshake(); | |
{ | |
char tx_buf[4] = {0x2, 0, 0, 0}; | |
char rx_buf[4] = {0, 0, 0, 0}; | |
transfer_4(tx_buf, rx_buf); | |
} | |
wait_handshake(); | |
{ | |
char tx_buf[4] = {4, 0, 0, 0x41}; | |
char rx_buf[4] = {0, 0, 0, 0}; | |
transfer_4(tx_buf, rx_buf); | |
} | |
wait_handshake(); | |
{ | |
char tx_buf[4] = {'A', 'T', '\r', '\n'}; | |
char rx_buf[4] = {0, 0, 0, 0}; | |
transfer_4(tx_buf, rx_buf); | |
} | |
wait_handshake(); | |
{ | |
char tx_buf[4] = {0x2, 0, 0, 0}; | |
char rx_buf[4] = {0, 0, 0, 0}; | |
transfer_4(tx_buf, rx_buf); | |
} | |
wait_handshake(); | |
{ | |
char tx_buf[4] = {0, 0, 0, 0}; | |
char rx_buf[4] = {0, 0, 0, 0}; | |
transfer_4(tx_buf, rx_buf); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment