Networking and Communication¶
Wired communication - Examples¶
UART
UART stands for Universal Asynchronous Receiver/Transmitter and is the piece of hardware in charge of managing the data. Microcontrollers might have one, many or none UARTs:

Libraries for Arduino
- Serial The most basic example of all time:
#include <Arduino.h>
void setup() {
Serial.begin(9600);
// OR, in some boards like the arduino Zero:
SerialUSB.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
}
void loop(){
Serial.println("Hello Fabacademy");
}
- SoftwareSerial Example using both, serial and software serial, when we only have one hardware serial comm:
#include <SoftwareSerial.h>
SoftwareSerial BT1(10, 11); // RX | TX
void setup() {
pinMode(8, OUTPUT); // Al poner en HIGH forzaremos el modo AT
pinMode(9, OUTPUT); // cuando se alimente de aqui
digitalWrite(9, HIGH);
delay (500) ; // Espera antes de encender el modulo
Serial.begin(9600);
Serial.println("Levantando el modulo HC-06");
digitalWrite (8, HIGH); //Enciende el modulo
Serial.println("Esperando comandos AT:");
BT1.begin(38400);
}
void loop() {
if (BT1.available())
Serial.write(BT1.read());
if (Serial.available())
BT1.write(Serial.read());
}
Libraries for Python
import serial
PORT = '/dev/cu.usbmodem1421'
BAUDRATE = 115200
ser = serial.Serial(PORT, BAUDRATE)
print ser.readline().replace("\r\n", "")
ser.write('Hello')
Synchronous communication - Examples¶
When timing and speed are are important, and it’s worth having more wires, we will use synchronous communication. This means that we will have a clock line that stablishes the rate at which data is transferred. Most common inter-chip communication is implemented like this.
I2C¶
Libraries for Arduino
Esp32 has problems in slave mode with the standart i2c library from Arduino IDE. If you use the Esp this library is a better option.
- Nice documentation by an student¶
Example 1 Master as receiver: requesting information
Receiver:
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
Sender:
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
Wire.write("hello "); // respond with message of 6 bytes
// as expected by master
}
Example 2 Master as sender: sending information
Sender:
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
}
byte x = 0;
void loop() {
Wire.beginTransmission(8); // transmit to device #8
Wire.write("x is "); // sends five bytes
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
x++;
delay(500);
}
Receiver:
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output
}
void loop() {
delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
while (1 < Wire.available()) { // loop through all but the last
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
int x = Wire.read(); // receive byte as an integer
Serial.println(x); // print the integer
}
Example (for an analog pressure sensor that sends data via I2C):
#include <Arduino.h>
#include <TinyWireS.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
// Set I2C Slave address
#define I2C_SLAVE_ADDRESS 0x13
#ifndef TWI_RX_BUFFER_SIZE
#define TWI_RX_BUFFER_SIZE ( 16 )
#endif
// Sensor and Indicator Led Pins
#define SENSOR 1
// Measurement
#define MAX_TICK 50
unsigned int tick = 0;
//Smoothing Factor
#define LPF_FACTOR 0.5
volatile byte reg_position = 0;
const byte reg_size = sizeof(i2c_regs);
unsigned long lastReadout = 0;
// I2C Stuff
volatile uint8_t i2c_regs[] =
{
0, //older 8
0 //younger 8
};
void requestEvent()
{
TinyWireS.send(i2c_regs[reg_position]);
reg_position++;
if (reg_position >= reg_size)
{
reg_position = 0;
}
}
void setup() {
analogReference(EXTERNAL);
// Setup I2C
TinyWireS.begin(I2C_SLAVE_ADDRESS);
TinyWireS.onRequest(requestEvent);
// set clock divider to /1
CLKPR = (1 << CLKPCE);
CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
}
void loop() {
unsigned long currentMillis = millis();
// On tick value 0, do measurements
if (abs(currentMillis - lastReadout) > MAX_TICK) {
// Read the values
int sensorReading = analogRead(SENSOR);
// Treat them
float Vs = 0;
float pressure = 0;
Vs = ((float) sensorReading + 0.5 ) / 1024.0 * 5.0;
pressure = (Vs*687.8/Va - 18.77); // in kPa
i2c_regs[0] = pressure >> 8 & 0xFF;
i2c_regs[1] = pressure & 0xFF;
// Update the last readout
lastReadout = currentMillis;
}
}
Libraries for Python
Example 1, master as receiver
import smbus
import time
bus = smbus.SMBus(1) # Indicates /dev/i2c-1
DEVICE_ADDRESS = 0x13
packet_size = 4
def ReadSensor(_address):
i = 0
_value = 0
while (i < packet_size):
_measure = bus.read_i2c_block_data(_address, 0, 1)
_value |= _measure[0] << (8*(packet_size-(1+i)))
i+=1
return _value
while True:
result = ReadSensor(DEVICE_ADDRESS)
print result
time.sleep(1)
Example 2, master as sender
import smbus
bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)
DEVICE_ADDRESS = 0x15 #7 bit address (will be left shifted to add the read write bit)
DEVICE_REG_MODE1 = 0x00
DEVICE_REG_LEDOUT0 = 0x1d
#Write a single register
bus.write_byte_data(DEVICE_ADDRESS, DEVICE_REG_MODE1, 0x80)
#Write an array of registers
ledout_values = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
bus.write_i2c_block_data(DEVICE_ADDRESS, DEVICE_REG_LEDOUT0, ledout_values)
WiringPi
If you are using a Raspberry Pi, you can use WiringPi (C++), instead of sm.BUS (Python).
More references
sm.BUS in python is not greatly documented with examples, but here you can find some reference
SPI¶
Serial Peripheral Interface (SPI) is a synchronous serial protocol, used for short-distance communication, primarily in embedded systems.
Libraries for arduino
Example, arduino as master, sending:
#include <SPI.h>
void setup (void)
{
digitalWrite(SS, HIGH); // ensure SS stays high
SPI.begin ();
} // end of setup
void loop (void)
{
byte c;
// enable Slave Select
digitalWrite(SS, LOW); // SS is pin 10
// send test string
for (const char * p = "Fab" ; c = *p; p++)
SPI.transfer (c);
// disable Slave Select
digitalWrite(SS, HIGH);
delay (100);
} // end of loop
Looking to implement SPI?
Check the first response on this thread
OTA communication¶

BlueTooth Communication - HC08¶
AT COMMANDS FOR CONFIGURATION
AT+VERSION, Firmware version
AT+NAMEXXX,Program the name we want to present when someone looks for us
AT+BAUDX, Set the communication speed between the module and the console according to the following table:
1 configure 1200bps
2 configure 2400bps
3 configure 4800bps
4 configure 9600bps (Default)
5 configure 19200bps
6 configure 38400bps
7 configure 57600bps
8 configure 115200bps
AT+PINXXXX, set the personal identification number, which will be required to establish the link
AT+ROLE It informs us if it is configured as Master 1, or as slave 0.
AT+ROLE1 Configure the module in master mode
AT+ROLE0 Configure the module in slave mode
Note
Some commands need to be send with a “?” string at the end of the command to make it work.
For The Master Module (The other one that will be controlling the link.)
-
Connect to the FTDI to the computer and the bluetooth to the ftdi, select the port connection on the arduino IDE
-
You may type AT+CMODE=1 (master mode), and press enter. This will connect to all bluetooth modules within range, but it will only connect to one master module.
-
Now, type AT+ADDR, and press enter. You should get an address like “587A62500108”, or something similar. Write this down, you will need it later.This is the mac address of the master module.
For The Slave Module (The other one that will be listening to the link.)
-
Connect to the FTDI to the computer and the bluetooth to the ftdi, select the port connection on the arduino IDE
-
You may type AT+CMODE=1 (master mode), and press enter. This will connect to all bluetooth modules within range, but it will only connect to one master module.
-
You may type AT+CMODE=0 ( slave mode), and press enter. This will connect to all bluetooth modules within range, but it will only connect to one master module.
-
Now, type AT+BIND=”MAC ADDRESS OF THE MASTER” obviously with your respective address to the slave. Note the commas instead of colons given by the slave module.(in case your mac address has comas)
What should happen?
The modules should auto link when plugged in if not check for setting up the same setting in both devices and check the MacAddress
Example-1
#include <SoftwareSerial.h>
SoftwareSerial BT1(10, 11); // RX | TX
void setup()
{ pinMode(8, OUTPUT); // Al poner en HIGH forzaremos el modo AT
pinMode(9, OUTPUT); // cuando se alimente de aqui
digitalWrite(9, HIGH);
delay (500) ; // Espera antes de encender el modulo
Serial.begin(9600);
Serial.println("Levantando el modulo HC-06");
digitalWrite (8, HIGH); //Enciende el modulo
Serial.println("Esperando comandos AT:");
BT1.begin(38400);
}
void loop()
{ if (BT1.available())
Serial.write(BT1.read());
if (Serial.available())
BT1.write(Serial.read());
}
Example-2
#include <SoftwareSerial.h>
SoftwareSerial EEBlue(10, 11); // RX | TX
void setup()
{
Serial.begin(9600); EEBlue.begin(38400); //Baud Rate for command Mode. Serial.println("Enter AT commands!");
}
void loop()
{
// Feed any data from bluetooth to Terminal.
if (EEBlue.available())
Serial.write(EEBlue.read());
// Feed all data from termial to bluetooth
if (Serial.available())
EEBlue.write(Serial.read());
}
Example 3 - Python
from Adafruit_SHT31 import *
import serial
import time
sensor = SHT31(address = 0x44)
#sensor = SHT31(address = 0x45)
ser = serial.Serial(
port='/dev/ttyS0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
def readSHT():
try:
return sensor.read_temperature(), sensor.read_humidity()
except:
return None, None
if __name__ == "__main__":
try:
while True:
temp, humidity = readSHT()
time.sleep(1)
print 'Temp = {0:0.3f} deg C'.format(temp)
print 'Humidity = {0:0.2f} %'.format(humidity)
try:
ser.write('T:')
ser.write(str(temp))
ser.write(',')
ser.write('H.')
ser.write(str(humidity))
ser.write('\n')
except:
print ('Serial problem')
pass
except KeyboardInterrupt:
raise SystemExit
WiFi¶
Libraries
Examples
Need security?
You can use TLS/SSL extensions to protect your data from being sniffed!