Arduino Microcontroller: How to Use I2C, SPI, and UART

I2C

#include <Arduino.h>
#include <Wire.h>
#define IC2_CLIENT 0x23void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(IC2_CLIENT);
Wire.write("Server Request");
Wire.endTransmission();
delay(3000);
}
#include <Arduino.h>
#include <Wire.h>
#define MY_I2C_ADDRESS 0x23void setup() {
Wire.begin(MY_I2C_ADDRESS);
Serial.begin(9600);
}
void loop() {
if (Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
}

SPI

#include <Arduino.h>
#include <SPI.h>
#define CLIENT_SELECT_PIN = 10
#define CLIENT_REGISTER_ADDRESS = 0x10;
void setup() {
pinMode(CLIENT_SELECT_PIN, OUTPUT);
SPI.begin();
}
void loop() {
delay(1000);
writeToSpiClient(0x10, millis());
}
void writeToSpiClient(char& buffer, int value) {
delay(100);
SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
SPI.transfer(buffer,value);
SPI.endTransaction();
digitalWrite(CLIENT_SELECT_PIN, HIGH);
delay(100);
}
  • Define the pin layout
  • Start the SPI server with SPI.begin()
  • Wrap any transaction in SPI.beginTransaction() and SPI.endTransaction()
  • Use SPI.transfer to send and receive data at the same time

UART

#include <Arduino.h>
#include <stdbool.h>
string msg;
bool only_once = true;
void setup() {
Serial.begin(9600);
}
void loop() {
(if only_once) {
only_once = false;
Serial.send("Hello Client");
}
if (Serial.available()) {
char c;
while (c = Serial.read()) {
msg += c;
}
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store